Navigation after sign-in (navPlan + navigate): App Store Connect Apps > + > New App (EN/TR), App Privacy by /apps/<appId>/distribution/privacy or the app list, Play app list by package name > Policy and programs > App content > Start / Manage. Every navigation click goes through navClick: the click gate stays absolute, only a link named exactly Start / Manage / Başla / Yönet passes. Each step is logged; a step not found in time or two matching apps -> the printed steps and wait (no crash). The TR gate now refuses "uygula" (apply) but not "uygulama" (app). Browser (cli/console/session.ts): attach to a Chrome with remote debugging (--cdp or DevToolsActivePort), else on macOS a temporary profile with only Local State and the profile's Cookies filtered to the console hosts, opened in real Chrome and deleted at the end, else storebound's own profile (--fresh-profile). Cookies are never printed. Desktop: fresh_profile option, the dialog says it uses the Chrome sign-in. Tests: navigation fixtures (ASC EN/TR, Play list, App content, missing step, duplicates, deny-listed decoys), session file selection, host filter, cleanup, and a real-Chrome copy-mode test on a throwaway profile and a local site.
458 lines
25 KiB
TypeScript
458 lines
25 KiB
TypeScript
// AI-assisted autofill of console forms that have no API, in a visible Chromium the owner signs in to:
|
|
// storebound console fill lists the forms
|
|
// storebound console fill <form> --dry [--json] the answers and the step-by-step guidance; opens no browser
|
|
// storebound console fill <form> [--store apple|play] [--json] [--profile <dir>]
|
|
// Forms: apple-app-record, apple-age-rating (guide only: `storebound apple appinfo` sets it), apple-app-privacy,
|
|
// play-content-rating, play-target-audience. Answers come from the config only (cli/lib/console-answers.ts); anything
|
|
// it does not prove stays EMPTY and highlighted (AGENTS.md rule 5).
|
|
// Safety: storebound never types passwords, never touches sign-in pages (it waits while the owner signs in), never reads
|
|
// cookies or storage, and never clicks Save / Submit / Publish / Create / Next: every click goes through safeClick and
|
|
// its gate. After sign-in it opens the form itself (navPlan in cli/lib/console-forms.ts: Apps > + > New App, the app's
|
|
// App Privacy page, Play app list > the app > App content > Start / Manage); those clicks go through navClick, which
|
|
// applies the same gate (only a link named exactly Start / Manage / Başla / Yönet is let through). A step not found in
|
|
// time -> the printed steps, and storebound waits as before. The owner reviews each page, clicks Next, and presses the
|
|
// final button; the command ends when the window is closed. Locators are accessible names only
|
|
// (cli/lib/console-forms.ts); a missing or ambiguous field means the UI changed: filling stops and the guidance is
|
|
// printed instead. Not exposed over MCP.
|
|
// Browser (cli/console/session.ts): the owner's running Chrome (--cdp / remote debugging), else a temporary copy of only
|
|
// their Chrome sign-in cookies (macOS; deleted at the end), else storebound's own profile
|
|
// (~/.storebound/console-profile/<store>, or --profile / STOREBOUND_CONSOLE_PROFILE / --fresh-profile).
|
|
// Sources (checked October 2026): see cli/lib/console-answers.ts; Playwright launchPersistentContext, getByRole,
|
|
// getByLabel: https://playwright.dev/docs/api/class-browsertype#browser-type-launch-persistent-context ,
|
|
// https://playwright.dev/docs/locators
|
|
import { homedir } from 'node:os';
|
|
import { join } from 'node:path';
|
|
import type { Ctx } from '../lib/ctx';
|
|
import { type Answer, type ConsoleResult, consoleResult, DISCLAIMER, FORM_IDS, type FormId, fillValue, formMeta, isForm, valueText } from '../lib/console-answers';
|
|
import { consoleReached, type FieldDef, type FormDef, formDef, FORM_OPENERS, forbiddenControl, hasToken, isSignInUrl, type Name, navAllowed, type NavStep, navPlan } from '../lib/console-forms';
|
|
import { log, printJson, warn } from '../lib/log';
|
|
import { type ConsoleBrowser, openConsoleBrowser } from './session';
|
|
|
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
type Page = any;
|
|
type Locator = any;
|
|
|
|
const TAG = 'console';
|
|
const CHECK = 'storebound: check this';
|
|
|
|
/** Locators with only the visible matches (hidden earlier pages stay in many consoles' DOM). */
|
|
const vis = (l: Locator): Locator => { try { return l.filter({ visible: true }); } catch { return l; } };
|
|
const nameOpts = (n: Name) => (typeof n === 'string' ? { name: n, exact: true } : { name: n });
|
|
|
|
type Found = { state: 'ok'; loc: Locator } | { state: 'none' | 'ambiguous' };
|
|
|
|
async function first(tries: Locator[]): Promise<Found> {
|
|
for (const t of tries) {
|
|
const l = vis(t);
|
|
const n = await l.count();
|
|
if (n === 1) return { state: 'ok', loc: l };
|
|
if (n > 1) return { state: 'ambiguous' };
|
|
}
|
|
return { state: 'none' };
|
|
}
|
|
|
|
async function find(root: Locator, role: string, names: Name[], label = false): Promise<Found> {
|
|
for (const n of names) {
|
|
const tries = [root.getByRole(role, nameOpts(n))];
|
|
if (label) tries.push(root.getByLabel(n, typeof n === 'string' ? { exact: true } : {}));
|
|
const f = await first(tries);
|
|
if (f.state !== 'none') return f;
|
|
}
|
|
return { state: 'none' };
|
|
}
|
|
|
|
interface Resolved { field: FieldDef; ok: boolean; seen: boolean; loc?: Locator; options?: Record<string, Locator> }
|
|
|
|
async function resolve(root: Locator, f: FieldDef): Promise<Resolved> {
|
|
if (f.kind !== 'radio') {
|
|
const role = f.kind === 'text' ? 'textbox' : f.kind === 'select' ? 'combobox' : 'checkbox';
|
|
const r = await find(root, role, f.names ?? [], f.kind !== 'checkbox');
|
|
return { field: f, ok: r.state === 'ok', seen: r.state !== 'none', ...(r.state === 'ok' ? { loc: r.loc } : {}) };
|
|
}
|
|
let scope = root, seen = false;
|
|
if (f.names?.length) {
|
|
let g = await find(root, 'radiogroup', f.names);
|
|
if (g.state === 'none') g = await find(root, 'group', f.names);
|
|
if (g.state !== 'ok') return { field: f, ok: false, seen: g.state !== 'none' };
|
|
scope = g.loc; seen = true;
|
|
}
|
|
const options: Record<string, Locator> = {};
|
|
let ok = true;
|
|
for (const [v, names] of Object.entries(f.options ?? {})) {
|
|
const r = await find(scope, 'radio', names);
|
|
if (r.state === 'ok') { options[v] = r.loc; seen = true; } else { ok = false; if (r.state === 'ambiguous') seen = true; }
|
|
}
|
|
return { field: f, ok, seen, ...(f.names?.length ? { loc: scope } : {}), options };
|
|
}
|
|
|
|
/** The accessible name of a control as the page labels it (what the click gate checks). */
|
|
async function accName(loc: Locator): Promise<string> {
|
|
return (await loc.evaluate((el: any) => {
|
|
const by = el.getAttribute('aria-labelledby');
|
|
const ref = by ? by.split(/\s+/).map((id: string) => el.ownerDocument.getElementById(id)?.textContent ?? '').join(' ') : '';
|
|
const labels = el.labels ? [...el.labels].map((l: any) => l.textContent).join(' ') : '';
|
|
return el.getAttribute('aria-label') || ref || labels || el.textContent || '';
|
|
})).trim().replace(/\s+/g, ' ');
|
|
}
|
|
|
|
/**
|
|
* The single click gate: refuses any control whose name says save, submit, publish, create, next ... (English and
|
|
* Turkish). Every click storebound makes, checkboxes and radio buttons included, goes through here.
|
|
*/
|
|
export async function safeClick(loc: Locator, name: string, action: 'click' | 'check' | 'uncheck' = 'click'): Promise<boolean> {
|
|
if (forbiddenControl(name)) { warn(TAG, `not clicking "${name}": storebound never presses save, submit, publish, next or similar`); return false; }
|
|
if (action === 'click') await loc.click();
|
|
else await loc.setChecked(action === 'check');
|
|
return true;
|
|
}
|
|
|
|
/** Outline + a small "storebound: check this" label next to the element (no SVG). */
|
|
export async function highlight(loc: Locator, text = CHECK): Promise<void> {
|
|
await loc.evaluate((el: any, t: string) => {
|
|
const box = (el.tagName === 'INPUT' && el.closest('label')) || el;
|
|
if (box.getAttribute('data-storebound-check')) return;
|
|
box.setAttribute('data-storebound-check', '1');
|
|
box.style.outline = '3px solid #d93025';
|
|
box.style.outlineOffset = '2px';
|
|
const s = el.ownerDocument.createElement('span');
|
|
s.textContent = t;
|
|
s.setAttribute('data-storebound-label', '1');
|
|
s.style.cssText = 'display:inline-block;margin:2px 6px;padding:1px 6px;border-radius:4px;background:#d93025;color:#fff;font:600 12px/18px system-ui,sans-serif';
|
|
box.insertAdjacentElement('afterend', s);
|
|
}, text);
|
|
}
|
|
|
|
async function setField(r: Resolved, v: string | boolean): Promise<boolean> {
|
|
const f = r.field;
|
|
if (f.kind === 'text') { await r.loc.fill(String(v)); return true; }
|
|
if (f.kind === 'checkbox') return safeClick(r.loc, await accName(r.loc), v ? 'check' : 'uncheck');
|
|
if (f.kind === 'radio') {
|
|
const o = r.options?.[String(v)];
|
|
return o ? safeClick(o, await accName(o), 'check') : false;
|
|
}
|
|
// select: only a native <select>; a custom dropdown is left to the owner (highlighted)
|
|
const idx: number = await r.loc.evaluate((el: any, want: string) => {
|
|
if (el.tagName !== 'SELECT') return -1;
|
|
const labels: string[] = [...el.options].map((o: any) => (o.label || o.textContent || '').trim());
|
|
const exact = labels.indexOf(want);
|
|
if (exact >= 0) return exact;
|
|
const near = labels.map((l, i) => [l, i] as const).filter(([l]) => l.endsWith(` - ${want}`) || l.endsWith(`(${want})`) || l.includes(want));
|
|
return near.length === 1 ? near[0]![1] : -1;
|
|
}, String(v));
|
|
if (idx < 0) return false;
|
|
await r.loc.selectOption({ index: idx });
|
|
return true;
|
|
}
|
|
|
|
async function mark(r: Resolved): Promise<void> {
|
|
if (r.loc) return highlight(r.loc);
|
|
for (const o of Object.values(r.options ?? {})) await highlight(o);
|
|
}
|
|
|
|
export interface FillStep {
|
|
/** Index of the section filled (or that triggered the fallback); null when no unfilled section is on the page. */
|
|
section: number | null;
|
|
title?: string;
|
|
filled: string[];
|
|
highlighted: string[];
|
|
/** Fields of the section that could not be located (UI change) -> fallback. */
|
|
missing: string[];
|
|
fallback: boolean;
|
|
}
|
|
|
|
/**
|
|
* Fills the first section of the form that is on the page and not done yet: locate every field first; any missing or
|
|
* ambiguous field -> fallback (nothing of that section is touched). Certain answers are set, the rest is highlighted
|
|
* and left empty. Never clicks Next / Save. `answers` carry the values the page gets (fillValue).
|
|
*/
|
|
export async function fillPage(page: Page, def: FormDef, answers: Answer[], done: Set<number> = new Set()): Promise<FillStep> {
|
|
const byId = new Map(answers.map(a => [a.id, a]));
|
|
for (const [i, sec] of def.sections.entries()) {
|
|
if (done.has(i)) continue;
|
|
let root: Locator = page;
|
|
if (sec.dialog) {
|
|
const d = await find(page, 'dialog', sec.dialog);
|
|
if (d.state === 'none') continue;
|
|
if (d.state !== 'ok') return { section: i, title: sec.title, filled: [], highlighted: [], missing: [`dialog ${sec.title}`], fallback: true };
|
|
root = d.loc;
|
|
}
|
|
const rs: Resolved[] = [];
|
|
for (const f of sec.fields) rs.push(await resolve(root, f));
|
|
if (!sec.dialog && !rs.some(r => r.seen)) continue;
|
|
const missing = rs.filter(r => !r.ok).map(r => r.field.id);
|
|
if (missing.length) return { section: i, title: sec.title, filled: [], highlighted: [], missing, fallback: true };
|
|
const filled: string[] = [], highlighted: string[] = [];
|
|
for (const r of rs) {
|
|
const a = byId.get(r.field.id);
|
|
if (!a) continue;
|
|
const set = a.certain && a.value !== null ? await setField(r, a.value) : false;
|
|
if (set) filled.push(a.id); else { await mark(r); highlighted.push(a.id); }
|
|
}
|
|
done.add(i);
|
|
return { section: i, title: sec.title, filled, highlighted, missing: [], fallback: false };
|
|
}
|
|
return { section: null, filled: [], highlighted: [], missing: [], fallback: false };
|
|
}
|
|
|
|
/** A sign-in page: Apple ID / Google accounts hosts, a sign-in frame, or any password field. Read-only check. */
|
|
export async function signInPage(page: Page): Promise<boolean> {
|
|
if (isSignInUrl(page.url())) return true;
|
|
if (page.frames().some((f: any) => isSignInUrl(f.url()))) return true;
|
|
try { return (await page.locator('input[type="password"]').count()) > 0; } catch { return false; }
|
|
}
|
|
|
|
|
|
// ---- navigation to the form (after sign-in) ----
|
|
|
|
/** The ARIA role the element really has (explicit role, else the implicit one for links, buttons and rows). */
|
|
async function realRole(loc: Locator): Promise<string> {
|
|
return loc.evaluate((el: any) => el.getAttribute('role') || (el.tagName === 'A' && el.hasAttribute('href') ? 'link' : el.tagName === 'BUTTON' ? 'button' : el.tagName === 'TR' ? 'row' : el.tagName.toLowerCase()));
|
|
}
|
|
|
|
/**
|
|
* The navigation click gate: reads the element's real accessible name and role and refuses it unless navAllowed says
|
|
* so (the click gate stays absolute: never Save / Submit / Publish / Create / Send / Next ...; only a link named exactly
|
|
* Start / Manage / Başla / Yönet is let through). Every navigation click goes through here.
|
|
*/
|
|
export async function navClick(loc: Locator): Promise<{ clicked: boolean; name: string }> {
|
|
const name = await accName(loc), role = await realRole(loc);
|
|
if (!navAllowed(name, role)) { warn(TAG, `not clicking "${name}" while opening the form: storebound never presses save, submit, publish, next or similar`); return { clicked: false, name }; }
|
|
await loc.click();
|
|
return { clicked: true, name };
|
|
}
|
|
|
|
export interface NavResult {
|
|
ok: boolean;
|
|
/** Labels of the steps done (["already open"] when the form was already on the page). */
|
|
steps: string[];
|
|
/** The step that could not be done (not found in time, ambiguous, or refused by the gate). */
|
|
failed?: string;
|
|
why?: string;
|
|
/** pickApp: the matching apps when more than one matched (storebound stops and lists them). */
|
|
candidates?: string[];
|
|
}
|
|
|
|
async function findAny(root: Locator, roles: string[], names: Name[]): Promise<Found> {
|
|
for (const role of roles) { const f = await find(root, role, names); if (f.state !== 'none') return f; }
|
|
return { state: 'none' };
|
|
}
|
|
|
|
/** Polls `fn` until it returns a value or the time is up (errors while the page navigates count as "not yet"). */
|
|
async function poll<T>(ms: number, fn: () => Promise<T | null>): Promise<T | null> {
|
|
const end = Date.now() + ms;
|
|
for (;;) {
|
|
try { const r = await fn(); if (r !== null) return r; } catch { /* navigating */ }
|
|
if (Date.now() >= end) return null;
|
|
await Bun.sleep(200);
|
|
}
|
|
}
|
|
|
|
const opener = new RegExp(`^(?:${FORM_OPENERS.join('|')})$`);
|
|
|
|
async function pickApp(page: Page, s: Extract<NavStep, { kind: 'pickApp' }>, ms: number): Promise<{ loc?: Locator; candidates?: string[] } | null> {
|
|
if (s.search && s.tokens[0]) {
|
|
const box = await poll(Math.min(ms, 3000), async () => { const f = await findAny(page, ['searchbox', 'textbox', 'combobox'], s.search!); return f.state === 'ok' ? f.loc : null; });
|
|
if (box) { await box.fill(s.tokens[0]); }
|
|
}
|
|
return poll(ms, async () => {
|
|
for (const role of ['row', 'link']) {
|
|
const all = vis(page.getByRole(role));
|
|
const n = await all.count();
|
|
const hits: { loc: Locator; name: string }[] = [];
|
|
for (let i = 0; i < n; i++) {
|
|
const loc = all.nth(i), name = await accName(loc);
|
|
const byToken = s.tokens.some(t => hasToken(name, t));
|
|
const byName = role === 'link' && s.name !== undefined && name === s.name;
|
|
if (byToken || byName) hits.push({ loc, name });
|
|
}
|
|
if (hits.length === 1) {
|
|
const row = hits[0]!.loc;
|
|
if (role === 'row') { const inner = vis(row.getByRole('link')); if (await inner.count() >= 1) return { loc: inner.first() }; }
|
|
return { loc: row };
|
|
}
|
|
if (hits.length > 1) return { candidates: hits.map(h => h.name) };
|
|
}
|
|
return null;
|
|
});
|
|
}
|
|
|
|
async function formLink(page: Page, entry: Name[], ms: number): Promise<{ loc?: Locator; ambiguous?: boolean } | null> {
|
|
return poll(ms, async () => {
|
|
const found: { loc: Locator; key: string }[] = [];
|
|
const add = async (box: Locator) => {
|
|
const l = vis(box.getByRole('link', { name: opener }));
|
|
if (await l.count() !== 1) return;
|
|
const b = await l.boundingBox();
|
|
const key = b ? `${Math.round(b.x)},${Math.round(b.y)}` : String(found.length);
|
|
if (!found.some(f => f.key === key)) found.push({ loc: l, key });
|
|
};
|
|
for (const n of entry) {
|
|
for (const role of ['region', 'listitem', 'row', 'group', 'article']) {
|
|
const boxes = vis(page.getByRole(role, nameOpts(n)));
|
|
const c = await boxes.count();
|
|
for (let i = 0; i < c; i++) await add(boxes.nth(i));
|
|
}
|
|
if (found.length) break;
|
|
const boxes = vis(page.locator('section, li, tr, article, [role="listitem"], [role="row"], [role="region"]').filter({ hasText: n }));
|
|
const c = await boxes.count();
|
|
for (let i = 0; i < c; i++) await add(boxes.nth(i));
|
|
if (found.length) break;
|
|
}
|
|
if (found.length === 1) return { loc: found[0]!.loc };
|
|
return found.length > 1 ? { ambiguous: true } : null;
|
|
});
|
|
}
|
|
|
|
/** The wait target is on the page (a heading of `level` when given). */
|
|
async function present(page: Page, s: Extract<NavStep, { kind: 'wait' }>): Promise<boolean> {
|
|
if (s.level === undefined) return (await findAny(page, s.roles, s.names)).state !== 'none';
|
|
for (const n of s.names) if (await vis(page.getByRole('heading', { ...nameOpts(n), level: s.level })).count() > 0) return true;
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Opens the form step by step (navPlan). Logs every step; stops at the first step that is not found within
|
|
* `timeoutMs`, is ambiguous, or is refused by the click gate, and says which. Never throws for a missing step.
|
|
*/
|
|
export async function navigate(page: Page, plan: NavStep[], opts: { timeoutMs?: number; say?: (m: string) => void } = {}): Promise<NavResult> {
|
|
const ms = opts.timeoutMs ?? 20_000, say = opts.say ?? ((m: string) => log(TAG, m));
|
|
const steps: string[] = [];
|
|
const target = plan.at(-1);
|
|
if (target?.kind === 'wait' && await present(page, target).catch(() => false)) {
|
|
say(`the form is already open (${target.label})`);
|
|
return { ok: true, steps: ['already open'] };
|
|
}
|
|
const fail = (s: NavStep, why: string, candidates?: string[]): NavResult => ({ ok: false, steps, failed: s.label, why, ...(candidates ? { candidates } : {}) });
|
|
for (const [i, s] of plan.entries()) {
|
|
say(`opening the form, step ${i + 1}/${plan.length}: ${s.label}`);
|
|
if (s.kind === 'goto') {
|
|
try { await page.goto(s.url, { waitUntil: 'domcontentloaded' }); } catch (e) { return fail(s, `could not load ${s.url} (${(e as Error).message.split('\n')[0]})`); }
|
|
} else if (s.kind === 'click') {
|
|
if (s.optional && s.unless && (await findAny(page, s.unless.roles, s.unless.names)).state !== 'none') { say(' (not needed)'); continue; }
|
|
const f = await poll(s.optional ? Math.min(ms, 2000) : ms, async () => { const r = await findAny(page, s.roles, s.names); return r.state === 'none' ? null : r; });
|
|
if (!f) { if (s.optional) { say(' (not on this page, skipped)'); continue; } return fail(s, 'not found'); }
|
|
if (f.state !== 'ok') return fail(s, 'more than one match');
|
|
const c = await navClick(f.loc);
|
|
if (!c.clicked) return fail(s, `refused to click "${c.name}"`);
|
|
} else if (s.kind === 'pickApp') {
|
|
if (!s.tokens.length && !s.name) return fail(s, 'no bundle id, package name or app name in the config');
|
|
const r = await pickApp(page, s, ms);
|
|
if (!r) return fail(s, `no app matching ${[...s.tokens, ...(s.name ? [`"${s.name}"`] : [])].join(' / ')} in the list`);
|
|
if (r.candidates) return fail(s, 'more than one app matches', r.candidates);
|
|
const c = await navClick(r.loc);
|
|
if (!c.clicked) return fail(s, `refused to click "${c.name}"`);
|
|
} else if (s.kind === 'formLink') {
|
|
const r = await formLink(page, s.entry, ms);
|
|
if (!r) return fail(s, 'no Start or Manage link next to it');
|
|
if (r.ambiguous) return fail(s, 'more than one Start or Manage link matches');
|
|
const c = await navClick(r.loc);
|
|
if (!c.clicked) return fail(s, `refused to click "${c.name}"`);
|
|
} else {
|
|
const f = await poll(ms, async () => ((await present(page, s)) ? true : null));
|
|
if (!f) return fail(s, 'did not appear');
|
|
}
|
|
steps.push(s.label);
|
|
}
|
|
return { ok: true, steps };
|
|
}
|
|
|
|
function printText(res: ConsoleResult): void {
|
|
console.log(`${res.title}\n${res.url}\n`);
|
|
for (const a of res.answers) console.log(` ${a.certain ? '[ok] ' : '[check]'} ${a.label}: ${valueText(a)} (${a.source})${a.certain || !a.note ? '' : `\n ${a.note}`}`);
|
|
console.log(`\n${res.uncertain} answer(s) to check yourself.\n\nSteps:\n${res.guidance.map(g => ` - ${g}`).join('\n')}`);
|
|
}
|
|
|
|
export async function run(ctx: Ctx): Promise<void> {
|
|
const { config, root } = ctx.loaded;
|
|
const args = ctx.args, json = args.has('json'), dry = args.has('dry');
|
|
const form = args._[0];
|
|
if (!form) {
|
|
const forms = FORM_IDS.map(id => { const m = formMeta(id, config); return { id, store: m.store, title: m.title, fillable: m.fillable }; });
|
|
if (json) return printJson({ forms });
|
|
console.log('storebound console fill <form> [--store apple|play] [--dry] [--json] [--profile <dir>]\n');
|
|
for (const f of forms) console.log(` ${f.id.padEnd(22)} ${f.store.padEnd(6)} ${f.title}${f.fillable ? '' : ' (guide only)'}`);
|
|
return;
|
|
}
|
|
if (!isForm(form)) throw new Error(`console fill: unknown form "${form}" (one of ${FORM_IDS.join(', ')})`);
|
|
const fid: FormId = form;
|
|
const meta = formMeta(form, config);
|
|
const store = args.get('store');
|
|
if (store && store !== 'apple' && store !== 'play') throw new Error('--store: apple | play');
|
|
if (store && store !== meta.store) throw new Error(`console fill: ${form} is a ${meta.store} form, not ${store}`);
|
|
const res = consoleResult(form, config);
|
|
if (dry || !meta.fillable) {
|
|
if (json) return printJson(dry ? res : { ...res, filled: 0, highlighted: 0, fallback: false, stoppedAt: null });
|
|
return printText(res);
|
|
}
|
|
|
|
const say = (m: string) => (json ? console.error(`[${TAG}] ${m}`) : log(TAG, m));
|
|
for (const d of DISCLAIMER) say(d);
|
|
const startUrl = args.get('start-url');
|
|
if (startUrl && !/^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?\//.test(startUrl)) throw new Error('--start-url: only a local test page (http://127.0.0.1:<port>/...)');
|
|
const ownProfile = args.has('profile') || !!process.env.STOREBOUND_CONSOLE_PROFILE;
|
|
const dir = args.get('profile') ?? process.env.STOREBOUND_CONSOLE_PROFILE ?? join(homedir(), '.storebound', 'console-profile', meta.store);
|
|
const b = await openConsoleBrowser(root, {
|
|
store: meta.store, profileDir: dir, say, fresh: args.has('fresh-profile') || ownProfile,
|
|
...(args.get('cdp') ? { cdp: args.get('cdp') } : {}), ...(args.get('chrome-profile') ? { chromeProfile: args.get('chrome-profile') } : {}),
|
|
});
|
|
// the temporary profile of copy mode goes away on every exit path
|
|
const bye = () => { b.cleanup(); process.exit(130); };
|
|
process.once('SIGINT', bye); process.once('SIGTERM', bye);
|
|
try { await fillRun(b); } finally { b.cleanup(); process.off('SIGINT', bye); process.off('SIGTERM', bye); }
|
|
|
|
async function fillRun(b: ConsoleBrowser): Promise<void> {
|
|
const active = (): Page | undefined => b.pages().at(-1);
|
|
const page = b.page;
|
|
await page.goto(startUrl ?? meta.url).catch(() => { /* the owner can navigate */ });
|
|
|
|
// 1. sign-in: the owner does it; storebound only watches the URL
|
|
const deadline = Date.now() + 10 * 60_000;
|
|
let told = false;
|
|
while (!b.isClosed() && Date.now() < deadline) {
|
|
const p = active();
|
|
if (p && !(await signInPage(p).catch(() => false)) && consoleReached(meta.store, p.url(), startUrl)) break;
|
|
if (p && !told && await signInPage(p).catch(() => false)) { say('sign in in the browser window, storebound waits'); told = true; }
|
|
await Bun.sleep(1000);
|
|
}
|
|
|
|
// 2. fill section by section as the owner moves through the form
|
|
const def = formDef(fid, res.answers);
|
|
const pageAnswers = res.answers.map(a => ({ ...a, value: fillValue(fid, a, config) }));
|
|
const labels = new Map(res.answers.map(a => [a.id, a.label]));
|
|
const done = new Set<number>();
|
|
let filled = 0, highlighted = 0, fallback = false;
|
|
// 2a. open the form: navigation clicks only (navClick); on any miss, the printed steps and wait as before
|
|
const plan = startUrl || b.isClosed() ? [] : navPlan(fid, config);
|
|
const nav = plan.length ? await navigate(active() ?? page, plan, { say }).catch((e: Error): NavResult => ({ ok: false, steps: [], failed: 'navigation', why: e.message.split('\n')[0] })) : null;
|
|
if (nav && !nav.ok) {
|
|
warn(TAG, `could not open the form by itself at step "${nav.failed}" (${nav.why}). Open it yourself; storebound waits and fills it when it appears:`);
|
|
if (nav.candidates) say(`apps that match: ${nav.candidates.join(' | ')} (set apple.appId / play.packageName in the config to pick one)`);
|
|
}
|
|
if (!nav?.ok) for (const o of meta.open) say(`open the form: ${o}`);
|
|
else if (meta.then) say(`now click ${meta.then} yourself; storebound fills the form when it appears`);
|
|
const last = def.sections.length - 1;
|
|
const finished = () => done.size === def.sections.length || (form !== 'apple-app-privacy' && done.has(last));
|
|
while (!b.isClosed() && !finished()) {
|
|
const p = active();
|
|
if (!p || await signInPage(p).catch(() => true)) { await Bun.sleep(1500); continue; }
|
|
let s: FillStep;
|
|
try { s = await fillPage(p, def, pageAnswers, done); } catch { await Bun.sleep(1500); continue; } // navigating
|
|
if (s.section !== null) {
|
|
if (s.fallback) {
|
|
fallback = true;
|
|
warn(TAG, `the page does not match what storebound expects (${s.missing.join(', ')}): the console UI changed. Nothing more is filled; follow these steps:`);
|
|
for (const g of res.guidance) say(` ${g}`);
|
|
break;
|
|
}
|
|
filled += s.filled.length; highlighted += s.highlighted.length;
|
|
say(`${s.title}: filled ${s.filled.length}, check ${s.highlighted.length}${s.highlighted.length ? `: ${s.highlighted.map(id => labels.get(id) ?? id).join('; ')}` : ''}`);
|
|
if (!finished()) say('review this page, then click Next (or open the next part) yourself; storebound fills it when it appears');
|
|
}
|
|
await Bun.sleep(1500);
|
|
}
|
|
if (!b.isClosed() && !fallback) say(`review every field and press ${meta.stopBefore} yourself. storebound never saves, submits or publishes. Close the window when done.`);
|
|
else if (!b.isClosed()) say('close the browser window when done');
|
|
await b.closed;
|
|
if (json) printJson({ ...res, filled, highlighted, fallback, stoppedAt: meta.stopBefore, browser: b.mode });
|
|
}
|
|
}
|