// The app folders of this machine: one list shared by the CLI and the desktop app, ~/.storebound/projects.json // (STOREBOUND_REGISTRY names another file). `storebound desktop` in an app folder, `storebound apps add`, `ws init` and // the desktop's App folders screen add to it; `storebound apps folders` and the desktop show it; `storebound ws ...` // without a storebound.workspace.json works over it. The desktop keeps its per-folder extras (mapped accounts, saved // reads) in its own state by the same id. Only paths and names: no keys, nothing from inside the folders. // { "version": 1, "projects": [{ "id": "<16 hex>", "path": "/abs/folder", "name": "Star Dash", "added": "" }], // "storeApps": [{ "id": "<16 hex>", "store": "apple", "appId": "6400000000", "account": "teamA", "name": "Demo App", // "bundleId": "com.example.demo", "added": "" }] } // storeApps: apps that are live on a store but have no project on this machine (`storebound apps add --store apple // --app-id --account `). The desktop shows them read-only (status, reviews, analytics) under that // profile's account, noted "no local project"; they carry no path. Absent when there are none (older readers ignore it). // Written atomically (temp file, rename); a missing or unreadable file reads as empty (an unreadable one is kept). import { consoleLink } from './console-links'; import { createHash } from 'node:crypto'; import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'; import { homedir } from 'node:os'; import { basename, dirname, join, resolve } from 'node:path'; /** The store sides an entry can be ignored on. */ export type IgnoreStore = 'apple' | 'play'; export const IGNORE_STORES: IgnoreStore[] = ['apple', 'play']; /** `ignored` (optional, on both kinds of entry): the store sides storebound leaves out of watch, events, portfolio reads and the * desktop lists. Both listed = the whole app is ignored. Storebound-side visibility only: nothing changes in the stores. */ export interface RegistryProject { id: string; path: string; name: string; added: string; ignored?: IgnoreStore[] } /** A store app without a local project: store + app id (Apple: the numeric app id; Play: the package name), the * credential profile that reads it. */ export interface StoreOnlyApp { id: string; store: 'apple' | 'play'; appId: string; account: string | null; name: string; bundleId: string | null; added: string; ignored?: IgnoreStore[] } export interface Registry { version: 1; projects: RegistryProject[]; storeApps?: StoreOnlyApp[] } export const registryFile = (env: Record = process.env): string => env.STOREBOUND_REGISTRY || join(homedir(), '.storebound', 'projects.json'); /** The id of a folder the CLI adds: stable per absolute path (the same as `ws desktop export`'s project ids). */ export const folderId = (absPath: string): string => createHash('sha256').update(`project:${absPath}`).digest('hex').slice(0, 16); const ID = /^[0-9a-f]{16}$/; /** The id of a store-only entry: stable per store and app id. */ export const storeAppId = (store: 'apple' | 'play', appId: string): string => createHash('sha256').update(`store:${store}:${appId}`).digest('hex').slice(0, 16); export const APPLE_APP_ID = /^\d{6,12}$/; export const PACKAGE_NAME = /^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+$/; /** The valid, unique, ordered store sides of a raw `ignored` value. */ const parseIgnored = (v: unknown): IgnoreStore[] => (Array.isArray(v) ? IGNORE_STORES.filter(x => v.includes(x)) : []); /** Store-only entries of the file's JSON; malformed ones are dropped. Pure. */ function parseStoreApps(list: unknown): StoreOnlyApp[] { const out: StoreOnlyApp[] = []; if (Array.isArray(list)) for (const x of list) { const o = x as Partial; if (o?.store !== 'apple' && o?.store !== 'play') continue; const appId = typeof o.appId === 'string' ? o.appId.trim() : ''; if (!(o.store === 'apple' ? APPLE_APP_ID : PACKAGE_NAME).test(appId) || out.some(a => a.store === o.store && a.appId === appId)) continue; out.push({ id: storeAppId(o.store, appId), store: o.store, appId, account: typeof o.account === 'string' && o.account ? o.account : null, name: typeof o.name === 'string' && o.name.trim() ? o.name : appId, bundleId: typeof o.bundleId === 'string' && o.bundleId ? o.bundleId : o.store === 'play' ? appId : null, added: typeof o.added === 'string' ? o.added : '', ...(parseIgnored(o.ignored).length ? { ignored: parseIgnored(o.ignored) } : {}) }); } return out; } /** Parses the file's text; drops entries that are not well formed (an id, an absolute path). Pure. */ export function parseRegistry(text: string): Registry { let raw: unknown; try { raw = JSON.parse(text); } catch { return { version: 1, projects: [] }; } const list = (raw as { projects?: unknown })?.projects; const out: RegistryProject[] = []; if (Array.isArray(list)) for (const p of list) { const o = p as Partial; if (typeof o?.path !== 'string' || !o.path.startsWith('/') && !/^[A-Za-z]:[\\/]/.test(o.path)) continue; if (out.some(x => x.path === o.path)) continue; out.push({ id: typeof o.id === 'string' && ID.test(o.id) && !out.some(x => x.id === o.id) ? o.id : folderId(o.path), path: o.path, name: typeof o.name === 'string' && o.name.trim() ? o.name : basename(o.path), added: typeof o.added === 'string' ? o.added : '', ...(parseIgnored(o.ignored).length ? { ignored: parseIgnored(o.ignored) } : {}) }); } const storeApps = parseStoreApps((raw as { storeApps?: unknown })?.storeApps); return storeApps.length ? { version: 1, projects: out, storeApps } : { version: 1, projects: out }; } export function readRegistry(file = registryFile()): Registry { if (!existsSync(file)) return { version: 1, projects: [] }; return parseRegistry(readFileSync(file, 'utf8')); } export function writeRegistry(r: Registry, file = registryFile()): void { mkdirSync(dirname(file), { recursive: true }); if (existsSync(file)) { // a file this version cannot read is kept once instead of being replaced silently try { JSON.parse(readFileSync(file, 'utf8')); } catch { copyFileSync(file, `${file}.unreadable`); } } const tmp = `${file}.tmp-${process.pid}`; writeFileSync(tmp, JSON.stringify({ version: 1, projects: r.projects, ...(r.storeApps?.length ? { storeApps: r.storeApps } : {}) }, null, 2) + '\n'); renameSync(tmp, file); } /** Adds a folder (by absolute path; the same path again only updates an empty name). Pure on the registry. */ export function withFolder(r: Registry, path: string, name: string | undefined, now: string): { registry: Registry; project: RegistryProject; added: boolean } { const abs = resolve(path); const have = r.projects.find(p => p.path === abs); if (have) return { registry: r, project: have, added: false }; const project = { id: folderId(abs), path: abs, name: name?.trim() || configAppName(abs) || basename(abs), added: now }; return { registry: { ...r, version: 1, projects: [...r.projects, project] }, project, added: true }; } /** Adds a store-only app (the same store + app id again updates its account, name and bundle id). Pure. */ export function withStoreApp(r: Registry, a: { store: 'apple' | 'play'; appId: string; account?: string | null; name?: string; bundleId?: string | null }, now: string): { registry: Registry; app: StoreOnlyApp; added: boolean } { const appId = a.appId.trim(); if (!(a.store === 'apple' ? APPLE_APP_ID : PACKAGE_NAME).test(appId)) throw new Error(a.store === 'apple' ? `--app-id ${appId}: the numeric Apple ID of the app (${consoleLink('asc.app-info')})` : `--app-id ${appId}: the Play package name (com.example.app)`); const list = r.storeApps ?? []; const have = list.find(x => x.store === a.store && x.appId === appId); const app: StoreOnlyApp = { id: storeAppId(a.store, appId), store: a.store, appId, account: a.account ?? have?.account ?? null, name: a.name?.trim() || have?.name || appId, bundleId: a.bundleId ?? have?.bundleId ?? (a.store === 'play' ? appId : null), added: have?.added ?? now, ...(have?.ignored?.length ? { ignored: have.ignored } : {}) }; if (have && JSON.stringify(have) === JSON.stringify(app)) return { registry: r, app: have, added: false }; return { registry: { ...r, version: 1, storeApps: [...list.filter(x => x !== have), app] }, app, added: !have }; } /** Removes a store-only app by id or ":". Pure. */ export function withoutStoreApp(r: Registry, key: string): { registry: Registry; removed: StoreOnlyApp | null } { const removed = (r.storeApps ?? []).find(x => x.id === key || `${x.store}:${x.appId}` === key) ?? null; if (!removed) return { registry: r, removed }; const rest = (r.storeApps ?? []).filter(x => x !== removed); const { storeApps: _, ...base } = r; return { registry: rest.length ? { ...base, storeApps: rest } : base, removed }; } // ---- ignore: dormant apps (whole app or one store side) ---- /** The store sides of an entry that are ignored. A store-only entry has one side: its store. */ export const ignoredStores = (e: RegistryProject | StoreOnlyApp): IgnoreStore[] => (e.ignored ?? []).filter(x => !('store' in e) || x === e.store); /** Whether the entry is ignored on `store`, or (no store) entirely: every side it has. */ export function isIgnored(e: RegistryProject | StoreOnlyApp, store?: IgnoreStore): boolean { const have = ignoredStores(e); if (store) return have.includes(store); return 'store' in e ? have.length > 0 : IGNORE_STORES.every(x => have.includes(x)); } type Found = { entry: RegistryProject | StoreOnlyApp; kind: 'project' | 'storeApp' }; /** Finds one entry by id, folder path, ":" or (unique, case-insensitive) name. Throws when it is ambiguous. */ export function findEntry(r: Registry, key: string): Found | null { const all: Found[] = [...r.projects.map(entry => ({ entry, kind: 'project' as const })), ...(r.storeApps ?? []).map(entry => ({ entry, kind: 'storeApp' as const }))]; const abs = ID.test(key) ? '' : resolve(key); const exact = all.filter(x => x.entry.id === key || ('path' in x.entry ? x.entry.path === abs : `${x.entry.store}:${x.entry.appId}` === key)); if (exact.length === 1) return exact[0]!; const named = all.filter(x => x.entry.name.toLowerCase() === key.toLowerCase()); if (named.length > 1) throw new Error(`"${key}" matches ${named.length} apps (${named.map(x => ('path' in x.entry ? x.entry.path : `${x.entry.store}:${x.entry.appId}`)).join(', ')}): use the id, folder or :`); return named[0] ?? null; } /** Ignores (on) or restores one entry, on one store side or on all of it. Pure. */ export function withIgnore(r: Registry, key: string, store: IgnoreStore | undefined, on: boolean): { registry: Registry; entry: RegistryProject | StoreOnlyApp; changed: boolean } { const f = findEntry(r, key); if (!f) throw new Error(`${key}: not in the app list (storebound apps folders)`); if (store && !IGNORE_STORES.includes(store)) throw new Error('--store: apple or play'); const only = f.kind === 'storeApp' ? (f.entry as StoreOnlyApp).store : null; if (only && store && store !== only) throw new Error(`${f.entry.name} is a ${only} app only: it has no ${store} side to ${on ? 'ignore' : 'restore'}`); const sides: IgnoreStore[] = only ? [only] : store ? [store] : IGNORE_STORES; const cur = f.entry.ignored ?? []; const next = IGNORE_STORES.filter(x => (on ? cur.includes(x) || sides.includes(x) : cur.includes(x) && !sides.includes(x))); if (next.join() === cur.join()) return { registry: r, entry: f.entry, changed: false }; const { ignored: _drop, ...rest } = f.entry; const entry = { ...rest, ...(next.length ? { ignored: next } : {}) } as RegistryProject | StoreOnlyApp; const swap = (list: T[]): T[] => list.map(x => (x === f.entry ? entry as T : x)); return { registry: { ...r, projects: f.kind === 'project' ? swap(r.projects) : r.projects, ...(r.storeApps ? { storeApps: f.kind === 'storeApp' ? swap(r.storeApps) : r.storeApps } : {}) }, entry, changed: true, }; } export function setIgnore(key: string, store: IgnoreStore | undefined, on: boolean, file = registryFile()): { entry: RegistryProject | StoreOnlyApp; changed: boolean } { const { registry, entry, changed } = withIgnore(readRegistry(file), key, store, on); if (changed) writeRegistry(registry, file); return { entry, changed }; } /** The folders that are not ignored on `store` (no store: not ignored at all). */ export const activeProjects = (r: Registry, store?: IgnoreStore): RegistryProject[] => r.projects.filter(p => !isIgnored(p, store)); /** The store-only apps that are not ignored. */ export const activeStoreApps = (r: Registry): StoreOnlyApp[] => (r.storeApps ?? []).filter(a => !isIgnored(a)); /** Store ids the config of a folder names (read as text, never run): Apple app ids / bundle ids and the Play package. */ export function configStoreIds(dir: string): { apple: string[]; play: string[] } { const out = { apple: [] as string[], play: [] as string[] }; for (const n of ['storebound.config.ts', 'storebound.config.mts', 'storebound.config.js', 'storebound.config.mjs', 'storebound.config.json']) { let t: string; try { t = readFileSync(join(dir, n), 'utf8'); } catch { continue; } for (const m of t.matchAll(/\b(?:bundleId|appId)["']?\s*:\s*["'`]([A-Za-z0-9._-]+)["'`]/g)) out.apple.push(m[1]!); for (const m of t.matchAll(/\bpackageName["']?\s*:\s*["'`]([A-Za-z]\w*(?:\.[A-Za-z]\w*)+)["'`]/g)) out.play.push(m[1]!); break; } return out; } /** The store ids (Apple app ids and bundle ids, Play packages) of everything ignored on that store. */ export function ignoredStoreIds(r: Registry): { apple: Set; play: Set } { const o = { apple: new Set(), play: new Set() }; for (const p of r.projects) { const ids = configStoreIds(p.path); for (const st of IGNORE_STORES) if (isIgnored(p, st)) for (const id of ids[st]) o[st].add(id); } for (const a of r.storeApps ?? []) if (isIgnored(a)) { o[a.store].add(a.appId); if (a.bundleId) o[a.store].add(a.bundleId); } return o; } export function addStoreApp(a: Parameters[1], file = registryFile()): { app: StoreOnlyApp; added: boolean; changed: boolean } { const cur = readRegistry(file); const { registry, app, added } = withStoreApp(cur, a, new Date().toISOString()); if (registry !== cur) writeRegistry(registry, file); return { app, added, changed: registry !== cur }; } export function removeStoreApp(key: string, file = registryFile()): StoreOnlyApp | null { const { registry, removed } = withoutStoreApp(readRegistry(file), key); if (removed) writeRegistry(registry, file); return removed; } /** Removes a folder by path or id. Pure. */ export function withoutFolder(r: Registry, pathOrId: string): { registry: Registry; removed: RegistryProject | null } { const abs = ID.test(pathOrId) ? '' : resolve(pathOrId); const removed = r.projects.find(p => p.id === pathOrId || p.path === abs) ?? null; return { registry: removed ? { ...r, version: 1, projects: r.projects.filter(p => p !== removed) } : r, removed }; } /** Reads, adds and writes (only when it changed). */ export function addFolder(path: string, name?: string, file = registryFile()): { project: RegistryProject; added: boolean } { const { registry, project, added } = withFolder(readRegistry(file), path, name, new Date().toISOString()); if (added) writeRegistry(registry, file); return { project, added }; } export function removeFolder(pathOrId: string, file = registryFile()): RegistryProject | null { const { registry, removed } = withoutFolder(readRegistry(file), pathOrId); if (removed) writeRegistry(registry, file); return removed; } /** The app name a storebound config gives (`app: { name: '...' }`), read as text (no config load), else null. */ export function configAppName(dir: string): string | null { for (const n of ['storebound.config.ts', 'storebound.config.mts', 'storebound.config.js', 'storebound.config.mjs']) { try { const text = readFileSync(join(dir, n), 'utf8'); const m = /\bapp\s*:\s*\{[^}]*?\bname\s*:\s*(['"`])([^'"`]+)\1/s.exec(text); if (m) return m[2]!.trim(); } catch { /* not this one */ } } return null; } /** Folders with a storebound config under the roots (depth 4; node_modules, .git and _arsiv skipped). */ export function configFolders(roots: string[], depth = 4): string[] { const out: string[] = []; const walk = (d: string, left: number) => { let names: string[] = []; try { names = readdirSync(d); } catch { return; } if (names.some(n => /^storebound\.config\.(ts|mts|js|mjs)$/.test(n))) out.push(d); if (left <= 0) return; for (const n of names) { if (n === 'node_modules' || n.startsWith('.') || n === '_arsiv') continue; const p = join(d, n); try { if (statSync(p).isDirectory()) walk(p, left - 1); } catch { /* unreadable */ } } }; for (const r of roots) walk(r, depth); return [...new Set(out)]; } /** * After a machine move the list keeps the old computer's paths ("folder not found"). For each missing folder: a * config folder under the roots whose last path parts match (some-game, Acme/frontend), else one whose app name is * the same as the entry's name. The id stays, so the desktop's per-app accounts and settings stay linked. Pure. */ export function relinkPlan(r: Registry, candidates: string[], exists: (p: string) => boolean, nameOf: (dir: string) => string | null): { id: string; name: string; from: string; to: string }[] { const parts = (p: string) => p.split(/[\\/]+/).filter(Boolean).map(x => x.toLowerCase()); const taken = new Set(r.projects.filter(p => exists(p.path)).map(p => resolve(p.path).toLowerCase())); const plan: { id: string; name: string; from: string; to: string }[] = []; for (const p of r.projects) { if (exists(p.path)) continue; const want = parts(p.path); const free = candidates.filter(c => !taken.has(resolve(c).toLowerCase())); let best: string | undefined; for (const k of [3, 2, 1]) { const tail = want.slice(-k).join('/'); best = free.find(c => parts(c).slice(-k).join('/') === tail); if (best) break; } best ??= free.find(c => nameOf(c)?.toLowerCase() === p.name.toLowerCase()); if (best) { plan.push({ id: p.id, name: p.name, from: p.path, to: resolve(best) }); taken.add(resolve(best).toLowerCase()); } } return plan; } export function applyRelink(plan: { id: string; to: string }[], file = registryFile()): void { const r = readRegistry(file); for (const s of plan) { const p = r.projects.find(x => x.id === s.id); if (p) p.path = s.to; } writeRegistry(r, file); }