CLI workspace for many apps and studios, credential profiles, release trains (release status / plan)
- storebound.workspace.json: app folders (globs), studios with accounts by credential profile, ignore list, the desktop's pairing overrides; ws init | list | status | check | validate | run | apps import | desktop export/import - credential profiles in ~/.storebound/credentials/<profile>.json or env, --account <profile> on any command - release status / release plan <version>, table or --json; MCP workspace_list, workspace_status, release_status, release_plan (read-only) - pairing rules (cli/lib/identity.ts), release lanes (cli/lib/train.ts) and the per-app status read (cli/lib/app-status.ts) shared with the desktop instead of copied - tests with sanitized fixtures, README, skills, CHANGELOG
This commit is contained in:
parent
02d90de77a
commit
7d70e58d76
26 changed files with 2220 additions and 292 deletions
61
cli/lib/app-status.ts
Normal file
61
cli/lib/app-status.ts
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
// One app's portfolio status: identity, offline config check, catalog parity and (live) the release trains from
|
||||
// `apple status --json` / `play status --json`. Shared by the desktop's `portfolio.status` (cli/serve.ts) and the CLI
|
||||
// workspace (`storebound ws status`, `storebound release status`), so all of them read an app the same way.
|
||||
// Every read is a storebound child command; `exec` runs it (serve tracks it for cancellation, the CLI just awaits it).
|
||||
import type { AppStatus, ProjectSummary } from './desktop-protocol';
|
||||
import { appIdentity, appleProductIds, appleReleases, catalogParity, playProductIds, playReleases, releaseTrains } from './portfolio';
|
||||
import type { RunResult } from './runner';
|
||||
|
||||
export type Exec = (argv: string[], cwd: string) => Promise<RunResult>;
|
||||
|
||||
export const lastLine = (s: string): string => s.trim().split('\n').filter(Boolean).at(-1)?.replace(/^error:\s*/, '') ?? '';
|
||||
|
||||
export const emptyStatus = (project: string): AppStatus =>
|
||||
({ project, ok: false, app: null, summary: null, check: null, release: { source: 'none', current: null, next: null }, catalog: null, storeErrors: {}, errors: [] });
|
||||
|
||||
/** `inspect --json` of a folder; throws "project: <reason>" when the config does not load. */
|
||||
export async function inspectApp(dir: string, exec: Exec): Promise<ProjectSummary> {
|
||||
const r = await exec(['inspect', '--json'], dir);
|
||||
if (r.cancelled) throw new Error('Request cancelled');
|
||||
if (r.code !== 0 || !r.data) throw new Error(`project: ${lastLine(r.out) || 'config could not be loaded'}`);
|
||||
return r.data as ProjectSummary;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fills `e` for the app in `dir`: summary, identity, check (skipped for a store-only app), and with `live` the release
|
||||
* trains and the live catalog parity. Errors are thrown; the caller records them in `e.errors`.
|
||||
*/
|
||||
export async function fillAppStatus(e: AppStatus, dir: string, o: { live: boolean; virtual?: boolean; exec: Exec }): Promise<AppStatus> {
|
||||
const summary = e.summary = await inspectApp(dir, o.exec);
|
||||
e.app = appIdentity(summary);
|
||||
e.catalog = catalogParity(summary);
|
||||
if (o.virtual) e.check = { ok: true, problems: [], warnings: [] };
|
||||
else {
|
||||
const c = await o.exec(['check', '--json'], dir);
|
||||
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: [] };
|
||||
}
|
||||
if (o.live) {
|
||||
const store = async (argv: string[]): Promise<{ data?: unknown; error?: string }> => {
|
||||
const r = await o.exec(argv, dir);
|
||||
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?.error) e.storeErrors.ios = apple.error;
|
||||
if (play?.error) e.storeErrors.android = play.error;
|
||||
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.ok = e.check.ok && !e.storeErrors.ios && !e.storeErrors.android && (e.catalog?.ok ?? true);
|
||||
return e;
|
||||
}
|
||||
|
||||
/** Runs `fn` over `items`, at most `limit` at a time; results in input order. */
|
||||
export async function pool<T, R>(items: T[], limit: number, fn: (x: T, i: number) => Promise<R>): Promise<R[]> {
|
||||
const out = new Array<R>(items.length);
|
||||
let next = 0;
|
||||
const n = Math.max(1, Math.min(limit, items.length));
|
||||
await Promise.all(Array.from({ length: n }, async () => { while (next < items.length) { const i = next++; out[i] = await fn(items[i]!, i); } }));
|
||||
return out;
|
||||
}
|
||||
|
|
@ -7,9 +7,13 @@
|
|||
// "reviewDemoAccount": { "username": "", "password": "" } }
|
||||
// The demo account for App Review can also come from env: REVIEW_DEMO_USER, REVIEW_DEMO_PASSWORD.
|
||||
// 3. ASC_P8 only: ~/.appstoreconnect/private_keys/AuthKey_<ASC_KEY_ID>.p8 (where Xcode / altool keep it)
|
||||
// With a credential profile (`--profile <name>` or STOREBOUND_PROFILE), the profile comes before all of these:
|
||||
// ~/.storebound/credentials/<name>.json (same four names; relative paths are relative to that file; folder:
|
||||
// STOREBOUND_CREDENTIALS_DIR) or env STOREBOUND_PROFILE_<NAME>_<KEY> (NAME upper case, other characters as _).
|
||||
// Many studios / store accounts from one machine: one profile per account; storebound.workspace.json names them.
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { isAbsolute, join, resolve } from 'node:path';
|
||||
|
||||
export interface ServiceAccount { client_email: string; private_key: string; token_uri?: string }
|
||||
export interface AscKey { keyId: string; issuerId: string; pem: string }
|
||||
|
|
@ -23,7 +27,51 @@ function fileStore(root: string): Store {
|
|||
try { return JSON.parse(readFileSync(p, 'utf8')) as Store; } catch (e) { throw new Error(`${p}: ${(e as Error).message}`); }
|
||||
}
|
||||
|
||||
/** The store credential names a profile holds (the same as the env names). */
|
||||
export const PROFILE_KEYS = ['PLAY_SERVICE_ACCOUNT', 'ASC_KEY_ID', 'ASC_ISSUER_ID', 'ASC_P8'] as const;
|
||||
export const PROFILE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
||||
|
||||
export const profileDir = (): string => process.env.STOREBOUND_CREDENTIALS_DIR || join(homedir(), '.storebound', 'credentials');
|
||||
const profileEnvName = (profile: string, key: string): string => `STOREBOUND_PROFILE_${profile.toUpperCase().replace(/[^A-Z0-9]/g, '_')}_${key}`;
|
||||
|
||||
/**
|
||||
* The credentials of one profile as env values (never printed). Env STOREBOUND_PROFILE_<NAME>_<KEY> wins over the
|
||||
* profile file; a relative key path in the file is relative to the file. Throws on a bad name or an unreadable file.
|
||||
*/
|
||||
export function profileEnv(profile: string): Record<string, string> {
|
||||
if (!PROFILE_RE.test(profile)) throw new Error(`credential profile "${profile}": letters, digits, . _ - (max 64)`);
|
||||
const file = join(profileDir(), `${profile}.json`);
|
||||
let stored: Store = {};
|
||||
if (existsSync(file)) {
|
||||
try { stored = JSON.parse(readFileSync(file, 'utf8')) as Store; } catch (e) { throw new Error(`credential profile ${profile}: ${file}: ${(e as Error).message}`); }
|
||||
}
|
||||
const out: Record<string, string> = {};
|
||||
for (const k of PROFILE_KEYS) {
|
||||
const env = process.env[profileEnvName(profile, k)];
|
||||
const v = env || (typeof stored[k] === 'string' ? stored[k] as string : '');
|
||||
if (!v) continue;
|
||||
// a path in the file: relative to the profile folder (inline JSON / PEM stays as it is)
|
||||
const isPath = !env && !/^\s*\{/.test(v) && !/BEGIN PRIVATE KEY/.test(v) && (k === 'PLAY_SERVICE_ACCOUNT' || k === 'ASC_P8');
|
||||
out[k] = isPath && !isAbsolute(v) && !v.startsWith('~') ? resolve(profileDir(), v) : v;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Which stores a profile can reach, and where it comes from. No values. */
|
||||
export function profileStatus(profile: string): { profile: string; source: 'file' | 'env' | 'missing' | 'invalid'; apple: boolean; play: boolean; error?: string } {
|
||||
try {
|
||||
const env = profileEnv(profile);
|
||||
const fromEnv = PROFILE_KEYS.some(k => !!process.env[profileEnvName(profile, k)]);
|
||||
const source = fromEnv ? 'env' : existsSync(join(profileDir(), `${profile}.json`)) ? 'file' : 'missing';
|
||||
return { profile, source, apple: !!(env.ASC_KEY_ID && env.ASC_ISSUER_ID), play: !!env.PLAY_SERVICE_ACCOUNT };
|
||||
} catch (e) {
|
||||
return { profile, source: 'invalid', apple: false, play: false, error: (e as Error).message };
|
||||
}
|
||||
}
|
||||
|
||||
function value(root: string, name: string): string | undefined {
|
||||
const profile = process.env.STOREBOUND_PROFILE;
|
||||
if (profile) { const v = profileEnv(profile)[name]; if (v) return v; }
|
||||
const env = process.env[name];
|
||||
if (env) return env;
|
||||
const v = fileStore(root)[name];
|
||||
|
|
|
|||
200
cli/lib/identity.ts
Normal file
200
cli/lib/identity.ts
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
// One app card per product, across studios and store accounts: the pairing rules the desktop app (apps/desktop) and
|
||||
// the CLI workspace (`storebound ws`, cli/lib/workspace.ts) share. Pure, so tests pin every rule
|
||||
// (apps/desktop/tests/identity.test.ts, tests/workspace.test.ts).
|
||||
//
|
||||
// Inputs: app folders (with the store ids of their config), the apps each store account can see (`apps list`), and
|
||||
// the owner's overrides (manual pairs / unpairs, links of a store app to a folder, studio moves, the ignore list).
|
||||
// Order of matching:
|
||||
// 1. a folder takes the store apps its config names (explicit link > App Store app id > bundle id / package name),
|
||||
// preferring the accounts mapped to the folder;
|
||||
// 2. the remaining store apps pair iOS + Android: manual pairs, then the same bundle id and package name, then a
|
||||
// close id (".ios" / ".android" suffixes, case, punctuation) or the same name; unpairs block an automatic pair;
|
||||
// 3. what is left is a single-platform store-only app.
|
||||
// A store-only app is read through a "store target" (store:ios:<account>:<app id>:<bundle>;android:<account>:<package>).
|
||||
import type { ProjectSummary, StoreApp } from './desktop-protocol';
|
||||
|
||||
/** An app folder as both front ends know it (the desktop's Project carries more fields). */
|
||||
export interface IdProject { id: string; path: string; name: string; playAccount: string | null; appleAccount: string | null }
|
||||
/** A store account: an id (16 hex) and its studio. */
|
||||
export interface IdAccount { id: string; studio?: string | null }
|
||||
|
||||
export interface Pair { ios: string; android: string }
|
||||
export interface Overrides {
|
||||
pairs: Pair[];
|
||||
unpairs: Pair[];
|
||||
links: { key: string; project: string }[];
|
||||
appStudio: { key: string; studio: string }[];
|
||||
ignored: string[];
|
||||
}
|
||||
export const NO_OVERRIDES: Overrides = { pairs: [], unpairs: [], links: [], appStudio: [], ignored: [] };
|
||||
|
||||
/** One app record of one store account. */
|
||||
export interface StoreRef { key: string; account: string; store: 'ios' | 'android'; app: StoreApp }
|
||||
|
||||
export type Pairing = 'folder' | 'manual' | 'id' | 'close' | 'name' | 'single';
|
||||
|
||||
export interface UnifiedApp<P extends IdProject = IdProject> {
|
||||
/** Route and list key: the project id, else the store target. */
|
||||
key: string;
|
||||
/** What reads use: the project id, else the store target ("store:..."). */
|
||||
target: string;
|
||||
name: string;
|
||||
project: P | null;
|
||||
ios: StoreRef | null;
|
||||
android: StoreRef | null;
|
||||
studio: string | null;
|
||||
pairing: Pairing;
|
||||
/** The keys an "ignore" puts on the list ("project:<id>" or "app:<store key>"). */
|
||||
ignoreKeys: string[];
|
||||
ignored: boolean;
|
||||
/** Store icon (data URL) when the folder has none. */
|
||||
storeIcon: string | null;
|
||||
}
|
||||
|
||||
export const refKey = (account: string, a: StoreApp): string => `${a.store}:${account}:${a.id}`;
|
||||
|
||||
/** Store target of a store-only app. */
|
||||
export function storeTarget(ios: StoreRef | null, android: StoreRef | null): string {
|
||||
const parts: string[] = [];
|
||||
if (ios) parts.push(`ios:${ios.account}:${ios.app.id}:${ios.app.bundleId}`);
|
||||
if (android) parts.push(`android:${android.account}:${android.app.id}`);
|
||||
return `store:${parts.join(';')}`;
|
||||
}
|
||||
|
||||
/** "com.example.Puzzle.ios" -> "comexamplepuzzle": ids that differ only by a platform suffix, case or punctuation. */
|
||||
export function normId(id: string): string {
|
||||
return id.toLowerCase().replace(/[._-](ios|iphone|android|droid|app)$/g, '').replace(/[^a-z0-9]/g, '');
|
||||
}
|
||||
export const normName = (n: string): string => n.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]/g, '');
|
||||
|
||||
const samePair = (p: Pair, ios: string, android: string) => p.ios === ios && p.android === android;
|
||||
|
||||
export interface BuildInput<P extends IdProject = IdProject> {
|
||||
projects: P[];
|
||||
/** Store ids of each folder's config (from the offline portfolio read). */
|
||||
summaryOf: (p: P) => ProjectSummary | null | undefined;
|
||||
accounts: IdAccount[];
|
||||
/** The last app list of each account. */
|
||||
storeApps: { account: string; apps: StoreApp[] }[];
|
||||
overrides: Overrides;
|
||||
}
|
||||
|
||||
export function buildApps<P extends IdProject>(i: BuildInput<P>): UnifiedApp<P>[] {
|
||||
const o = i.overrides;
|
||||
const ignoredAccounts = new Set(o.ignored.filter(x => x.startsWith('account:')).map(x => x.slice(8)));
|
||||
const accountStudio = new Map(i.accounts.map(a => [a.id, a.studio ?? null] as const));
|
||||
const known = new Set(i.accounts.map(a => a.id));
|
||||
// every store app of every (not ignored) account
|
||||
const refs: StoreRef[] = [];
|
||||
for (const s of i.storeApps) {
|
||||
if (!known.has(s.account) || ignoredAccounts.has(s.account)) continue;
|
||||
for (const app of s.apps) refs.push({ key: refKey(s.account, app), account: s.account, store: app.store, app });
|
||||
}
|
||||
const used = new Set<string>();
|
||||
const take = (r: StoreRef | null | undefined): StoreRef | null => { if (!r || used.has(r.key)) return null; used.add(r.key); return r; };
|
||||
const studioOverride = new Map(o.appStudio.map(x => [x.key, x.studio] as const));
|
||||
const ignored = new Set(o.ignored);
|
||||
const out: UnifiedApp<P>[] = [];
|
||||
|
||||
// 1. folders
|
||||
for (const p of i.projects) {
|
||||
const s = i.summaryOf(p);
|
||||
const mine = (r: StoreRef) => r.account === (r.store === 'ios' ? p.appleAccount : p.playAccount);
|
||||
const rank = (rs: StoreRef[]) => [...rs].sort((a, b) => Number(mine(b)) - Number(mine(a)));
|
||||
const linked = o.links.filter(l => l.project === p.id).map(l => refs.find(r => r.key === l.key)).filter((r): r is StoreRef => !!r && !used.has(r.key));
|
||||
let ios = take(linked.find(r => r.store === 'ios'));
|
||||
let android = take(linked.find(r => r.store === 'android'));
|
||||
if (!ios && s?.apple) {
|
||||
const free = refs.filter(r => r.store === 'ios' && !used.has(r.key) && !o.links.some(l => l.key === r.key));
|
||||
ios = take(rank(free.filter(r => s.apple!.appId && r.app.id === s.apple!.appId))[0] ?? rank(free.filter(r => r.app.bundleId === s.apple!.bundleId))[0]);
|
||||
}
|
||||
if (!android && s?.play) {
|
||||
const free = refs.filter(r => r.store === 'android' && !used.has(r.key) && !o.links.some(l => l.key === r.key));
|
||||
android = take(rank(free.filter(r => r.app.id === s.play!.packageName))[0]);
|
||||
}
|
||||
const studio = studioOverride.get(`project:${p.id}`)
|
||||
?? (p.appleAccount && accountStudio.get(p.appleAccount)) ?? (p.playAccount && accountStudio.get(p.playAccount))
|
||||
?? (ios && accountStudio.get(ios.account)) ?? (android && accountStudio.get(android.account)) ?? null;
|
||||
out.push({
|
||||
key: p.id, target: p.id, name: p.name, project: p, ios, android, studio, pairing: 'folder',
|
||||
ignoreKeys: [`project:${p.id}`], ignored: ignored.has(`project:${p.id}`), storeIcon: ios?.app.icon ?? android?.app.icon ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
// 2. pairs among the remaining store apps
|
||||
const freeIos = () => refs.filter(r => r.store === 'ios' && !used.has(r.key));
|
||||
const freeAndroid = () => refs.filter(r => r.store === 'android' && !used.has(r.key));
|
||||
const blocked = (a: StoreRef, b: StoreRef) => o.unpairs.some(p => samePair(p, a.key, b.key));
|
||||
const sameStudio = (a: StoreRef, b: StoreRef) => (accountStudio.get(a.account) ?? null) === (accountStudio.get(b.account) ?? null);
|
||||
const pairs: [StoreRef, StoreRef, Pairing][] = [];
|
||||
for (const m of o.pairs) {
|
||||
const a = freeIos().find(r => r.key === m.ios), b = freeAndroid().find(r => r.key === m.android);
|
||||
if (a && b) { take(a); take(b); pairs.push([a, b, 'manual']); }
|
||||
}
|
||||
const auto = (how: Pairing, match: (a: StoreRef, b: StoreRef) => boolean) => {
|
||||
for (const a of freeIos()) {
|
||||
const cands = freeAndroid().filter(b => !blocked(a, b) && match(a, b)).sort((x, y) => Number(sameStudio(a, y)) - Number(sameStudio(a, x)));
|
||||
const b = cands[0];
|
||||
if (b) { take(a); take(b); pairs.push([a, b, how]); }
|
||||
}
|
||||
};
|
||||
auto('id', (a, b) => a.app.bundleId === b.app.id);
|
||||
auto('close', (a, b) => normId(a.app.bundleId) !== '' && normId(a.app.bundleId) === normId(b.app.id));
|
||||
auto('name', (a, b) => normName(a.app.name) !== '' && normName(a.app.name) === normName(b.app.name));
|
||||
|
||||
const storeOnly = (ios: StoreRef | null, android: StoreRef | null, pairing: Pairing) => {
|
||||
const target = storeTarget(ios, android);
|
||||
const keys = [ios, android].filter((r): r is StoreRef => !!r).map(r => r.key);
|
||||
const studio = keys.map(k => studioOverride.get(k)).find(Boolean)
|
||||
?? (ios && accountStudio.get(ios.account)) ?? (android && accountStudio.get(android.account)) ?? null;
|
||||
out.push({
|
||||
key: target, target, name: ios?.app.name ?? android?.app.name ?? '?', project: null, ios, android, studio, pairing,
|
||||
ignoreKeys: keys.map(k => `app:${k}`), ignored: keys.some(k => ignored.has(`app:${k}`)), storeIcon: ios?.app.icon ?? android?.app.icon ?? null,
|
||||
});
|
||||
};
|
||||
for (const [a, b, how] of pairs) storeOnly(a, b, how);
|
||||
// 3. singles
|
||||
for (const r of refs) if (!used.has(r.key)) { used.add(r.key); storeOnly(r.store === 'ios' ? r : null, r.store === 'android' ? r : null, 'single'); }
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Candidates to pair a single-platform app with (the other store's single apps), closest first. */
|
||||
export function pairCandidates<P extends IdProject>(app: UnifiedApp<P>, all: UnifiedApp<P>[]): UnifiedApp<P>[] {
|
||||
if (app.project || (app.ios && app.android)) return [];
|
||||
const want = app.ios ? 'android' : 'ios';
|
||||
const me = (app.ios ?? app.android)!;
|
||||
const score = (x: UnifiedApp<P>) => {
|
||||
const r = (want === 'ios' ? x.ios : x.android)!;
|
||||
return (normId(r.app.bundleId) === normId(me.app.bundleId) ? 4 : 0) + (normName(r.app.name) === normName(me.app.name) ? 2 : 0) + (x.studio === app.studio ? 1 : 0);
|
||||
};
|
||||
return all.filter(x => !x.project && !x.ignored && (want === 'ios' ? x.ios && !x.android : x.android && !x.ios)).sort((a, b) => score(b) - score(a) || a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
/** Overrides after pairing two single store apps by hand (drops an unpair of the same two). */
|
||||
export function withPair(o: Overrides, ios: string, android: string): Overrides {
|
||||
return { ...o, pairs: [...o.pairs.filter(p => p.ios !== ios && p.android !== android), { ios, android }], unpairs: o.unpairs.filter(p => !samePair(p, ios, android)) };
|
||||
}
|
||||
|
||||
/** Overrides after splitting a paired app (keeps it apart from now on). */
|
||||
export function withUnpair(o: Overrides, ios: string, android: string): Overrides {
|
||||
return { ...o, pairs: o.pairs.filter(p => !samePair(p, ios, android)), unpairs: [...o.unpairs.filter(p => !samePair(p, ios, android)), { ios, android }] };
|
||||
}
|
||||
|
||||
export function withIgnored(o: Overrides, keys: string[], on: boolean): Overrides {
|
||||
const set = new Set(o.ignored);
|
||||
for (const k of keys) { if (on) set.add(k); else set.delete(k); }
|
||||
return { ...o, ignored: [...set] };
|
||||
}
|
||||
|
||||
/** Moves an app to a studio (null: back to its accounts' studio). */
|
||||
export function withStudio(o: Overrides, app: UnifiedApp, studio: string | null): Overrides {
|
||||
const keys = app.project ? [`project:${app.project.id}`] : [app.ios?.key, app.android?.key].filter((k): k is string => !!k);
|
||||
const rest = o.appStudio.filter(x => !keys.includes(x.key));
|
||||
return { ...o, appStudio: studio ? [...rest, ...keys.map(key => ({ key, studio }))] : rest };
|
||||
}
|
||||
|
||||
/** Links the store apps of a store-only app to a folder. */
|
||||
export function withLink(o: Overrides, app: UnifiedApp, project: string): Overrides {
|
||||
const keys = [app.ios?.key, app.android?.key].filter((k): k is string => !!k);
|
||||
return { ...o, links: [...o.links.filter(l => !keys.includes(l.key)), ...keys.map(key => ({ key, project }))] };
|
||||
}
|
||||
229
cli/lib/train.ts
Normal file
229
cli/lib/train.ts
Normal file
|
|
@ -0,0 +1,229 @@
|
|||
// Release trains: one version across the App Store and Google Play, on one track of stages
|
||||
// (build -> testing -> review -> live -> rollout). The desktop app's Releases tab (apps/desktop/src/lib/model.ts
|
||||
// re-exports these) and `storebound release status | plan` (cli/release.ts) share this file, so both show the same
|
||||
// stage for the same store state. Pure; the store reads are `apple status --json` / `play status --json`, turned into
|
||||
// StoreRelease rows by cli/lib/portfolio.ts.
|
||||
import type { ReleaseTrain, StoreRelease } from './desktop-protocol';
|
||||
import { cmpVersion } from './portfolio';
|
||||
import type { Finding } from './validate-rules';
|
||||
|
||||
export { cmpVersion };
|
||||
|
||||
export type Tone = 'ok' | 'warn' | 'bad' | 'info' | 'neutral' | 'accent';
|
||||
|
||||
/** Stages of one version on one store, left to right. */
|
||||
export const STAGES = ['build', 'testing', 'review', 'live', 'rollout'] as const;
|
||||
export type Stage = (typeof STAGES)[number];
|
||||
|
||||
export interface Lane {
|
||||
store: 'ios' | 'android';
|
||||
release: StoreRelease | null;
|
||||
/** Index of the stage it is at (-1: not on this store). */
|
||||
at: number;
|
||||
tone: Tone;
|
||||
/** Rollout share 0-1 when live or rolling out (1 = everyone). */
|
||||
share: number | null;
|
||||
/** The store's state word, for a tooltip. */
|
||||
state: string;
|
||||
}
|
||||
|
||||
/** Where a store release is on the track. Rollout counts as the last stage; a full release fills it. */
|
||||
export function laneOf(store: 'ios' | 'android', r: StoreRelease | null, testflightReached = false): Lane {
|
||||
if (!r) return { store, release: null, at: -1, tone: 'neutral', share: null, state: '' };
|
||||
const base = { store, release: r, state: r.state };
|
||||
switch (r.phase) {
|
||||
case 'draft': return { ...base, at: testflightReached ? 1 : 0, tone: testflightReached ? 'info' : 'neutral', share: null };
|
||||
case 'testing': return { ...base, at: 1, tone: 'info', share: null };
|
||||
case 'review': return { ...base, at: 2, tone: 'warn', share: null };
|
||||
case 'approved': return { ...base, at: 2, tone: 'ok', share: null };
|
||||
case 'rejected': return { ...base, at: 2, tone: 'bad', share: null };
|
||||
case 'live': return { ...base, at: 4, tone: 'ok', share: 1 };
|
||||
case 'rollout': return { ...base, at: 4, tone: 'accent', share: r.fraction ?? null };
|
||||
case 'halted': return { ...base, at: 4, tone: 'bad', share: r.fraction ?? null };
|
||||
default: return { ...base, at: 0, tone: 'neutral', share: null };
|
||||
}
|
||||
}
|
||||
|
||||
/** TestFlight builds as `apple testflight status --json` lists them (only what the lanes need). */
|
||||
export interface BetaBuilds { builds: { version: string | null; internal: string | null; external: string | null }[] }
|
||||
|
||||
/** Both lanes of a train; iOS counts TestFlight as reached when a build of that version is in beta testing. */
|
||||
export function trainLanes(t: ReleaseTrain, tf?: BetaBuilds | null): Lane[] {
|
||||
const inBeta = !!tf?.builds.some(b => b.version === t.version && /IN_BETA_TESTING|BETA_APPROVED|READY_FOR_BETA_TESTING/.test(`${b.internal ?? ''} ${b.external ?? ''}`));
|
||||
return [laneOf('ios', t.ios, inBeta), laneOf('android', t.android)];
|
||||
}
|
||||
|
||||
/** Every distinct version of the store releases, newest first, with both stores' release (best phase per store). */
|
||||
export function versionHistory(all: StoreRelease[]): ReleaseTrain[] {
|
||||
const rank: Record<string, number> = { live: 0, rollout: 1, halted: 2, approved: 3, review: 4, rejected: 5, testing: 6, draft: 7, other: 8 };
|
||||
const versions = [...new Set(all.map(r => r.version).filter((v): v is string => !!v))].sort(cmpVersion).reverse();
|
||||
const best = (store: 'ios' | 'android', v: string) => all.filter(r => r.store === store && r.version === v).sort((a, b) => (rank[a.phase] ?? 9) - (rank[b.phase] ?? 9))[0] ?? null;
|
||||
return versions.map(v => ({ version: v, ios: best('ios', v), android: best('android', v) }));
|
||||
}
|
||||
|
||||
/** On one store: the highest version reaching users (live or rolling out) and the highest version above it. */
|
||||
export function storeNow(all: StoreRelease[], store: 'ios' | 'android'): { now: StoreRelease | null; next: StoreRelease | null } {
|
||||
const rs = all.filter((r): r is StoreRelease & { version: string } => r.store === store && !!r.version);
|
||||
const desc = (a: { version: string }, b: { version: string }) => cmpVersion(b.version, a.version);
|
||||
const now = rs.filter(r => r.phase === 'live' || r.phase === 'rollout' || r.phase === 'halted').sort(desc)[0] ?? null;
|
||||
const next = rs.filter(r => !now || cmpVersion(r.version, now.version) > 0).sort(desc)[0] ?? null;
|
||||
return { now, next };
|
||||
}
|
||||
|
||||
// ---- Terminal view of a lane (release status) ----
|
||||
|
||||
const pctText = (x: number | null): string => (x === null ? '' : `${Math.round(x * 1000) / 10}%`);
|
||||
|
||||
/** "review (approved)", "rollout 20%", "rollout (halted) 5%", "live", "-" for a store without this version. */
|
||||
export function laneText(l: Lane): string {
|
||||
if (!l.release) return '-';
|
||||
const stage = STAGES[l.at] ?? 'build';
|
||||
const p = l.release.phase;
|
||||
if (p === 'live') return 'live'; // the whole track filled: everyone has it
|
||||
const word = p === stage || (p === 'draft' && stage === 'build') || (p === 'other' && stage === 'build') ? stage : `${stage} (${p})`;
|
||||
if (p === 'rollout' || p === 'halted') return `${word} ${pctText(l.share)}`.trim();
|
||||
return word;
|
||||
}
|
||||
|
||||
/** "build > testing > [review] > live > rollout" with the reached stage in brackets. */
|
||||
export function trackText(l: Lane): string {
|
||||
return STAGES.map((s, i) => (i === l.at ? `[${s}]` : s)).join(' > ');
|
||||
}
|
||||
|
||||
// ---- Release plan: what is left for one version on each store, in fix order ----
|
||||
|
||||
export type PlanKind = 'config' | 'store' | 'blocker' | 'owner' | 'wait' | 'warning' | 'done';
|
||||
|
||||
export interface PlanStep {
|
||||
kind: PlanKind;
|
||||
text: string;
|
||||
/** The command or console place that does it. Owner steps name what the owner runs; storebound never does them. */
|
||||
fix?: string;
|
||||
code?: string;
|
||||
}
|
||||
|
||||
export interface StorePlan {
|
||||
store: 'ios' | 'android';
|
||||
/** The store's release of this version (best phase), or null when the version is not on the store yet. */
|
||||
release: StoreRelease | null;
|
||||
lane: Lane;
|
||||
steps: PlanStep[];
|
||||
done: boolean;
|
||||
}
|
||||
|
||||
export interface ReleasePlan {
|
||||
version: string;
|
||||
/** Offline config problems (storebound check): both stores need them fixed first. */
|
||||
shared: PlanStep[];
|
||||
ios: StorePlan | null;
|
||||
android: StorePlan | null;
|
||||
/** Every store the app is on has the version live to everyone. */
|
||||
done: boolean;
|
||||
/** What the plan could not read ("unknown, never false"). */
|
||||
unknown: string[];
|
||||
}
|
||||
|
||||
export interface PlanInput {
|
||||
version: string;
|
||||
platforms: { ios: boolean; android: boolean };
|
||||
/** `storebound check --json`, or null when it did not run. */
|
||||
check: { problems: string[]; warnings: string[] } | null;
|
||||
/** `storebound validate --json` findings, or null when it did not run. Validate reads the editable App Store version
|
||||
* and the Play edit, so its blockers count for a version that is not yet in review. */
|
||||
validate: Finding[] | null;
|
||||
/** Every store release read (`AppStatus.release.all`), or null when the stores were not read. */
|
||||
releases: StoreRelease[] | null;
|
||||
storeErrors?: { ios?: string; android?: string };
|
||||
}
|
||||
|
||||
const STORE_NAME = { ios: 'App Store', android: 'Google Play' } as const;
|
||||
|
||||
/** Phases where the store blockers of `validate` still matter (nothing is submitted yet). */
|
||||
const BEFORE_REVIEW = new Set(['none', 'draft', 'testing', 'rejected', 'other']);
|
||||
|
||||
function storeSteps(store: 'ios' | 'android', v: string, r: StoreRelease | null, findings: Finding[] | null): PlanStep[] {
|
||||
const steps: PlanStep[] = [];
|
||||
const phase = r?.phase ?? 'none';
|
||||
const name = STORE_NAME[store];
|
||||
// 1. the version itself on the store
|
||||
if (!r) {
|
||||
steps.push(store === 'ios'
|
||||
? { kind: 'store', text: `${v} is not on ${name} yet: upload a build (Xcode / Transporter), then create the version with its texts`, fix: `storebound apple next-build; storebound apple listing --version ${v} --build <N> --dry` }
|
||||
: { kind: 'store', text: `${v} is not on ${name} yet: upload the AAB to a testing track`, fix: 'storebound play next-version-code; storebound play release <aab> --internal completed --dry' });
|
||||
} else if (phase === 'rejected') {
|
||||
steps.push({ kind: 'blocker', text: `${v} was rejected (${r.state}): read the reason, fix it, then resubmit`, fix: 'review-rejections skill', code: 'rejected' });
|
||||
}
|
||||
// 2. store blockers (validate, already in fix order), only while nothing is submitted
|
||||
const tag = store === 'ios' ? 'apple' : 'play';
|
||||
const mine = (findings ?? []).filter(f => f.store === tag);
|
||||
if (BEFORE_REVIEW.has(phase)) for (const f of mine.filter(x => x.level === 'blocker')) steps.push({ kind: 'blocker', text: f.msg, ...(f.fix ? { fix: f.fix } : {}), code: f.code });
|
||||
// 3. the next move on the track
|
||||
switch (phase) {
|
||||
case 'none': case 'other':
|
||||
break;
|
||||
case 'draft':
|
||||
steps.push(store === 'ios'
|
||||
? { kind: 'owner', text: `submit ${v} for App Review (owner)`, fix: 'App Store Connect > the version > Add for Review' }
|
||||
: r!.track && r!.track !== 'production'
|
||||
? { kind: 'owner', text: `roll out the ${r!.track} draft of ${v} to its testers (owner)`, fix: `Play Console > Test and release > ${r!.track}` }
|
||||
: { kind: 'owner', text: `send the production draft of ${v} for review (owner)`, fix: 'Play Console > Publishing overview > Send for review' });
|
||||
break;
|
||||
case 'testing':
|
||||
steps.push({ kind: 'owner', text: `promote ${v} from ${r!.track ?? 'testing'} to production (owner)`, fix: 'Play Console > Test and release > Production, or `storebound play release <aab> --production draft` in a terminal' });
|
||||
break;
|
||||
case 'rejected':
|
||||
steps.push({ kind: 'owner', text: `resubmit ${v} after the fix (owner)`, fix: store === 'ios' ? 'App Store Connect > App Review > reply / resubmit' : 'Play Console > Publishing overview' });
|
||||
break;
|
||||
case 'review':
|
||||
steps.push({ kind: 'wait', text: `${v} is in review (${r!.state}); nothing to do until the store answers`, fix: store === 'ios' ? 'storebound apple status --wait-review' : 'storebound play status' });
|
||||
break;
|
||||
case 'approved':
|
||||
steps.push({ kind: 'owner', text: `${v} is approved (${r!.state}): release it (owner)`, fix: store === 'ios' ? 'App Store Connect > Release this version, or `storebound apple release --manual-release` in a terminal' : 'Play Console > Publishing overview' });
|
||||
break;
|
||||
case 'rollout':
|
||||
steps.push({ kind: 'owner', text: `${v} reaches ${pctText(r!.fraction) || 'part'} of users: raise or complete the rollout when health is good (owner)`,
|
||||
fix: store === 'ios' ? 'storebound health; then `storebound apple release --phased complete` in a terminal' : 'storebound health; then `storebound play rollout --fraction <x>` or `--complete` in a terminal' });
|
||||
break;
|
||||
case 'halted':
|
||||
steps.push({ kind: 'owner', text: `the rollout of ${v} is halted at ${pctText(r!.fraction) || '?'}: fix and resume, or ship a new version (owner)`,
|
||||
fix: store === 'ios' ? '`storebound apple release --phased resume` in a terminal' : '`storebound play rollout --resume` in a terminal' });
|
||||
break;
|
||||
case 'live':
|
||||
steps.push({ kind: 'done', text: `${v} is live on ${name} for everyone` });
|
||||
break;
|
||||
}
|
||||
// 4. warnings last (they do not block)
|
||||
if (BEFORE_REVIEW.has(phase)) for (const f of mine.filter(x => x.level === 'warn')) steps.push({ kind: 'warning', text: f.msg, ...(f.fix ? { fix: f.fix } : {}), code: f.code });
|
||||
return steps;
|
||||
}
|
||||
|
||||
/**
|
||||
* What is left for `version` on each store, in fix order: config problems (offline check) first, then per store the
|
||||
* version itself, the store blockers (validate), the next move on the track (owner steps are named, never done) and
|
||||
* the warnings. A store whose state could not be read is listed in `unknown`, never planned as "not there".
|
||||
*/
|
||||
export function releasePlan(i: PlanInput): ReleasePlan {
|
||||
const unknown: string[] = [];
|
||||
const shared: PlanStep[] = [];
|
||||
if (i.check) {
|
||||
for (const p of i.check.problems) shared.push({ kind: 'config', text: p, fix: 'storebound check' });
|
||||
} else unknown.push('config check did not run');
|
||||
const trains = i.releases ? versionHistory(i.releases) : [];
|
||||
const train = trains.find(t => cmpVersion(t.version, i.version) === 0 && t.version.split('.').length === i.version.split('.').length)
|
||||
?? trains.find(t => cmpVersion(t.version, i.version) === 0) ?? null;
|
||||
const one = (store: 'ios' | 'android'): StorePlan | null => {
|
||||
if (!i.platforms[store]) return null;
|
||||
const err = i.storeErrors?.[store];
|
||||
if (!i.releases || err) {
|
||||
unknown.push(`${STORE_NAME[store]} state not read${err ? `: ${err}` : ''}`);
|
||||
return { store, release: null, lane: laneOf(store, null), steps: [{ kind: 'store', text: `${STORE_NAME[store]} could not be read: the plan for this store is unknown`, fix: store === 'ios' ? 'storebound apple status' : 'storebound play status' }], done: false };
|
||||
}
|
||||
const r = train?.[store] ?? null;
|
||||
const steps = storeSteps(store, i.version, r, i.validate);
|
||||
return { store, release: r, lane: laneOf(store, r), steps, done: r?.phase === 'live' };
|
||||
};
|
||||
if (!i.validate) unknown.push('store readiness (validate) did not run');
|
||||
const ios = one('ios'), android = one('android');
|
||||
const stores = [ios, android].filter((x): x is StorePlan => !!x);
|
||||
return { version: i.version, shared, ios, android, done: !shared.length && stores.length > 0 && stores.every(s => s.done), unknown };
|
||||
}
|
||||
404
cli/lib/workspace.ts
Normal file
404
cli/lib/workspace.ts
Normal file
|
|
@ -0,0 +1,404 @@
|
|||
// The multi-app workspace: one storebound.workspace.json (or .ts) in a folder above many app folders. It names the
|
||||
// app folders (globs allowed), the studios and their store accounts (by credential profile, never a secret), an
|
||||
// ignore list and the owner's pairing overrides. It is the same model as the desktop app's state (studios, accounts,
|
||||
// projects, overrides: apps/desktop/src-tauri/src/store.rs, workspace.rs), so `storebound ws desktop export | import`
|
||||
// moves it both ways. Pairing of store apps with folders is cli/lib/identity.ts, shared with the desktop.
|
||||
//
|
||||
// {
|
||||
// "apps": ["apps/*", { "path": "games/puzzle", "apple": "acme-apple", "play": "acme-play" }],
|
||||
// "studios": [{ "name": "Acme Games", "color": "indigo", "apps": ["games/*"],
|
||||
// "accounts": [{ "store": "apple", "profile": "acme-apple" }, { "store": "play", "profile": "acme-play" }] }],
|
||||
// "accounts": [{ "store": "play", "profile": "solo-play" }],
|
||||
// "ignore": ["apps/old-*", "app:ios:<account id>:<app id>", "account:solo-play"],
|
||||
// "overrides": { "pairs": [], "unpairs": [], "links": [], "appStudio": [] },
|
||||
// "concurrency": 4
|
||||
// }
|
||||
import { createHash } from 'node:crypto';
|
||||
import { existsSync, readFileSync, statSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
||||
import { CONFIG_NAMES } from './config';
|
||||
import { PROFILE_RE } from './credentials';
|
||||
import type { StoreApp } from './desktop-protocol';
|
||||
import { type IdProject, NO_OVERRIDES, type Overrides, type Pair } from './identity';
|
||||
|
||||
export const WORKSPACE_NAMES = ['storebound.workspace.json', 'storebound.workspace.ts', 'storebound.workspace.js'];
|
||||
/** Colours a studio can carry: the desktop's set (workspace.rs STUDIO_COLORS). */
|
||||
export const STUDIO_COLORS = ['indigo', 'violet', 'rose', 'amber', 'emerald', 'teal', 'sky', 'slate'] as const;
|
||||
export type StudioColor = (typeof STUDIO_COLORS)[number];
|
||||
export type Store = 'apple' | 'play';
|
||||
|
||||
export interface WsAccount {
|
||||
store: Store;
|
||||
/** Credential profile: ~/.storebound/credentials/<profile>.json or env STOREBOUND_PROFILE_<NAME>_* */
|
||||
profile: string;
|
||||
label?: string;
|
||||
/** The desktop's account id (16 hex) when it came from there; else derived from store + profile. */
|
||||
id?: string;
|
||||
}
|
||||
export interface WsStudio { id?: string; name: string; color?: StudioColor; accounts?: WsAccount[]; apps?: string[] }
|
||||
export interface WsAppEntry { path: string; name?: string; apple?: string; play?: string }
|
||||
/** Pairing overrides as the desktop keeps them; a project is named by its folder (relative to the workspace). */
|
||||
export interface WsOverrides { pairs?: Pair[]; unpairs?: Pair[]; links?: { key: string; project: string }[]; appStudio?: { key: string; studio: string }[] }
|
||||
export interface Workspace {
|
||||
apps: (string | WsAppEntry)[];
|
||||
studios?: WsStudio[];
|
||||
accounts?: WsAccount[];
|
||||
ignore?: string[];
|
||||
overrides?: WsOverrides;
|
||||
/** Apps read at the same time (1-8, default 4: the desktop's default). */
|
||||
concurrency?: number;
|
||||
}
|
||||
|
||||
/** For a storebound.workspace.ts: `export default defineWorkspace({ ... })`. */
|
||||
export const defineWorkspace = (w: Workspace): Workspace => w;
|
||||
|
||||
export interface LoadedWorkspace { file: string; root: string; ws: Workspace }
|
||||
|
||||
/** Resolved account: the workspace entry with its id and studio. */
|
||||
export interface Account extends WsAccount { id: string; studio: string | null }
|
||||
export interface Studio { id: string; name: string; color: StudioColor }
|
||||
/** One app folder of the workspace. `id` is its path relative to the workspace (forward slashes). */
|
||||
export interface AppFolder extends IdProject { rel: string; ignored: boolean; studio: string | null; appleProfile: string | null; playProfile: string | null }
|
||||
|
||||
const hex16 = (s: string): string => createHash('sha256').update(s).digest('hex').slice(0, 16);
|
||||
export const accountId = (a: WsAccount): string => (a.id && /^[0-9a-f]{16}$/.test(a.id) ? a.id : hex16(`${a.store}:${a.profile}`));
|
||||
export const slug = (s: string): string => s.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 48) || 'studio';
|
||||
export const studioId = (s: WsStudio): string => s.id || slug(s.name);
|
||||
const posix = (p: string): string => p.split(sep).join('/');
|
||||
|
||||
/** Finds the workspace file in `from` or a folder above it. */
|
||||
export function findWorkspace(from: string, explicit?: string): string | null {
|
||||
if (explicit) {
|
||||
const p = resolve(from, explicit);
|
||||
if (existsSync(p) && statSync(p).isDirectory()) return WORKSPACE_NAMES.map(n => join(p, n)).find(existsSync) ?? null;
|
||||
return existsSync(p) ? p : null;
|
||||
}
|
||||
let d = resolve(from);
|
||||
for (;;) {
|
||||
const hit = WORKSPACE_NAMES.map(n => join(d, n)).find(existsSync);
|
||||
if (hit) return hit;
|
||||
const up = resolve(d, '..');
|
||||
if (up === d) return null;
|
||||
d = up;
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadWorkspace(from: string, explicit?: string): Promise<LoadedWorkspace> {
|
||||
const file = findWorkspace(from, explicit);
|
||||
if (!file) throw new Error(`no storebound.workspace.json in ${from} or above (storebound ws init creates one)`);
|
||||
let raw: unknown;
|
||||
if (file.endsWith('.json')) {
|
||||
try { raw = JSON.parse(readFileSync(file, 'utf8')); } catch (e) { throw new Error(`${file}: ${(e as Error).message}`); }
|
||||
} else raw = ((await import(file)) as { default?: unknown }).default;
|
||||
const problems = checkWorkspace(raw);
|
||||
if (problems.length) throw new Error(`${file}:\n ${problems.join('\n ')}`);
|
||||
return { file, root: resolve(file, '..'), ws: raw as Workspace };
|
||||
}
|
||||
|
||||
const ACCOUNT_KEYS = ['store', 'profile', 'label', 'id'];
|
||||
|
||||
/** Problems of a workspace file (empty = fine). Secrets are refused: only profile names belong here. */
|
||||
export function checkWorkspace(raw: unknown): string[] {
|
||||
const e: string[] = [];
|
||||
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return ['not an object'];
|
||||
const w = raw as Record<string, unknown>;
|
||||
const known = ['$schema', 'apps', 'studios', 'accounts', 'ignore', 'overrides', 'concurrency'];
|
||||
for (const k of Object.keys(w)) if (!known.includes(k)) e.push(`${k}: unknown field (${known.slice(1).join(', ')})`);
|
||||
if (!Array.isArray(w.apps)) e.push('apps: a list of app folders or globs ("apps/*")');
|
||||
else w.apps.forEach((a, i) => {
|
||||
if (typeof a === 'string') { if (!a.trim()) e.push(`apps[${i}]: empty`); return; }
|
||||
if (typeof a !== 'object' || a === null || typeof (a as WsAppEntry).path !== 'string') { e.push(`apps[${i}]: a path or { path, name?, apple?, play? }`); return; }
|
||||
for (const k of Object.keys(a)) if (!['path', 'name', 'apple', 'play'].includes(k)) e.push(`apps[${i}].${k}: unknown`);
|
||||
for (const s of ['apple', 'play'] as const) { const p = (a as WsAppEntry)[s]; if (p !== undefined && (typeof p !== 'string' || !PROFILE_RE.test(p))) e.push(`apps[${i}].${s}: a credential profile name`); }
|
||||
});
|
||||
const account = (a: unknown, where: string) => {
|
||||
if (typeof a !== 'object' || a === null) { e.push(`${where}: { store, profile }`); return; }
|
||||
const o = a as Record<string, unknown>;
|
||||
for (const k of Object.keys(o)) if (!ACCOUNT_KEYS.includes(k)) e.push(`${where}.${k}: unknown (secrets never go here: put them in the credential profile)`);
|
||||
if (o.store !== 'apple' && o.store !== 'play') e.push(`${where}.store: apple or play`);
|
||||
if (typeof o.profile !== 'string' || !PROFILE_RE.test(o.profile)) e.push(`${where}.profile: a credential profile name (letters, digits, . _ -)`);
|
||||
if (o.id !== undefined && (typeof o.id !== 'string' || !/^[0-9a-f]{16}$/.test(o.id))) e.push(`${where}.id: 16 hex characters (the desktop's account id)`);
|
||||
if (o.label !== undefined && (typeof o.label !== 'string' || o.label.length > 60)) e.push(`${where}.label: up to 60 characters`);
|
||||
};
|
||||
if (w.accounts !== undefined) { if (!Array.isArray(w.accounts)) e.push('accounts: a list'); else w.accounts.forEach((a, i) => account(a, `accounts[${i}]`)); }
|
||||
if (w.studios !== undefined) {
|
||||
if (!Array.isArray(w.studios)) e.push('studios: a list');
|
||||
else w.studios.forEach((s, i) => {
|
||||
if (typeof s !== 'object' || s === null) { e.push(`studios[${i}]: { name, color?, accounts?, apps? }`); return; }
|
||||
const o = s as Record<string, unknown>;
|
||||
for (const k of Object.keys(o)) if (!['id', 'name', 'color', 'accounts', 'apps'].includes(k)) e.push(`studios[${i}].${k}: unknown`);
|
||||
if (typeof o.name !== 'string' || !o.name.trim() || o.name.length > 48) e.push(`studios[${i}].name: 1 to 48 characters`);
|
||||
if (o.color !== undefined && !(STUDIO_COLORS as readonly unknown[]).includes(o.color)) e.push(`studios[${i}].color: one of ${STUDIO_COLORS.join(', ')}`);
|
||||
if (o.accounts !== undefined) { if (!Array.isArray(o.accounts)) e.push(`studios[${i}].accounts: a list`); else o.accounts.forEach((a, j) => account(a, `studios[${i}].accounts[${j}]`)); }
|
||||
if (o.apps !== undefined && (!Array.isArray(o.apps) || o.apps.some(x => typeof x !== 'string'))) e.push(`studios[${i}].apps: a list of folder globs`);
|
||||
});
|
||||
}
|
||||
if (w.ignore !== undefined && (!Array.isArray(w.ignore) || w.ignore.some(x => typeof x !== 'string'))) e.push('ignore: a list of folder globs, app:<store app key> or account:<profile>');
|
||||
if (w.concurrency !== undefined && !(Number.isInteger(w.concurrency) && (w.concurrency as number) >= 1 && (w.concurrency as number) <= 8)) e.push('concurrency: 1 to 8');
|
||||
if (w.overrides !== undefined && (typeof w.overrides !== 'object' || w.overrides === null || Array.isArray(w.overrides))) e.push('overrides: { pairs, unpairs, links, appStudio }');
|
||||
// duplicate profiles per store would make two accounts with one id
|
||||
const all = [...((w.accounts as WsAccount[] | undefined) ?? []), ...(((w.studios as WsStudio[] | undefined) ?? []).flatMap(s => s?.accounts ?? []))];
|
||||
const seen = new Set<string>();
|
||||
for (const a of all) { const k = `${a?.store}:${a?.profile}`; if (seen.has(k)) e.push(`account ${k}: listed twice`); seen.add(k); }
|
||||
return e;
|
||||
}
|
||||
|
||||
/** Every account of the workspace (studio accounts and the loose ones) with ids and studios. */
|
||||
export function accountsOf(ws: Workspace): Account[] {
|
||||
const out: Account[] = [];
|
||||
for (const s of ws.studios ?? []) for (const a of s.accounts ?? []) out.push({ ...a, id: accountId(a), studio: studioId(s) });
|
||||
for (const a of ws.accounts ?? []) out.push({ ...a, id: accountId(a), studio: null });
|
||||
return out;
|
||||
}
|
||||
|
||||
export const studiosOf = (ws: Workspace): Studio[] =>
|
||||
(ws.studios ?? []).map((s, i) => ({ id: studioId(s), name: s.name, color: s.color ?? STUDIO_COLORS[i % STUDIO_COLORS.length]! }));
|
||||
|
||||
const isGlob = (p: string): boolean => /[*?[{]/.test(p);
|
||||
const matchAny = (globs: string[], rel: string): boolean => globs.some(g => new Bun.Glob(g.replace(/\/+$/, '')).match(rel));
|
||||
const hasConfig = (dir: string): boolean => CONFIG_NAMES.some(n => existsSync(join(dir, n)));
|
||||
|
||||
/**
|
||||
* The app folders: globs expanded (folders with a storebound config only; node_modules and dot folders skipped), the
|
||||
* ignore globs applied (kept with `ignored: true`, so `ws list --all` can show them), accounts and studio resolved:
|
||||
* an entry's own profiles > the single account of that store in the studio whose `apps` globs match > the single
|
||||
* account of that store in the workspace > none (the folder's own credentials, env or .storebound/).
|
||||
*/
|
||||
export function resolveApps(l: LoadedWorkspace): { apps: AppFolder[]; warnings: string[] } {
|
||||
const { root, ws } = l;
|
||||
const warnings: string[] = [];
|
||||
const found = new Map<string, WsAppEntry>();
|
||||
for (const a of ws.apps) {
|
||||
const entry: WsAppEntry = typeof a === 'string' ? { path: a } : a;
|
||||
const p = entry.path.replace(/^~(?=\/)/, homedir());
|
||||
if (isGlob(p)) {
|
||||
const base = isAbsolute(p) ? '/' : root;
|
||||
const pattern = isAbsolute(p) ? p.slice(1) : p;
|
||||
let hits = 0;
|
||||
for (const m of new Bun.Glob(pattern.replace(/\/+$/, '')).scanSync({ cwd: base, onlyFiles: false, dot: false })) {
|
||||
if (/(^|\/)(node_modules|\.git)(\/|$)/.test(m)) continue;
|
||||
const dir = resolve(base, m);
|
||||
try { if (!statSync(dir).isDirectory()) continue; } catch { continue; }
|
||||
if (!hasConfig(dir)) continue;
|
||||
hits++;
|
||||
if (!found.has(dir)) found.set(dir, { ...entry, path: dir });
|
||||
}
|
||||
if (!hits) warnings.push(`${entry.path}: no app folder (with a storebound config) matches`);
|
||||
} else {
|
||||
const dir = resolve(root, p);
|
||||
if (!existsSync(dir)) { warnings.push(`${entry.path}: folder not found`); continue; }
|
||||
if (!hasConfig(dir)) { warnings.push(`${entry.path}: no storebound.config.ts in it`); continue; }
|
||||
found.set(dir, { ...found.get(dir), ...entry, path: dir });
|
||||
}
|
||||
}
|
||||
const accounts = accountsOf(ws);
|
||||
const byProfile = (store: Store, profile: string | undefined) => (profile ? accounts.find(a => a.store === store && a.profile === profile) : undefined);
|
||||
const ignoreGlobs = (ws.ignore ?? []).filter(x => !/^(app|account|project):/.test(x));
|
||||
const apps: AppFolder[] = [];
|
||||
for (const [dir, entry] of found) {
|
||||
const rel = posix(relative(root, dir)) || '.';
|
||||
const studio = (ws.studios ?? []).find(s => matchAny(s.apps ?? [], rel)) ?? null;
|
||||
const pick = (store: Store): WsAccount | null => {
|
||||
const named = entry[store];
|
||||
// a profile the workspace does not list is still usable (its id is derived the same way)
|
||||
if (named) return byProfile(store, named) ?? { store, profile: named };
|
||||
const inStudio = (studio?.accounts ?? []).filter(a => a.store === store);
|
||||
if (inStudio.length === 1) return inStudio[0]!;
|
||||
const all = accounts.filter(a => a.store === store);
|
||||
return all.length === 1 ? all[0]! : null;
|
||||
};
|
||||
const apple = pick('apple'), play = pick('play');
|
||||
apps.push({ id: rel, rel, path: dir, name: entry.name ?? basename(dir), appleAccount: apple ? accountId(apple) : null, playAccount: play ? accountId(play) : null,
|
||||
appleProfile: apple?.profile ?? null, playProfile: play?.profile ?? null,
|
||||
ignored: matchAny(ignoreGlobs, rel) || (ws.ignore ?? []).includes(`project:${rel}`), studio: studio ? studioId(studio) : null });
|
||||
}
|
||||
apps.sort((a, b) => a.rel.localeCompare(b.rel));
|
||||
return { apps, warnings };
|
||||
}
|
||||
|
||||
/** Desktop-style overrides of the workspace: folder studios from `studios[].apps`, ignore keys with account ids. */
|
||||
export function overridesOf(ws: Workspace, apps: AppFolder[]): Overrides {
|
||||
const o = ws.overrides ?? {};
|
||||
const accounts = accountsOf(ws);
|
||||
const explicit = o.appStudio ?? [];
|
||||
const fromGlobs = apps.filter(a => a.studio && !explicit.some(x => x.key === `project:${a.id}`)).map(a => ({ key: `project:${a.id}`, studio: a.studio! }));
|
||||
const ignored: string[] = [];
|
||||
for (const x of ws.ignore ?? []) {
|
||||
if (x.startsWith('app:') || x.startsWith('project:')) ignored.push(x);
|
||||
else if (x.startsWith('account:')) {
|
||||
const p = x.slice(8);
|
||||
const hit = accounts.filter(a => a.profile === p || a.id === p);
|
||||
ignored.push(...(hit.length ? hit.map(a => `account:${a.id}`) : [x]));
|
||||
}
|
||||
}
|
||||
for (const a of apps) if (a.ignored && !ignored.includes(`project:${a.id}`)) ignored.push(`project:${a.id}`);
|
||||
return { ...NO_OVERRIDES, pairs: o.pairs ?? [], unpairs: o.unpairs ?? [], links: o.links ?? [], appStudio: [...explicit, ...fromGlobs], ignored };
|
||||
}
|
||||
|
||||
/** Filters apps by `--apps a,b` (folder, folder name or app name, case-insensitive; globs allowed). */
|
||||
export function selectApps<T extends { rel: string; name: string }>(apps: T[], names: string[]): { picked: T[]; unknown: string[] } {
|
||||
if (!names.length) return { picked: apps, unknown: [] };
|
||||
const unknown: string[] = [];
|
||||
const picked = new Set<T>();
|
||||
for (const n of names) {
|
||||
const lc = n.toLowerCase();
|
||||
const hits = apps.filter(a => a.rel.toLowerCase() === lc || basename(a.rel).toLowerCase() === lc || a.name.toLowerCase() === lc || (isGlob(n) && new Bun.Glob(n).match(a.rel)));
|
||||
if (!hits.length) unknown.push(n);
|
||||
hits.forEach(h => picked.add(h));
|
||||
}
|
||||
return { picked: apps.filter(a => picked.has(a)), unknown };
|
||||
}
|
||||
|
||||
// ---- Store app lists (ws apps import): a local cache, gitignored with the rest of .storebound/ ----
|
||||
|
||||
export interface StoreAppsCache { profile: string; store: Store; account: string; at: string; apps: StoreApp[] }
|
||||
|
||||
export const cacheDir = (root: string): string => join(root, '.storebound', 'workspace');
|
||||
export const cacheFile = (root: string, a: { store: Store; profile: string }): string => join(cacheDir(root), `apps-${a.store}-${a.profile}.json`);
|
||||
|
||||
export function readStoreApps(root: string, accounts: Account[]): { account: string; apps: StoreApp[]; at: string }[] {
|
||||
const out: { account: string; apps: StoreApp[]; at: string }[] = [];
|
||||
for (const a of accounts) {
|
||||
const f = cacheFile(root, a);
|
||||
if (!existsSync(f)) continue;
|
||||
try {
|
||||
const c = JSON.parse(readFileSync(f, 'utf8')) as StoreAppsCache;
|
||||
if (Array.isArray(c.apps)) out.push({ account: a.id, apps: c.apps, at: c.at });
|
||||
} catch { /* a broken cache is a cache miss */ }
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- The desktop's state (state.json in its data folder) <-> the workspace ----
|
||||
|
||||
export interface DesktopProject { id: string; path: string; name: string; playAccount: string | null; appleAccount: string | null; added: string }
|
||||
export interface DesktopAccount { id: string; label: string; kind: Store; created: string; studio: string | null }
|
||||
export interface DesktopStudio { id: string; name: string; color: string; logo: string | null; created: string }
|
||||
export interface DesktopState {
|
||||
version: number;
|
||||
projects: DesktopProject[];
|
||||
accounts: DesktopAccount[];
|
||||
studios: DesktopStudio[];
|
||||
overrides: Overrides;
|
||||
settings?: unknown;
|
||||
}
|
||||
|
||||
/** Where the desktop app keeps state.json (Tauri app data folder of dev.storebound.desktop). */
|
||||
export function desktopStateFile(env: Record<string, string | undefined> = process.env, platform = process.platform): string {
|
||||
if (env.STOREBOUND_DESKTOP_DATA) return join(env.STOREBOUND_DESKTOP_DATA, 'state.json');
|
||||
const id = 'dev.storebound.desktop';
|
||||
if (platform === 'darwin') return join(homedir(), 'Library', 'Application Support', id, 'state.json');
|
||||
if (platform === 'win32') return join(env.APPDATA ?? join(homedir(), 'AppData', 'Roaming'), id, 'state.json');
|
||||
return join(env.XDG_DATA_HOME ?? join(homedir(), '.local', 'share'), id, 'state.json');
|
||||
}
|
||||
|
||||
/** The desktop's project id of a folder: stable per absolute path (16 hex, like the desktop's own ids). */
|
||||
export const desktopProjectId = (absPath: string): string => hex16(`project:${absPath}`);
|
||||
|
||||
/**
|
||||
* Workspace -> desktop state (format 2). Accounts carry labels only: their keys go into the desktop's keychain from
|
||||
* its Accounts screen (the desktop never reads the profiles). Project keys in the overrides become the desktop's ids.
|
||||
*/
|
||||
export function toDesktopState(ws: Workspace, apps: AppFolder[], now = new Date().toISOString()): DesktopState {
|
||||
const accounts = accountsOf(ws);
|
||||
const idOf = new Map(apps.map(a => [a.id, desktopProjectId(a.path)] as const));
|
||||
const mapKey = (k: string) => (k.startsWith('project:') && idOf.has(k.slice(8)) ? `project:${idOf.get(k.slice(8))}` : k);
|
||||
const o = overridesOf(ws, apps);
|
||||
return {
|
||||
version: 2,
|
||||
projects: apps.map(a => ({ id: idOf.get(a.id)!, path: a.path, name: a.name, playAccount: a.playAccount, appleAccount: a.appleAccount, added: now })),
|
||||
accounts: accounts.map(a => ({ id: a.id, label: a.label ?? a.profile, kind: a.store, created: now, studio: a.studio })),
|
||||
studios: studiosOf(ws).map(s => ({ id: s.id, name: s.name, color: s.color, logo: null, created: now })),
|
||||
overrides: {
|
||||
pairs: o.pairs, unpairs: o.unpairs,
|
||||
links: o.links.map(l => ({ key: l.key, project: idOf.get(l.project) ?? l.project })),
|
||||
appStudio: o.appStudio.map(x => ({ key: mapKey(x.key), studio: x.studio })),
|
||||
ignored: o.ignored.map(mapKey),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A profile name for a desktop account: its label as a slug, made unique per store. */
|
||||
function profileFor(a: DesktopAccount, taken: Set<string>): string {
|
||||
const base = (slug(a.label).slice(0, 56) || 'account');
|
||||
let name = taken.has(base) ? `${base}-${a.kind}` : base;
|
||||
for (let i = 2; taken.has(name); i++) name = `${base}-${a.kind}-${i}`;
|
||||
taken.add(name);
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Desktop state -> workspace. Folders under `root` become relative paths, others stay absolute. Each account becomes
|
||||
* a credential profile name (the owner creates ~/.storebound/credentials/<profile>.json; the desktop's keychain is
|
||||
* never read). Account ids are kept, so the overrides' store app keys stay valid.
|
||||
*/
|
||||
export function fromDesktopState(state: DesktopState, root: string): { ws: Workspace; profiles: { profile: string; store: Store; label: string }[] } {
|
||||
const taken = new Set<string>();
|
||||
const profile = new Map(state.accounts.map(a => [a.id, profileFor(a, taken)] as const));
|
||||
const acc = (a: DesktopAccount): WsAccount => ({ store: a.kind, profile: profile.get(a.id)!, label: a.label, id: a.id });
|
||||
const relOf = new Map(state.projects.map(p => {
|
||||
const r = posix(relative(root, p.path));
|
||||
return [p.id, !r || r.startsWith('..') || isAbsolute(r) ? p.path : r] as const;
|
||||
}));
|
||||
const proj = (k: string) => (k.startsWith('project:') && relOf.has(k.slice(8)) ? `project:${relOf.get(k.slice(8))}` : k);
|
||||
const studios: WsStudio[] = state.studios.map(s => ({ id: s.id, name: s.name, ...((STUDIO_COLORS as readonly string[]).includes(s.color) ? { color: s.color as StudioColor } : {}),
|
||||
accounts: state.accounts.filter(a => a.studio === s.id).map(acc) }));
|
||||
const ignore: string[] = [];
|
||||
for (const x of state.overrides?.ignored ?? []) {
|
||||
if (x.startsWith('account:')) ignore.push(`account:${profile.get(x.slice(8)) ?? x.slice(8)}`);
|
||||
else ignore.push(proj(x));
|
||||
}
|
||||
const ws: Workspace = {
|
||||
apps: state.projects.map(p => {
|
||||
const e: WsAppEntry = { path: relOf.get(p.id)! };
|
||||
if (p.name && p.name !== basename(p.path)) e.name = p.name;
|
||||
if (p.appleAccount && profile.has(p.appleAccount)) e.apple = profile.get(p.appleAccount)!;
|
||||
if (p.playAccount && profile.has(p.playAccount)) e.play = profile.get(p.playAccount)!;
|
||||
return Object.keys(e).length === 1 ? e.path : e;
|
||||
}),
|
||||
studios,
|
||||
accounts: state.accounts.filter(a => !a.studio || !state.studios.some(s => s.id === a.studio)).map(acc),
|
||||
ignore,
|
||||
overrides: {
|
||||
pairs: state.overrides?.pairs ?? [], unpairs: state.overrides?.unpairs ?? [],
|
||||
links: (state.overrides?.links ?? []).map(l => ({ key: l.key, project: relOf.get(l.project) ?? l.project })),
|
||||
appStudio: (state.overrides?.appStudio ?? []).map(x => ({ key: proj(x.key), studio: x.studio })),
|
||||
},
|
||||
};
|
||||
return { ws, profiles: state.accounts.map(a => ({ profile: profile.get(a.id)!, store: a.kind, label: a.label })) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the workspace's desktop state to an existing desktop state: folders by path (an existing project keeps its id
|
||||
* and accounts), accounts and studios by id (existing ones win), overrides as a union. Nothing is removed.
|
||||
*/
|
||||
export function mergeDesktopState(cur: DesktopState, add: DesktopState): { state: DesktopState; added: { projects: number; accounts: number; studios: number; overrides: number } } {
|
||||
const idMap = new Map<string, string>();
|
||||
const projects = [...cur.projects];
|
||||
let np = 0;
|
||||
for (const p of add.projects) {
|
||||
const have = projects.find(x => x.path === p.path);
|
||||
if (have) idMap.set(p.id, have.id);
|
||||
else { projects.push(p); np++; }
|
||||
}
|
||||
const remap = (k: string) => (k.startsWith('project:') && idMap.has(k.slice(8)) ? `project:${idMap.get(k.slice(8))}` : k);
|
||||
const accounts = [...cur.accounts];
|
||||
let na = 0;
|
||||
for (const a of add.accounts) if (!accounts.some(x => x.id === a.id)) { accounts.push(a); na++; }
|
||||
const studios = [...cur.studios];
|
||||
let ns = 0;
|
||||
for (const s of add.studios) if (!studios.some(x => x.id === s.id)) { studios.push(s); ns++; }
|
||||
const co = { ...NO_OVERRIDES, ...cur.overrides };
|
||||
const ao = add.overrides;
|
||||
const uniq = <T>(xs: T[]) => { const seen = new Set<string>(); return xs.filter(x => { const k = JSON.stringify(x); if (seen.has(k)) return false; seen.add(k); return true; }); };
|
||||
const overrides: Overrides = {
|
||||
pairs: uniq([...co.pairs, ...ao.pairs]),
|
||||
unpairs: uniq([...co.unpairs, ...ao.unpairs]),
|
||||
links: uniq([...co.links, ...ao.links.map(l => ({ key: l.key, project: idMap.get(l.project) ?? l.project }))]),
|
||||
appStudio: uniq([...co.appStudio, ...ao.appStudio.map(x => ({ key: remap(x.key), studio: x.studio })).filter(x => !co.appStudio.some(y => y.key === x.key))]),
|
||||
ignored: uniq([...co.ignored, ...ao.ignored.map(remap)]),
|
||||
};
|
||||
const count = (o: Overrides) => o.pairs.length + o.unpairs.length + o.links.length + o.appStudio.length + o.ignored.length;
|
||||
return { state: { ...cur, version: Math.max(cur.version ?? 1, 2), projects, accounts, studios, overrides }, added: { projects: np, accounts: na, studios: ns, overrides: count(overrides) - count(co) } };
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue