diff --git a/cli/inspect.ts b/cli/inspect.ts index dd93d148..56ae93d0 100644 --- a/cli/inspect.ts +++ b/cli/inspect.ts @@ -14,6 +14,9 @@ export function summarize(ctx: Ctx): ProjectSummary { play: config.play ? { packageName: config.play.packageName } : null, apple: config.apple ? { bundleId: config.apple.bundleId, appId: config.apple.appId ?? null } : null, products: config.products?.length ?? 0, + productIds: (config.products ?? []).map(p => p.id), + // subscriptions arrive in the config schema separately; counted when present + subscriptions: ((config as { subscriptions?: unknown[] }).subscriptions ?? []).length, shots: !!config.shots, testflightGroups: config.apple?.testflight?.groups?.length ?? 0, }; diff --git a/cli/lib/desktop-protocol.ts b/cli/lib/desktop-protocol.ts index bb2e2d04..abddce30 100644 --- a/cli/lib/desktop-protocol.ts +++ b/cli/lib/desktop-protocol.ts @@ -78,22 +78,72 @@ export interface ProjectSummary { languages: string[]; play: { packageName: string } | null; apple: { bundleId: string; appId: string | null } | null; + /** One-time in-app products in the config (shared by both stores). */ products: number; + productIds: string[]; + /** Subscriptions in the config (0 until the config defines them). */ + subscriptions: number; shots: boolean; testflightGroups: number; } +// ---- App-centric model (one app = one product on up to two platforms; a workspace holds many apps) ---- + +/** One product across platforms. id = its project folder (one storebound.config.ts per app). */ +export interface AppIdentity { + id: string; + name: string; + platforms: { ios: { bundleId: string; ascAppId: string | null } | null; android: { packageName: string } | null }; +} + +/** Where a version is on one store. */ +export type ReleasePhase = 'live' | 'rollout' | 'halted' | 'approved' | 'review' | 'rejected' | 'testing' | 'draft' | 'other'; + +export interface StoreRelease { + store: 'ios' | 'android'; + version: string | null; + /** iOS build number (CFBundleVersion) / highest Android versionCode. */ + build: string | null; + /** The store's own state word (READY_FOR_SALE, inProgress ...). */ + state: string; + phase: ReleasePhase; + /** Android staged rollout user fraction (0-1); iOS phased release percentage comes with D2. */ + fraction: number | null; + /** Android track (production, beta, internal ...). */ + track: string | null; +} + +/** A release train: one version (e.g. 2.3.0) across both stores. */ +export interface ReleaseTrain { version: string; ios: StoreRelease | null; android: StoreRelease | null } + +/** In-app catalog parity between the config and both stores. */ +export interface CatalogParity { + checked: 'config' | 'live'; + products: number; + subscriptions: number; + /** Live: ids on one store only, and config ids missing on a store the app is on. */ + onlyIos: string[]; + onlyAndroid: string[]; + missingIos: string[]; + missingAndroid: string[]; + ok: boolean; +} + export interface PortfolioParams { projects: string[]; live?: boolean; credentials?: Credentials } -export interface PortfolioEntry { +export interface AppStatus { + /** Project folder as given. */ project: string; ok: boolean; + app: AppIdentity | null; summary: ProjectSummary | null; check: { ok: boolean; problems: string[]; warnings: string[] } | null; - /** live only: `apple status --json` / `play status --json` data, or the error text. */ - apple?: { data?: unknown; error?: string }; - play?: { data?: unknown; error?: string }; + /** Release trains; `source: none` offline (no store data read). */ + release: { source: 'none' | 'live'; current: ReleaseTrain | null; next: ReleaseTrain | null }; + catalog: CatalogParity | null; + /** live only: per-platform read errors ("unknown, never false"). */ + storeErrors: { ios?: string; android?: string }; errors: string[]; } -export interface PortfolioResult { projects: PortfolioEntry[]; at: string } +export interface PortfolioResult { apps: AppStatus[]; at: string } diff --git a/cli/lib/portfolio.ts b/cli/lib/portfolio.ts new file mode 100644 index 00000000..4153ac7d --- /dev/null +++ b/cli/lib/portfolio.ts @@ -0,0 +1,100 @@ +// Pure pieces of `portfolio.status` (serve.ts): an app's identity across platforms, its release trains (one version +// across the App Store and Google Play) and the in-app catalog parity between the config and both stores. +// Inputs are the `apple status --json` / `play status --json` results, read defensively: "unknown, never false". +import type { AppIdentity, CatalogParity, ProjectSummary, ReleasePhase, ReleaseTrain, StoreRelease } from './desktop-protocol'; + +type J = Record; // eslint-disable-line @typescript-eslint/no-explicit-any + +export function appIdentity(s: ProjectSummary): AppIdentity { + return { + id: s.dir, + name: s.name, + platforms: { + ios: s.apple ? { bundleId: s.apple.bundleId, ascAppId: s.apple.appId } : null, + android: s.play ? { packageName: s.play.packageName } : null, + }, + }; +} + +/** Numeric compare of dotted versions ("2.10.0" > "2.9.1"); non-numeric parts compare as 0. */ +export function cmpVersion(a: string, b: string): number { + const pa = a.split('.').map(x => parseInt(x, 10) || 0), pb = b.split('.').map(x => parseInt(x, 10) || 0); + for (let i = 0; i < Math.max(pa.length, pb.length); i++) { const d = (pa[i] ?? 0) - (pb[i] ?? 0); if (d) return d; } + return 0; +} + +/** App Store version states (appStoreState / appVersionState) -> phase. */ +export function applePhase(state: string): ReleasePhase { + if (/^(READY_FOR_SALE|READY_FOR_DISTRIBUTION)$/.test(state)) return 'live'; + if (/^(PENDING_DEVELOPER_RELEASE|PENDING_APPLE_RELEASE|ACCEPTED)$/.test(state)) return 'approved'; + if (/^(WAITING_FOR_REVIEW|IN_REVIEW|WAITING_FOR_EXPORT_COMPLIANCE|PROCESSING_FOR_DISTRIBUTION|PROCESSING_FOR_APP_STORE)$/.test(state)) return 'review'; + if (/REJECTED$/.test(state)) return 'rejected'; + if (/^(PREPARE_FOR_SUBMISSION|DEVELOPER_ACTION_NEEDED)$/.test(state)) return 'draft'; + return 'other'; +} + +export function appleReleases(data: unknown): StoreRelease[] { + 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)); + 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 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 }; + }); +} + +/** Leading dotted version of a Play release name ("2.3.0 (45)" -> "2.3.0"). */ +export const versionOfName = (name: unknown): string | null => (typeof name === 'string' ? name.match(/\d+(?:\.\d+){0,3}/)?.[0] ?? null : null); + +export function playReleases(data: unknown): StoreRelease[] { + const out: StoreRelease[] = []; + for (const t of ((data as J)?.tracks ?? []) as J[]) { + for (const r of (t?.releases ?? []) as J[]) { + const codes = ((r.versionCodes ?? []) as unknown[]).map(Number).filter(Number.isFinite); + const production = t.track === 'production'; + const status = String(r.status ?? 'unknown'); + const phase: ReleasePhase = !production ? (status === 'draft' ? 'draft' : 'testing') + : status === 'completed' ? 'live' : status === 'inProgress' ? 'rollout' : status === 'halted' ? 'halted' : status === 'draft' ? 'draft' : 'other'; + out.push({ store: 'android', version: versionOfName(r.name), build: codes.length ? String(Math.max(...codes)) : null, state: status, phase, fraction: typeof r.userFraction === 'number' ? r.userFraction : null, track: String(t.track) }); + } + } + return out; +} + +const PHASE_RANK: Record = { live: 0, rollout: 1, halted: 2, approved: 3, review: 4, rejected: 5, testing: 6, draft: 7, other: 8 }; +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; + * next = the highest version above it on either store (review, testing, rollout, draft ...). A store without that + * version has null in the train. + */ +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 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 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 }; +} + +/** Product ids on App Store Connect (`apple status --json` iaps) and Google Play (`play status --json` products). */ +export const appleProductIds = (data: unknown): string[] => (((data as J)?.iaps ?? []) as J[]).map(p => p?.attributes?.productId).filter((x): x is string => typeof x === 'string'); +export const playProductIds = (data: unknown): string[] => (((data as J)?.products ?? []) as J[]).map(p => p?.productId ?? p?.sku).filter((x): x is string => typeof x === 'string'); + +/** + * Catalog parity. Without store data (offline) only the config side is known. With it: ids only on one store, + * and config ids missing from a store the app is on. + */ +export function catalogParity(s: ProjectSummary, apple?: string[], play?: string[]): CatalogParity { + const ids = s.productIds; + const live = apple !== undefined || play !== undefined; + const onlyIos = apple && play ? apple.filter(x => !play.includes(x)) : []; + const onlyAndroid = apple && play ? play.filter(x => !apple.includes(x)) : []; + const missingIos = s.apple && apple ? ids.filter(x => !apple.includes(x)) : []; + const missingAndroid = s.play && play ? ids.filter(x => !play.includes(x)) : []; + return { + checked: live ? 'live' : 'config', products: s.products, subscriptions: s.subscriptions, + onlyIos, onlyAndroid, missingIos, missingAndroid, + ok: !onlyIos.length && !onlyAndroid.length && !missingIos.length && !missingAndroid.length, + }; +} diff --git a/cli/lib/runner.ts b/cli/lib/runner.ts index 1af8f758..98f1ab06 100644 --- a/cli/lib/runner.ts +++ b/cli/lib/runner.ts @@ -3,6 +3,7 @@ // binary re-executes itself. Output is streamed line by line (progress) and the `--json` result line is picked out. import { join } from 'node:path'; import { RESULT_MARK } from './log'; +import { toolPath } from './tools'; /** True inside a `bun build --compile` executable (the entry module lives in Bun's embedded file system). */ export const compiled = (): boolean => /^(\/\$bunfs\/|[A-Z]:[\\/]~BUN[\\/])/.test(Bun.main); @@ -39,6 +40,8 @@ export function pickCallEnv(env: Record | undefined): Record = {}, machine = false): Record { const base: Record = {}; for (const [k, v] of Object.entries(process.env)) if (v !== undefined && !k.startsWith('STOREBOUND_SESSION')) base[k] = v; + // app-managed tools (desktop data folder) come first on PATH + if (base.STOREBOUND_TOOL_PATH) base.PATH = toolPath(base); return { ...base, ...extra, NO_COLOR: '1', ...(machine ? { STOREBOUND_MACHINE: '1', STOREBOUND_SERVE: '1' } : {}) }; } diff --git a/cli/lib/tools.ts b/cli/lib/tools.ts new file mode 100644 index 00000000..a3960cbf --- /dev/null +++ b/cli/lib/tools.ts @@ -0,0 +1,90 @@ +// Optional local tools storebound uses (screenshots, previews, icons, simulator and emulator captures), found on this +// machine with their versions. The desktop app can manage its own copies of ffmpeg and Chrome for Testing in its data +// folder and points storebound at them: +// STOREBOUND_TOOL_PATH folders put in front of PATH for every command (app-managed ffmpeg / ffprobe) +// STOREBOUND_CHROME Chrome / Chrome for Testing executable for renders and web captures +// Nothing is installed system-wide. Sources and licenses: docs/desktop.md. +import { existsSync } from 'node:fs'; +import { delimiter, join } from 'node:path'; + +export type ToolId = 'ffmpeg' | 'ffprobe' | 'chrome' | 'xcode' | 'simctl' | 'adb' | 'git'; + +export interface ToolStatus { + id: ToolId; + name: string; + found: boolean; + path: string | null; + version: string | null; + /** 'app' = the desktop app's own copy (STOREBOUND_TOOL_PATH / STOREBOUND_CHROME), 'system' = installed by the user. */ + source: 'app' | 'system' | null; + /** What needs it. */ + usedFor: string; + /** How to get it: the desktop app downloads ffmpeg and Chrome for Testing; Xcode and the Android SDK are link-out. */ + install: { kind: 'download' | 'link'; url: string; note: string }; +} + +/** PATH with the app-managed tool folders first. */ +export function toolPath(env: Record = process.env): string { + const extra = (env.STOREBOUND_TOOL_PATH ?? '').split(delimiter).filter(Boolean); + return [...extra, env.PATH ?? ''].filter(Boolean).join(delimiter); +} + +/** First line of ` ` (version banners), or null. */ +function firstLine(cmd: string[], env: Record): string | null { + try { + const r = Bun.spawnSync(cmd, { stdout: 'pipe', stderr: 'pipe', env, timeout: 5_000 }); + if (r.exitCode !== 0) return null; + return (r.stdout.toString() || r.stderr.toString()).trim().split('\n')[0]?.trim() || null; + } catch { return null; } +} + +/** "ffmpeg version 7.1.1 Copyright ..." -> "7.1.1"; "Google Chrome for Testing 131.0.6778.85" -> "131.0.6778.85". */ +export function parseVersion(line: string | null): string | null { + if (!line) return null; + return line.match(/version\s+([^\s,]+)/i)?.[1] ?? line.match(/(\d+(?:\.\d+)+)/)?.[1] ?? null; +} + +export function systemChrome(platform = process.platform, env: Record = process.env): string | null { + const c = platform === 'darwin' ? ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'] + : platform === 'win32' ? [env.PROGRAMFILES, env['PROGRAMFILES(X86)'], env.LOCALAPPDATA].filter((d): d is string => !!d).map(d => join(d, 'Google/Chrome/Application/chrome.exe')) + : ['/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser']; + return c.find(p => existsSync(p)) ?? null; +} + +const FFMPEG_NOTE = 'Static build into the app data folder (GPL; never bundled with the app). Checksum-verified.'; + +export function detectTools(env: Record = process.env): ToolStatus[] { + const PATH = toolPath(env); + const spawnEnv: Record = { ...Object.fromEntries(Object.entries(env).filter((e): e is [string, string] => e[1] !== undefined)), PATH }; + const appDirs = (env.STOREBOUND_TOOL_PATH ?? '').split(delimiter).filter(Boolean); + const which = (n: string): string | null => Bun.which(n, { PATH }); + const src = (p: string | null): ToolStatus['source'] => (!p ? null : appDirs.some(d => p.startsWith(d)) ? 'app' : 'system'); + const bin = (id: ToolId, name: string, usedFor: string, install: ToolStatus['install'], versionArgs: string[]): ToolStatus => { + const path = which(id); + const version = path ? parseVersion(firstLine([path, ...versionArgs], spawnEnv)) : null; + return { id, name, found: !!path, path, version, source: src(path), usedFor, install }; + }; + const out: ToolStatus[] = [ + bin('ffmpeg', 'ffmpeg', 'icons, screenshot renders, app preview videos, frame crops', { kind: 'download', url: 'https://ffmpeg.org/download.html', note: FFMPEG_NOTE }, ['-version']), + bin('ffprobe', 'ffprobe', 'checks of app preview videos and clips', { kind: 'download', url: 'https://ffmpeg.org/download.html', note: 'Comes with the ffmpeg download.' }, ['-version']), + ]; + const appChrome = env.STOREBOUND_CHROME && existsSync(env.STOREBOUND_CHROME) ? env.STOREBOUND_CHROME : null; + const chrome = appChrome ?? systemChrome(process.platform, env); + out.push({ + id: 'chrome', name: appChrome ? 'Chrome for Testing' : 'Google Chrome', found: !!chrome, path: chrome, + version: chrome ? parseVersion(firstLine([chrome, '--version'], spawnEnv)) : null, source: appChrome ? 'app' : chrome ? 'system' : null, + usedFor: 'screenshot renders, captions, web captures and recordings', + install: { kind: 'download', url: 'https://googlechromelabs.github.io/chrome-for-testing/', note: 'Chrome for Testing from Google\'s official endpoints into the app data folder.' }, + }); + if (process.platform === 'darwin') { + const dev = firstLine(['xcode-select', '-p'], spawnEnv); + out.push({ id: 'xcode', name: 'Xcode command line tools', found: !!dev, path: dev, version: parseVersion(firstLine(['xcodebuild', '-version'], spawnEnv)), source: dev ? 'system' : null, + usedFor: 'iOS builds, the iOS Simulator (simctl)', install: { kind: 'link', url: 'https://developer.apple.com/xcode/', note: 'Install Xcode from the App Store or developer.apple.com.' } }); + const simctl = firstLine(['xcrun', '--find', 'simctl'], spawnEnv); + out.push({ id: 'simctl', name: 'simctl (iOS Simulator)', found: !!simctl, path: simctl, version: null, source: simctl ? 'system' : null, + usedFor: 'iOS Simulator screenshots and recordings', install: { kind: 'link', url: 'https://developer.apple.com/xcode/', note: 'Part of Xcode.' } }); + } + out.push(bin('adb', 'adb (Android platform tools)', 'Android emulator / device screenshots and recordings', { kind: 'link', url: 'https://developer.android.com/tools/releases/platform-tools', note: 'Install Android Studio or the SDK platform tools.' }, ['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; +} diff --git a/cli/serve.ts b/cli/serve.ts index 06985694..8db2777f 100644 --- a/cli/serve.ts +++ b/cli/serve.ts @@ -15,8 +15,10 @@ import pkg from '../package.json' with { type: 'json' }; import { parseSecret, TokenGuard } from './lib/confirm-token'; import { CONFIG_NAMES } from './lib/config'; import { - DESKTOP_PROTOCOL, ERR, type MethodDescriptor, type PortfolioEntry, type PortfolioResult, type ProjectSummary, type ToolResult, + DESKTOP_PROTOCOL, ERR, type AppStatus, type MethodDescriptor, type PortfolioResult, type ProjectSummary, type ToolResult, } from './lib/desktop-protocol'; +import { appIdentity, appleProductIds, appleReleases, catalogParity, playProductIds, playReleases, releaseTrains } from './lib/portfolio'; +import { detectTools } from './lib/tools'; import { compiled, pickCallEnv, runCommand, type RunOptions, type Running } from './lib/runner'; import { inputSchema, type ToolDef, TOOLS, toArgv, validateInput } from './mcp-tools'; @@ -57,10 +59,10 @@ const SYSTEM: MethodDescriptor[] = [ args: obj({ secret: { type: 'string' }, client: { type: 'object' } }, ['secret']) }, { method: 'system.version', title: 'Version', description: 'storebound version, platform and whether this is the compiled sidecar.', kind: 'system', network: false, destructive: false, json: true, args: obj({}) }, { method: 'system.methods', title: 'Methods', description: 'Every method of this profile with its argument schema.', kind: 'system', network: false, destructive: false, json: true, args: obj({}) }, - { method: 'system.tools', title: 'Local tools', description: 'Which optional local tools are installed (git, ffmpeg, Google Chrome, Playwright); screenshot and video features need them.', kind: 'system', network: false, destructive: false, json: true, args: obj({}) }, + { method: 'system.tools', title: 'Local tools', description: 'Optional local tools with versions and where they come from (ffmpeg, ffprobe, Chrome, Xcode / simctl, adb, git); screenshot, video and capture features need them.', kind: 'system', network: false, destructive: false, json: true, args: obj({}) }, { method: 'project.inspect', title: 'Inspect a project', description: 'Offline summary of a folder\'s storebound.config.ts (name, store ids, languages, products).', kind: 'read', network: false, destructive: false, json: true, args: obj({ project: { type: 'string', description: 'Absolute folder path' } }, ['project']) }, - { method: 'portfolio.status', title: 'Portfolio status', description: 'Summary + offline check of many projects; with live, also App Store and Google Play status (read-only).', kind: 'portfolio', network: true, destructive: false, json: true, + { method: 'portfolio.status', title: 'Portfolio status', description: 'Apps (one per project folder) across iOS and Android: identity, offline config check, catalog parity; with live, release trains (current / next version on both stores) and live catalog parity from App Store and Google Play status (read-only).', kind: 'portfolio', network: true, destructive: false, json: true, args: obj({ projects: { type: 'array' }, live: { type: 'boolean', default: false } }, ['projects']) }, ]; @@ -180,7 +182,8 @@ export class Session { if (!t.write) dryRun = false; else { if (params.confirmToken === undefined) throw new RpcError(ERR.confirmRequired, `${method} writes: dryRun false needs a confirmToken from the desktop host`); - const v = this.guard!.verify(params.confirmToken, method, { project, args }); + // Bound to the project string exactly as sent (the host mints over what it sends) and the args object. + const v = this.guard!.verify(params.confirmToken, method, { project: params.project, args }); if (!v.ok) throw new RpcError(ERR.confirmInvalid, `confirm token rejected: ${v.error}`, { reason: v.error }); dryRun = false; } @@ -214,16 +217,18 @@ export class Session { if (!Array.isArray(list) || !list.length || list.length > 200) throw new RpcError(ERR.invalidParams, 'projects: 1-200 absolute folder paths'); const live = params.live === true; const env = credentialsOf(params.credentials); - const out: PortfolioEntry[] = new Array(list.length); + const out: AppStatus[] = new Array(list.length); let done = 0; const one = async (i: number): Promise => { const raw = list[i]; - const e: PortfolioEntry = { project: String(raw), ok: false, summary: null, check: null, errors: [] }; + const e: AppStatus = { project: String(raw), ok: false, app: null, summary: null, check: null, release: { source: 'none', current: null, next: null }, catalog: null, storeErrors: {}, errors: [] }; out[i] = e; try { const dir = checkProject(raw); e.project = dir; const summary = e.summary = await this.inspect(dir, env, id); + e.app = appIdentity(summary); + e.catalog = catalogParity(summary); const c = await this.track(id, this.run(['check', '--json'], { cwd: dir, env, machine: true })).result; const cd = c.data as { ok?: boolean; problems?: string[]; warnings?: string[] } | undefined; e.check = cd ? { ok: !!cd.ok, problems: cd.problems ?? [], warnings: cd.warnings ?? [] } : { ok: false, problems: [lastLine(c.out) || `check exit ${c.code}`], warnings: [] }; @@ -233,10 +238,12 @@ export class Session { return r.code === 0 && r.data !== undefined ? { data: r.data } : { error: lastLine(r.out) || `exit ${r.code}` }; }; const [apple, play] = await Promise.all([summary.apple ? store(['apple', 'status', '--json']) : undefined, summary.play ? store(['play', 'status', '--json']) : undefined]); - if (apple) e.apple = apple; - if (play) e.play = play; + if (apple?.error) e.storeErrors.ios = apple.error; + if (play?.error) e.storeErrors.android = play.error; + e.release = { source: 'live', ...releaseTrains(apple?.data ? appleReleases(apple.data) : [], play?.data ? playReleases(play.data) : []) }; + e.catalog = catalogParity(summary, apple?.data ? appleProductIds(apple.data) : undefined, play?.data ? playProductIds(play.data) : undefined); } - e.ok = e.check.ok && !e.apple?.error && !e.play?.error; + e.ok = e.check.ok && !e.storeErrors.ios && !e.storeErrors.android && (e.catalog?.ok ?? true); } catch (err) { if (this.cancelled.has(id)) throw err; e.errors.push((err as Error).message); @@ -247,25 +254,15 @@ export class Session { let next = 0; await Promise.all(Array.from({ length: Math.min(3, list.length) }, async () => { while (next < list.length) await one(next++); })); if (this.cancelled.has(id)) throw new RpcError(ERR.cancelled, 'Request cancelled'); - return { projects: out, at: new Date(this.clock()).toISOString() }; + return { apps: out, at: new Date(this.clock()).toISOString() }; } } const lastLine = (s: string): string => s.trim().split('\n').filter(Boolean).at(-1)?.replace(/^error:\s*/, '') ?? ''; +/** Optional local tools with versions; app-managed copies (STOREBOUND_TOOL_PATH / STOREBOUND_CHROME) included. */ export function localTools(): Json { - const which = (n: string): string | null => Bun.which(n); - const chrome = process.platform === 'darwin' ? existsSync('/Applications/Google Chrome.app') - : process.platform === 'win32' ? [process.env['PROGRAMFILES'], process.env['PROGRAMFILES(X86)'], process.env.LOCALAPPDATA].some(d => d && existsSync(join(d, 'Google/Chrome/Application/chrome.exe'))) - : !!(which('google-chrome') || which('google-chrome-stable') || which('chromium')); - const ffmpeg = which('ffmpeg'); - return { - git: !!which('git'), ffmpeg: !!ffmpeg, chrome, - notes: [ - ...(ffmpeg ? [] : ['ffmpeg not found: icons, screenshot renders and app preview videos need it (brew install ffmpeg / apt install ffmpeg / winget install ffmpeg)']), - ...(chrome ? [] : ['Google Chrome not found: screenshot renders and web captures need Chrome or Playwright\'s Chromium in the project']), - ], - }; + return { tools: detectTools() }; } export async function serveStdio(): Promise { diff --git a/cli/shots/browser.ts b/cli/shots/browser.ts index d44ba360..cd31dcbc 100644 --- a/cli/shots/browser.ts +++ b/cli/shots/browser.ts @@ -17,6 +17,9 @@ async function chromium(root: string): Promise { // eslint-disable-next-line @typescript-eslint/no-explicit-any export async function launch(root: string, opts: Record): Promise { const c = await chromium(root); + // the desktop app's own Chrome for Testing (or any Chrome the user points at) + const exe = process.env.STOREBOUND_CHROME; + if (exe) { try { return await c.launch({ ...opts, executablePath: exe }); } catch { /* fall back below */ } } try { return await c.launch(opts); } catch (e) { try { return await c.launch({ ...opts, channel: 'chrome' }); } catch { throw e; } } diff --git a/tests/portfolio.test.ts b/tests/portfolio.test.ts new file mode 100644 index 00000000..cbd08376 --- /dev/null +++ b/tests/portfolio.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, test } from 'bun:test'; +import type { ProjectSummary } from '../cli/lib/desktop-protocol'; +import { appIdentity, applePhase, appleProductIds, appleReleases, catalogParity, cmpVersion, playProductIds, playReleases, releaseTrains, versionOfName } from '../cli/lib/portfolio'; + +const summary: ProjectSummary = { + dir: '/games/demo', config: '/games/demo/storebound.config.ts', name: 'Demo', languages: ['en'], + play: { packageName: 'com.example.demo' }, apple: { bundleId: 'com.example.demo', appId: null }, + products: 2, productIds: ['coins', 'no_ads'], subscriptions: 0, shots: false, testflightGroups: 0, +}; + +const apple = { + versions: [ + { attributes: { versionString: '2.3.0', appVersionState: 'WAITING_FOR_REVIEW', platform: 'IOS' }, relationships: { build: { data: { id: 'b2' } } } }, + { attributes: { versionString: '2.2.1', appStoreState: 'READY_FOR_SALE', platform: 'IOS' }, relationships: { build: { data: { id: 'b1' } } } }, + { attributes: { versionString: '9.9.9', appStoreState: 'READY_FOR_SALE', platform: 'TV_OS' } }, + ], + builds: [{ id: 'b1', attributes: { version: '41' } }, { id: 'b2', attributes: { version: '45' } }], + iaps: [{ attributes: { productId: 'coins' } }, { attributes: { productId: 'ios_only' } }], +}; +const play = { + tracks: [ + { track: 'production', releases: [{ name: '2.2.1 (220)', versionCodes: ['220'], status: 'completed' }, { name: '2.3.0', versionCodes: ['230', '231'], status: 'inProgress', userFraction: 0.2 }] }, + { track: 'internal', releases: [{ name: '2.4.0', versionCodes: ['240'], status: 'completed' }] }, + ], + products: [{ productId: 'coins' }, { productId: 'no_ads' }, { sku: 'android_only' }], +}; + +describe('portfolio (apps, release trains, catalog parity)', () => { + test('identity: one app, both platforms', () => { + expect(appIdentity(summary)).toEqual({ id: '/games/demo', name: 'Demo', platforms: { ios: { bundleId: 'com.example.demo', ascAppId: null }, android: { packageName: 'com.example.demo' } } }); + expect(appIdentity({ ...summary, apple: null }).platforms.ios).toBeNull(); + }); + test('versions and phases', () => { + expect(cmpVersion('2.10.0', '2.9.1')).toBeGreaterThan(0); + expect(cmpVersion('2.3', '2.3.0')).toBe(0); + expect(versionOfName('2.3.0 (45)')).toBe('2.3.0'); + expect(versionOfName(undefined)).toBeNull(); + expect(applePhase('READY_FOR_SALE')).toBe('live'); + expect(applePhase('PENDING_DEVELOPER_RELEASE')).toBe('approved'); + expect(applePhase('METADATA_REJECTED')).toBe('rejected'); + expect(applePhase('PREPARE_FOR_SUBMISSION')).toBe('draft'); + expect(applePhase('SOMETHING_NEW')).toBe('other'); + }); + test('store releases from status data; garbage gives nothing', () => { + 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']]); + const android = playReleases(play); + expect(android.map(r => [r.version, r.build, r.phase, r.fraction, r.track])).toEqual([['2.2.1', '220', 'live', null, 'production'], ['2.3.0', '231', 'rollout', 0.2, 'production'], ['2.4.0', '240', 'testing', null, 'internal']]); + expect(appleReleases(null)).toEqual([]); + expect(playReleases({ tracks: 'x' })).toEqual([]); + }); + test('trains: current = highest live version, next = highest above it, per store', () => { + 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.next).toMatchObject({ version: '2.4.0', ios: null, android: { phase: 'testing' } }); + expect(releaseTrains([], [])).toEqual({ current: null, next: null }); + const onlyNext = releaseTrains(appleReleases({ versions: [apple.versions[0]] }), []); + expect(onlyNext.current).toBeNull(); + expect(onlyNext.next?.version).toBe('2.3.0'); + }); + test('catalog parity: config only offline, both stores live', () => { + expect(catalogParity(summary)).toEqual({ checked: 'config', products: 2, subscriptions: 0, onlyIos: [], onlyAndroid: [], missingIos: [], missingAndroid: [], ok: true }); + const live = catalogParity(summary, appleProductIds(apple), playProductIds(play)); + expect(live).toMatchObject({ checked: 'live', onlyIos: ['ios_only'], onlyAndroid: ['no_ads', 'android_only'], missingIos: ['no_ads'], missingAndroid: [], ok: false }); + // one store unreadable: no cross-store claims + expect(catalogParity(summary, undefined, playProductIds(play))).toMatchObject({ onlyIos: [], onlyAndroid: [], missingIos: [], missingAndroid: [] }); + }); +}); diff --git a/tests/serve.test.ts b/tests/serve.test.ts index 63930ac1..f0cea414 100644 --- a/tests/serve.test.ts +++ b/tests/serve.test.ts @@ -162,15 +162,19 @@ describe('serve --stdio: session', () => { await s.handle({ jsonrpc: '2.0', method: '$/cancelRequest', params: { id } }); expect(errOf(await pending).code).toBe(ERR.cancelled); }); - test('portfolio.status: many projects, per-project errors, progress n/total', async () => { - const { call, sent } = await session(argv => argv[0] === 'inspect' ? { data: { name: 'Demo', apple: { bundleId: 'a.b' }, play: null } } + test('portfolio.status: apps across platforms, release trains, catalog parity, per-app errors, progress n/total', async () => { + const summary = { dir: DEMO, name: 'Demo', apple: { bundleId: 'com.example.demo', appId: null }, play: { packageName: 'com.example.demo' }, products: 2, productIds: ['coins', 'no_ads'], subscriptions: 0 }; + const { call, sent } = await session(argv => argv[0] === 'inspect' ? { data: summary } : argv[0] === 'check' ? { data: { ok: true, problems: [], warnings: ['w'] } } - : argv[0] === 'apple' ? { code: 1, out: 'error: ASC_KEY_ID and ASC_ISSUER_ID are not set' } : {}); - const r = resOf(await call('portfolio.status', { projects: [DEMO, '/nope/game'], live: true })) as { projects: J[] }; - expect(r.projects[0]).toMatchObject({ project: DEMO, summary: { name: 'Demo' }, check: { ok: true, warnings: ['w'] }, apple: { error: 'ASC_KEY_ID and ASC_ISSUER_ID are not set' }, ok: false }); - expect(r.projects[0]!.play).toBeUndefined(); - expect(r.projects[1]).toMatchObject({ ok: false, summary: null }); - expect((r.projects[1]!.errors as string[])[0]).toContain('not a folder'); + : argv[0] === 'apple' ? { code: 1, out: 'error: ASC_KEY_ID and ASC_ISSUER_ID are not set' } + : argv[0] === 'play' ? { data: { tracks: [{ track: 'production', releases: [{ name: '1.2.0 (12)', versionCodes: ['12'], status: 'completed' }] }, { track: 'beta', releases: [{ name: '1.3.0', versionCodes: ['13'], status: 'completed' }] }], products: [{ productId: 'coins' }] } } : {}); + const r = resOf(await call('portfolio.status', { projects: [DEMO, '/nope/game'], live: true })) as { apps: J[] }; + expect(r.apps[0]).toMatchObject({ project: DEMO, app: { id: DEMO, name: 'Demo', platforms: { ios: { bundleId: 'com.example.demo' }, android: { packageName: 'com.example.demo' } } }, + check: { ok: true, warnings: ['w'] }, storeErrors: { ios: 'ASC_KEY_ID and ASC_ISSUER_ID are not set' }, ok: false }); + expect(r.apps[0]!.release).toMatchObject({ source: 'live', current: { version: '1.2.0', ios: null, android: { phase: 'live', build: '12' } }, next: { version: '1.3.0', android: { phase: 'testing', track: 'beta' } } }); + expect(r.apps[0]!.catalog).toMatchObject({ checked: 'live', missingAndroid: ['no_ads'], missingIos: [], ok: false }); + expect(r.apps[1]).toMatchObject({ ok: false, summary: null, app: null }); + expect((r.apps[1]!.errors as string[])[0]).toContain('not a folder'); const prog = sent.filter(m => m.method === 'progress').map(m => (m.params as J).n); expect(prog.sort()).toEqual([1, 2]); expect(errOf(await call('portfolio.status', { projects: [] })).code).toBe(ERR.invalidParams); diff --git a/tests/tools.test.ts b/tests/tools.test.ts new file mode 100644 index 00000000..7ea341fc --- /dev/null +++ b/tests/tools.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, test } from 'bun:test'; +import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { delimiter, join } from 'node:path'; +import { childEnv } from '../cli/lib/runner'; +import { detectTools, parseVersion, toolPath } from '../cli/lib/tools'; + +describe('local tools (desktop Dependencies screen)', () => { + test('version banners', () => { + expect(parseVersion('ffmpeg version 7.1.1 Copyright (c) 2000-2025')).toBe('7.1.1'); + expect(parseVersion('ffmpeg version N-118000-g1234abcd-20250101 Copyright')).toBe('N-118000-g1234abcd-20250101'); + expect(parseVersion('Google Chrome for Testing 131.0.6778.85')).toBe('131.0.6778.85'); + expect(parseVersion('Android Debug Bridge version 1.0.41')).toBe('1.0.41'); + expect(parseVersion('git version 2.50.1')).toBe('2.50.1'); + expect(parseVersion(null)).toBeNull(); + }); + test('app-managed folders go first on PATH, also for every child command', () => { + expect(toolPath({ PATH: '/usr/bin', STOREBOUND_TOOL_PATH: '/app/tools/bin' })).toBe(['/app/tools/bin', '/usr/bin'].join(delimiter)); + expect(toolPath({ PATH: '/usr/bin' })).toBe('/usr/bin'); + const before = process.env.STOREBOUND_TOOL_PATH; + process.env.STOREBOUND_TOOL_PATH = '/app/tools/bin'; + try { expect(childEnv().PATH!.startsWith('/app/tools/bin' + delimiter)).toBe(true); } finally { + if (before === undefined) delete process.env.STOREBOUND_TOOL_PATH; else process.env.STOREBOUND_TOOL_PATH = before; + } + }); + test('an app-managed ffmpeg is found first and marked as the app\'s', () => { + if (process.platform === 'win32') return; + const dir = mkdtempSync(join(tmpdir(), 'sb-tools-')); + try { + const f = join(dir, 'ffmpeg'); + writeFileSync(f, '#!/bin/sh\necho "ffmpeg version 7.1.1-test Copyright"\n'); + chmodSync(f, 0o755); + const tools = detectTools({ PATH: '/usr/bin:/bin', STOREBOUND_TOOL_PATH: dir }); + const ff = tools.find(t => t.id === 'ffmpeg')!; + expect(ff).toMatchObject({ found: true, path: f, version: '7.1.1-test', source: 'app', install: { kind: 'download' } }); + expect(tools.map(t => t.id)).toEqual(expect.arrayContaining(['ffmpeg', 'ffprobe', 'chrome', 'adb', 'git'])); + for (const t of tools) if (t.id === 'xcode' || t.id === 'simctl' || t.id === 'adb') expect(t.install.kind).toBe('link'); + } finally { rmSync(dir, { recursive: true, force: true }); } + }); +});