CLI for desktop D2: doctor, inspect --icon / --listings, reviews drafts / approve, init --dry from embedded templates, iOS phased release share, playwright as optional peer (sidecar bundles playwright-core)
This commit is contained in:
parent
94d2f3d6ca
commit
0ace432e87
22 changed files with 808 additions and 40 deletions
15
CHANGELOG.md
15
CHANGELOG.md
|
|
@ -17,6 +17,21 @@
|
||||||
Releases / Catalog / Listings / Health / Reviews / TestFlight, App folders, Accounts, Dependencies, Settings), store
|
Releases / Catalog / Listings / Health / Reviews / TestFlight, App folders, Accounts, Dependencies, Settings), store
|
||||||
keys in the OS keychain, native confirm dialogs with the dry run before any write. See `docs/desktop.md`.
|
keys in the OS keychain, native confirm dialogs with the dry run before any write. See `docs/desktop.md`.
|
||||||
- `--json` on `catalog diff` goes through the same machine-readable result line.
|
- `--json` on `catalog diff` goes through the same machine-readable result line.
|
||||||
|
- **`storebound doctor`** (`--json`): ffmpeg, ffprobe, Chrome, playwright, Xcode tools, simctl, adb and git with
|
||||||
|
versions (the same detection as the desktop Dependencies screen) and the install commands for this OS. It runs none.
|
||||||
|
- `playwright` is an optional peer dependency (it was only documented before). The compiled desktop sidecar bundles
|
||||||
|
`playwright-core` and renders with the app's Chrome for Testing (`STOREBOUND_CHROME`), so desktop users need neither.
|
||||||
|
- `inspect --icon` / `inspect --listings` (listing completeness per language on both stores, rendered screenshots),
|
||||||
|
`reviews drafts [--json]` (local reply drafts with the send checks), `reviews approve <draft> [--undo] [--dry]`,
|
||||||
|
`init --dry`; templates are embedded so `init` works from a single-file binary.
|
||||||
|
- `apple status --json` includes the phased release of the newest live versions; release trains now count a staged
|
||||||
|
rollout or iOS phased release (also halted / paused) as the current train.
|
||||||
|
- **Desktop D2** (`apps/desktop`): redesigned shell (command palette, toasts with progress and cancel, skeletons,
|
||||||
|
illustrated empty states, first-run guide), release timeline per app, catalog parity matrix, listing completeness,
|
||||||
|
health sparklines against the Play thresholds, reviews inbox with star distribution and draft approval, TestFlight
|
||||||
|
groups and builds, store readiness with fix hints; offline cache of the last reads (SQLite, "last read" stamps);
|
||||||
|
one-click ffmpeg (pinned SHA-256) and Chrome for Testing (Google's code signature) downloads into app data;
|
||||||
|
English and Turkish with an i18n check, 7:1 text contrast checked in both themes.
|
||||||
- `tools/build-sidecars.ts`: single-file executables for macOS (arm64, x64), Linux (x64, arm64) and Windows (x64),
|
- `tools/build-sidecars.ts`: single-file executables for macOS (arm64, x64), Linux (x64, arm64) and Windows (x64),
|
||||||
re-signed ad hoc on macOS and checked for build-machine paths. The MCP server now also runs from such a binary.
|
re-signed ad hoc on macOS and checked for build-machine paths. The MCP server now also runs from such a binary.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -182,6 +182,7 @@ run in the background with a log (`storebound shots render > .storebound/render.
|
||||||
| `validate [--apple] [--play]` | API, read-only | readiness report with ordered blockers plus the local renders checks (`--no-local` skips); exit 1 while any blocker is left |
|
| `validate [--apple] [--play]` | API, read-only | readiness report with ordered blockers plus the local renders checks (`--no-local` skips); exit 1 while any blocker is left |
|
||||||
| `whats-new [--since <tag>]` | local | draft player-facing release notes from git log into both listing files |
|
| `whats-new [--since <tag>]` | local | draft player-facing release notes from git log into both listing files |
|
||||||
| `privacy-manifest --ios <path>` | local | PrivacyInfo.xcprivacy, required-reason APIs, SDKs without manifests |
|
| `privacy-manifest --ios <path>` | local | PrivacyInfo.xcprivacy, required-reason APIs, SDKs without manifests |
|
||||||
|
| `doctor [--json]` | local | which local tools are here (ffmpeg, Chrome, playwright, Xcode, adb, git) and how to install the missing ones |
|
||||||
| `icons` | local | App Store 1024 (no alpha), Play 512, web, Capacitor sources, Android legacy launcher icons |
|
| `icons` | local | App Store 1024 (no alpha), Play 512, web, Capacitor sources, Android legacy launcher icons |
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
|
||||||
|
|
@ -54,7 +54,17 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
const builds = (await c.asc('GET', `/v1/builds?filter[app]=${appId}&sort=-uploadedDate&limit=5&include=preReleaseVersion`));
|
const builds = (await c.asc('GET', `/v1/builds?filter[app]=${appId}&sort=-uploadedDate&limit=5&include=preReleaseVersion`));
|
||||||
const iaps = await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`);
|
const iaps = await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`);
|
||||||
const subs = await c.all(`/v1/reviewSubmissions?filter[app]=${appId}&limit=20`);
|
const subs = await c.all(`/v1/reviewSubmissions?filter[app]=${appId}&limit=20`);
|
||||||
if (ctx.args.has('json')) { printJson({ app, versions, builds: builds.data, iaps, subs }); return; }
|
if (ctx.args.has('json')) {
|
||||||
|
// phased release of the newest versions that are live or close to it (rollout share on the desktop timeline)
|
||||||
|
const phased: Record<string, unknown> = {};
|
||||||
|
for (const v of versions.slice(0, 3)) {
|
||||||
|
const st = String(v.attributes.appVersionState ?? v.attributes.appStoreState ?? '');
|
||||||
|
if (!/READY_FOR_SALE|READY_FOR_DISTRIBUTION|PENDING_DEVELOPER_RELEASE|PENDING_APPLE_RELEASE|ACCEPTED/.test(st)) continue;
|
||||||
|
phased[v.id] = (await c.maybe(`/v1/appStoreVersions/${v.id}/appStoreVersionPhasedRelease`))?.data ?? null;
|
||||||
|
}
|
||||||
|
printJson({ app, versions, builds: builds.data, iaps, subs, phased });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
console.log(`${app.attributes.name} · ${app.attributes.bundleId} · Apple ID ${appId}`);
|
console.log(`${app.attributes.name} · ${app.attributes.bundleId} · Apple ID ${appId}`);
|
||||||
for (const v of versions) console.log(` version ${v.attributes.versionString.padEnd(8)} ${v.attributes.appVersionState ?? v.attributes.appStoreState}${v.relationships?.build?.data ? ' (build attached)' : ''}`);
|
for (const v of versions) console.log(` version ${v.attributes.versionString.padEnd(8)} ${v.attributes.appVersionState ?? v.attributes.appStoreState}${v.relationships?.build?.data ? ' (build attached)' : ''}`);
|
||||||
|
|
|
||||||
52
cli/doctor.ts
Normal file
52
cli/doctor.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
||||||
|
// What this machine has for storebound, and how to get what is missing. The same detection as the desktop app's
|
||||||
|
// Dependencies screen (lib/tools.ts). Store work (listings, products, releases, reviews) needs none of these tools;
|
||||||
|
// screenshots, app previews, icons and simulator / emulator captures do. Read-only: it prints commands, it runs none.
|
||||||
|
// storebound doctor [--dir .] [--json]
|
||||||
|
import { existsSync } from 'node:fs';
|
||||||
|
import { join, resolve } from 'node:path';
|
||||||
|
import pkg from '../package.json' with { type: 'json' };
|
||||||
|
import type { Args } from './lib/args';
|
||||||
|
import { CONFIG_NAMES } from './lib/config';
|
||||||
|
import { log } from './lib/log';
|
||||||
|
import { textTable } from './lib/table';
|
||||||
|
import { detectTools, findPlaywright, installCommands, type ToolStatus } from './lib/tools';
|
||||||
|
|
||||||
|
export interface DoctorRow {
|
||||||
|
id: ToolStatus['id'] | 'playwright';
|
||||||
|
name: string;
|
||||||
|
found: boolean;
|
||||||
|
version: string | null;
|
||||||
|
path: string | null;
|
||||||
|
source: ToolStatus['source'];
|
||||||
|
usedFor: string;
|
||||||
|
/** Install commands for this OS (empty when found). */
|
||||||
|
install: string[];
|
||||||
|
url: string | null;
|
||||||
|
}
|
||||||
|
export interface DoctorResult { storebound: string; bun: string; platform: string; project: string | null; tools: DoctorRow[]; missing: number }
|
||||||
|
|
||||||
|
export function doctor(cwd: string, env: Record<string, string | undefined> = process.env): DoctorResult {
|
||||||
|
const tools: DoctorRow[] = detectTools(env).map(t => ({ id: t.id, name: t.name, found: t.found, version: t.version, path: t.path, source: t.source, usedFor: t.usedFor,
|
||||||
|
install: t.found ? [] : installCommands(t.id), url: t.install.url }));
|
||||||
|
const pw = findPlaywright([cwd, join(import.meta.dir, '..')]);
|
||||||
|
tools.splice(3, 0, { id: 'playwright', name: 'playwright', found: !!pw, version: null, path: pw, source: pw ? 'system' : null,
|
||||||
|
usedFor: 'screenshot renders and web captures from a terminal (the desktop app brings its own)', install: pw ? [] : installCommands('playwright'), url: 'https://playwright.dev/docs/intro' });
|
||||||
|
const project = CONFIG_NAMES.some(n => existsSync(join(cwd, n))) ? cwd : null;
|
||||||
|
return { storebound: pkg.version, bun: Bun.version, platform: `${process.platform}-${process.arch}`, project, tools, missing: tools.filter(t => !t.found).length };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function run(args: Args): Promise<void> {
|
||||||
|
const r = doctor(resolve(args.str('dir', '.')));
|
||||||
|
if (args.has('json')) { console.log(JSON.stringify(r, null, 2)); return; }
|
||||||
|
log('doctor', `storebound ${r.storebound} · bun ${r.bun} · ${r.platform}${r.project ? ' · project config found' : ''}`);
|
||||||
|
console.log(textTable(['tool', 'status', 'version', 'used for'], r.tools.map(t => [t.name, t.found ? (t.source === 'app' ? 'ok (app copy)' : 'ok') : 'missing', t.version ?? '', t.usedFor])));
|
||||||
|
const missing = r.tools.filter(t => !t.found);
|
||||||
|
if (!missing.length) { log('doctor', 'everything storebound can use is here'); return; }
|
||||||
|
console.log('\nTo install what is missing (pick one per tool; storebound never runs these for you):');
|
||||||
|
for (const t of missing) {
|
||||||
|
console.log(` ${t.name}`);
|
||||||
|
for (const c of t.install) console.log(` ${c}`);
|
||||||
|
if (t.url) console.log(` ${t.url}`);
|
||||||
|
}
|
||||||
|
log('doctor', `${missing.length} missing. Store work needs none of them; screenshots, previews, icons and captures do.`);
|
||||||
|
}
|
||||||
|
|
@ -13,6 +13,7 @@ const PLAIN: Record<string, [() => Promise<Plain>, string]> = {
|
||||||
'install': [() => import('./install'), 'skills + MCP server for --agent claude|codex|cursor|copilot|windsurf|gemini|opencode'],
|
'install': [() => import('./install'), 'skills + MCP server for --agent claude|codex|cursor|copilot|windsurf|gemini|opencode'],
|
||||||
'mcp': [async () => ({ run: async () => (await import('./mcp')).serve() }), 'stdio MCP server wrapping these commands (for any MCP-capable AI tool)'],
|
'mcp': [async () => ({ run: async () => (await import('./mcp')).serve() }), 'stdio MCP server wrapping these commands (for any MCP-capable AI tool)'],
|
||||||
'serve': [() => import('./serve'), '--stdio: JSON-RPC session for the storebound desktop app (dry runs; writes need a host confirm token)'],
|
'serve': [() => import('./serve'), '--stdio: JSON-RPC session for the storebound desktop app (dry runs; writes need a host confirm token)'],
|
||||||
|
'doctor': [() => import('./doctor'), 'local tools for screenshots, previews, icons and captures (ffmpeg, Chrome, playwright, Xcode, adb, git) and how to install what is missing; --json'],
|
||||||
'privacy-manifest': [() => import('./privacy-manifest'), 'iOS PrivacyInfo.xcprivacy + required-reason API + SDK manifest scan (--ios <path>)'],
|
'privacy-manifest': [() => import('./privacy-manifest'), 'iOS PrivacyInfo.xcprivacy + required-reason API + SDK manifest scan (--ios <path>)'],
|
||||||
};
|
};
|
||||||
const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
|
const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
|
||||||
|
|
|
||||||
35
cli/init.ts
35
cli/init.ts
|
|
@ -1,15 +1,16 @@
|
||||||
// Copies the templates into the current project without overwriting anything, and makes sure .storebound/ is ignored.
|
// Copies the templates into the current project without overwriting anything, and makes sure .storebound/ is ignored.
|
||||||
// storebound init [--dir .] [--profile app|game|subscription-app]
|
// storebound init [--dir .] [--profile app|game|subscription-app] [--dry]
|
||||||
// Profiles (default app): app = utility / productivity app with an optional account and analytics, no ads;
|
// Profiles (default app): app = utility / productivity app with an optional account and analytics, no ads;
|
||||||
// game = free-to-play game with ads and in-app purchases (the templates storebound shipped before 0.5.0);
|
// game = free-to-play game with ads and in-app purchases (the templates storebound shipped before 0.5.0);
|
||||||
// subscription-app = accounts plus auto-renewable subscriptions. Each profile has its own config, declarations,
|
// subscription-app = accounts plus auto-renewable subscriptions. Each profile has its own config, declarations,
|
||||||
// App Privacy answers, Data safety section, listing copy and screenshot copy; every answer is a starting point to edit.
|
// App Privacy answers, Data safety section, listing copy and screenshot copy; every answer is a starting point to edit.
|
||||||
// Lookup per file: templates/profiles/<profile>/<file>, then the profile it builds on, then templates/<file>.
|
// Lookup per file: templates/profiles/<profile>/<file>, then the profile it builds on, then templates/<file>.
|
||||||
import { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||||
import { dirname, join, resolve } from 'node:path';
|
import { dirname, join, relative, resolve } from 'node:path';
|
||||||
import type { Args } from './lib/args';
|
import type { Args } from './lib/args';
|
||||||
import { type AppProfile, PROFILES } from './lib/config';
|
import { type AppProfile, PROFILES } from './lib/config';
|
||||||
import { log } from './lib/log';
|
import { log } from './lib/log';
|
||||||
|
import { TEMPLATE_TEXT } from './lib/template-files';
|
||||||
|
|
||||||
const T = join(import.meta.dir, '..', 'templates');
|
const T = join(import.meta.dir, '..', 'templates');
|
||||||
export const FILES: [string, string][] = [
|
export const FILES: [string, string][] = [
|
||||||
|
|
@ -24,33 +25,43 @@ export const FILES: [string, string][] = [
|
||||||
['testers.csv', '.storebound/testers.csv'],
|
['testers.csv', '.storebound/testers.csv'],
|
||||||
];
|
];
|
||||||
|
|
||||||
/** Template folders a profile reads from, most specific first. game = the root templates. */
|
/** Template folders a profile reads from (relative to templates/), most specific first. game = the root templates. */
|
||||||
const CHAIN: Record<AppProfile, string[]> = {
|
const CHAIN: Record<AppProfile, string[]> = {
|
||||||
'game': [T],
|
'game': [''],
|
||||||
'app': [join(T, 'profiles', 'app'), T],
|
'app': ['profiles/app/', ''],
|
||||||
'subscription-app': [join(T, 'profiles', 'subscription-app'), join(T, 'profiles', 'app'), T],
|
'subscription-app': ['profiles/subscription-app/', 'profiles/app/', ''],
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Source file of one template for a profile. Pure apart from existsSync. */
|
/** Key (path under templates/) of one template for a profile. Pure: looks it up in the embedded list. */
|
||||||
export function templateFor(profile: AppProfile, name: string): string {
|
export function templateKey(profile: AppProfile, name: string): string {
|
||||||
for (const dir of CHAIN[profile]) if (existsSync(join(dir, name))) return join(dir, name);
|
for (const dir of CHAIN[profile]) if (TEMPLATE_TEXT[dir + name] !== undefined) return dir + name;
|
||||||
throw new Error(`template ${name} not found`);
|
throw new Error(`template ${name} not found`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Source file of one template for a profile (in the storebound folder; the compiled sidecar has none). */
|
||||||
|
export const templateFor = (profile: AppProfile, name: string): string => join(T, ...templateKey(profile, name).split('/'));
|
||||||
|
|
||||||
|
/** Template text: the embedded copy (the same bytes as the file; tests/apps.test.ts checks it). */
|
||||||
|
export const templateText = (profile: AppProfile, name: string): string => TEMPLATE_TEXT[templateKey(profile, name)]!;
|
||||||
|
|
||||||
export async function run(args: Args): Promise<void> {
|
export async function run(args: Args): Promise<void> {
|
||||||
const root = resolve(args.str('dir', '.'));
|
const root = resolve(args.str('dir', '.'));
|
||||||
const profile = args.str('profile', 'app') as AppProfile;
|
const profile = args.str('profile', 'app') as AppProfile;
|
||||||
if (!PROFILES.includes(profile)) throw new Error(`--profile ${profile}: one of ${PROFILES.join(', ')}`);
|
if (!PROFILES.includes(profile)) throw new Error(`--profile ${profile}: one of ${PROFILES.join(', ')}`);
|
||||||
log('init', `profile ${profile} (templates are starting points: edit every answer to match your app)`);
|
const dry = args.has('dry');
|
||||||
|
log('init', `profile ${profile}${dry ? ' (dry run: nothing is written)' : ''} (templates are starting points: edit every answer to match your app)`);
|
||||||
for (const [from, to] of FILES) {
|
for (const [from, to] of FILES) {
|
||||||
const dest = join(root, to);
|
const dest = join(root, to);
|
||||||
|
if (relative(root, dest).startsWith('..')) throw new Error(`template target outside the project: ${to}`);
|
||||||
if (existsSync(dest)) { log('init', `keep ${to} (exists)`); continue; }
|
if (existsSync(dest)) { log('init', `keep ${to} (exists)`); continue; }
|
||||||
|
if (dry) { log('init', `would create ${to}`); continue; }
|
||||||
mkdirSync(dirname(dest), { recursive: true });
|
mkdirSync(dirname(dest), { recursive: true });
|
||||||
copyFileSync(templateFor(profile, from), dest);
|
writeFileSync(dest, templateText(profile, from));
|
||||||
log('init', `create ${to}`);
|
log('init', `create ${to}`);
|
||||||
}
|
}
|
||||||
const gi = join(root, '.gitignore');
|
const gi = join(root, '.gitignore');
|
||||||
const cur = existsSync(gi) ? readFileSync(gi, 'utf8') : '';
|
const cur = existsSync(gi) ? readFileSync(gi, 'utf8') : '';
|
||||||
|
if (dry) { if (!/^\/?\.storebound\/?$/m.test(cur)) log('init', 'would add .storebound/ to .gitignore'); return; }
|
||||||
if (!/^\/?\.storebound\/?$/m.test(cur)) {
|
if (!/^\/?\.storebound\/?$/m.test(cur)) {
|
||||||
if (cur) appendFileSync(gi, `${cur.endsWith('\n') ? '' : '\n'}# storebound: credentials, fonts, temp files\n.storebound/\n`);
|
if (cur) appendFileSync(gi, `${cur.endsWith('\n') ? '' : '\n'}# storebound: credentials, fonts, temp files\n.storebound/\n`);
|
||||||
else writeFileSync(gi, '# storebound: credentials, fonts, temp files\n.storebound/\n');
|
else writeFileSync(gi, '# storebound: credentials, fonts, temp files\n.storebound/\n');
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,12 @@
|
||||||
// Offline summary of the project config: app name, store ids, languages, products, shots. No network, no credentials.
|
// Offline summary of the project config: app name, store ids, languages, products, shots. No network, no credentials.
|
||||||
// storebound inspect [--json]
|
// storebound inspect [--json]
|
||||||
import { platformsOf, sellsOn } from './lib/config';
|
// storebound inspect --icon --json the app icon as a data: URL (for the desktop app)
|
||||||
|
// storebound inspect --listings [--json] listing completeness per language on both stores (+ rendered screenshots)
|
||||||
|
import { platformsOf, profileOf, sellsOn } from './lib/config';
|
||||||
import type { Ctx } from './lib/ctx';
|
import type { Ctx } from './lib/ctx';
|
||||||
import type { ProjectSummary } from './lib/desktop-protocol';
|
import type { ProjectSummary } from './lib/desktop-protocol';
|
||||||
import { log, printJson } from './lib/log';
|
import { log, printJson } from './lib/log';
|
||||||
|
import { findIcon, iconDataUrl, listingCompleteness } from './lib/project-files';
|
||||||
|
|
||||||
export function summarize(ctx: Ctx): ProjectSummary {
|
export function summarize(ctx: Ctx): ProjectSummary {
|
||||||
const { config, root, path } = ctx.loaded;
|
const { config, root, path } = ctx.loaded;
|
||||||
|
|
@ -27,10 +30,21 @@ export function summarize(ctx: Ctx): ProjectSummary {
|
||||||
},
|
},
|
||||||
shots: !!config.shots,
|
shots: !!config.shots,
|
||||||
testflightGroups: config.apple?.testflight?.groups?.length ?? 0,
|
testflightGroups: config.apple?.testflight?.groups?.length ?? 0,
|
||||||
|
profile: profileOf(config),
|
||||||
|
icon: findIcon(config, root),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function run(ctx: Ctx): Promise<void> {
|
export async function run(ctx: Ctx): Promise<void> {
|
||||||
|
const { config, root } = ctx.loaded;
|
||||||
|
if (ctx.args.has('icon')) { printJson(iconDataUrl(findIcon(config, root))); return; }
|
||||||
|
if (ctx.args.has('listings')) {
|
||||||
|
const l = listingCompleteness(config, root);
|
||||||
|
if (ctx.args.has('json')) { printJson(l); return; }
|
||||||
|
for (const p of l.problems) log('inspect', p);
|
||||||
|
for (const x of l.locales) log('inspect', `${x.lang.padEnd(6)} ${Math.round(x.complete * 100)} % complete${x.screenshots === null ? '' : ` · ${x.screenshots} screenshots`}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
const s = summarize(ctx);
|
const s = summarize(ctx);
|
||||||
if (ctx.args.has('json')) { printJson(s); return; }
|
if (ctx.args.has('json')) { printJson(s); return; }
|
||||||
log('inspect', `${s.name} · ${s.platforms.join(' + ')} · ${s.languages.length} languages · ${s.products} products · ${s.subscriptions} subscriptions`);
|
log('inspect', `${s.name} · ${s.platforms.join(' + ')} · ${s.languages.length} languages · ${s.products} products · ${s.subscriptions} subscriptions`);
|
||||||
|
|
|
||||||
|
|
@ -90,6 +90,10 @@ export interface ProjectSummary {
|
||||||
catalog: { ios: string[]; android: string[] };
|
catalog: { ios: string[]; android: string[] };
|
||||||
shots: boolean;
|
shots: boolean;
|
||||||
testflightGroups: number;
|
testflightGroups: number;
|
||||||
|
/** App profile from the config (app, game, subscription-app). */
|
||||||
|
profile?: string;
|
||||||
|
/** Absolute path of the app icon the config or the usual places point at (project.icon reads it), or null. */
|
||||||
|
icon?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- App-centric model (one app = one product on up to two platforms; a workspace holds many apps) ----
|
// ---- App-centric model (one app = one product on up to two platforms; a workspace holds many apps) ----
|
||||||
|
|
@ -112,10 +116,14 @@ export interface StoreRelease {
|
||||||
/** The store's own state word (READY_FOR_SALE, inProgress ...). */
|
/** The store's own state word (READY_FOR_SALE, inProgress ...). */
|
||||||
state: string;
|
state: string;
|
||||||
phase: ReleasePhase;
|
phase: ReleasePhase;
|
||||||
/** Android staged rollout user fraction (0-1); iOS phased release percentage comes with D2. */
|
/** Rollout share (0-1): Android staged rollout user fraction, iOS phased release day -> 1, 2, 5, 10, 20, 50, 100 %. */
|
||||||
fraction: number | null;
|
fraction: number | null;
|
||||||
/** Android track (production, beta, internal ...). */
|
/** Android track (production, beta, internal ...). */
|
||||||
track: string | null;
|
track: string | null;
|
||||||
|
/** iOS phased release: day 1-7 and its state (ACTIVE, PAUSED, COMPLETE); null without one. */
|
||||||
|
phased?: { state: string; day: number | null } | null;
|
||||||
|
/** When the store record was made (iOS version createdDate), if the store says. */
|
||||||
|
date?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A release train: one version (e.g. 2.3.0) across both stores. */
|
/** A release train: one version (e.g. 2.3.0) across both stores. */
|
||||||
|
|
@ -143,8 +151,8 @@ export interface AppStatus {
|
||||||
app: AppIdentity | null;
|
app: AppIdentity | null;
|
||||||
summary: ProjectSummary | null;
|
summary: ProjectSummary | null;
|
||||||
check: { ok: boolean; problems: string[]; warnings: string[] } | null;
|
check: { ok: boolean; problems: string[]; warnings: string[] } | null;
|
||||||
/** Release trains; `source: none` offline (no store data read). */
|
/** Release trains; `source: none` offline (no store data read). `all`: every store release read (live only). */
|
||||||
release: { source: 'none' | 'live'; current: ReleaseTrain | null; next: ReleaseTrain | null };
|
release: { source: 'none' | 'live'; current: ReleaseTrain | null; next: ReleaseTrain | null; all?: StoreRelease[] };
|
||||||
catalog: CatalogParity | null;
|
catalog: CatalogParity | null;
|
||||||
/** live only: per-platform read errors ("unknown, never false"). */
|
/** live only: per-platform read errors ("unknown, never false"). */
|
||||||
storeErrors: { ios?: string; android?: string };
|
storeErrors: { ios?: string; android?: string };
|
||||||
|
|
@ -152,3 +160,47 @@ export interface AppStatus {
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PortfolioResult { apps: AppStatus[]; at: string }
|
export interface PortfolioResult { apps: AppStatus[]; at: string }
|
||||||
|
|
||||||
|
// ---- Offline project reads (D2) ----
|
||||||
|
|
||||||
|
/** One listing field of one language on one store: length against the store limit. */
|
||||||
|
export interface ListingField { field: string; length: number; limit: number; required: boolean; state: 'ok' | 'missing' | 'over' | 'empty-optional' }
|
||||||
|
|
||||||
|
/** Listing completeness of one language (config language id) on both stores. */
|
||||||
|
export interface ListingLocale {
|
||||||
|
lang: string;
|
||||||
|
rtl: boolean;
|
||||||
|
play: { code: string | null; fields: ListingField[] } | null;
|
||||||
|
apple: { code: string | null; fields: ListingField[] } | null;
|
||||||
|
/** Rendered screenshots found for this language (renders folder), null when there is no renders folder. */
|
||||||
|
screenshots: number | null;
|
||||||
|
/** Required fields present and within limits, 0-1 (both stores). */
|
||||||
|
complete: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ListingsResult {
|
||||||
|
files: { play: string | null; apple: string | null };
|
||||||
|
/** File-level problems (missing file, unreadable section). */
|
||||||
|
problems: string[];
|
||||||
|
locales: ListingLocale[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A local review reply draft (.storebound/replies/<store>-<id>.md) with its checks. */
|
||||||
|
export interface ReplyDraft {
|
||||||
|
file: string;
|
||||||
|
store: 'apple' | 'play';
|
||||||
|
reviewId: string;
|
||||||
|
approved: boolean;
|
||||||
|
sent: string | null;
|
||||||
|
reply: string;
|
||||||
|
rating: number | null;
|
||||||
|
title: string | null;
|
||||||
|
body: string | null;
|
||||||
|
date: string | null;
|
||||||
|
issues: { level: 'error' | 'warn'; msg: string }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DraftsResult { dir: string; drafts: ReplyDraft[]; problems: string[] }
|
||||||
|
|
||||||
|
/** project.icon: the icon as a data: URL (PNG / JPEG / WebP / SVG, at most 1.5 MB), or null. */
|
||||||
|
export interface IconResult { path: string | null; dataUrl: string | null }
|
||||||
|
|
|
||||||
|
|
@ -33,13 +33,36 @@ export function applePhase(state: string): ReleasePhase {
|
||||||
return 'other';
|
return 'other';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Apple's phased release schedule: share of users with automatic updates on day 1-7. */
|
||||||
|
export const PHASED_SCHEDULE = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1] as const;
|
||||||
|
|
||||||
|
/** Phased release of a version (`apple status --json` phased[versionId]) -> rollout share, or null. */
|
||||||
|
export function phasedFraction(p: { state?: string; currentDayNumber?: number | null } | null | undefined): number | null {
|
||||||
|
if (!p?.state) return null;
|
||||||
|
if (p.state === 'COMPLETE') return 1;
|
||||||
|
const d = typeof p.currentDayNumber === 'number' ? Math.min(7, Math.max(1, Math.round(p.currentDayNumber))) : null;
|
||||||
|
return d ? PHASED_SCHEDULE[d - 1]! : p.state === 'INACTIVE' ? 0 : null;
|
||||||
|
}
|
||||||
|
|
||||||
export function appleReleases(data: unknown): StoreRelease[] {
|
export function appleReleases(data: unknown): StoreRelease[] {
|
||||||
const versions = ((data as J)?.versions ?? []) as J[];
|
const versions = ((data as J)?.versions ?? []) as J[];
|
||||||
const builds = new Map((((data as J)?.builds ?? []) as J[]).map(b => [b.id, b.attributes?.version] as const));
|
const builds = new Map((((data as J)?.builds ?? []) as J[]).map(b => [b.id, b.attributes?.version] as const));
|
||||||
|
const phasedById = (((data as J)?.phased ?? {}) as Record<string, J | null>);
|
||||||
return versions.filter(v => typeof v?.attributes?.versionString === 'string' && (v.attributes.platform ?? 'IOS') === 'IOS').map(v => {
|
return versions.filter(v => typeof v?.attributes?.versionString === 'string' && (v.attributes.platform ?? 'IOS') === 'IOS').map(v => {
|
||||||
const state = String(v.attributes.appVersionState ?? v.attributes.appStoreState ?? 'UNKNOWN');
|
const state = String(v.attributes.appVersionState ?? v.attributes.appStoreState ?? 'UNKNOWN');
|
||||||
const buildId = v.relationships?.build?.data?.id;
|
const buildId = v.relationships?.build?.data?.id;
|
||||||
return { store: 'ios', version: v.attributes.versionString as string, build: (buildId && builds.get(buildId)) ? String(builds.get(buildId)) : null, state, phase: applePhase(state), fraction: null, track: null };
|
let phase = applePhase(state);
|
||||||
|
const pr = (typeof v.id === 'string' ? phasedById[v.id] : null) ?? null;
|
||||||
|
const prState = typeof pr?.attributes?.phasedReleaseState === 'string' ? String(pr.attributes.phasedReleaseState) : null;
|
||||||
|
const day = typeof pr?.attributes?.currentDayNumber === 'number' ? pr.attributes.currentDayNumber as number : null;
|
||||||
|
const fraction = phase === 'live' && prState ? phasedFraction({ state: prState, currentDayNumber: day }) : null;
|
||||||
|
// live but still rolling out (phased release on, not complete): the same as a Play staged rollout
|
||||||
|
if (phase === 'live' && prState === 'ACTIVE') phase = 'rollout';
|
||||||
|
if (phase === 'live' && prState === 'PAUSED') phase = 'halted';
|
||||||
|
const r: StoreRelease = { store: 'ios', version: v.attributes.versionString as string, build: (buildId && builds.get(buildId)) ? String(builds.get(buildId)) : null, state, phase, fraction, track: null };
|
||||||
|
if (prState) r.phased = { state: prState, day };
|
||||||
|
if (typeof v.attributes.createdDate === 'string') r.date = v.attributes.createdDate;
|
||||||
|
return r;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -65,14 +88,14 @@ const PHASE_RANK: Record<ReleasePhase, number> = { live: 0, rollout: 1, halted:
|
||||||
const pick = (rs: StoreRelease[]): StoreRelease | null => [...rs].sort((a, b) => PHASE_RANK[a.phase] - PHASE_RANK[b.phase])[0] ?? null;
|
const pick = (rs: StoreRelease[]): StoreRelease | null => [...rs].sort((a, b) => PHASE_RANK[a.phase] - PHASE_RANK[b.phase])[0] ?? null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Release trains: one version across both stores. current = the highest version that is live (fully) on a store;
|
* Release trains: one version across both stores. current = the highest version that reaches users on a store (live,
|
||||||
* next = the highest version above it on either store (review, testing, rollout, draft ...). A store without that
|
* or rolling out: a staged rollout or an iOS phased release, also when halted / paused); next = the highest version
|
||||||
* version has null in the train.
|
* above it on either store (review, testing, draft ...). A store without that version has null in the train.
|
||||||
*/
|
*/
|
||||||
export function releaseTrains(ios: StoreRelease[], android: StoreRelease[]): { current: ReleaseTrain | null; next: ReleaseTrain | null } {
|
export function releaseTrains(ios: StoreRelease[], android: StoreRelease[]): { current: ReleaseTrain | null; next: ReleaseTrain | null } {
|
||||||
const all = [...ios, ...android].filter((r): r is StoreRelease & { version: string } => !!r.version);
|
const all = [...ios, ...android].filter((r): r is StoreRelease & { version: string } => !!r.version);
|
||||||
const train = (v: string): ReleaseTrain => ({ version: v, ios: pick(all.filter(r => r.store === 'ios' && r.version === v)), android: pick(all.filter(r => r.store === 'android' && r.version === v)) });
|
const train = (v: string): ReleaseTrain => ({ version: v, ios: pick(all.filter(r => r.store === 'ios' && r.version === v)), android: pick(all.filter(r => r.store === 'android' && r.version === v)) });
|
||||||
const live = all.filter(r => r.phase === 'live').map(r => r.version).sort(cmpVersion).at(-1) ?? null;
|
const live = all.filter(r => r.phase === 'live' || r.phase === 'rollout' || r.phase === 'halted').map(r => r.version).sort(cmpVersion).at(-1) ?? null;
|
||||||
const above = all.filter(r => !live || cmpVersion(r.version, live) > 0).map(r => r.version).sort(cmpVersion).at(-1) ?? null;
|
const above = all.filter(r => !live || cmpVersion(r.version, live) > 0).map(r => r.version).sort(cmpVersion).at(-1) ?? null;
|
||||||
return { current: live ? train(live) : null, next: above ? train(above) : null };
|
return { current: live ? train(live) : null, next: above ? train(above) : null };
|
||||||
}
|
}
|
||||||
|
|
|
||||||
180
cli/lib/project-files.ts
Normal file
180
cli/lib/project-files.ts
Normal file
|
|
@ -0,0 +1,180 @@
|
||||||
|
// Offline reads of a project's own files for the desktop app (serve.ts): the app icon, listing completeness per
|
||||||
|
// language on both stores, and the local review reply drafts. Tolerant on purpose: a broken file becomes a problem
|
||||||
|
// line, never an exception, so one bad section does not hide the rest ("unknown, never false").
|
||||||
|
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
||||||
|
import { extname, isAbsolute, join, resolve } from 'node:path';
|
||||||
|
import { type ShipConfig, playCodes } from './config';
|
||||||
|
import { APPLE_LIMITS, len, PLAY_LIMITS } from './copy';
|
||||||
|
import type { DraftsResult, IconResult, ListingField, ListingLocale, ListingsResult, ReplyDraft } from './desktop-protocol';
|
||||||
|
import { parseFrontMatter, stringifyFrontMatter } from './frontmatter';
|
||||||
|
import { checkReply, parseDraft } from './reviews';
|
||||||
|
|
||||||
|
const IMAGE = /\.(png|jpe?g|webp|svg)$/i;
|
||||||
|
export const ICON_MAX_BYTES = 1_500_000;
|
||||||
|
|
||||||
|
/** Icon candidates, most specific first: icons.composite, the rendered store icons, play.icon, the usual places. */
|
||||||
|
export function iconCandidates(config: Pick<ShipConfig, 'icons' | 'play'>, root: string): string[] {
|
||||||
|
const r = (p: string) => (isAbsolute(p) ? p : resolve(root, p));
|
||||||
|
const out: string[] = [];
|
||||||
|
if (config.icons?.composite) out.push(r(config.icons.composite));
|
||||||
|
if (config.icons?.out) out.push(r(join(config.icons.out, 'app-store-1024.png')), r(join(config.icons.out, 'play-512.png')));
|
||||||
|
if (config.play?.icon) out.push(r(config.play.icon));
|
||||||
|
for (const p of ['store/icons/app-store-1024.png', 'store/icons/play-512.png', 'store/icon.png', 'store/icon-1024.png', 'icon.png', 'assets/icon.png',
|
||||||
|
'resources/icon.png', 'assets/icon-only.png', 'public/icon-512.png', 'web/icon-512.png']) out.push(r(p));
|
||||||
|
return [...new Set(out)];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** First candidate that exists and is an image file, or null. */
|
||||||
|
export function findIcon(config: Pick<ShipConfig, 'icons' | 'play'>, root: string): string | null {
|
||||||
|
for (const p of iconCandidates(config, root)) {
|
||||||
|
try { if (IMAGE.test(p) && statSync(p).isFile()) return p; } catch { /* next */ }
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MIME: Record<string, string> = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.svg': 'image/svg+xml' };
|
||||||
|
|
||||||
|
/** The icon as a data: URL for the desktop window (its CSP allows data: images only). Too big or unreadable -> null. */
|
||||||
|
export function iconDataUrl(path: string | null): IconResult {
|
||||||
|
if (!path) return { path: null, dataUrl: null };
|
||||||
|
try {
|
||||||
|
const st = statSync(path);
|
||||||
|
if (!st.isFile() || st.size > ICON_MAX_BYTES) return { path, dataUrl: null };
|
||||||
|
const mime = MIME[extname(path).toLowerCase()];
|
||||||
|
if (!mime) return { path, dataUrl: null };
|
||||||
|
return { path, dataUrl: `data:${mime};base64,${readFileSync(path).toString('base64')}` };
|
||||||
|
} catch { return { path, dataUrl: null }; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "### heading" sub-sections of a "## " section with their first fenced block (like lib/copy.ts, never throws). */
|
||||||
|
function blocks(section: string): { heading: string; text: string }[] {
|
||||||
|
const out: { heading: string; text: string }[] = [];
|
||||||
|
for (const part of section.split(/^### /m).slice(1)) {
|
||||||
|
const heading = part.split('\n')[0]!.trim();
|
||||||
|
const m = /^```[^\n]*\n([\s\S]*?)\n```/m.exec(part);
|
||||||
|
out.push({ heading, text: m ? m[1]!.trim() : '' });
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function field(name: string, text: string | undefined, limit: number, required: boolean): ListingField {
|
||||||
|
const n = text ? len(text) : 0;
|
||||||
|
const state: ListingField['state'] = !n ? (required ? 'missing' : 'empty-optional') : n > limit ? 'over' : 'ok';
|
||||||
|
return { field: name, length: n, limit, required, state };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Play sections by Play language code: { title, short, full, whatsNew } texts. */
|
||||||
|
export function playSections(md: string): Map<string, Record<string, string | undefined>> {
|
||||||
|
const out = new Map<string, Record<string, string | undefined>>();
|
||||||
|
for (const sec of md.split(/^## /m).slice(1)) {
|
||||||
|
const m = /^<!--\s*play:\s*([^>]+?)\s*-->$/m.exec(sec);
|
||||||
|
if (!m) continue;
|
||||||
|
const bs = blocks(sec);
|
||||||
|
const find = (re: RegExp): string | undefined => bs.find(b => re.test(b.heading))?.text;
|
||||||
|
const f = { title: find(/\btitle\b/i), short: find(/\bshort\b/i), full: find(/\bfull\b/i), whatsNew: find(/what'?s new|release notes/i) };
|
||||||
|
for (const lang of m[1]!.split(',').map(s => s.trim()).filter(Boolean)) out.set(lang, f);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** App Store sections by App Store Connect locale: field -> text. */
|
||||||
|
export function appleSections(md: string): Map<string, Record<string, string | undefined>> {
|
||||||
|
const out = new Map<string, Record<string, string | undefined>>();
|
||||||
|
for (const sec of md.split(/^## /m).slice(1)) {
|
||||||
|
const locale = sec.split(/[\s·]/)[0]!.trim();
|
||||||
|
if (!/^[a-z]{2,3}(-[A-Za-z]{2,4})?$/.test(locale)) continue;
|
||||||
|
const f: Record<string, string | undefined> = {};
|
||||||
|
for (const b of blocks(sec)) if (b.heading in APPLE_LIMITS) f[b.heading] = b.text;
|
||||||
|
out.set(locale, f);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function countImages(dir: string): number {
|
||||||
|
let n = 0;
|
||||||
|
try {
|
||||||
|
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
||||||
|
if (e.isDirectory()) n += countImages(join(dir, e.name));
|
||||||
|
else if (/\.(png|jpe?g)$/i.test(e.name)) n++;
|
||||||
|
}
|
||||||
|
} catch { /* unreadable: 0 */ }
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Listing completeness per config language, both stores, plus rendered screenshots per language. */
|
||||||
|
export function listingCompleteness(config: ShipConfig, root: string): ListingsResult {
|
||||||
|
const problems: string[] = [];
|
||||||
|
const read = (rel: string | undefined, fallback: string): { path: string | null; text: string | null } => {
|
||||||
|
const p = resolve(root, rel ?? fallback);
|
||||||
|
if (!existsSync(p)) { problems.push(`${rel ?? fallback}: file not found`); return { path: null, text: null }; }
|
||||||
|
try { return { path: p, text: readFileSync(p, 'utf8') }; } catch (e) { problems.push(`${rel ?? fallback}: ${(e as Error).message}`); return { path: p, text: null }; }
|
||||||
|
};
|
||||||
|
const playFile = config.play ? read(config.play.listing, 'store/listing.md') : { path: null, text: null };
|
||||||
|
const appleFile = config.apple ? read(config.apple.listing, 'store/appstore.md') : { path: null, text: null };
|
||||||
|
const play = playFile.text !== null ? playSections(playFile.text) : null;
|
||||||
|
const apple = appleFile.text !== null ? appleSections(appleFile.text) : null;
|
||||||
|
const rendersDir = resolve(root, config.renders ?? config.shots?.out ?? 'store/renders');
|
||||||
|
const hasRenders = existsSync(rendersDir);
|
||||||
|
const locales: ListingLocale[] = config.languages.map(l => {
|
||||||
|
let req = 0, good = 0;
|
||||||
|
const tally = (fs: ListingField[]) => { for (const f of fs) if (f.required) { req++; if (f.state === 'ok') good++; } return fs; };
|
||||||
|
const pc = config.play ? playCodes(l)[0] ?? null : null;
|
||||||
|
const ps = pc && play ? play.get(pc) : undefined;
|
||||||
|
const playPart = config.play ? {
|
||||||
|
code: pc,
|
||||||
|
fields: tally([
|
||||||
|
field('title', ps?.title ?? (ps ? config.app.name : undefined), PLAY_LIMITS.title, true),
|
||||||
|
field('short', ps?.short, PLAY_LIMITS.short, true),
|
||||||
|
field('full', ps?.full, PLAY_LIMITS.full, true),
|
||||||
|
field('whatsNew', ps?.whatsNew, PLAY_LIMITS.whatsNew, false),
|
||||||
|
]),
|
||||||
|
} : null;
|
||||||
|
const ac = config.apple ? l.apple ?? null : null;
|
||||||
|
const as = ac && apple ? apple.get(ac) : undefined;
|
||||||
|
const applePart = config.apple ? {
|
||||||
|
code: ac,
|
||||||
|
fields: tally([
|
||||||
|
field('name', as?.name ?? (as ? config.app.name : undefined), APPLE_LIMITS.name, true),
|
||||||
|
field('subtitle', as?.subtitle, APPLE_LIMITS.subtitle, true),
|
||||||
|
field('promotionalText', as?.promotionalText, APPLE_LIMITS.promotionalText, true),
|
||||||
|
field('keywords', as?.keywords, APPLE_LIMITS.keywords, true),
|
||||||
|
field('description', as?.description, APPLE_LIMITS.description, true),
|
||||||
|
field('whatsNew', as?.whatsNew, APPLE_LIMITS.whatsNew, false),
|
||||||
|
]),
|
||||||
|
} : null;
|
||||||
|
const screenshots = hasRenders ? countImages(join(rendersDir, l.id)) : null;
|
||||||
|
return { lang: l.id, rtl: !!l.rtl, play: playPart, apple: applePart, screenshots, complete: req ? good / req : 0 };
|
||||||
|
});
|
||||||
|
return { files: { play: playFile.path, apple: appleFile.path }, problems, locales };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Local reply drafts with their send checks. Unparsable files become problems. */
|
||||||
|
export function readReplyDrafts(dir: string): DraftsResult {
|
||||||
|
const out: DraftsResult = { dir, drafts: [], problems: [] };
|
||||||
|
if (!existsSync(dir)) return out;
|
||||||
|
for (const name of readdirSync(dir).filter(n => n.endsWith('.md')).sort()) {
|
||||||
|
const file = join(dir, name);
|
||||||
|
try {
|
||||||
|
const text = readFileSync(file, 'utf8');
|
||||||
|
const d = parseDraft(file, text);
|
||||||
|
const { data, body } = parseFrontMatter(text);
|
||||||
|
const quote = body.split(/^## Reply\s*$/m)[0]!.split('\n').filter(l => l.startsWith('>')).map(l => l.replace(/^>\s?/, '')).join('\n').trim();
|
||||||
|
const num = (v: unknown): number | null => (typeof v === 'number' ? v : typeof v === 'string' && /^\d+$/.test(v) ? Number(v) : null);
|
||||||
|
const str = (v: unknown): string | null => (typeof v === 'string' && v ? v : null);
|
||||||
|
const draft: ReplyDraft = {
|
||||||
|
file, store: d.store, reviewId: d.reviewId, approved: d.approved, sent: d.sent, reply: d.reply,
|
||||||
|
rating: num(data.rating), title: str(data.title) ?? (/^# [★☆]*\s*(.+)$/m.exec(body)?.[1]?.trim() || null), body: quote || null, date: str(data.date),
|
||||||
|
issues: d.reply ? checkReply(d.reply, d.store) : [],
|
||||||
|
};
|
||||||
|
out.drafts.push(draft);
|
||||||
|
} catch (e) { out.problems.push(`${name}: ${(e as Error).message}`); }
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Front matter `approved: <bool>` set in a draft file text; the body unchanged. */
|
||||||
|
export function setApproved(text: string, approved: boolean): string {
|
||||||
|
const { data, body } = parseFrontMatter(text);
|
||||||
|
if (data.store !== 'apple' && data.store !== 'play') throw new Error('not a review reply draft (front matter "store" missing)');
|
||||||
|
return stringifyFrontMatter({ ...data, approved }, body);
|
||||||
|
}
|
||||||
51
cli/lib/template-files.ts
Normal file
51
cli/lib/template-files.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
||||||
|
// Every file under templates/, embedded as text so `storebound init` also works from the compiled desktop sidecar
|
||||||
|
// (a `bun build --compile` binary has no templates folder next to it). tests/apps.test.ts checks this list against the
|
||||||
|
// folder: add a line here when a template is added.
|
||||||
|
import t0 from '../../templates/app-privacy.md' with { type: 'text' };
|
||||||
|
import t1 from '../../templates/appstore.md' with { type: 'text' };
|
||||||
|
import t2 from '../../templates/credentials.example.json' with { type: 'text' };
|
||||||
|
import t3 from '../../templates/data-safety.csv' with { type: 'text' };
|
||||||
|
import t4 from '../../templates/declarations.md' with { type: 'text' };
|
||||||
|
import t5 from '../../templates/listing.md' with { type: 'text' };
|
||||||
|
import t6 from '../../templates/privacy-policy.html' with { type: 'text' };
|
||||||
|
import t7 from '../../templates/profiles/app/app-privacy.md' with { type: 'text' };
|
||||||
|
import t8 from '../../templates/profiles/app/appstore.md' with { type: 'text' };
|
||||||
|
import t9 from '../../templates/profiles/app/declarations.md' with { type: 'text' };
|
||||||
|
import t10 from '../../templates/profiles/app/listing.md' with { type: 'text' };
|
||||||
|
import t11 from '../../templates/profiles/app/privacy-policy.html' with { type: 'text' };
|
||||||
|
import t12 from '../../templates/profiles/app/shots-copy.json' with { type: 'text' };
|
||||||
|
import t13 from '../../templates/profiles/app/storebound.config.ts' with { type: 'text' };
|
||||||
|
import t14 from '../../templates/profiles/subscription-app/app-privacy.md' with { type: 'text' };
|
||||||
|
import t15 from '../../templates/profiles/subscription-app/appstore.md' with { type: 'text' };
|
||||||
|
import t16 from '../../templates/profiles/subscription-app/declarations.md' with { type: 'text' };
|
||||||
|
import t17 from '../../templates/profiles/subscription-app/listing.md' with { type: 'text' };
|
||||||
|
import t18 from '../../templates/profiles/subscription-app/storebound.config.ts' with { type: 'text' };
|
||||||
|
import t19 from '../../templates/shots-copy.json' with { type: 'text' };
|
||||||
|
import t20 from '../../templates/storebound.config.ts' with { type: 'text' };
|
||||||
|
import t21 from '../../templates/testers.csv' with { type: 'text' };
|
||||||
|
|
||||||
|
/** Template text by its path under templates/ (forward slashes). */
|
||||||
|
export const TEMPLATE_TEXT: Record<string, string> = {
|
||||||
|
'app-privacy.md': t0 as unknown as string,
|
||||||
|
'appstore.md': t1 as unknown as string,
|
||||||
|
'credentials.example.json': t2 as unknown as string,
|
||||||
|
'data-safety.csv': t3 as unknown as string,
|
||||||
|
'declarations.md': t4 as unknown as string,
|
||||||
|
'listing.md': t5 as unknown as string,
|
||||||
|
'privacy-policy.html': t6 as unknown as string,
|
||||||
|
'profiles/app/app-privacy.md': t7 as unknown as string,
|
||||||
|
'profiles/app/appstore.md': t8 as unknown as string,
|
||||||
|
'profiles/app/declarations.md': t9 as unknown as string,
|
||||||
|
'profiles/app/listing.md': t10 as unknown as string,
|
||||||
|
'profiles/app/privacy-policy.html': t11 as unknown as string,
|
||||||
|
'profiles/app/shots-copy.json': t12 as unknown as string,
|
||||||
|
'profiles/app/storebound.config.ts': t13 as unknown as string,
|
||||||
|
'profiles/subscription-app/app-privacy.md': t14 as unknown as string,
|
||||||
|
'profiles/subscription-app/appstore.md': t15 as unknown as string,
|
||||||
|
'profiles/subscription-app/declarations.md': t16 as unknown as string,
|
||||||
|
'profiles/subscription-app/listing.md': t17 as unknown as string,
|
||||||
|
'profiles/subscription-app/storebound.config.ts': t18 as unknown as string,
|
||||||
|
'shots-copy.json': t19 as unknown as string,
|
||||||
|
'storebound.config.ts': t20 as unknown as string,
|
||||||
|
'testers.csv': t21 as unknown as string,
|
||||||
|
};
|
||||||
|
|
@ -88,3 +88,28 @@ export function detectTools(env: Record<string, string | undefined> = process.en
|
||||||
out.push(bin('git', 'git', 'release notes from history, analytics compare', { kind: 'link', url: 'https://git-scm.com/downloads', note: 'Install git from your OS package manager.' }, ['--version']));
|
out.push(bin('git', 'git', 'release notes from history, analytics compare', { kind: 'link', url: 'https://git-scm.com/downloads', note: 'Install git from your OS package manager.' }, ['--version']));
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Commands that install a tool on this OS (shown by `storebound doctor` and the desktop Dependencies screen, never
|
||||||
|
* run by storebound). Package managers only; the desktop app can also download ffmpeg and Chrome for Testing itself.
|
||||||
|
*/
|
||||||
|
export function installCommands(id: ToolId | 'playwright', platform: NodeJS.Platform = process.platform): string[] {
|
||||||
|
const mac = platform === 'darwin', win = platform === 'win32';
|
||||||
|
switch (id) {
|
||||||
|
case 'ffmpeg': case 'ffprobe': return mac ? ['brew install ffmpeg'] : win ? ['winget install --id Gyan.FFmpeg'] : ['sudo apt install ffmpeg', 'sudo dnf install ffmpeg'];
|
||||||
|
case 'chrome': return ['bunx playwright install chromium', ...(mac ? ['brew install --cask google-chrome'] : win ? ['winget install --id Google.Chrome'] : [])];
|
||||||
|
case 'playwright': return ['bun add -d playwright'];
|
||||||
|
case 'xcode': return mac ? ['xcode-select --install'] : [];
|
||||||
|
case 'simctl': return mac ? ['Install Xcode from the App Store, then: sudo xcode-select -s /Applications/Xcode.app'] : [];
|
||||||
|
case 'adb': return mac ? ['brew install --cask android-platform-tools'] : win ? ['winget install --id Google.PlatformTools'] : ['sudo apt install adb'];
|
||||||
|
case 'git': return mac ? ['xcode-select --install', 'brew install git'] : win ? ['winget install --id Git.Git'] : ['sudo apt install git'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where playwright resolves from (the project, then the storebound folder), or null. */
|
||||||
|
export function findPlaywright(bases: string[]): string | null {
|
||||||
|
for (const base of bases) {
|
||||||
|
try { return Bun.resolveSync('playwright', base); } catch { /* next */ }
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,8 @@
|
||||||
// storebound reviews list [--store apple|play] [--days 14] [--unanswered] [--rating 1,2] [--json]
|
// storebound reviews list [--store apple|play] [--days 14] [--unanswered] [--rating 1,2] [--json]
|
||||||
// storebound reviews draft [--store apple|play] [--days 14] [--rating 1,2,3] [--all] [--dir .storebound/replies] [--dry]
|
// storebound reviews draft [--store apple|play] [--days 14] [--rating 1,2,3] [--all] [--dir .storebound/replies] [--dry]
|
||||||
// storebound reviews send [--dir .storebound/replies] [--dry] [--yes]
|
// storebound reviews send [--dir .storebound/replies] [--dry] [--yes]
|
||||||
|
// storebound reviews drafts [--json] the local drafts with the checks `send` applies (offline)
|
||||||
|
// storebound reviews approve <draft file> [--undo] [--dry] sets approved: true (false) in one draft (local file)
|
||||||
// `draft` writes one Markdown file per unanswered review into .storebound/replies/ (gitignored): front matter
|
// `draft` writes one Markdown file per unanswered review into .storebound/replies/ (gitignored): front matter
|
||||||
// (store, review_id, rating, approved: false), the review, and an empty "## Reply" section. Existing files are never
|
// (store, review_id, rating, approved: false), the review, and an empty "## Reply" section. Existing files are never
|
||||||
// overwritten (your edits stay). The owner or an agent with the review-replies skill writes the reply; the owner sets
|
// overwritten (your edits stay). The owner or an agent with the review-replies skill writes the reply; the owner sets
|
||||||
|
|
@ -9,7 +11,7 @@
|
||||||
// confirmation, then writes `sent: <time>` into the file. Replies are public: `send` is not an MCP tool.
|
// confirmation, then writes `sent: <time>` into the file. Replies are public: `send` is not an MCP tool.
|
||||||
// Google Play's API only returns reviews created or edited in the last 7 days.
|
// Google Play's API only returns reviews created or edited in the last 7 days.
|
||||||
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { join, relative, resolve } from 'node:path';
|
||||||
import { ascClient, type J } from './apple/asc';
|
import { ascClient, type J } from './apple/asc';
|
||||||
import type { Ctx } from './lib/ctx';
|
import type { Ctx } from './lib/ctx';
|
||||||
import { confirm } from './lib/ctx';
|
import { confirm } from './lib/ctx';
|
||||||
|
|
@ -19,6 +21,7 @@ import {
|
||||||
type Review, sendPlan,
|
type Review, sendPlan,
|
||||||
} from './lib/reviews';
|
} from './lib/reviews';
|
||||||
import { textTable } from './lib/table';
|
import { textTable } from './lib/table';
|
||||||
|
import { readReplyDrafts, setApproved } from './lib/project-files';
|
||||||
import { playClient } from './play/client';
|
import { playClient } from './play/client';
|
||||||
|
|
||||||
const TAG = 'reviews';
|
const TAG = 'reviews';
|
||||||
|
|
@ -139,5 +142,34 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
done(TAG, `${sent}/${plan.send.length} sent (Apple shows replies within about 24 hours)`);
|
done(TAG, `${sent}/${plan.send.length} sent (Apple shows replies within about 24 hours)`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
throw new Error('usage: storebound reviews list | draft | send');
|
if (sub === 'drafts') {
|
||||||
|
// read-only: the local drafts with the checks `send` applies (no network)
|
||||||
|
const r = readReplyDrafts(dir);
|
||||||
|
if (a.has('json')) { printJson(r); return; }
|
||||||
|
console.log(textTable(['store', 'review', 'state', 'chars', 'checks'], r.drafts.map(d => [d.store, d.reviewId, d.sent ? `sent ${d.sent.slice(0, 10)}` : d.approved ? 'approved' : 'draft',
|
||||||
|
[...d.reply].length, d.issues.map(i => `${i.level}: ${i.msg}`).join('; ')])));
|
||||||
|
for (const p of r.problems) warn(TAG, p);
|
||||||
|
done(TAG, `${r.drafts.length} draft(s) in ${dir}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sub === 'approve') {
|
||||||
|
// marks one draft approved (or not, with --undo); local file only, nothing is sent
|
||||||
|
const file = a.get('file') ?? a._[1];
|
||||||
|
if (!file) throw new Error('usage: storebound reviews approve <draft file> [--undo] [--dry]');
|
||||||
|
const p = resolve(dir, file);
|
||||||
|
if (relative(dir, p).startsWith('..') || !p.endsWith('.md') || !existsSync(p)) throw new Error(`no draft ${file} in ${dir}`);
|
||||||
|
const text = readFileSync(p, 'utf8');
|
||||||
|
const d = parseDraft(p, text);
|
||||||
|
const approved = !a.has('undo');
|
||||||
|
if (approved) {
|
||||||
|
const errors = checkReply(d.reply, d.store).filter(i => i.level === 'error');
|
||||||
|
if (errors.length) throw new Error(`${file}: ${errors.map(i => i.msg).join('; ')}`);
|
||||||
|
}
|
||||||
|
if (a.has('dry')) { done(TAG, `would set approved: ${approved} in ${p} (dry run)`); return; }
|
||||||
|
writeFileSync(p, setApproved(text, approved));
|
||||||
|
done(TAG, `${approved ? 'approved' : 'approval removed'}: ${p} (send with storebound reviews send)`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new Error('usage: storebound reviews list | draft | drafts | approve | send');
|
||||||
}
|
}
|
||||||
|
|
|
||||||
44
cli/serve.ts
44
cli/serve.ts
|
|
@ -37,12 +37,36 @@ export const FORBIDDEN_METHOD_WORDS = /submit|release|publish|rollout|resume|com
|
||||||
|
|
||||||
/** Read tools whose command prints a structured result with --json. */
|
/** Read tools whose command prints a structured result with --json. */
|
||||||
export const JSON_TOOLS = new Set(['check', 'check_aso', 'validate', 'health', 'reviews_list', 'prices_diff', 'analytics_compare', 'apple_status',
|
export const JSON_TOOLS = new Set(['check', 'check_aso', 'validate', 'health', 'reviews_list', 'prices_diff', 'analytics_compare', 'apple_status',
|
||||||
'apple_next_build', 'play_status', 'play_next_version_code', 'shots_check', 'apple_testflight_status', 'apple_ppo_status', 'catalog_diff']);
|
'apple_next_build', 'play_status', 'play_next_version_code', 'shots_check', 'apple_testflight_status', 'apple_ppo_status', 'catalog_diff',
|
||||||
|
'project_icon', 'project_listings', 'reviews_drafts']);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Methods only the desktop profile has (not MCP tools): offline reads of the project's own files, and two local
|
||||||
|
* writes the owner confirms in a native dialog. Approving a reply draft is the owner's decision, so AI tools do not get
|
||||||
|
* it; `project.init` writes the templates into a new folder (the host passes that folder, it has no config yet).
|
||||||
|
*/
|
||||||
|
export const DESKTOP_ONLY: ToolDef[] = [
|
||||||
|
{ name: 'project_icon', title: 'App icon', command: ['inspect', '--icon'], write: false, network: false,
|
||||||
|
description: 'The app icon (icons.composite, the rendered store icons, play.icon or the usual places) as a data: URL, at most 1.5 MB.' },
|
||||||
|
{ name: 'project_listings', title: 'Listing completeness', command: ['inspect', '--listings'], write: false, network: false,
|
||||||
|
description: 'Per config language and store: listing fields present and within the store limits (store/listing.md, store/appstore.md), and rendered screenshots per language.' },
|
||||||
|
{ name: 'reviews_drafts', title: 'Reply drafts', command: ['reviews', 'drafts'], write: false, network: false,
|
||||||
|
description: 'The local review reply drafts (.storebound/replies) with the checks `reviews send` applies: approved, sent, length, no incentives, no personal data.' },
|
||||||
|
{ name: 'reviews_approve', title: 'Approve a reply draft', command: ['reviews', 'approve'], write: true, network: false, idempotent: true,
|
||||||
|
description: 'Sets approved: true (or false with undo) in one local reply draft after its checks pass. Nothing is sent: replies go out with `storebound reviews send` in a terminal.',
|
||||||
|
props: { file: { type: 'string', pattern: '^(apple|play)-[A-Za-z0-9._-]{1,120}\\.md$', description: 'Draft file name in .storebound/replies' }, undo: { type: 'boolean', default: false } },
|
||||||
|
required: ['file'], args: i => [String(i.file), ...(i.undo === true ? ['--undo'] : [])] },
|
||||||
|
{ name: 'project_init', title: 'Start an app folder', command: ['init'], write: true, network: false, idempotent: true,
|
||||||
|
description: 'Copies the storebound templates (config, listing, screenshot copy, declarations, privacy policy) for a profile into an empty app folder; existing files are kept.',
|
||||||
|
props: { profile: { type: 'string', enum: ['app', 'game', 'subscription-app'], default: 'app' } }, args: i => ['--profile', String(i.profile ?? 'app')] },
|
||||||
|
];
|
||||||
|
/** Desktop-only methods whose `project` is a folder without a config yet. */
|
||||||
|
const NEW_PROJECT = new Set(['project_init']);
|
||||||
|
|
||||||
/** `apple_testflight_status` -> `apple.testflight_status`: first underscore becomes the namespace dot. */
|
/** `apple_testflight_status` -> `apple.testflight_status`: first underscore becomes the namespace dot. */
|
||||||
export const methodName = (tool: string): string => tool.replace('_', '.');
|
export const methodName = (tool: string): string => tool.replace('_', '.');
|
||||||
|
|
||||||
export const DESKTOP_TOOLS: ToolDef[] = TOOLS.filter(t => !DESKTOP_EXCLUDED.has(t.name));
|
export const DESKTOP_TOOLS: ToolDef[] = [...TOOLS.filter(t => !DESKTOP_EXCLUDED.has(t.name)), ...DESKTOP_ONLY];
|
||||||
const byMethod = new Map(DESKTOP_TOOLS.map(t => [methodName(t.name), t] as const));
|
const byMethod = new Map(DESKTOP_TOOLS.map(t => [methodName(t.name), t] as const));
|
||||||
|
|
||||||
function argsSchema(t: ToolDef): MethodDescriptor['args'] {
|
function argsSchema(t: ToolDef): MethodDescriptor['args'] {
|
||||||
|
|
@ -97,6 +121,17 @@ function credentialsOf(v: unknown): Record<string, string> {
|
||||||
return pickCallEnv(v as Record<string, unknown>);
|
return pickCallEnv(v as Record<string, unknown>);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Absolute existing folder without a storebound config (project.init), else an error. */
|
||||||
|
export function checkNewProject(p: unknown): string {
|
||||||
|
if (typeof p !== 'string' || !p || !isAbsolute(p)) throw new RpcError(ERR.invalidParams, 'project: absolute folder path required');
|
||||||
|
const dir = resolve(p);
|
||||||
|
let isDir = false;
|
||||||
|
try { isDir = statSync(dir).isDirectory(); } catch { /* missing */ }
|
||||||
|
if (!isDir) throw new RpcError(ERR.invalidParams, `project: not a folder: ${dir}`);
|
||||||
|
if (CONFIG_NAMES.some(n => existsSync(join(dir, n)))) throw new RpcError(ERR.invalidParams, `project: ${dir} already has a storebound config`);
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
|
|
||||||
/** One sidecar session: state is the secret (after hello), the token guard and the running requests. */
|
/** One sidecar session: state is the secret (after hello), the token guard and the running requests. */
|
||||||
export class Session {
|
export class Session {
|
||||||
private guard: TokenGuard | null = null;
|
private guard: TokenGuard | null = null;
|
||||||
|
|
@ -170,7 +205,7 @@ export class Session {
|
||||||
|
|
||||||
private async tool(method: string, t: ToolDef, params: Json, id: Id): Promise<ToolResult> {
|
private async tool(method: string, t: ToolDef, params: Json, id: Id): Promise<ToolResult> {
|
||||||
for (const k of Object.keys(params)) if (!['project', 'args', 'dryRun', 'confirmToken', 'credentials'].includes(k)) throw new RpcError(ERR.invalidParams, `unknown param: ${k}`);
|
for (const k of Object.keys(params)) if (!['project', 'args', 'dryRun', 'confirmToken', 'credentials'].includes(k)) throw new RpcError(ERR.invalidParams, `unknown param: ${k}`);
|
||||||
const project = checkProject(params.project);
|
const project = NEW_PROJECT.has(t.name) ? checkNewProject(params.project) : checkProject(params.project);
|
||||||
const args = (params.args ?? {}) as Json;
|
const args = (params.args ?? {}) as Json;
|
||||||
if (typeof args !== 'object' || args === null || Array.isArray(args)) throw new RpcError(ERR.invalidParams, 'args must be an object');
|
if (typeof args !== 'object' || args === null || Array.isArray(args)) throw new RpcError(ERR.invalidParams, 'args must be an object');
|
||||||
if ('dry_run' in args) throw new RpcError(ERR.invalidParams, 'args.dry_run: use params.dryRun');
|
if ('dry_run' in args) throw new RpcError(ERR.invalidParams, 'args.dry_run: use params.dryRun');
|
||||||
|
|
@ -240,7 +275,8 @@ export class Session {
|
||||||
const [apple, play] = await Promise.all([summary.apple ? store(['apple', 'status', '--json']) : undefined, summary.play ? store(['play', 'status', '--json']) : undefined]);
|
const [apple, play] = await Promise.all([summary.apple ? store(['apple', 'status', '--json']) : undefined, summary.play ? store(['play', 'status', '--json']) : undefined]);
|
||||||
if (apple?.error) e.storeErrors.ios = apple.error;
|
if (apple?.error) e.storeErrors.ios = apple.error;
|
||||||
if (play?.error) e.storeErrors.android = play.error;
|
if (play?.error) e.storeErrors.android = play.error;
|
||||||
e.release = { source: 'live', ...releaseTrains(apple?.data ? appleReleases(apple.data) : [], play?.data ? playReleases(play.data) : []) };
|
const ios = apple?.data ? appleReleases(apple.data) : [], android = play?.data ? playReleases(play.data) : [];
|
||||||
|
e.release = { source: 'live', ...releaseTrains(ios, android), all: [...ios, ...android] };
|
||||||
e.catalog = catalogParity(summary, apple?.data ? appleProductIds(apple.data) : undefined, play?.data ? playProductIds(play.data) : undefined);
|
e.catalog = catalogParity(summary, apple?.data ? appleProductIds(apple.data) : undefined, play?.data ? playProductIds(play.data) : undefined);
|
||||||
}
|
}
|
||||||
e.ok = e.check.ok && !e.storeErrors.ios && !e.storeErrors.android && (e.catalog?.ok ?? true);
|
e.ok = e.check.ok && !e.storeErrors.ios && !e.storeErrors.android && (e.catalog?.ok ?? true);
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,10 @@
|
||||||
// Playwright is not a dependency of storebound: it is resolved from the project (or the storebound folder), so a project
|
// Playwright is an optional peer dependency of storebound, resolved from the project (or the storebound folder), so a
|
||||||
// that never renders screenshots never downloads a browser. Launch order: Playwright's own Chromium, then an installed
|
// project that never renders screenshots never downloads a browser. The compiled desktop sidecar carries its own
|
||||||
// Google Chrome (channel "chrome"), so `bunx playwright install chromium` is optional when Chrome is there.
|
// playwright-core (tools/build-sidecars.ts bundles it) and renders with the Chrome for Testing the desktop app manages
|
||||||
|
// (STOREBOUND_CHROME), so desktop users need neither playwright nor a browser in their project.
|
||||||
|
// Launch order: STOREBOUND_CHROME, Playwright's own Chromium, then an installed Google Chrome (channel "chrome").
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
|
import { compiled } from '../lib/runner';
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
async function chromium(root: string): Promise<any> {
|
async function chromium(root: string): Promise<any> {
|
||||||
|
|
@ -11,6 +14,8 @@ async function chromium(root: string): Promise<any> {
|
||||||
return (await import(p)).chromium;
|
return (await import(p)).chromium;
|
||||||
} catch { /* next */ }
|
} catch { /* next */ }
|
||||||
}
|
}
|
||||||
|
// only reached in the compiled sidecar: the bundled playwright-core (not a runtime dependency of the npm package)
|
||||||
|
if (compiled()) return (await import('playwright-core')).chromium;
|
||||||
throw new Error('playwright not found: in your project run `bun add -d playwright` (and `bunx playwright install chromium` if Google Chrome is not installed)');
|
throw new Error('playwright not found: in your project run `bun add -d playwright` (and `bunx playwright install chromium` if Google Chrome is not installed)');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
4
cli/text-modules.d.ts
vendored
Normal file
4
cli/text-modules.d.ts
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
// Template files imported as text (lib/template-files.ts, `with { type: 'text' }`).
|
||||||
|
declare module '*.md' { const text: string; export default text; }
|
||||||
|
declare module '*.csv' { const text: string; export default text; }
|
||||||
|
declare module '*.html' { const text: string; export default text; }
|
||||||
|
|
@ -60,9 +60,18 @@
|
||||||
"ci": "bun tools/ci.ts",
|
"ci": "bun tools/ci.ts",
|
||||||
"check": "bun run typecheck && bun test"
|
"check": "bun run typecheck && bun test"
|
||||||
},
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"playwright": ">=1.45"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"playwright": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/bun": "1.3.0",
|
"@types/bun": "1.3.0",
|
||||||
"playwright": "1.55.0",
|
"playwright": "1.55.0",
|
||||||
|
"playwright-core": "1.55.0",
|
||||||
"typescript": "5.9.3"
|
"typescript": "5.9.3"
|
||||||
},
|
},
|
||||||
"homepage": "https://git.crt.fyi/CRT/storebound",
|
"homepage": "https://git.crt.fyi/CRT/storebound",
|
||||||
|
|
|
||||||
165
tests/desktop-d2.test.ts
Normal file
165
tests/desktop-d2.test.ts
Normal file
|
|
@ -0,0 +1,165 @@
|
||||||
|
// Desktop D2 on the CLI side: app icon discovery, listing completeness, reply drafts (read + approve), embedded
|
||||||
|
// templates for `init` from the compiled sidecar, `storebound doctor`, and the optional playwright peer.
|
||||||
|
import { describe, expect, test } from 'bun:test';
|
||||||
|
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join, relative } from 'node:path';
|
||||||
|
import pkg from '../package.json' with { type: 'json' };
|
||||||
|
import { doctor } from '../cli/doctor';
|
||||||
|
import { FILES, templateFor, templateKey, templateText } from '../cli/init';
|
||||||
|
import type { ShipConfig } from '../cli/lib/config';
|
||||||
|
import { draftMarkdown, draftName, parseDraft } from '../cli/lib/reviews';
|
||||||
|
import { findIcon, iconCandidates, iconDataUrl, listingCompleteness, readReplyDrafts, setApproved } from '../cli/lib/project-files';
|
||||||
|
import { TEMPLATE_TEXT } from '../cli/lib/template-files';
|
||||||
|
import { installCommands } from '../cli/lib/tools';
|
||||||
|
import { NEUTRAL_ROOT, neutralize } from '../tools/build-sidecars';
|
||||||
|
|
||||||
|
const ROOT = join(import.meta.dir, '..');
|
||||||
|
const tmp = () => mkdtempSync(join(tmpdir(), 'sb-d2-'));
|
||||||
|
const APP = { name: 'Demo', privacyPolicyUrl: 'https://example.com/p', supportUrl: 'https://example.com', website: 'https://example.com', contactEmail: 'a@example.com' };
|
||||||
|
const PNG = Buffer.from('89504e470d0a1a0a0000000d4948445200000001000000010806000000', 'hex');
|
||||||
|
|
||||||
|
describe('app icon', () => {
|
||||||
|
test('config first, then the rendered store icons, then the usual places; data: URL with a size cap', () => {
|
||||||
|
const d = tmp();
|
||||||
|
try {
|
||||||
|
const cfg = { icons: { composite: 'art/icon.png', out: 'store/icons' }, play: { packageName: 'x', icon: 'play.png' } } as unknown as ShipConfig;
|
||||||
|
expect(iconCandidates(cfg, d).slice(0, 4).map(p => relative(d, p))).toEqual(['art/icon.png', 'store/icons/app-store-1024.png', 'store/icons/play-512.png', 'play.png']);
|
||||||
|
expect(findIcon(cfg, d)).toBeNull();
|
||||||
|
mkdirSync(join(d, 'store/icons'), { recursive: true });
|
||||||
|
writeFileSync(join(d, 'store/icons/play-512.png'), PNG);
|
||||||
|
expect(findIcon(cfg, d)).toBe(join(d, 'store/icons/play-512.png'));
|
||||||
|
const u = iconDataUrl(findIcon(cfg, d));
|
||||||
|
expect(u.dataUrl).toStartWith('data:image/png;base64,');
|
||||||
|
writeFileSync(join(d, 'big.png'), Buffer.alloc(1_600_000));
|
||||||
|
expect(iconDataUrl(join(d, 'big.png')).dataUrl).toBeNull();
|
||||||
|
expect(iconDataUrl(null)).toEqual({ path: null, dataUrl: null });
|
||||||
|
} finally { rmSync(d, { recursive: true, force: true }); }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('listing completeness', () => {
|
||||||
|
test('per language and store: present, missing, over the limit, optional; screenshots counted; missing files reported', () => {
|
||||||
|
const d = tmp();
|
||||||
|
try {
|
||||||
|
const cfg = { app: APP, languages: [{ id: 'en', play: 'en-US', apple: 'en-US' }, { id: 'tr', play: 'tr-TR', apple: 'tr' }], play: { packageName: 'x' }, apple: { bundleId: 'x' }, renders: 'r' } as unknown as ShipConfig;
|
||||||
|
const none = listingCompleteness(cfg, d);
|
||||||
|
expect(none.problems).toEqual(['store/listing.md: file not found', 'store/appstore.md: file not found']);
|
||||||
|
expect(none.locales.map(l => [l.lang, l.complete, l.screenshots])).toEqual([['en', 0, null], ['tr', 0, null]]);
|
||||||
|
mkdirSync(join(d, 'store'));
|
||||||
|
writeFileSync(join(d, 'store/listing.md'), '## English\n<!-- play: en-US -->\n### Short description\n```\nShort text\n```\n### Full description\n```\nFull text\n```\n');
|
||||||
|
writeFileSync(join(d, 'store/appstore.md'), `## en-US\n### subtitle\n\`\`\`\n${'x'.repeat(31)}\n\`\`\`\n### promotionalText\n\`\`\`\nPromo\n\`\`\`\n### keywords\n\`\`\`\na,b\n\`\`\`\n### description\n\`\`\`\nDesc\n\`\`\`\n`);
|
||||||
|
mkdirSync(join(d, 'r/en/phone'), { recursive: true });
|
||||||
|
for (const n of ['01.png', '02.jpg', 'notes.txt']) writeFileSync(join(d, 'r/en/phone', n), 'x');
|
||||||
|
const l = listingCompleteness(cfg, d);
|
||||||
|
expect(l.problems).toEqual([]);
|
||||||
|
const en = l.locales[0]!;
|
||||||
|
expect(en.play!.fields.map(f => [f.field, f.state])).toEqual([['title', 'ok'], ['short', 'ok'], ['full', 'ok'], ['whatsNew', 'empty-optional']]);
|
||||||
|
expect(en.apple!.fields.find(f => f.field === 'subtitle')).toMatchObject({ length: 31, limit: 30, state: 'over' });
|
||||||
|
expect(en.screenshots).toBe(2);
|
||||||
|
expect(en.complete).toBeCloseTo(7 / 8);
|
||||||
|
expect(l.locales[1]!).toMatchObject({ complete: 0, screenshots: 0 });
|
||||||
|
expect(l.locales[1]!.play!.fields[1]).toMatchObject({ field: 'short', state: 'missing' });
|
||||||
|
} finally { rmSync(d, { recursive: true, force: true }); }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('reply drafts', () => {
|
||||||
|
const review = { store: 'play' as const, id: 'gp:1', rating: 2, title: 'Crash', body: 'It crashes', date: '2026-10-09T10:00:00.000Z', where: 'en' };
|
||||||
|
test('read with checks; approve sets the front matter only; unparsable files are problems', () => {
|
||||||
|
const d = tmp();
|
||||||
|
try {
|
||||||
|
const f = join(d, draftName(review));
|
||||||
|
writeFileSync(f, draftMarkdown(review).replace('## Reply\n\n', '## Reply\n\nSorry! Fixed in 2.4. Rate us 5 stars!\n'));
|
||||||
|
writeFileSync(join(d, 'apple-bad.md'), 'no front matter');
|
||||||
|
const r = readReplyDrafts(d);
|
||||||
|
expect(r.problems).toHaveLength(1);
|
||||||
|
expect(r.drafts).toHaveLength(1);
|
||||||
|
expect(r.drafts[0]).toMatchObject({ store: 'play', reviewId: 'gp:1', approved: false, sent: null, rating: 2, title: 'Crash', body: 'It crashes' });
|
||||||
|
expect(r.drafts[0]!.issues.some(i => i.level === 'error')).toBe(true);
|
||||||
|
const text = readFileSync(f, 'utf8');
|
||||||
|
const approved = setApproved(text, true);
|
||||||
|
expect(parseDraft(f, approved).approved).toBe(true);
|
||||||
|
expect(approved.split('---').slice(2).join('---')).toBe(text.split('---').slice(2).join('---'));
|
||||||
|
expect(() => setApproved('---\nfoo: 1\n---\nx', true)).toThrow();
|
||||||
|
expect(readReplyDrafts(join(d, 'none'))).toEqual({ dir: join(d, 'none'), drafts: [], problems: [] });
|
||||||
|
} finally { rmSync(d, { recursive: true, force: true }); }
|
||||||
|
});
|
||||||
|
test('CLI: reviews drafts --json and reviews approve (refuses a draft that fails the checks)', async () => {
|
||||||
|
const d = tmp();
|
||||||
|
try {
|
||||||
|
writeFileSync(join(d, 'storebound.config.ts'), `export default ${JSON.stringify({ app: APP, languages: [{ id: 'en', play: 'en-US' }], play: { packageName: 'com.example.demo' } })};\n`);
|
||||||
|
const dir = join(d, '.storebound/replies');
|
||||||
|
mkdirSync(dir, { recursive: true });
|
||||||
|
const good = draftName({ ...review, id: 'gp:2' }), bad = draftName(review);
|
||||||
|
writeFileSync(join(dir, good), draftMarkdown({ ...review, id: 'gp:2' }).replace('## Reply\n\n', '## Reply\n\nThanks, fixed in 2.4.\n'));
|
||||||
|
writeFileSync(join(dir, bad), draftMarkdown(review).replace('## Reply\n\n', '## Reply\n\nRate us 5 stars for free coins!\n'));
|
||||||
|
const run = (args: string[]) => Bun.spawnSync([process.execPath, join(ROOT, 'cli/index.ts'), ...args], { cwd: d, stdout: 'pipe', stderr: 'pipe' });
|
||||||
|
const list = run(['reviews', 'drafts', '--json']);
|
||||||
|
expect(list.exitCode).toBe(0);
|
||||||
|
expect((JSON.parse(list.stdout.toString()) as { drafts: unknown[] }).drafts).toHaveLength(2);
|
||||||
|
expect(run(['reviews', 'approve', good, '--dry']).exitCode).toBe(0);
|
||||||
|
expect(parseDraft(good, readFileSync(join(dir, good), 'utf8')).approved).toBe(false);
|
||||||
|
expect(run(['reviews', 'approve', good]).exitCode).toBe(0);
|
||||||
|
expect(parseDraft(good, readFileSync(join(dir, good), 'utf8')).approved).toBe(true);
|
||||||
|
expect(run(['reviews', 'approve', bad]).exitCode).not.toBe(0);
|
||||||
|
expect(run(['reviews', 'approve', '../storebound.config.ts']).exitCode).not.toBe(0);
|
||||||
|
expect(run(['reviews', 'approve', good, '--undo']).exitCode).toBe(0);
|
||||||
|
expect(parseDraft(good, readFileSync(join(dir, good), 'utf8')).approved).toBe(false);
|
||||||
|
} finally { rmSync(d, { recursive: true, force: true }); }
|
||||||
|
}, 30_000);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('init from the compiled sidecar', () => {
|
||||||
|
test('every template file is embedded with the same bytes, and init writes from the embedded copy', () => {
|
||||||
|
const all: string[] = [];
|
||||||
|
const walk = (dir: string) => { for (const n of readdirSync(dir)) { const p = join(dir, n); if (statSync(p).isDirectory()) walk(p); else all.push(relative(join(ROOT, 'templates'), p).split('\\').join('/')); } };
|
||||||
|
walk(join(ROOT, 'templates'));
|
||||||
|
expect(Object.keys(TEMPLATE_TEXT).sort()).toEqual(all.sort());
|
||||||
|
for (const k of all) expect(TEMPLATE_TEXT[k], k).toBe(readFileSync(join(ROOT, 'templates', k), 'utf8'));
|
||||||
|
for (const p of ['app', 'game', 'subscription-app'] as const) for (const [f] of FILES) expect(templateText(p, f)).toBe(readFileSync(templateFor(p, f), 'utf8'));
|
||||||
|
expect(templateKey('subscription-app', 'privacy-policy.html')).toBe('profiles/app/privacy-policy.html');
|
||||||
|
});
|
||||||
|
test('init --dry writes nothing', () => {
|
||||||
|
const d = tmp();
|
||||||
|
try {
|
||||||
|
const r = Bun.spawnSync([process.execPath, join(ROOT, 'cli/index.ts'), 'init', '--profile', 'game', '--dry'], { cwd: d, stdout: 'pipe', stderr: 'pipe' });
|
||||||
|
expect(r.exitCode).toBe(0);
|
||||||
|
expect(r.stdout.toString()).toContain('would create storebound.config.ts');
|
||||||
|
expect(readdirSync(d)).toEqual([]);
|
||||||
|
} finally { rmSync(d, { recursive: true, force: true }); }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('doctor and playwright', () => {
|
||||||
|
test('doctor: the GUI\'s detection plus playwright, install commands for what is missing', () => {
|
||||||
|
const r = doctor(ROOT, { PATH: '/nonexistent' });
|
||||||
|
expect(r.tools.map(t => t.id)).toEqual(expect.arrayContaining(['ffmpeg', 'ffprobe', 'chrome', 'playwright', 'git']));
|
||||||
|
const ff = r.tools.find(t => t.id === 'ffmpeg')!;
|
||||||
|
expect(ff.found).toBe(false);
|
||||||
|
expect(ff.install.length).toBeGreaterThan(0);
|
||||||
|
expect(r.missing).toBe(r.tools.filter(t => !t.found).length);
|
||||||
|
expect(r.project).toBeNull();
|
||||||
|
});
|
||||||
|
test('sidecar bundle: no checkout path, and bundled require.resolve of own files cannot throw', () => {
|
||||||
|
const js = 'var a = __require.resolve("/work/sb/node_modules/x/package.json"); var __dirname = "/work/sb/node_modules/x/lib";';
|
||||||
|
expect(neutralize(js, '/work/sb')).toBe(`var a = "${NEUTRAL_ROOT}/node_modules/x/package.json"; var __dirname = "${NEUTRAL_ROOT}/node_modules/x/lib";`);
|
||||||
|
});
|
||||||
|
test('install commands per OS, never empty for the tools that have a package', () => {
|
||||||
|
expect(installCommands('ffmpeg', 'darwin')).toEqual(['brew install ffmpeg']);
|
||||||
|
expect(installCommands('ffmpeg', 'win32')[0]).toContain('winget');
|
||||||
|
expect(installCommands('adb', 'linux')).toEqual(['sudo apt install adb']);
|
||||||
|
expect(installCommands('xcode', 'linux')).toEqual([]);
|
||||||
|
expect(installCommands('playwright')).toEqual(['bun add -d playwright']);
|
||||||
|
});
|
||||||
|
test('playwright is an optional peer, not a runtime dependency; playwright-core is only a dev dependency for the sidecar', () => {
|
||||||
|
const p = pkg as unknown as { dependencies?: Record<string, string>; peerDependencies: Record<string, string>; peerDependenciesMeta: Record<string, { optional: boolean }>; devDependencies: Record<string, string> };
|
||||||
|
expect(p.dependencies ?? {}).toEqual({});
|
||||||
|
expect(p.peerDependencies.playwright).toBeString();
|
||||||
|
expect(p.peerDependenciesMeta.playwright).toEqual({ optional: true });
|
||||||
|
expect(p.devDependencies['playwright-core']).toBe(p.devDependencies.playwright);
|
||||||
|
// the CLI reaches playwright-core only when compiled (the sidecar bundles it)
|
||||||
|
const browser = readFileSync(join(ROOT, 'cli/shots/browser.ts'), 'utf8');
|
||||||
|
expect(browser).toMatch(/if \(compiled\(\)\) return \(await import\('playwright-core'\)\)\.chromium;/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import { describe, expect, test } from 'bun:test';
|
import { describe, expect, test } from 'bun:test';
|
||||||
import type { ProjectSummary } from '../cli/lib/desktop-protocol';
|
import type { ProjectSummary } from '../cli/lib/desktop-protocol';
|
||||||
import { appIdentity, applePhase, appleProductIds, appleReleases, catalogParity, cmpVersion, playProductIds, playReleases, releaseTrains, versionOfName } from '../cli/lib/portfolio';
|
import { appIdentity, applePhase, appleProductIds, appleReleases, catalogParity, cmpVersion, phasedFraction, playProductIds, playReleases, releaseTrains, versionOfName } from '../cli/lib/portfolio';
|
||||||
|
|
||||||
const summary: ProjectSummary = {
|
const summary: ProjectSummary = {
|
||||||
dir: '/games/demo', config: '/games/demo/storebound.config.ts', name: 'Demo', languages: ['en'],
|
dir: '/games/demo', config: '/games/demo/storebound.config.ts', name: 'Demo', languages: ['en'],
|
||||||
|
|
@ -43,6 +43,18 @@ describe('portfolio (apps, release trains, catalog parity)', () => {
|
||||||
expect(applePhase('PREPARE_FOR_SUBMISSION')).toBe('draft');
|
expect(applePhase('PREPARE_FOR_SUBMISSION')).toBe('draft');
|
||||||
expect(applePhase('SOMETHING_NEW')).toBe('other');
|
expect(applePhase('SOMETHING_NEW')).toBe('other');
|
||||||
});
|
});
|
||||||
|
test('iOS phased release: day -> share, paused -> halted, complete -> live', () => {
|
||||||
|
expect(phasedFraction({ state: 'ACTIVE', currentDayNumber: 5 })).toBe(0.2);
|
||||||
|
expect(phasedFraction({ state: 'ACTIVE', currentDayNumber: 1 })).toBe(0.01);
|
||||||
|
expect(phasedFraction({ state: 'PAUSED', currentDayNumber: 6 })).toBe(0.5);
|
||||||
|
expect(phasedFraction({ state: 'COMPLETE', currentDayNumber: 7 })).toBe(1);
|
||||||
|
expect(phasedFraction({ state: 'ACTIVE', currentDayNumber: 99 })).toBe(1);
|
||||||
|
expect(phasedFraction(null)).toBeNull();
|
||||||
|
const v = (id: string, state: string) => ({ id, attributes: { versionString: id, appStoreState: state, platform: 'IOS' } });
|
||||||
|
const rs = appleReleases({ versions: [v('3.0.0', 'READY_FOR_SALE'), v('2.9.0', 'READY_FOR_SALE'), v('2.8.0', 'READY_FOR_SALE'), v('2.7.0', 'WAITING_FOR_REVIEW')],
|
||||||
|
phased: { '3.0.0': { attributes: { phasedReleaseState: 'ACTIVE', currentDayNumber: 4 } }, '2.9.0': { attributes: { phasedReleaseState: 'PAUSED', currentDayNumber: 2 } }, '2.8.0': { attributes: { phasedReleaseState: 'COMPLETE', currentDayNumber: 7 } } } });
|
||||||
|
expect(rs.map(r => [r.version, r.phase, r.fraction, r.phased?.state ?? null])).toEqual([['3.0.0', 'rollout', 0.1, 'ACTIVE'], ['2.9.0', 'halted', 0.02, 'PAUSED'], ['2.8.0', 'live', 1, 'COMPLETE'], ['2.7.0', 'review', null, null]]);
|
||||||
|
});
|
||||||
test('store releases from status data; garbage gives nothing', () => {
|
test('store releases from status data; garbage gives nothing', () => {
|
||||||
const ios = appleReleases(apple);
|
const ios = appleReleases(apple);
|
||||||
expect(ios.map(r => [r.version, r.build, r.phase])).toEqual([['2.3.0', '45', 'review'], ['2.2.1', '41', 'live']]);
|
expect(ios.map(r => [r.version, r.build, r.phase])).toEqual([['2.3.0', '45', 'review'], ['2.2.1', '41', 'live']]);
|
||||||
|
|
@ -51,10 +63,13 @@ describe('portfolio (apps, release trains, catalog parity)', () => {
|
||||||
expect(appleReleases(null)).toEqual([]);
|
expect(appleReleases(null)).toEqual([]);
|
||||||
expect(playReleases({ tracks: 'x' })).toEqual([]);
|
expect(playReleases({ tracks: 'x' })).toEqual([]);
|
||||||
});
|
});
|
||||||
test('trains: current = highest live version, next = highest above it, per store', () => {
|
test('trains: current = highest version reaching users (live or rolling out), next = highest above it, per store', () => {
|
||||||
const t = releaseTrains(appleReleases(apple), playReleases(play));
|
const t = releaseTrains(appleReleases(apple), playReleases(play));
|
||||||
expect(t.current).toMatchObject({ version: '2.2.1', ios: { phase: 'live', build: '41' }, android: { phase: 'live', build: '220' } });
|
expect(t.current).toMatchObject({ version: '2.3.0', ios: { phase: 'review', build: '45' }, android: { phase: 'rollout', fraction: 0.2, build: '231' } });
|
||||||
expect(t.next).toMatchObject({ version: '2.4.0', ios: null, android: { phase: 'testing' } });
|
expect(t.next).toMatchObject({ version: '2.4.0', ios: null, android: { phase: 'testing' } });
|
||||||
|
const done = releaseTrains(appleReleases(apple), playReleases({ tracks: [play.tracks[0]!.releases[0] && { track: 'production', releases: [play.tracks[0]!.releases[0]] }] }));
|
||||||
|
expect(done.current).toMatchObject({ version: '2.2.1', ios: { phase: 'live', build: '41' }, android: { phase: 'live', build: '220' } });
|
||||||
|
expect(done.next).toMatchObject({ version: '2.3.0', ios: { phase: 'review' }, android: null });
|
||||||
expect(releaseTrains([], [])).toEqual({ current: null, next: null });
|
expect(releaseTrains([], [])).toEqual({ current: null, next: null });
|
||||||
const onlyNext = releaseTrains(appleReleases({ versions: [apple.versions[0]] }), []);
|
const onlyNext = releaseTrains(appleReleases({ versions: [apple.versions[0]] }), []);
|
||||||
expect(onlyNext.current).toBeNull();
|
expect(onlyNext.current).toBeNull();
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ import { canonical, mac, MAX_TTL_MS, mint, parseSecret, TokenGuard } from '../cl
|
||||||
import { ERR } from '../cli/lib/desktop-protocol';
|
import { ERR } from '../cli/lib/desktop-protocol';
|
||||||
import { childEnv, pickCallEnv, type RunOptions, type Running } from '../cli/lib/runner';
|
import { childEnv, pickCallEnv, type RunOptions, type Running } from '../cli/lib/runner';
|
||||||
import { FORBIDDEN_ARGS, TOOLS } from '../cli/mcp-tools';
|
import { FORBIDDEN_ARGS, TOOLS } from '../cli/mcp-tools';
|
||||||
import { describeMethods, DESKTOP_TOOLS, FORBIDDEN_METHOD_WORDS, JSON_TOOLS, methodName, Session } from '../cli/serve';
|
import { describeMethods, DESKTOP_ONLY, DESKTOP_TOOLS, FORBIDDEN_METHOD_WORDS, JSON_TOOLS, methodName, Session } from '../cli/serve';
|
||||||
import { buildOne, hostTarget, leaks } from '../tools/build-sidecars';
|
import { buildOne, hostTarget, leaks } from '../tools/build-sidecars';
|
||||||
|
|
||||||
type J = Record<string, unknown>;
|
type J = Record<string, unknown>;
|
||||||
|
|
@ -97,7 +97,10 @@ describe('serve --stdio: methods', () => {
|
||||||
const ms = describeMethods();
|
const ms = describeMethods();
|
||||||
expect(ms.filter(m => m.kind === 'read' || m.kind === 'write').length).toBe(DESKTOP_TOOLS.length + 1); // + project.inspect
|
expect(ms.filter(m => m.kind === 'read' || m.kind === 'write').length).toBe(DESKTOP_TOOLS.length + 1); // + project.inspect
|
||||||
for (const m of ms) { expect(m.args.type).toBe('object'); expect(m.args.additionalProperties).toBe(false); expect(m.args.properties.dry_run).toBeUndefined(); }
|
for (const m of ms) { expect(m.args.type).toBe('object'); expect(m.args.additionalProperties).toBe(false); expect(m.args.properties.dry_run).toBeUndefined(); }
|
||||||
for (const t of JSON_TOOLS) expect(TOOLS.find(x => x.name === t)?.write).toBe(false);
|
for (const t of JSON_TOOLS) expect(DESKTOP_TOOLS.find(x => x.name === t)?.write).toBe(false);
|
||||||
|
// desktop-only methods are not MCP tools (approving a reply is the owner's decision)
|
||||||
|
for (const t of DESKTOP_ONLY) expect(TOOLS.some(x => x.name === t.name)).toBe(false);
|
||||||
|
expect(ms.map(m => m.method)).toEqual(expect.arrayContaining(['project.icon', 'project.listings', 'reviews.drafts', 'reviews.approve', 'project.init']));
|
||||||
expect(ms.map(m => m.method)).toEqual(expect.arrayContaining(['portfolio.status', 'project.inspect', 'check', 'validate', 'apple.status', 'play.status', 'reviews.list', 'apple.testflight_status']));
|
expect(ms.map(m => m.method)).toEqual(expect.arrayContaining(['portfolio.status', 'project.inspect', 'check', 'validate', 'apple.status', 'play.status', 'reviews.list', 'apple.testflight_status']));
|
||||||
expect(methodName('apple_testflight_status')).toBe('apple.testflight_status');
|
expect(methodName('apple_testflight_status')).toBe('apple.testflight_status');
|
||||||
});
|
});
|
||||||
|
|
@ -154,6 +157,37 @@ describe('serve --stdio: session', () => {
|
||||||
// a read method never needs a token, and dryRun false on it is just a normal run
|
// a read method never needs a token, and dryRun false on it is just a normal run
|
||||||
expect(resOf(await call('check', { project: DEMO, dryRun: false })).dryRun).toBe(false);
|
expect(resOf(await call('check', { project: DEMO, dryRun: false })).dryRun).toBe(false);
|
||||||
});
|
});
|
||||||
|
test('desktop-only methods: offline reads, reply approval and project.init are dry runs without a host token', async () => {
|
||||||
|
let now = 7_000_000;
|
||||||
|
const { call, calls } = await session(argv => (argv[0] === 'inspect' ? { data: { path: null, dataUrl: null } } : {}), () => now);
|
||||||
|
expect(resOf(await call('project.icon', { project: DEMO }))).toMatchObject({ ok: true, data: { dataUrl: null } });
|
||||||
|
expect(calls.at(-1)!.argv).toEqual(['inspect', '--icon', '--json']);
|
||||||
|
await call('project.listings', { project: DEMO });
|
||||||
|
expect(calls.at(-1)!.argv).toEqual(['inspect', '--listings', '--json']);
|
||||||
|
await call('reviews.drafts', { project: DEMO });
|
||||||
|
expect(calls.at(-1)!.argv).toEqual(['reviews', 'drafts', '--json']);
|
||||||
|
// approve: file names only, dry run unless the token matches
|
||||||
|
expect(errOf(await call('reviews.approve', { project: DEMO, args: { file: '../x.md' } })).code).toBe(ERR.invalidParams);
|
||||||
|
const a = { project: DEMO, args: { file: 'play-abc.md' } };
|
||||||
|
expect(resOf(await call('reviews.approve', a))).toMatchObject({ dryRun: true });
|
||||||
|
expect(calls.at(-1)!.argv).toEqual(['reviews', 'approve', 'play-abc.md', '--dry']);
|
||||||
|
expect(errOf(await call('reviews.approve', { ...a, dryRun: false })).code).toBe(ERR.confirmRequired);
|
||||||
|
await call('reviews.approve', { ...a, dryRun: false, confirmToken: mint(SECRET, 'reviews.approve', a, { now }) });
|
||||||
|
expect(calls.at(-1)!.argv).toEqual(['reviews', 'approve', 'play-abc.md']);
|
||||||
|
// init: an existing folder without a config; never one that has a config
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'sb-init-'));
|
||||||
|
try {
|
||||||
|
expect(errOf(await call('project.init', { project: DEMO, args: { profile: 'game' } })).message).toContain('already has a storebound config');
|
||||||
|
const i = { project: dir, args: { profile: 'game' } };
|
||||||
|
expect(resOf(await call('project.init', i))).toMatchObject({ dryRun: true });
|
||||||
|
expect(calls.at(-1)).toMatchObject({ argv: ['init', '--profile', 'game', '--dry'], o: { cwd: dir } });
|
||||||
|
expect(errOf(await call('project.init', { ...i, dryRun: false, confirmToken: mint(SECRET, 'project.init', { ...i, args: { profile: 'app' } }, { now }) })).code).toBe(ERR.confirmInvalid);
|
||||||
|
await call('project.init', { ...i, dryRun: false, confirmToken: mint(SECRET, 'project.init', i, { now }) });
|
||||||
|
expect(calls.at(-1)!.argv).toEqual(['init', '--profile', 'game']);
|
||||||
|
// project.init is not a way to run other tools in a config-less folder
|
||||||
|
expect(errOf(await call('check', { project: dir })).message).toContain('no storebound.config.ts');
|
||||||
|
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||||
|
});
|
||||||
test('cancellation answers -32800 and kills the child', async () => {
|
test('cancellation answers -32800 and kills the child', async () => {
|
||||||
const { s, call, nextId } = await session(() => ({ wait: new Promise(() => {}) }));
|
const { s, call, nextId } = await session(() => ({ wait: new Promise(() => {}) }));
|
||||||
const id = nextId();
|
const id = nextId();
|
||||||
|
|
|
||||||
|
|
@ -7,8 +7,8 @@
|
||||||
// macOS outputs are re-signed ad hoc: the signature `bun build --compile` leaves is invalid once the payload is
|
// macOS outputs are re-signed ad hoc: the signature `bun build --compile` leaves is invalid once the payload is
|
||||||
// appended, and the kernel kills such a binary on start (exit 137). Release builds re-sign with Developer ID (D5).
|
// appended, and the kernel kills such a binary on start (exit 137). Release builds re-sign with Developer ID (D5).
|
||||||
// Every output is scanned for the build machine's home and checkout paths: nothing private may ship.
|
// Every output is scanned for the build machine's home and checkout paths: nothing private may ship.
|
||||||
import { mkdirSync, readFileSync, rmSync, statSync } from 'node:fs';
|
import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
||||||
import { homedir } from 'node:os';
|
import { homedir, tmpdir } from 'node:os';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
|
|
||||||
export const TARGETS: Record<string, string> = {
|
export const TARGETS: Record<string, string> = {
|
||||||
|
|
@ -20,6 +20,8 @@ export const TARGETS: Record<string, string> = {
|
||||||
};
|
};
|
||||||
|
|
||||||
export const ROOT = join(import.meta.dir, '..');
|
export const ROOT = join(import.meta.dir, '..');
|
||||||
|
/** Modules playwright-core references but the sidecar never loads (Electron apps, the WebDriver BiDi protocol). */
|
||||||
|
export const SIDECAR_EXTERNALS = ['electron', 'chromium-bidi'];
|
||||||
export const OUT_DIR = join(ROOT, 'apps/desktop/src-tauri/binaries');
|
export const OUT_DIR = join(ROOT, 'apps/desktop/src-tauri/binaries');
|
||||||
|
|
||||||
export function hostTarget(): string {
|
export function hostTarget(): string {
|
||||||
|
|
@ -40,13 +42,43 @@ export function leaks(file: string, needles = privateStrings()): string[] {
|
||||||
return needles.filter(n => buf.includes(Buffer.from(n)));
|
return needles.filter(n => buf.includes(Buffer.from(n)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Neutral prefix the checkout path is replaced with in the bundle (bundled packages carry their own paths). */
|
||||||
|
export const NEUTRAL_ROOT = '/storebound';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stage 1: one JavaScript bundle of the CLI (target bun, platform independent). playwright-core is bundled, so
|
||||||
|
* screenshot renders work without playwright in the user's project (it drives the app-managed Chrome for Testing,
|
||||||
|
* STOREBOUND_CHROME); its Electron and BiDi loaders are never used and stay out. Bundled CommonJS modules carry their
|
||||||
|
* absolute source paths (__dirname, require.resolve): the checkout path becomes NEUTRAL_ROOT, so no build machine
|
||||||
|
* path ships. Those paths only matter for features the sidecar never uses (Electron, trace viewer, app icon).
|
||||||
|
*/
|
||||||
|
export function bundle(): string {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'sb-sidecar-'));
|
||||||
|
const p = Bun.spawnSync(['bun', 'build', 'cli/index.ts', '--target=bun', ...SIDECAR_EXTERNALS.flatMap(e => ['--external', e]), '--outdir', dir],
|
||||||
|
{ cwd: ROOT, stdout: 'pipe', stderr: 'pipe' });
|
||||||
|
if (p.exitCode !== 0) throw new Error(`bundle failed\n${p.stderr.toString()}${p.stdout.toString()}`);
|
||||||
|
const entry = join(dir, 'index.js');
|
||||||
|
writeFileSync(entry, neutralize(readFileSync(entry, 'utf8')));
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The checkout path out of a bundle. `require.resolve("<checkout>/...")` of a bundled file (playwright-core asks
|
||||||
|
* for its own package.json, only to know its folder) becomes the plain path string, so it cannot throw at run time. */
|
||||||
|
export function neutralize(js: string, root = ROOT): string {
|
||||||
|
const esc = root.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||||
|
return js.replace(new RegExp(`__require\\.resolve\\(("${esc}[^"]*")\\)`, 'g'), '$1').split(root).join(NEUTRAL_ROOT);
|
||||||
|
}
|
||||||
|
|
||||||
|
let bundled: string | null = null;
|
||||||
|
|
||||||
export async function buildOne(target: string, outDir = OUT_DIR): Promise<string> {
|
export async function buildOne(target: string, outDir = OUT_DIR): Promise<string> {
|
||||||
if (!TARGETS[target]) throw new Error(`unknown target ${target} (${Object.keys(TARGETS).join(', ')})`);
|
if (!TARGETS[target]) throw new Error(`unknown target ${target} (${Object.keys(TARGETS).join(', ')})`);
|
||||||
mkdirSync(outDir, { recursive: true });
|
mkdirSync(outDir, { recursive: true });
|
||||||
const out = join(outDir, outName(target));
|
const out = join(outDir, outName(target));
|
||||||
rmSync(out, { force: true });
|
rmSync(out, { force: true });
|
||||||
const t = Date.now();
|
const t = Date.now();
|
||||||
const p = Bun.spawnSync(['bun', 'build', '--compile', `--target=${target}`, '--minify-syntax', '--minify-whitespace', 'cli/index.ts', '--outfile', out],
|
bundled ??= bundle();
|
||||||
|
const p = Bun.spawnSync(['bun', 'build', '--compile', `--target=${target}`, '--minify-syntax', '--minify-whitespace', bundled, '--outfile', out],
|
||||||
{ cwd: ROOT, stdout: 'pipe', stderr: 'pipe' });
|
{ cwd: ROOT, stdout: 'pipe', stderr: 'pipe' });
|
||||||
if (p.exitCode !== 0) throw new Error(`${target}: bun build failed\n${p.stderr.toString()}${p.stdout.toString()}`);
|
if (p.exitCode !== 0) throw new Error(`${target}: bun build failed\n${p.stderr.toString()}${p.stdout.toString()}`);
|
||||||
if (target.startsWith('bun-darwin') && process.platform === 'darwin') {
|
if (target.startsWith('bun-darwin') && process.platform === 'darwin') {
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,8 @@
|
||||||
"noImplicitOverride": true,
|
"noImplicitOverride": true,
|
||||||
"noEmit": true,
|
"noEmit": true,
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
"resolveJsonModule": true
|
"resolveJsonModule": true,
|
||||||
|
"allowImportingTsExtensions": true
|
||||||
},
|
},
|
||||||
"include": ["cli", "tests", "tools", "templates/storebound.config.ts", "examples/demo-game/storebound.config.ts", "examples/demo-game/serve.ts", "examples/demo-app/storebound.config.ts", "examples/demo-app/serve.ts", "templates/profiles/*/storebound.config.ts", "media/teaser/render.ts"]
|
"include": ["cli", "tests", "tools", "templates/storebound.config.ts", "examples/demo-game/storebound.config.ts", "examples/demo-game/serve.ts", "examples/demo-app/storebound.config.ts", "examples/demo-app/serve.ts", "templates/profiles/*/storebound.config.ts", "media/teaser/render.ts"]
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue