diff --git a/.cursor/rules/storebound.mdc b/.cursor/rules/storebound.mdc index 2fb58d16..fb0757a2 100644 --- a/.cursor/rules/storebound.mdc +++ b/.cursor/rules/storebound.mdc @@ -49,4 +49,5 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t - `skills/store-iap-setup/SKILL.md`: Create and price in-app purchases (consumables, non-consumables like "remove ads", coin/gem packs, starter packs) on Google Play and App Store Connect from one product list - `skills/store-preflight/SKILL.md`: Run and read the storebound readiness checks before submitting a mobile game - `skills/store-screenshots/SKILL.md`: Produce store screenshots and the Play feature graphic for a mobile game in every required size and many languages +- `skills/testflight/SKILL.md`: Run TestFlight for a mobile game through the App Store Connect API - `skills/whats-new/SKILL.md`: Write player-facing release notes ("What's new") for a mobile game update from the git log since the last tag diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index dbf4edb2..9782c120 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -51,4 +51,5 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t | `store-iap-setup` | Create and price in-app purchases (consumables, non-consumables like "remove ads", coin/gem packs, starter packs) on Google Play and App Store Connect from one product list | | `store-preflight` | Run and read the storebound readiness checks before submitting a mobile game | | `store-screenshots` | Produce store screenshots and the Play feature graphic for a mobile game in every required size and many languages | +| `testflight` | Run TestFlight for a mobile game through the App Store Connect API | | `whats-new` | Write player-facing release notes ("What's new") for a mobile game update from the git log since the last tag | diff --git a/AGENTS.md b/AGENTS.md index cd0b267d..cf7e1b33 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,6 +49,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t - `skills/store-iap-setup/SKILL.md`: Create and price in-app purchases (consumables, non-consumables like "remove ads", coin/gem packs, starter packs) on Google Play and App Store Connect from one product list - `skills/store-preflight/SKILL.md`: Run and read the storebound readiness checks before submitting a mobile game - `skills/store-screenshots/SKILL.md`: Produce store screenshots and the Play feature graphic for a mobile game in every required size and many languages +- `skills/testflight/SKILL.md`: Run TestFlight for a mobile game through the App Store Connect API - `skills/whats-new/SKILL.md`: Write player-facing release notes ("What's new") for a mobile game update from the git log since the last tag ## Working on storebound itself diff --git a/GEMINI.md b/GEMINI.md index fa776b20..b0821268 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -50,4 +50,5 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t | `store-iap-setup` | Create and price in-app purchases (consumables, non-consumables like "remove ads", coin/gem packs, starter packs) on Google Play and App Store Connect from one product list | | `store-preflight` | Run and read the storebound readiness checks before submitting a mobile game | | `store-screenshots` | Produce store screenshots and the Play feature graphic for a mobile game in every required size and many languages | +| `testflight` | Run TestFlight for a mobile game through the App Store Connect API | | `whats-new` | Write player-facing release notes ("What's new") for a mobile game update from the git log since the last tag | diff --git a/cli/apple/jsonapi.ts b/cli/apple/jsonapi.ts new file mode 100644 index 00000000..72764644 --- /dev/null +++ b/cli/apple/jsonapi.ts @@ -0,0 +1,29 @@ +// JSON:API request builders for App Store Connect. Pure: commands build `Req`s, print them on --dry and send them +// with the client otherwise. Request / response format: https://developer.apple.com/documentation/appstoreconnectapi +import { log } from '../lib/log'; + +export interface Req { method: 'GET' | 'POST' | 'PATCH' | 'DELETE'; path: string; body?: unknown; note?: string } + +export const one = (type: string, id: string) => ({ data: { type, id } }); +export const many = (type: string, ids: string[]) => ({ data: ids.map(id => ({ type, id })) }); + +/** One-line description of a request for dry runs and logs. Attribute values are cut short; `hide` keys (emails, + * passwords) are masked. */ +export function describeReq(r: Req, hide: string[] = ['email', 'demoAccountPassword', 'contactEmail', 'contactPhone']): string { + const attrs = (r.body as { data?: { attributes?: Record } } | undefined)?.data?.attributes; + const show = (k: string, v: unknown) => (hide.includes(k) ? '"***"' : typeof v === 'string' && v.length > 40 ? JSON.stringify(v.slice(0, 37) + '...') : JSON.stringify(v)); + const keys = attrs ? Object.entries(attrs).map(([k, v]) => `${k}=${show(k, v)}`) : []; + return `${r.method} ${r.path}${keys.length ? ` {${keys.join(', ')}}` : ''}${r.note ? ` # ${r.note}` : ''}`; +} + +/** Logs every planned request; sends them in order unless dry. Returns the responses (empty on dry). */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export async function execute(asc: (m: string, p: string, b?: unknown) => Promise, reqs: Req[], o: { dry: boolean; tag: string }): Promise { + const out: unknown[] = []; + for (const r of reqs) { + if (o.dry) { log(o.tag, `would ${describeReq(r)}`); continue; } + out.push(await asc(r.method, r.path, r.body)); + log(o.tag, `${describeReq(r)}: done`); + } + return out; +} diff --git a/cli/apple/testflight.ts b/cli/apple/testflight.ts new file mode 100644 index 00000000..626b55fd --- /dev/null +++ b/cli/apple/testflight.ts @@ -0,0 +1,182 @@ +// TestFlight through the App Store Connect API. +// storebound apple testflight status groups, testers per group, recent builds + beta states +// storebound apple testflight groups [--dry] create the groups of apple.testflight.groups that are missing +// storebound apple testflight testers [--csv f] [--group a,b] [--remove] [--invite] [--dry] [--yes] +// storebound apple testflight what-to-test --build N [--version x.y.z] [--locale en-US,tr] [--text "..."] [--dry] +// storebound apple testflight info [--dry] Test Information + Beta App Review contact / notes +// storebound apple testflight distribute --build N --group a,b [--version x.y.z] [--internal-only] [--submit-review] [--dry] [--yes] +// Testers come from a CSV in .storebound/ (gitignored; never commit tester emails): email, first_name, last_name, +// groups (";"-separated). Emails are masked in every log line. Adding testers makes Apple email TestFlight invitations +// (once the group has a build), so `testers` asks first; `--remove` takes testers out of the managed groups. +// `distribute --submit-review` sends the build to Beta App Review (external groups) after a confirmation; neither +// testers nor external distribution nor the review submission are MCP tools. Pure planning: cli/lib/testflight.ts. +import { existsSync, readFileSync } from 'node:fs'; +import type { Ctx } from '../lib/ctx'; +import { confirm, need } from '../lib/ctx'; +import { reviewContact } from '../lib/credentials'; +import { done, log, warn } from '../lib/log'; +import { textTable } from '../lib/table'; +import { + type ApiBuild, betaDescriptions, betaReadiness, betaReviewReq, buildsWithVersion, type Group, groupFromApi, inviteReq, maskEmail, + parseTesters, pickBuild, planBetaInfo, planBetaReviewDetail, planDistribute, planGroups, planTesters, planWhatToTest, whatToTestFromListing, +} from '../lib/testflight'; +import { type Asc, ascClient, type J } from './asc'; +import { execute } from './jsonapi'; + +const TAG = 'testflight'; +const USAGE = 'usage: storebound apple testflight status | groups | testers | what-to-test --build N | info | distribute --build N --group '; + +async function groups(c: Asc, appId: string): Promise { + return (await c.all(`/v1/apps/${appId}/betaGroups?limit=200`)).map(groupFromApi); +} + +async function findBuild(c: Asc, appId: string, number: string, marketing?: string): Promise { + const q = new URLSearchParams({ 'filter[app]': appId, 'filter[version]': number, 'filter[preReleaseVersion.platform]': 'IOS', include: 'preReleaseVersion,buildBetaDetail', limit: '50' }); + if (marketing) q.set('filter[preReleaseVersion.version]', marketing); + const resp = await c.asc('GET', `/v1/builds?${q}`); + const b = pickBuild(buildsWithVersion(resp), number, marketing); + const detail = (resp.included ?? []).find((x: J) => x.type === 'buildBetaDetails' && x.id === (b as J).relationships?.buildBetaDetail?.data?.id)?.attributes ?? null; + return { ...b, detail }; +} + +export async function run(ctx: Ctx): Promise { + const { config, root, resolve } = ctx.loaded; + const a = ctx.args; + const sub = a._[0]; + if (!sub) throw new Error(USAGE); + const dry = a.has('dry'); + const tf = config.apple?.testflight; + const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId); + const appId = await c.app(); + + if (sub === 'status') { + const gs = await groups(c, appId); + const rows: (string | number)[][] = []; + for (const g of gs) { + const testers = await c.all(`/v1/betaGroups/${g.id}/betaTesters?limit=200`); + const builds = await c.all(`/v1/betaGroups/${g.id}/builds?limit=200`); + rows.push([g.name, g.internal ? 'internal' : 'external', testers.length, g.internal && g.hasAccessToAllBuilds ? 'all' : builds.length, g.publicLinkEnabled ? 'public link on' : '']); + } + console.log(textTable(['group', 'kind', 'testers', 'builds', ''], rows)); + const q = new URLSearchParams({ 'filter[app]': appId, include: 'preReleaseVersion,buildBetaDetail', sort: '-uploadedDate', limit: '8' }); + const resp = await c.asc('GET', `/v1/builds?${q}`); + const details = new Map((resp.included ?? []).filter((x: J) => x.type === 'buildBetaDetails').map((x: J) => [x.id, x.attributes] as const)); + console.log('\n' + textTable(['version', 'build', 'processing', 'internal', 'external', 'uploaded'], buildsWithVersion(resp).map(b => { + const d = details.get((b as J).relationships?.buildBetaDetail?.data?.id) as J; + return [b.marketing ?? '', b.attributes.version ?? '', b.attributes.processingState ?? '', d?.internalBuildState ?? '', d?.externalBuildState ?? '', (b.attributes.uploadedDate ?? '').slice(0, 10)]; + }))); + const missing = (tf?.groups ?? []).filter(w => !gs.some(g => g.name === w.name)).map(w => w.name); + if (missing.length) warn(TAG, `configured but not on App Store Connect: ${missing.join(', ')} (storebound apple testflight groups)`); + return; + } + + if (sub === 'groups') { + const plan = planGroups(appId, await groups(c, appId), tf?.groups ?? []); + if (!tf?.groups?.length) warn(TAG, 'apple.testflight.groups is empty: nothing to create'); + for (const n of plan.existing) log(TAG, `group "${n}": exists`); + await execute(c.asc, plan.create, { dry, tag: TAG }); + done(TAG, dry ? `groups checked (dry run): ${plan.create.length} to create` : `groups done (${plan.create.length} created)`); + return; + } + + if (sub === 'testers') { + const csvPath = resolve(a.get('csv') ?? tf?.testers ?? '.storebound/testers.csv'); + if (!existsSync(csvPath)) throw new Error(`no tester CSV at ${csvPath} (columns: email, first_name, last_name, groups; keep it in .storebound/)`); + const only = a.list('group'); + const want = parseTesters(readFileSync(csvPath, 'utf8'), only.length === 1 ? only[0] : undefined); + const gs = await groups(c, appId); + const existing = new Map(); + const resp = await c.all(`/v1/betaTesters?filter[apps]=${appId}&include=betaGroups&limit=200`); + for (const t of resp) existing.set(String(t.attributes.email ?? '').toLowerCase(), { id: t.id, groupIds: (t.relationships?.betaGroups?.data ?? []).map((g: J) => g.id), state: t.attributes.state }); + const plan = planTesters(gs, existing, want, { remove: a.has('remove'), only }); + if (plan.unknownGroups.length) throw new Error(`unknown group(s): ${plan.unknownGroups.join(', ')} (storebound apple testflight groups creates the configured ones)`); + const internal = gs.filter(g => g.internal && want.some(t => t.groups.includes(g.name))); + if (internal.length) warn(TAG, `internal groups (${internal.map(g => g.name).join(', ')}) only take App Store Connect users of your team (Users and Access)`); + log(TAG, `${want.length} testers in the CSV: ${plan.summary.join(', ')}`); + const reqs = [...plan.create, ...plan.add, ...plan.remove]; + if (!reqs.length && !a.has('invite')) { done(TAG, 'testers up to date'); return; } + if (dry) { await execute(c.asc, reqs, { dry, tag: TAG }); done(TAG, 'testers checked (dry run)'); return; } + if (reqs.length && !(await confirm(ctx, `Apply ${plan.summary.join(', ')}? New testers get a TestFlight invitation email from Apple.`))) return; + await execute(c.asc, reqs, { dry, tag: TAG }); + if (a.has('invite')) { + const fresh = new Map((await c.all(`/v1/betaTesters?filter[apps]=${appId}&limit=200`)).map((t: J) => [String(t.attributes.email ?? '').toLowerCase(), t] as const)); + const pending = want.map(t => fresh.get(t.email)).filter((t): t is J => !!t && ['NOT_INVITED', 'INVITED'].includes(t.attributes.state)); + if (pending.length && await confirm(ctx, `(Re)send the TestFlight invitation email to ${pending.length} tester(s)?`)) + await execute(c.asc, pending.map(t => inviteReq(appId, t.id, maskEmail(String(t.attributes.email)))), { dry: false, tag: TAG }); + } + done(TAG, 'testers done'); + return; + } + + if (sub === 'what-to-test') { + const number = need(a.get('build'), '--build N (the exact build number)'); + const b = await findBuild(c, appId, number, a.get('version')); + let want: Record; + const locales = a.list('locale'); + if (a.get('text')) { + const ls = locales.length ? locales : [config.apple?.primaryLocale ?? config.languages.find(l => l.apple)?.apple ?? 'en-US']; + want = Object.fromEntries(ls.map(l => [l, a.get('text')!])); + } else { + const f = resolve(config.apple?.listing ?? 'store/appstore.md'); + want = whatToTestFromListing(readFileSync(f, 'utf8')); + if (locales.length) want = Object.fromEntries(Object.entries(want).filter(([l]) => locales.includes(l))); + if (!Object.keys(want).length) throw new Error(`${f}: no "### whatToTest" or "### whatsNew" block (storebound whats-new drafts one), or pass --text`); + } + const existing = (await c.all(`/v1/builds/${b.id}/betaBuildLocalizations?limit=200`)).map((l: J) => ({ id: l.id, locale: l.attributes.locale, whatsNew: l.attributes.whatsNew })); + const reqs = planWhatToTest(b.id, existing, want); + if (!reqs.length) { done(TAG, `build ${number}: What to Test up to date (${Object.keys(want).join(', ')})`); return; } + await execute(c.asc, reqs, { dry, tag: TAG }); + done(TAG, dry ? `build ${number}: ${reqs.length} locale(s) to set (dry run)` : `build ${number}: What to Test set for ${reqs.length} locale(s)`); + return; + } + + if (sub === 'info') { + const desc = betaDescriptions(tf, config.languages); + if (!Object.keys(desc).length) warn(TAG, 'apple.testflight.description is not set: external testing needs a Beta App Description per locale'); + const want = Object.fromEntries(Object.entries(desc).map(([locale, description]) => [locale, { description, feedbackEmail: config.app.contactEmail, + privacyPolicyUrl: config.app.privacyPolicyUrl, marketingUrl: config.app.marketingUrl ?? config.app.website }])); + const locs = (await c.all(`/v1/apps/${appId}/betaAppLocalizations?limit=200`)).map((l: J) => ({ id: l.id, locale: l.attributes.locale, attributes: l.attributes })); + const detail = (await c.maybe(`/v1/apps/${appId}/betaAppReviewDetail`))?.data ?? null; + const contact = reviewContact(root); + if (!contact) warn(TAG, 'no reviewContact in .storebound/credentials.json: Beta App Review contact left as it is'); + const reqs = [...planBetaInfo(appId, locs, want), ...planBetaReviewDetail(detail, contact, tf?.reviewNotes ?? config.apple?.info?.reviewNotes)]; + await execute(c.asc, reqs, { dry, tag: TAG }); + done(TAG, reqs.length ? (dry ? `${reqs.length} change(s) (dry run)` : `test information updated (${reqs.length})`) : 'test information up to date'); + return; + } + + if (sub === 'distribute') { + const number = need(a.get('build'), '--build N (the exact build number you uploaded)'); + const names = a.list('group'); + if (!names.length) throw new Error('--group [,]: which beta groups get the build'); + const gs = await groups(c, appId); + const target = names.map(n => gs.find(g => g.name === n) ?? (() => { throw new Error(`unknown group "${n}" (${gs.map(g => g.name).join(', ')})`); })()); + const external = target.filter(g => !g.internal); + if (a.has('internal-only') && external.length) throw new Error(`external group(s) ${external.map(g => g.name).join(', ')}: distribute to external testers from the terminal (asks first)`); + const b = await findBuild(c, appId, number, a.get('version')); + const problems = betaReadiness(b.attributes, b.detail); + if (problems.length) throw new Error(`build ${number}: ${problems.join('; ')}`); + log(TAG, `build ${number} (${b.marketing ?? '?'}): internal ${b.detail?.internalBuildState ?? '?'}, external ${b.detail?.externalBuildState ?? '?'}`); + const inGroups = (await c.all(`/v1/betaGroups?filter[app]=${appId}&filter[builds]=${b.id}&limit=200`)).map((g: J) => g.id); + const reqs = planDistribute(b.id, target, inGroups); + const review = a.has('submit-review') && external.length ? (await c.maybe(`/v1/builds/${b.id}/betaAppReviewSubmission`))?.data ?? null : null; + const wantsReview = a.has('submit-review') && external.length > 0 && !review && !['BETA_APPROVED', 'IN_BETA_REVIEW', 'WAITING_FOR_BETA_REVIEW', 'IN_BETA_TESTING'].includes(b.detail?.externalBuildState); + if (a.has('submit-review') && review) log(TAG, `beta review: already submitted (${review.attributes?.betaReviewState ?? '?'})`); + if (external.length && !a.has('submit-review') && b.detail?.externalBuildState === 'READY_FOR_BETA_SUBMISSION') + warn(TAG, 'external testers only get the build after Beta App Review: add --submit-review (asks first) or submit it in App Store Connect'); + if (dry) { + await execute(c.asc, [...reqs, ...(wantsReview ? [betaReviewReq(b.id)] : [])], { dry, tag: TAG }); + done(TAG, 'distribute checked (dry run)'); + return; + } + if (external.length && reqs.some(r => external.some(g => r.path.includes(g.id))) && !(await confirm(ctx, `Give build ${number} to external group(s) ${external.map(g => g.name).join(', ')}? Testers are notified once Beta App Review approves it.`))) return; + await execute(c.asc, reqs, { dry, tag: TAG }); + if (wantsReview) { + if (await confirm(ctx, `Submit build ${number} to Beta App Review now? Apple reviews it for external testing (Test Information must be complete: storebound apple testflight info).`)) + await execute(c.asc, [betaReviewReq(b.id)], { dry: false, tag: TAG }); + } + done(TAG, `build ${number}: ${reqs.length ? `added to ${reqs.length} group(s)` : 'already in every group'}`); + return; + } + throw new Error(`unknown testflight command "${sub}"\n${USAGE}`); +} diff --git a/cli/index.ts b/cli/index.ts index 55522348..0318a972 100755 --- a/cli/index.ts +++ b/cli/index.ts @@ -38,6 +38,7 @@ const COMMANDS: Record Promise, string]> = { 'apple release': [() => import('./apple/release'), 'phased release on|pause|resume|complete, --manual-release (asks first)'], 'apple next-build': [() => import('./apple/next-build'), 'next safe build number (prints the number)'], 'apple encryption': [() => import('./apple/encryption'), 'export compliance answer for builds, from the config'], + 'apple testflight': [() => import('./apple/testflight'), 'TestFlight: status | groups | testers (CSV in .storebound/) | what-to-test --build N | info | distribute --build N --group g [--submit-review]'], 'icons': [() => import('./icons'), 'App Store / Play / web / adaptive / legacy launcher icons from one artwork'], 'shots capture': [() => import('./shots/capture'), 'raw frames: --source web (playwright) | ios-sim (simctl) | android-emu (adb) | folder; --dry'], 'shots fonts': [() => import('./shots/fonts'), 'download font subsets for the copy (CJK / Arabic / Cyrillic ...)'], diff --git a/cli/init.ts b/cli/init.ts index 55e1c154..fbf4ff96 100644 --- a/cli/init.ts +++ b/cli/init.ts @@ -15,6 +15,7 @@ const FILES: [string, string][] = [ ['declarations.md', 'store/declarations.md'], ['privacy-policy.html', 'store/privacy-policy.html'], ['credentials.example.json', '.storebound/credentials.json'], + ['testers.csv', '.storebound/testers.csv'], ]; export async function run(args: Args): Promise { diff --git a/cli/lib/config.ts b/cli/lib/config.ts index 219c954b..2dbb50d9 100644 --- a/cli/lib/config.ts +++ b/cli/lib/config.ts @@ -3,6 +3,7 @@ import { existsSync } from 'node:fs'; import { dirname, isAbsolute, join, resolve } from 'node:path'; import { validateCapture, validateRecord } from '../shots/devices'; +import { type TfConfig, validateTestflight } from './testflight'; export type ProductType = 'consumable' | 'non_consumable'; @@ -283,6 +284,8 @@ export interface ShipConfig { screenshotTypes?: string[]; /** The app runs on iPad: renders, checks and uploads 13" iPad screenshots (2064 x 2752) and iPad app previews. */ ipad?: boolean; + /** TestFlight beta groups, the tester CSV (in .storebound/) and Test Information (`storebound apple testflight`). */ + testflight?: TfConfig; }; products?: Product[]; dataSafety?: DataSafety; @@ -331,6 +334,7 @@ export function validateConfig(c: unknown): string[] { const enc = cfg.apple.usesNonExemptEncryption; if (enc !== undefined && typeof enc !== 'boolean') e.push('apple.usesNonExemptEncryption: true | false'); if (cfg.apple.screenshotTypes && !cfg.apple.screenshotTypes.every(t => /^APP_[A-Z0-9_]+$/.test(t))) e.push('apple.screenshotTypes: display types like APP_IPHONE_67'); + e.push(...validateTestflight(cfg.apple.testflight)); } if (cfg.ads?.appAdsTxt && !cfg.ads.appAdsTxt.every(l => typeof l === 'string' && l.split(',').length >= 3)) e.push('ads.appAdsTxt: lines like "example-network.com, pub-123, DIRECT, abc123"'); diff --git a/cli/lib/csv.ts b/cli/lib/csv.ts new file mode 100644 index 00000000..f39b6a13 --- /dev/null +++ b/cli/lib/csv.ts @@ -0,0 +1,43 @@ +// Small RFC 4180 CSV reader / writer (quotes, doubled quotes, CR LF, a UTF-8 BOM). Pure. Used for tester lists, +// price sheets and the Play statistics exports. +import { csvCell } from './data-safety'; + +/** Rows of cells. Empty lines are dropped. */ +export function parseCsv(text: string, sep = ','): string[][] { + const rows: string[][] = []; + let row: string[] = []; + let cell = ''; + let quoted = false; + const s = text.replace(/^/, ''); + for (let i = 0; i < s.length; i++) { + const ch = s[i]!; + if (quoted) { + if (ch === '"') { if (s[i + 1] === '"') { cell += '"'; i++; } else quoted = false; } + else cell += ch; + continue; + } + if (ch === '"' && cell === '') { quoted = true; continue; } + if (ch === sep) { row.push(cell); cell = ''; continue; } + if (ch === '\n' || ch === '\r') { + if (ch === '\r' && s[i + 1] === '\n') i++; + row.push(cell); cell = ''; + if (row.some(c => c !== '')) rows.push(row); + row = []; + continue; + } + cell += ch; + } + row.push(cell); + if (row.some(c => c !== '')) rows.push(row); + return rows; +} + +/** Header row -> objects keyed by the lower-cased, trimmed header (spaces and dashes become "_"). */ +export function parseCsvRecords(text: string, sep = ','): Record[] { + const [head, ...rest] = parseCsv(text, sep); + if (!head) return []; + const keys = head.map(h => h.trim().toLowerCase().replace(/[\s-]+/g, '_')); + return rest.map(r => Object.fromEntries(keys.map((k, i) => [k, (r[i] ?? '').trim()]))); +} + +export const toCsv = (rows: (string | number)[][]): string => rows.map(r => r.map(c => csvCell(String(c))).join(',')).join('\n') + '\n'; diff --git a/cli/lib/table.ts b/cli/lib/table.ts new file mode 100644 index 00000000..d2f082cf --- /dev/null +++ b/cli/lib/table.ts @@ -0,0 +1,16 @@ +// Aligned text tables for the terminal and Markdown tables for reports. Pure. + +export function textTable(head: string[], rows: (string | number)[][]): string { + const all = [head, ...rows.map(r => r.map(String))]; + const w = head.map((_, i) => Math.max(...all.map(r => [...(r[i] ?? '')].length))); + const line = (r: string[]) => r.map((c, i) => c + ' '.repeat(w[i]! - [...c].length)).join(' ').trimEnd(); + return [line(head), line(w.map(n => '-'.repeat(n))), ...all.slice(1).map(line)].join('\n'); +} + +const md = (c: string | number) => String(c).replace(/\|/g, '\\|').replace(/\n/g, ' '); +export function mdTable(head: string[], rows: (string | number)[][]): string { + return [`| ${head.map(md).join(' | ')} |`, `|${head.map(() => '---').join('|')}|`, ...rows.map(r => `| ${r.map(md).join(' | ')} |`)].join('\n'); +} + +/** 0.01234 -> "1.23%" */ +export const pct = (x: number | null | undefined, digits = 2): string => (x === null || x === undefined || Number.isNaN(x) ? 'n/a' : `${(x * 100).toFixed(digits)}%`); diff --git a/cli/lib/testflight.ts b/cli/lib/testflight.ts new file mode 100644 index 00000000..cb7d073b --- /dev/null +++ b/cli/lib/testflight.ts @@ -0,0 +1,297 @@ +// TestFlight through the App Store Connect API, as pure planners: what exists (read with GETs) + what the config / CSV +// wants -> the requests to send. The command (cli/apple/testflight.ts) reads, plans, prints the plan on --dry and sends. +// API references (checked October 2026): +// beta groups https://developer.apple.com/documentation/appstoreconnectapi/beta-groups +// beta testers https://developer.apple.com/documentation/appstoreconnectapi/beta-testers +// invitations https://developer.apple.com/documentation/appstoreconnectapi/beta-tester-invitations +// What to Test https://developer.apple.com/documentation/appstoreconnectapi/beta-build-localizations +// beta review https://developer.apple.com/documentation/appstoreconnectapi/beta-app-review-submissions +// test information https://developer.apple.com/documentation/appstoreconnectapi/beta-app-localizations +// https://developer.apple.com/documentation/appstoreconnectapi/beta-app-review-details +import { type Req, many, one } from '../apple/jsonapi'; +import { parseCsvRecords } from './csv'; +import { len } from './copy'; + +/** "What to Test" per build and locale (betaBuildLocalizations.whatsNew). Apple's API docs state no maximum; 4000 is + * assumed (the App Store "What's New" limit). NOT VERIFIED: keep it well below, testers read it on a phone. */ +export const WHAT_TO_TEST_LIMIT = 4000; +/** Beta App Review notes (betaAppReviewDetails.notes): "Review notes have a maximum of 4,000 characters." */ +export const BETA_NOTES_LIMIT = 4000; +/** Beta App Description (betaAppLocalizations.description) shown to external testers. */ +export const BETA_DESCRIPTION_LIMIT = 4000; + +export interface TfGroupSpec { + name: string; + /** Internal group (App Store Connect users of your team; no beta review). Default false = external. */ + internal?: boolean; + /** Internal groups only: every new build is available to the group automatically. */ + allBuilds?: boolean; + /** External groups only: public TestFlight link (anyone with the link can join, up to publicLinkLimit). */ + publicLink?: boolean; + publicLinkLimit?: number; + /** Testers can send feedback (screenshots, comments) from TestFlight. Default true. */ + feedback?: boolean; +} + +export interface TfConfig { + groups?: TfGroupSpec[]; + /** CSV of testers: email, first_name, last_name, groups (";"-separated group names). Must live in .storebound/ + * (gitignored): tester emails are personal data and never go into the repo. Default .storebound/testers.csv. */ + testers?: string; + /** Beta App Description per language id (or one text for every locale); shown to external testers. */ + description?: string | Record; + /** Notes for Beta App Review (where to find what, test account hints). The contact comes from + * .storebound/credentials.json reviewContact like for App Review. */ + reviewNotes?: string; +} + +export interface Group { id: string; name: string; internal: boolean; publicLinkEnabled?: boolean; publicLink?: string | null; hasAccessToAllBuilds?: boolean } + +export const groupFromApi = (g: { id: string; attributes: Record }): Group => ({ + id: g.id, name: String(g.attributes.name ?? ''), internal: g.attributes.isInternalGroup === true, + publicLinkEnabled: g.attributes.publicLinkEnabled as boolean | undefined, publicLink: (g.attributes.publicLink as string | null | undefined) ?? null, + hasAccessToAllBuilds: g.attributes.hasAccessToAllBuilds as boolean | undefined, +}); + +/** Problems with the testflight config. Pure. */ +export function validateTestflight(t: TfConfig | undefined): string[] { + if (!t) return []; + const e: string[] = []; + const names = new Set(); + for (const [i, g] of (t.groups ?? []).entries()) { + const at = `apple.testflight.groups[${i}]`; + if (!g.name || len(g.name) > 50) e.push(`${at}.name: 1-50 characters`); + if (names.has(g.name)) e.push(`${at}.name: duplicate "${g.name}"`); + names.add(g.name); + if (g.internal && (g.publicLink || g.publicLinkLimit !== undefined)) e.push(`${at}: public links are for external groups only`); + if (!g.internal && g.allBuilds !== undefined) e.push(`${at}.allBuilds: internal groups only (external builds go through beta review one by one)`); + if (g.publicLinkLimit !== undefined && !(Number.isInteger(g.publicLinkLimit) && g.publicLinkLimit >= 1 && g.publicLinkLimit <= 10000)) e.push(`${at}.publicLinkLimit: 1-10000`); + } + if (t.testers !== undefined && !/^\.storebound\//.test(t.testers.replace(/^\.\//, ''))) + e.push('apple.testflight.testers: keep the tester CSV in .storebound/ (gitignored); emails never go into the repo'); + return e; +} + +/** POST /v1/betaGroups for every configured group missing on App Store Connect (matched by name). Existing groups are + * never renamed, changed or deleted. */ +export function planGroups(appId: string, existing: Group[], want: TfGroupSpec[]): { create: Req[]; existing: string[] } { + const have = new Set(existing.map(g => g.name)); + const create: Req[] = want.filter(g => !have.has(g.name)).map(g => ({ + method: 'POST', path: '/v1/betaGroups', note: `${g.internal ? 'internal' : 'external'} group "${g.name}"`, + body: { data: { type: 'betaGroups', attributes: { + name: g.name, + ...(g.internal ? { isInternalGroup: true, hasAccessToAllBuilds: g.allBuilds ?? false } : {}), + ...(!g.internal && g.publicLink ? { publicLinkEnabled: true, publicLinkLimitEnabled: g.publicLinkLimit !== undefined, ...(g.publicLinkLimit !== undefined ? { publicLinkLimit: g.publicLinkLimit } : {}) } : {}), + feedbackEnabled: g.feedback ?? true, + }, relationships: { app: one('apps', appId) } } }, + })); + return { create, existing: want.filter(g => have.has(g.name)).map(g => g.name) }; +} + +export interface Tester { email: string; firstName?: string; lastName?: string; groups: string[] } + +const EMAIL = /^[^@\s,;]+@[^@\s,;]+\.[^@\s,;]+$/; + +/** Tester CSV -> testers. Columns (header row, any order): email, first_name (or firstname / first), last_name, + * groups (";"-separated group names; empty = `defaultGroup`). Throws on bad emails or duplicates. */ +export function parseTesters(csv: string, defaultGroup?: string): Tester[] { + const out: Tester[] = []; + const seen = new Set(); + const errors: string[] = []; + for (const [i, r] of parseCsvRecords(csv).entries()) { + const email = (r.email ?? '').toLowerCase(); + if (!EMAIL.test(email)) { errors.push(`row ${i + 2}: "${maskEmail(email)}" is not an email`); continue; } + if (seen.has(email)) { errors.push(`row ${i + 2}: ${maskEmail(email)} listed twice`); continue; } + seen.add(email); + const groups = (r.groups ?? r.group ?? '').split(';').map(s => s.trim()).filter(Boolean); + if (!groups.length && defaultGroup) groups.push(defaultGroup); + out.push({ email, firstName: r.first_name || r.firstname || r.first || undefined, lastName: r.last_name || r.lastname || r.last || undefined, groups }); + } + if (errors.length) throw new Error(`testers CSV: ${errors.join('; ')}`); + return out; +} + +/** "jane.doe@example.com" -> "j***@example.com": emails in logs and MCP output stay readable but not harvestable. */ +export function maskEmail(e: string): string { + const at = e.indexOf('@'); + if (at < 1) return '***'; + return `${e[0]}***${e.slice(at)}`; +} + +export interface TesterPlan { + /** New testers: POST /v1/betaTesters with their groups (Apple emails the invitation once a build is available). */ + create: Req[]; + /** Existing testers added to more groups: POST /v1/betaGroups/{id}/relationships/betaTesters. */ + add: Req[]; + /** Testers in a managed group but not in the CSV (only with remove): DELETE .../relationships/betaTesters. */ + remove: Req[]; + unknownGroups: string[]; + summary: string[]; +} + +/** + * Testers of the managed groups (those named in the CSV or `only`) vs the CSV. `existing` maps a beta tester (by + * lower-case email) to its id and current group ids. Removal only with `remove` (it ends their access to the builds + * of that group; the tester record itself is kept). + */ +export function planTesters(groups: Group[], existing: Map, want: Tester[], o: { remove?: boolean; only?: string[] } = {}): TesterPlan { + const byName = new Map(groups.map(g => [g.name, g] as const)); + const plan: TesterPlan = { create: [], add: [], remove: [], unknownGroups: [], summary: [] }; + const managed = new Set(o.only?.length ? o.only : want.flatMap(t => t.groups)); + for (const n of managed) if (!byName.has(n)) plan.unknownGroups.push(n); + const addTo = new Map(); + for (const t of want) { + const target = t.groups.filter(n => managed.has(n) && byName.has(n)).map(n => byName.get(n)!); + if (!target.length) continue; + const cur = existing.get(t.email); + if (!cur) { + plan.create.push({ method: 'POST', path: '/v1/betaTesters', note: `${maskEmail(t.email)} -> ${target.map(g => g.name).join(', ')}`, + body: { data: { type: 'betaTesters', attributes: { email: t.email, ...(t.firstName ? { firstName: t.firstName } : {}), ...(t.lastName ? { lastName: t.lastName } : {}) }, + relationships: { betaGroups: many('betaGroups', target.map(g => g.id)) } } } }); + continue; + } + for (const g of target) if (!cur.groupIds.includes(g.id)) addTo.set(g.id, [...(addTo.get(g.id) ?? []), cur.id]); + } + for (const [gid, ids] of addTo) { + const g = groups.find(x => x.id === gid)!; + plan.add.push({ method: 'POST', path: `/v1/betaGroups/${gid}/relationships/betaTesters`, body: many('betaTesters', ids), note: `${ids.length} existing tester(s) -> "${g.name}"` }); + } + if (o.remove) { + const wanted = new Map>(); + for (const t of want) for (const n of t.groups) if (byName.has(n)) wanted.set(byName.get(n)!.id, (wanted.get(byName.get(n)!.id) ?? new Set()).add(t.email)); + const drop = new Map(); + for (const [email, cur] of existing) for (const gid of cur.groupIds) { + const g = groups.find(x => x.id === gid); + if (!g || !managed.has(g.name)) continue; + if (!wanted.get(gid)?.has(email)) drop.set(gid, [...(drop.get(gid) ?? []), cur.id]); + } + for (const [gid, ids] of drop) { + const g = groups.find(x => x.id === gid)!; + plan.remove.push({ method: 'DELETE', path: `/v1/betaGroups/${gid}/relationships/betaTesters`, body: many('betaTesters', ids), note: `${ids.length} tester(s) leave "${g.name}"` }); + } + } + plan.summary.push(`${plan.create.length} new tester(s)`, `${plan.add.reduce((n, r) => n + (r.body as { data: unknown[] }).data.length, 0)} added to groups`, + `${plan.remove.reduce((n, r) => n + (r.body as { data: unknown[] }).data.length, 0)} removed from groups`); + return plan; +} + +/** POST /v1/betaTesterInvitations: (re)send the TestFlight invitation email of one tester for this app. */ +export const inviteReq = (appId: string, testerId: string, label: string): Req => ({ method: 'POST', path: '/v1/betaTesterInvitations', note: `invite ${label}`, + body: { data: { type: 'betaTesterInvitations', relationships: { app: one('apps', appId), betaTester: one('betaTesters', testerId) } } } }); + +/** POST /v1/betaGroups/{id}/relationships/builds for every group that does not have the build yet. */ +export function planDistribute(buildId: string, groups: Group[], buildGroupIds: string[]): Req[] { + return groups.filter(g => !buildGroupIds.includes(g.id) && !(g.internal && g.hasAccessToAllBuilds)).map(g => ({ method: 'POST', path: `/v1/betaGroups/${g.id}/relationships/builds`, + body: many('builds', [buildId]), note: `build -> ${g.internal ? 'internal' : 'external'} group "${g.name}"` })); +} + +/** + * "What to Test" texts for TestFlight per App Store locale from the App Store listing file: a `### whatToTest` block + * when a locale section has one, else its `### whatsNew` block (what `storebound whats-new` drafts). Pure. + */ +export function whatToTestFromListing(md: string): Record { + const out: Record = {}; + for (const sec of md.split(/^## /m).slice(1)) { + const locale = sec.split(/[\s·]/)[0]!.trim(); + if (!/^[a-z]{2,3}(-[A-Za-z]{2,4})?$/.test(locale)) continue; + const block = (name: string) => new RegExp(`^### ${name}[^\\n]*\\n\`\`\`[^\\n]*\\n([\\s\\S]*?)\\n\`\`\``, 'm').exec(sec)?.[1]?.trim(); + const text = block('whatToTest') ?? block('whatsNew'); + if (text) out[locale] = text; + } + return out; +} + +/** betaBuildLocalizations to create (POST) or update (PATCH) so the build has exactly these texts. Locales on the + * build that are not in `want` are left alone. Throws when a text is over the limit. */ +export function planWhatToTest(buildId: string, existing: { id: string; locale: string; whatsNew?: string | null }[], want: Record): Req[] { + const tooLong = Object.entries(want).filter(([, t]) => len(t) > WHAT_TO_TEST_LIMIT).map(([l, t]) => `${l} ${len(t)}`); + if (tooLong.length) throw new Error(`What to Test over ${WHAT_TO_TEST_LIMIT} characters: ${tooLong.join(', ')}`); + const have = new Map(existing.map(l => [l.locale, l] as const)); + const out: Req[] = []; + for (const [locale, whatsNew] of Object.entries(want)) { + const cur = have.get(locale); + if (!cur) out.push({ method: 'POST', path: '/v1/betaBuildLocalizations', note: locale, + body: { data: { type: 'betaBuildLocalizations', attributes: { locale, whatsNew }, relationships: { build: one('builds', buildId) } } } }); + else if ((cur.whatsNew ?? '') !== whatsNew) out.push({ method: 'PATCH', path: `/v1/betaBuildLocalizations/${cur.id}`, note: locale, + body: { data: { type: 'betaBuildLocalizations', id: cur.id, attributes: { whatsNew } } } }); + } + return out; +} + +/** POST /v1/betaAppReviewSubmissions: send one build to Beta App Review (needed once per version for external + * testing; later builds of the same version are often approved automatically). */ +export const betaReviewReq = (buildId: string): Req => ({ method: 'POST', path: '/v1/betaAppReviewSubmissions', note: 'submit for Beta App Review', + body: { data: { type: 'betaAppReviewSubmissions', relationships: { build: one('builds', buildId) } } } }); + +/** Build states in which a build can be tested / sent to beta review. */ +export function betaReadiness(b: { processingState?: string; expired?: boolean; usesNonExemptEncryption?: boolean | null }, detail: { externalBuildState?: string; internalBuildState?: string } | null): string[] { + const p: string[] = []; + if (b.processingState !== 'VALID') p.push(`processing state ${b.processingState ?? 'unknown'} (wait for VALID)`); + if (b.expired) p.push('expired (TestFlight builds expire after 90 days)'); + if (b.usesNonExemptEncryption === null || b.usesNonExemptEncryption === undefined) { + if (detail?.internalBuildState === 'MISSING_EXPORT_COMPLIANCE' || detail?.externalBuildState === 'MISSING_EXPORT_COMPLIANCE') + p.push('export compliance missing (storebound apple encryption --build N)'); + } + return p; +} + +export interface BetaInfo { description?: string; feedbackEmail?: string; privacyPolicyUrl?: string; marketingUrl?: string } + +/** Test Information per locale (betaAppLocalizations): POST missing locales, PATCH changed fields. Apple requires a + * description on every beta app localization before a build can go to Beta App Review; fields cannot be cleared. */ +export function planBetaInfo(appId: string, existing: { id: string; locale: string; attributes: BetaInfo }[], want: Record): Req[] { + const have = new Map(existing.map(l => [l.locale, l] as const)); + const out: Req[] = []; + for (const [locale, w] of Object.entries(want)) { + const attrs = Object.fromEntries(Object.entries(w).filter(([, v]) => v !== undefined && v !== '')) as BetaInfo; + if (attrs.description && len(attrs.description) > BETA_DESCRIPTION_LIMIT) throw new Error(`beta description ${locale}: over ${BETA_DESCRIPTION_LIMIT} characters`); + const cur = have.get(locale); + if (!cur) { out.push({ method: 'POST', path: '/v1/betaAppLocalizations', note: locale, body: { data: { type: 'betaAppLocalizations', attributes: { locale, ...attrs }, relationships: { app: one('apps', appId) } } } }); continue; } + const changed = Object.fromEntries(Object.entries(attrs).filter(([k, v]) => (cur.attributes as Record)[k] !== v)); + if (Object.keys(changed).length) out.push({ method: 'PATCH', path: `/v1/betaAppLocalizations/${cur.id}`, note: locale, body: { data: { type: 'betaAppLocalizations', id: cur.id, attributes: changed } } }); + } + return out; +} + +export interface ReviewContactLike { firstName: string; lastName: string; phone: string; email: string } + +/** Beta App Review contact + notes (PATCH /v1/betaAppReviewDetails/{id}; the record exists for every app). */ +export function planBetaReviewDetail(detail: { id: string; attributes: Record } | null, contact: ReviewContactLike | null, notes?: string): Req[] { + if (!detail) return []; + if (notes && len(notes) > BETA_NOTES_LIMIT) throw new Error(`beta review notes: over ${BETA_NOTES_LIMIT} characters`); + const want: Record = { + ...(contact ? { contactFirstName: contact.firstName, contactLastName: contact.lastName, contactPhone: contact.phone, contactEmail: contact.email } : {}), + ...(notes ? { notes } : {}), + }; + const changed = Object.fromEntries(Object.entries(want).filter(([k, v]) => v && detail.attributes[k] !== v)); + return Object.keys(changed).length ? [{ method: 'PATCH', path: `/v1/betaAppReviewDetails/${detail.id}`, note: 'Beta App Review contact / notes', + body: { data: { type: 'betaAppReviewDetails', id: detail.id, attributes: changed } } }] : []; +} + +export interface ApiBuild { id: string; attributes: { version?: string; processingState?: string; expired?: boolean; usesNonExemptEncryption?: boolean | null; uploadedDate?: string }; marketing?: string } + +/** The one build with this number (CFBundleVersion), optionally of one marketing version. Never "the latest". */ +export function pickBuild(builds: ApiBuild[], number: string, marketing?: string): ApiBuild { + const hits = builds.filter(b => b.attributes.version === number && (!marketing || b.marketing === marketing)); + if (!hits.length) throw new Error(`no build ${number}${marketing ? ` of version ${marketing}` : ''} on App Store Connect (still processing? storebound apple status)`); + if (hits.length > 1) throw new Error(`build number ${number} exists for several versions (${hits.map(b => b.marketing ?? '?').join(', ')}): add --version x.y.z`); + return hits[0]!; +} + +/** Builds response with include=preReleaseVersion -> builds tagged with their marketing version. */ +export function buildsWithVersion(resp: { data?: ApiBuild[]; included?: { type: string; id: string; attributes?: { version?: string } }[] }): ApiBuild[] { + const pre = new Map((resp.included ?? []).filter(x => x.type === 'preReleaseVersions').map(x => [x.id, x.attributes?.version] as const)); + return (resp.data ?? []).map(b => ({ ...b, marketing: pre.get((b as unknown as { relationships?: { preReleaseVersion?: { data?: { id: string } } } }).relationships?.preReleaseVersion?.data?.id ?? '') })); +} + +/** Beta App Description per App Store locale from the config (a string = every locale). */ +export function betaDescriptions(t: TfConfig | undefined, langs: { id: string; apple?: string }[]): Record { + if (!t?.description) return {}; + const out: Record = {}; + for (const l of langs) { + if (!l.apple) continue; + const d = typeof t.description === 'string' ? t.description : t.description[l.id]; + if (d) out[l.apple] = d; + } + return out; +} diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index a555d214..f3f5c0c8 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -129,12 +129,29 @@ export const TOOLS: ToolDef[] = [ description: 'Sync app preview videos per locale to the editable App Store version (checked locally first; MD5-idempotent, changed sets are replaced; poster frame time code). Not public until the version is submitted and released. Slow: prefer the terminal with a log.', props: { only, poster: { type: 'integer', minimum: 0, maximum: 29, description: 'Poster frame second (default shots.video.poster or 5)' } }, args: i => [...opt('only', i.only), ...opt('poster', i.poster)] }, + { name: 'apple_testflight_status', title: 'TestFlight status', command: ['apple', 'testflight', 'status'], write: false, network: true, + description: 'Read-only TestFlight overview: beta groups (internal / external, tester and build counts, public link), recent builds with processing, internal and external beta states.' }, + { name: 'apple_testflight_groups', title: 'Create TestFlight groups', command: ['apple', 'testflight', 'groups'], write: true, network: true, idempotent: true, + description: 'Create the beta groups of apple.testflight.groups that are missing on App Store Connect (matched by name; existing groups are never changed or deleted). Sends nothing to testers.' }, + { name: 'apple_testflight_what_to_test', title: 'TestFlight What to Test', command: ['apple', 'testflight', 'what-to-test'], write: true, network: true, idempotent: true, + description: 'Set "What to Test" (betaBuildLocalizations) of one build, by its exact number, per locale from the App Store listing file (### whatToTest, else ### whatsNew) or from text.', + props: { build: { type: 'string', pattern: '^[0-9][0-9.]*$', description: 'Exact build number (CFBundleVersion) you uploaded' }, version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$', description: 'Marketing version when the build number repeats' }, + locale: { type: 'string', description: 'Comma-separated App Store locales (default: every locale with text)' }, text: { type: 'string', description: 'Same text for the given locales instead of the listing file' } }, + required: ['build'], args: i => [...opt('build', i.build), ...opt('version', i.version), ...opt('locale', i.locale), ...opt('text', i.text)] }, + { name: 'apple_testflight_info', title: 'TestFlight test information', command: ['apple', 'testflight', 'info'], write: true, network: true, idempotent: true, + description: 'Beta App Description per locale (apple.testflight.description), feedback email, privacy and marketing URLs, and the Beta App Review contact (.storebound/credentials.json) and notes. Needed before external testing.' }, + { name: 'apple_testflight_distribute', title: 'Build to internal TestFlight groups', command: ['apple', 'testflight', 'distribute'], write: true, network: true, idempotent: true, + description: 'Add one build (exact number) to INTERNAL beta groups (your App Store Connect team; they get the TestFlight notification). External groups and Beta App Review submissions are owner-only terminal commands.', + props: { build: { type: 'string', pattern: '^[0-9][0-9.]*$', description: 'Exact build number you uploaded' }, groups: { type: 'string', description: 'Comma-separated internal group names' }, + version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$' } }, + required: ['build', 'groups'], args: i => [...opt('build', i.build), ...opt('group', i.groups), ...opt('version', i.version), '--internal-only'] }, { name: 'icons', title: 'Generate icons', command: ['icons'], write: true, network: false, idempotent: true, description: 'Write every store / launcher / web icon from the artwork in the config (local files, needs ffmpeg).' }, ]; /** CLI flags / commands that must never be reachable through MCP. Tests assert none of the tools can produce them. */ -export const FORBIDDEN_ARGS = ['--yes', '--manual-release', '--cancel-submission', '--production', 'rollout', 'resume', 'complete']; +export const FORBIDDEN_ARGS = ['--yes', '--manual-release', '--cancel-submission', '--production', 'rollout', 'resume', 'complete', + '--submit-review', '--remove', '--invite', 'testers']; export function inputSchema(t: ToolDef): Record { const props: Record = { ...(t.props ?? {}) }; diff --git a/skills/appstore-first-release/SKILL.md b/skills/appstore-first-release/SKILL.md index 8d410edb..4e9a1744 100644 --- a/skills/appstore-first-release/SKILL.md +++ b/skills/appstore-first-release/SKILL.md @@ -35,8 +35,9 @@ of a first version is the owner's click. Shared agent rules: `docs/agents-core.m automatic. `MARKETING_VERSION` / `CURRENT_PROJECT_VERSION` overrides beat the project values. Take the build number from `storebound apple next-build` right before archiving and **note it**: every later step selects that exact build, never "the latest". Processing takes 5-30 min (`storebound apple status` shows VALID). -6. **UI · TestFlight.** Create an internal group with "access to all builds" (hasAccessToAllBuilds) once: every new - build reaches the testers automatically. Sandbox testers: Users and Access > Sandbox. +6. **API · TestFlight.** Put an internal group with `allBuilds: true` in `apple.testflight.groups` and run + `storebound apple testflight groups`: every new build reaches the team automatically. External testers, What to + Test, Test Information and Beta App Review: the testflight skill. Sandbox testers stay UI: Users and Access > Sandbox. 7. **API · Version + text.** Fill `store/appstore.md`, then `storebound apple listing --version 1.0.0 --build 3` (version, copyright, MANUAL release, the build with exactly that number, name / subtitle / privacy URL, description / keywords / promo / URLs). Then `storebound apple release --phased on`: manual release + phased diff --git a/skills/store-preflight/SKILL.md b/skills/store-preflight/SKILL.md index 70d20730..160550ed 100644 --- a/skills/store-preflight/SKILL.md +++ b/skills/store-preflight/SKILL.md @@ -39,4 +39,5 @@ Each line: number, level (`BLOCKER`, `warn`, `ok`), store, message, and a `fix:` ## What validate cannot see (UI-only, check by hand) App Privacy labels published, Play App content declarations (ads, target audience, content rating, advertising ID), -agreements / tax / banking, TestFlight groups, countries for production on Play. Tell the owner which are still open. +agreements / tax / banking, countries for production on Play. (TestFlight groups and testers: `storebound apple +testflight status`.) Tell the owner which are still open. diff --git a/skills/testflight/SKILL.md b/skills/testflight/SKILL.md new file mode 100644 index 00000000..6dc64fe7 --- /dev/null +++ b/skills/testflight/SKILL.md @@ -0,0 +1,79 @@ +--- +name: testflight +description: Run TestFlight for a mobile game through the App Store Connect API - beta groups (internal / external, public links), testers from a CSV that never enters git, adding a build by its exact number to groups, "What to Test" per locale from the release notes, Test Information, and the Beta App Review submission the owner confirms. Use when the user wants testers on a build, sets up beta groups, writes What to Test, or asks why external testers do not see a build. +--- + +# TestFlight + +CLI: `storebound apple testflight ` (or `bunx storebound` +in a project that has it). Every write has `--dry`; run it first and show the plan. API references are cited at the top +of `cli/lib/testflight.ts` (developer.apple.com/documentation/appstoreconnectapi: beta groups, beta testers, beta build +localizations, beta app localizations, beta app review submissions). + +## Prerequisites +- The build is uploaded and processed (`storebound apple status`, `VALID`), with export compliance answered + (`storebound apple encryption --build N`, export-compliance skill). A build missing it shows + `MISSING_EXPORT_COMPLIANCE` and nobody can test it. +- API key role Admin or App Manager. + +## 1. Groups (config, no emails) +```ts +apple: { + testflight: { + groups: [ + { name: 'Team', internal: true, allBuilds: true }, // App Store Connect users of your team, no review + { name: 'Friends' }, // external, by email, Beta App Review first + { name: 'Public', publicLink: true, publicLinkLimit: 500 }, + ], + description: { en: 'Match tiles, clear 60 levels.', tr: '...' }, // Beta App Description per language id + reviewNotes: 'No login needed. IAPs are sandbox purchases.', + }, +}, +``` +`storebound apple testflight groups --dry`, then without `--dry`. Groups are matched by name; storebound never renames, +changes or deletes a group. + +## 2. Testers (CSV in .storebound/, never in git) +- Columns: `email,first_name,last_name,groups` (groups separated by `;`). Default path `.storebound/testers.csv` + (gitignored); the config refuses a path outside `.storebound/`. Never paste tester emails into chat, docs, issues or + commits; storebound masks them in every log line (`j***@example.com`). +- `storebound apple testflight testers --dry` shows: new testers, testers added to more groups, (with `--remove`) + testers who leave a managed group. The real run **asks first**: Apple emails each new tester an invitation once the + group has a build. `--invite` (re)sends invitations to testers still `NOT_INVITED` / `INVITED` (asks again). +- Internal groups only take App Store Connect users (Users and Access); add people there first. +- Testers are an owner action: not an MCP tool. An agent prepares the CSV format and the dry run, the owner runs it. + +## 3. What to Test +- `storebound whats-new` drafts release notes into `store/appstore.md` (`### whatsNew` per locale). For testers you can + add a `### whatToTest` block per locale: it wins over `whatsNew` for TestFlight. +- `storebound apple testflight what-to-test --build N --dry`, then for real. `--text "..." --locale en-US` sets one + text instead. Pick the build by the exact number you uploaded, never "the latest"; `--version x.y.z` when the same + build number exists for two versions. +- Write it for testers: what changed, what to try, known issues. Short; it is read on a phone. Apple documents no + maximum; storebound stops at 4000 characters (assumption, see the README's unverified list). + +## 4. Test Information (needed for external testing) +`storebound apple testflight info --dry`: Beta App Description per locale (`apple.testflight.description`), feedback +email (`app.contactEmail`), privacy policy and marketing URL, and the Beta App Review contact (from +`.storebound/credentials.json` `reviewContact`) plus notes (4000 characters max). Apple requires a description on every +beta app localization before a Beta App Review submission, and fields cannot be cleared once set. + +## 5. Distribute +- Internal: `storebound apple testflight distribute --build N --group Team --dry`, then for real (MCP: + `apple_testflight_distribute`, internal groups only). Groups with `allBuilds: true` get every build automatically. +- External: same command with an external group; it asks first. External testers only get the build after **Beta App + Review**: add `--submit-review` (asks again) or submit in App Store Connect. The first build of a version is + reviewed; later builds of the same version are often approved quickly. Beta review states: `WAITING_FOR_REVIEW`, + `IN_REVIEW`, `APPROVED`, `REJECTED` (`storebound apple testflight status` shows internal / external build states). +- The Beta App Review submission is public-facing and the owner's call: never through MCP; an agent explains and the + owner confirms in the terminal. + +## Gotchas +- Builds expire after 90 days in TestFlight; upload a new one (`storebound apple next-build`). +- Up to 100 internal testers and 10,000 external testers per app (TestFlight overview in App Store Connect Help: + https://developer.apple.com/help/app-store-connect/test-a-beta-version/testflight-overview). +- A public link (`publicLink: true`) lets anyone with it join, up to `publicLinkLimit` (1-10000). Share it only where + the owner wants; it still needs the approved build. +- External testers of a game with IAP buy with sandbox accounts automatically (no charge); say so in What to Test. +- Rejected beta review: read the message in App Store Connect > TestFlight, fix, upload a new build, submit again + (review-rejections skill for the tone of the reply). diff --git a/templates/storebound.config.ts b/templates/storebound.config.ts index 0b3ddec3..acd92b67 100644 --- a/templates/storebound.config.ts +++ b/templates/storebound.config.ts @@ -41,6 +41,14 @@ const config: ShipConfig = { // usesNonExemptEncryption: false, // ipad: true, // the app runs on iPad: 13" iPad screenshots (2064 x 2752, ipad13) are rendered, checked and uploaded // screenshotTypes: ['APP_IPHONE_67'], // what `storebound validate` requires per locale (default; + APP_IPAD_PRO_3GEN_129 with ipad) + // TestFlight (`storebound apple testflight`, testflight skill). Tester emails live in .storebound/testers.csv only. + testflight: { + groups: [ + { name: 'Team', internal: true, allBuilds: true }, + { name: 'Friends' }, + ], + description: { en: 'Example Game beta: try the new levels and tell us what feels too hard.' }, + }, info: { categories: { primary: 'GAMES', primarySubOne: 'GAMES_CASUAL', primarySubTwo: 'GAMES_PUZZLE', secondary: 'ENTERTAINMENT' }, ageRating: { advertising: true }, // everything else NONE / false diff --git a/templates/testers.csv b/templates/testers.csv new file mode 100644 index 00000000..987ced9b --- /dev/null +++ b/templates/testers.csv @@ -0,0 +1 @@ +email,first_name,last_name,groups diff --git a/tests/testflight.test.ts b/tests/testflight.test.ts new file mode 100644 index 00000000..da41337b --- /dev/null +++ b/tests/testflight.test.ts @@ -0,0 +1,150 @@ +import { describe, expect, test } from 'bun:test'; +import { describeReq } from '../cli/apple/jsonapi'; +import { parseCsv, parseCsvRecords, toCsv } from '../cli/lib/csv'; +import { validateConfig } from '../cli/lib/config'; +import { + betaDescriptions, betaReadiness, betaReviewReq, buildsWithVersion, type Group, groupFromApi, inviteReq, maskEmail, parseTesters, pickBuild, + planBetaInfo, planBetaReviewDetail, planDistribute, planGroups, planTesters, planWhatToTest, validateTestflight, whatToTestFromListing, +} from '../cli/lib/testflight'; +import { TOOLS, toArgv, validateInput } from '../cli/mcp-tools'; + +const G: Group[] = [ + { id: 'g-int', name: 'Team', internal: true, hasAccessToAllBuilds: false }, + { id: 'g-all', name: 'Everyone inside', internal: true, hasAccessToAllBuilds: true }, + { id: 'g-ext', name: 'Friends', internal: false }, +]; + +describe('csv', () => { + test('quotes, doubled quotes, CRLF, BOM, empty lines', () => { + expect(parseCsv('a,b\r\n"x, y","say ""hi"""\r\n\r\nz,\n')).toEqual([['a', 'b'], ['x, y', 'say "hi"'], ['z', '']]); + expect(parseCsv('a\tb\n1\t2', '\t')).toEqual([['a', 'b'], ['1', '2']]); + expect(parseCsvRecords('Email, First Name\nA@example.com ,Jo')).toEqual([{ email: 'A@example.com', first_name: 'Jo' }]); + expect(toCsv([['a', 'b,c'], [1, 'say "x"']])).toBe('a,"b,c"\n1,"say ""x"""\n'); + }); +}); + +describe('testflight config', () => { + test('groups and the tester CSV location', () => { + expect(validateTestflight({ groups: [{ name: 'Team', internal: true, allBuilds: true }, { name: 'Friends', publicLink: true, publicLinkLimit: 100 }], testers: '.storebound/testers.csv' })).toEqual([]); + const e = validateTestflight({ groups: [{ name: 'A', internal: true, publicLink: true }, { name: 'A', allBuilds: true }, { name: 'B', publicLinkLimit: 0 }], testers: 'store/testers.csv' }); + expect(e.join('\n')).toContain('public links are for external groups only'); + expect(e.join('\n')).toContain('duplicate "A"'); + expect(e.join('\n')).toContain('allBuilds: internal groups only'); + expect(e.join('\n')).toContain('publicLinkLimit: 1-10000'); + expect(e.join('\n')).toContain('keep the tester CSV in .storebound/'); + const base = { app: { name: 'X', privacyPolicyUrl: 'https://example.com/p', supportUrl: 'https://example.com', website: 'https://example.com', contactEmail: 'a@example.com' }, languages: [{ id: 'en', apple: 'en-US' }] }; + expect(validateConfig({ ...base, apple: { bundleId: 'com.example.game', testflight: { testers: 'testers.csv' } } }).join()).toContain('.storebound/'); + }); +}); + +describe('testflight groups', () => { + test('creates only missing groups, with the right attributes', () => { + const p = planGroups('app1', G, [{ name: 'Team', internal: true }, { name: 'QA', internal: true, allBuilds: true }, { name: 'Public', publicLink: true, publicLinkLimit: 500, feedback: false }]); + expect(p.existing).toEqual(['Team']); + expect(p.create).toHaveLength(2); + expect(p.create[0]!.body).toEqual({ data: { type: 'betaGroups', attributes: { name: 'QA', isInternalGroup: true, hasAccessToAllBuilds: true, feedbackEnabled: true }, relationships: { app: { data: { type: 'apps', id: 'app1' } } } } }); + expect((p.create[1]!.body as { data: { attributes: unknown } }).data.attributes).toEqual({ name: 'Public', publicLinkEnabled: true, publicLinkLimitEnabled: true, publicLinkLimit: 500, feedbackEnabled: false }); + expect(groupFromApi({ id: 'x', attributes: { name: 'N', isInternalGroup: true, hasAccessToAllBuilds: true } })).toMatchObject({ id: 'x', name: 'N', internal: true, hasAccessToAllBuilds: true }); + }); +}); + +describe('testflight testers', () => { + const csv = 'email,first_name,last_name,groups\nJane@Example.com,Jane,Doe,Friends\nbob@example.com,,,Friends;Team\nnew@example.com,New,,\n'; + test('parse: lower-cases emails, default group, rejects bad rows without leaking emails', () => { + const t = parseTesters(csv, 'Friends'); + expect(t.map(x => [x.email, x.groups])).toEqual([['jane@example.com', ['Friends']], ['bob@example.com', ['Friends', 'Team']], ['new@example.com', ['Friends']]]); + expect(() => parseTesters('email\nnot-an-email\n')).toThrow('is not an email'); + try { parseTesters('email\nsecret.person@example.com\nsecret.person@example.com\n'); } catch (e) { expect(String(e)).toContain('s***@example.com listed twice'); expect(String(e)).not.toContain('secret.person'); } + expect(maskEmail('jane.doe@example.com')).toBe('j***@example.com'); + }); + test('plan: create new, add existing to more groups, remove only with --remove and only from managed groups', () => { + const want = parseTesters(csv, 'Friends'); + const existing = new Map([ + ['jane@example.com', { id: 't-jane', groupIds: ['g-ext'] }], + ['bob@example.com', { id: 't-bob', groupIds: ['g-ext'] }], + ['old@example.com', { id: 't-old', groupIds: ['g-ext', 'g-all'] }], + ]); + const p = planTesters(G, existing, want); + expect(p.create).toHaveLength(1); + expect(p.create[0]!.body).toEqual({ data: { type: 'betaTesters', attributes: { email: 'new@example.com', firstName: 'New' }, relationships: { betaGroups: { data: [{ type: 'betaGroups', id: 'g-ext' }] } } } }); + expect(p.add).toEqual([{ method: 'POST', path: '/v1/betaGroups/g-int/relationships/betaTesters', body: { data: [{ type: 'betaTesters', id: 't-bob' }] }, note: '1 existing tester(s) -> "Team"' }]); + expect(p.remove).toEqual([]); + const r = planTesters(G, existing, want, { remove: true }); + expect(r.remove).toEqual([{ method: 'DELETE', path: '/v1/betaGroups/g-ext/relationships/betaTesters', body: { data: [{ type: 'betaTesters', id: 't-old' }] }, note: '1 tester(s) leave "Friends"' }]); + expect(r.summary).toEqual(['1 new tester(s)', '1 added to groups', '1 removed from groups']); + expect(planTesters(G, existing, want, { only: ['Nope'] }).unknownGroups).toEqual(['Nope']); + expect(describeReq(p.create[0]!)).not.toContain('new@example.com'); + expect(describeReq(p.create[0]!)).toContain('n***@example.com'); + }); + test('invitation request', () => { + expect(inviteReq('app1', 't1', 'x').body).toEqual({ data: { type: 'betaTesterInvitations', relationships: { app: { data: { type: 'apps', id: 'app1' } }, betaTester: { data: { type: 'betaTesters', id: 't1' } } } } }); + }); +}); + +describe('testflight builds', () => { + const resp = { + data: [ + { id: 'b1', attributes: { version: '42', processingState: 'VALID' }, relationships: { preReleaseVersion: { data: { id: 'p1' } } } }, + { id: 'b2', attributes: { version: '42', processingState: 'VALID' }, relationships: { preReleaseVersion: { data: { id: 'p2' } } } }, + { id: 'b3', attributes: { version: '43', processingState: 'PROCESSING' }, relationships: { preReleaseVersion: { data: { id: 'p2' } } } }, + ], + included: [{ type: 'preReleaseVersions', id: 'p1', attributes: { version: '1.0.0' } }, { type: 'preReleaseVersions', id: 'p2', attributes: { version: '1.1.0' } }], + }; + test('pick by explicit number, ambiguity needs --version', () => { + const builds = buildsWithVersion(resp); + expect(pickBuild(builds, '43').id).toBe('b3'); + expect(pickBuild(builds, '42', '1.1.0').id).toBe('b2'); + expect(() => pickBuild(builds, '42')).toThrow('add --version'); + expect(() => pickBuild(builds, '99')).toThrow('no build 99'); + }); + test('readiness', () => { + expect(betaReadiness({ processingState: 'VALID', usesNonExemptEncryption: false }, { internalBuildState: 'READY_FOR_BETA_TESTING' })).toEqual([]); + expect(betaReadiness({ processingState: 'PROCESSING' }, null)[0]).toContain('PROCESSING'); + expect(betaReadiness({ processingState: 'VALID', expired: true }, null)[0]).toContain('expired'); + expect(betaReadiness({ processingState: 'VALID', usesNonExemptEncryption: null }, { internalBuildState: 'MISSING_EXPORT_COMPLIANCE' })[0]).toContain('export compliance'); + }); + test('distribute skips groups that have it and internal all-builds groups', () => { + expect(planDistribute('b1', G, ['g-ext']).map(r => r.path)).toEqual(['/v1/betaGroups/g-int/relationships/builds']); + expect(planDistribute('b1', G, [])[0]!.body).toEqual({ data: [{ type: 'builds', id: 'b1' }] }); + expect(betaReviewReq('b1').body).toEqual({ data: { type: 'betaAppReviewSubmissions', relationships: { build: { data: { type: 'builds', id: 'b1' } } } } }); + }); +}); + +describe('testflight what to test and info', () => { + const md = '# App Store\n\n## en-US · English\n\n### whatsNew\n```\nNew: desert world.\n```\n\n### whatToTest\n```\nPlay level 3 twice.\n```\n\n## tr · Türkçe\n\n### whatsNew\n```\nYeni: çöl dünyası.\n```\n\n## Notes\n\ntext\n'; + test('listing -> per locale text, whatToTest wins over whatsNew', () => { + expect(whatToTestFromListing(md)).toEqual({ 'en-US': 'Play level 3 twice.', tr: 'Yeni: çöl dünyası.' }); + }); + test('create missing, patch changed, leave equal, refuse over the limit', () => { + const reqs = planWhatToTest('b1', [{ id: 'l1', locale: 'en-US', whatsNew: 'old' }, { id: 'l2', locale: 'de-DE', whatsNew: 'x' }, { id: 'l3', locale: 'ja', whatsNew: 'same' }], { 'en-US': 'new', tr: 'yeni', ja: 'same' }); + expect(reqs.map(r => `${r.method} ${r.path}`)).toEqual(['PATCH /v1/betaBuildLocalizations/l1', 'POST /v1/betaBuildLocalizations']); + expect(reqs[1]!.body).toEqual({ data: { type: 'betaBuildLocalizations', attributes: { locale: 'tr', whatsNew: 'yeni' }, relationships: { build: { data: { type: 'builds', id: 'b1' } } } } }); + expect(() => planWhatToTest('b1', [], { en: 'x'.repeat(4001) })).toThrow('over 4000'); + }); + test('test information and beta review details', () => { + const want = { 'en-US': { description: 'A puzzle game.', feedbackEmail: 'support@example.com', privacyPolicyUrl: 'https://example.com/p' }, tr: { description: 'Bulmaca.' } }; + const r = planBetaInfo('app1', [{ id: 'bl1', locale: 'en-US', attributes: { description: 'A puzzle game.', feedbackEmail: 'old@example.com' } }], want); + expect(r.map(x => `${x.method} ${x.path}`)).toEqual(['PATCH /v1/betaAppLocalizations/bl1', 'POST /v1/betaAppLocalizations']); + expect((r[0]!.body as { data: { attributes: unknown } }).data.attributes).toEqual({ feedbackEmail: 'support@example.com', privacyPolicyUrl: 'https://example.com/p' }); + expect(betaDescriptions({ description: { en: 'Hi' } }, [{ id: 'en', apple: 'en-US' }, { id: 'tr', apple: 'tr' }])).toEqual({ 'en-US': 'Hi' }); + expect(betaDescriptions({ description: 'All' }, [{ id: 'en', apple: 'en-US' }, { id: 'x' }])).toEqual({ 'en-US': 'All' }); + const d = planBetaReviewDetail({ id: 'd1', attributes: { contactEmail: 'a@example.com', notes: null } }, { firstName: 'A', lastName: 'B', phone: '+1 555 0100', email: 'a@example.com' }, 'Tap Play.'); + expect((d[0]!.body as { data: { attributes: unknown } }).data.attributes).toEqual({ contactFirstName: 'A', contactLastName: 'B', contactPhone: '+1 555 0100', notes: 'Tap Play.' }); + expect(describeReq(d[0]!)).not.toContain('555'); + expect(planBetaReviewDetail(null, null, 'x')).toEqual([]); + expect(() => planBetaReviewDetail({ id: 'd', attributes: {} }, null, 'x'.repeat(4001))).toThrow('4000'); + }); +}); + +describe('testflight mcp tools', () => { + const tool = (n: string) => TOOLS.find(t => t.name === n)!; + test('status read-only, writes dry by default, distribute is internal-only, testers / review not exposed', () => { + expect(tool('apple_testflight_status')).toMatchObject({ write: false, network: true }); + expect(toArgv(tool('apple_testflight_groups')).argv).toEqual(['apple', 'testflight', 'groups', '--dry']); + expect(toArgv(tool('apple_testflight_what_to_test'), { build: '42', locale: 'en-US,tr' }).argv).toEqual(['apple', 'testflight', 'what-to-test', '--build', '42', '--locale', 'en-US,tr', '--dry']); + expect(toArgv(tool('apple_testflight_distribute'), { build: '42', groups: 'Team', dry_run: false }).argv).toEqual(['apple', 'testflight', 'distribute', '--build', '42', '--group', 'Team', '--internal-only']); + expect(validateInput(tool('apple_testflight_distribute'), { build: 'latest', groups: 'Team' })[0]).toContain('does not match'); + expect(TOOLS.some(t => t.command.includes('testers'))).toBe(false); + for (const t of TOOLS) expect(toArgv(t, { build: '1', groups: 'x', dry_run: false }).argv).not.toContain('--submit-review'); + }); +});