@sprid/release 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.ts ADDED
@@ -0,0 +1,207 @@
1
+ #!/usr/bin/env bun
2
+ /** Store assets and local binary releases. App configuration supplies every identifier and path. */
3
+
4
+ import { loadReleaseConfig, listingLocaleMap, releasePath, type AppReleaseConfig } from './config.ts';
5
+ import { pushAscMetadata } from './asc/metadata.ts';
6
+ import { pushAscScreenshots } from './asc/screenshots.ts';
7
+ import { pushPlayMetadata } from './play/metadata.ts';
8
+ import { pushPlayScreenshots } from './play/screenshots.ts';
9
+ import { pushPlayGraphics } from './play/graphics.ts';
10
+ import { ship } from './ship.ts';
11
+ import { bumpVersion, readAppVersion } from './bump.ts';
12
+ import { uploadIpa } from './asc/upload.ts';
13
+ import { submitForReview } from './asc/submit.ts';
14
+ import { uploadAab } from './play/upload.ts';
15
+ import { annotate, appSlugFromRepo } from './annotate.ts';
16
+
17
+ const has = (...names: string[]) => names.some((n) => process.argv.includes(`--${n}`));
18
+ const value = (name: string) => {
19
+ const arg = process.argv.find(a => a.startsWith(`--${name}=`));
20
+ if (arg) return arg.slice(name.length + 3);
21
+ const index = process.argv.indexOf(`--${name}`);
22
+ return index < 0 ? undefined : process.argv[index + 1];
23
+ };
24
+
25
+ // Every command's accepted flags. An unknown flag is a hard error: a typo must
26
+ // never fall through and run a real push with defaults.
27
+ const COMMANDS: Record<string, { usage: string; bool: string[]; values?: string[] }> = {
28
+ ship: { usage: 'ship [--execute] [--patch|--minor|--major] [--ios-only|--android-only] [--build-only|--submit-only]', bool: ['execute', 'patch', 'minor', 'major', 'ios-only', 'android-only', 'build-only', 'submit-only', 'no-bump', 'no-submit', 'internal', 'allow-dirty', 'push-store-copy', 'replace-submission'] },
29
+ bump: { usage: 'bump [--execute] [--patch|--minor|--major]', bool: ['execute', 'patch', 'minor', 'major'] },
30
+ 'asc-upload': { usage: 'asc-upload --ipa <file> [--execute]', bool: ['execute'], values: ['ipa'] },
31
+ 'play-upload': { usage: 'play-upload --aab <file> --version <version> [--track production|beta|internal] [--execute]', bool: ['execute'], values: ['aab', 'version', 'track'] },
32
+ 'asc-submit': { usage: 'asc-submit --version <version> --build <number> [--execute] [--attach-only]', bool: ['execute', 'attach-only', 'push-store-copy', 'replace-submission'], values: ['version', 'build'] },
33
+ metadata: { usage: 'metadata [--execute] [--asc|--play]', bool: ['execute', 'asc', 'play'] },
34
+ screenshots: { usage: 'screenshots [--execute] [--asc|--play]', bool: ['execute', 'asc', 'play'] },
35
+ graphics: { usage: 'graphics [--execute]', bool: ['execute'] },
36
+ 'asc-metadata': { usage: 'asc-metadata [--execute]', bool: ['execute'] },
37
+ 'play-metadata': { usage: 'play-metadata [--execute]', bool: ['execute'] },
38
+ 'asc-screenshots': { usage: 'asc-screenshots [--execute]', bool: ['execute'] },
39
+ 'play-screenshots': { usage: 'play-screenshots [--execute]', bool: ['execute'] },
40
+ 'play-graphics': { usage: 'play-graphics [--execute]', bool: ['execute'] },
41
+ };
42
+
43
+ function printUsage(command?: string): void {
44
+ const spec = command ? COMMANDS[command] : undefined;
45
+ if (spec) {
46
+ console.log(`Usage: sprid release ${spec.usage} [--config <file>] [--locale <locale,...>] [--annotate]`);
47
+ return;
48
+ }
49
+ console.log('Usage: sprid release <command> [flags]\n');
50
+ console.log('Commands:');
51
+ for (const name of ['ship', 'bump', 'asc-upload', 'play-upload', 'asc-submit', 'metadata', 'screenshots', 'graphics']) console.log(` ${COMMANDS[name].usage}`);
52
+ console.log('\nWithout --execute every command is a dry run: it prints what it would send.');
53
+ console.log('Per-store names also work: asc-metadata, play-metadata, asc-screenshots, play-screenshots, play-graphics.');
54
+ console.log('\n--config <file> accepts TS, JS, MJS or JSON. Paths resolve beside that file.');
55
+ console.log('--locale <locale,...> selects store locale codes. --annotate records executed changes in Sprid (opt-in).');
56
+ console.log('\nCredentials (never read into an agent conversation):');
57
+ console.log(' App Store Connect asc.keyPath in release.config.ts, or $ASC_KEY_PATH + $ASC_KEY_ID + $ASC_ISSUER');
58
+ console.log(' Google Play play.keyPath in release.config.ts, or $GOOGLE_SERVICE_ACCOUNT_KEY_PATH');
59
+ }
60
+
61
+ function validateArgs(command: string): void {
62
+ const spec = COMMANDS[command];
63
+ if (!spec) {
64
+ console.error(`Unknown command: ${command}\n`);
65
+ printUsage();
66
+ process.exit(2);
67
+ }
68
+ const args = process.argv.slice(3);
69
+ for (let i = 0; i < args.length; i++) {
70
+ const arg = args[i];
71
+ const name = arg.slice(2).split('=')[0];
72
+ if (!arg.startsWith('--')) throw new Error(`Unexpected argument: ${arg}`);
73
+ if (['config', 'locale', ...(spec.values ?? [])].includes(name)) {
74
+ const v = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : args[++i];
75
+ if (!v || v.startsWith('--')) throw new Error(`--${name} needs a value.`);
76
+ } else if (![...spec.bool, 'annotate'].includes(name) || arg.includes('=')) {
77
+ throw new Error(`Unknown flag or invalid boolean: ${arg}`);
78
+ }
79
+ }
80
+ if (has('asc') && has('play')) {
81
+ console.error('Pass --asc or --play, not both (omit both for both stores).\n');
82
+ process.exit(2);
83
+ }
84
+ }
85
+
86
+ /** Which stores a two-store command touches. Default to configured stores. */
87
+ function stores(config: AppReleaseConfig): { asc: boolean; play: boolean } {
88
+ if (has('asc')) return { asc: true, play: false };
89
+ if (has('play')) return { asc: false, play: true };
90
+ return { asc: Boolean(config.appId || config.ascAppId), play: Boolean(config.play?.packageName) };
91
+ }
92
+
93
+ async function main() {
94
+ const command = process.argv[2];
95
+ if (!command || command === 'help' || command === '--help' || command === '-h') {
96
+ printUsage(command === 'help' ? process.argv[3] : undefined);
97
+ process.exit(command ? 0 : 1);
98
+ }
99
+ if (process.argv.slice(3).includes('--help')) { printUsage(command); return; }
100
+ validateArgs(command);
101
+
102
+ const config = await loadReleaseConfig(value('config'));
103
+ const selectedLocales = value('locale')?.split(',').map(s => s.trim());
104
+ if (selectedLocales?.some(s => !s)) throw new Error('--locale needs non-empty comma-separated store locale codes.');
105
+ const localeMap = (store: 'apple' | 'play') => {
106
+ const map = listingLocaleMap(config, store);
107
+ if (!selectedLocales) return map;
108
+ for (const locale of selectedLocales) if (!map[locale]) throw new Error(`Locale ${locale} is not configured for ${store}; select a store with --asc or --play.`);
109
+ return Object.fromEntries(selectedLocales.map(locale => [locale, map[locale]]));
110
+ };
111
+ const execute = has('execute');
112
+ if (!execute) console.log('Dry run. Nothing is sent without --execute.\n');
113
+
114
+ const requireValue = (name: string) => { const v = value(name); if (!v) throw new Error(`--${name} is required.`); return v; };
115
+ const bumpKinds = (['patch', 'minor', 'major'] as const).filter(k => has(k));
116
+ if (bumpKinds.length > 1) throw new Error('Choose one version bump.');
117
+ if (has('ios-only') && has('android-only')) throw new Error('Choose one platform flag or omit both.');
118
+ if (has('build-only') && has('submit-only')) throw new Error('--build-only and --submit-only conflict.');
119
+ if (has('no-bump') && bumpKinds.length) throw new Error('--no-bump conflicts with a version bump.');
120
+ if (command === 'ship') {
121
+ await ship(config, { execute, ios: !has('android-only') && Boolean(config.appId || config.ascAppId), android: !has('ios-only') && Boolean(config.play), upload: !has('build-only'), submitIos: !has('no-submit'), bumpKind: bumpKinds[0], skipBump: has('no-bump'), submitOnly: has('submit-only'), track: has('internal') ? 'internal' : 'production', allowDirty: has('allow-dirty'), pushStoreCopy: has('push-store-copy'), replaceSubmission: has('replace-submission') });
122
+ return;
123
+ }
124
+ if (command === 'bump') { if (execute) bumpVersion(config, bumpKinds[0]); else console.log({ current: readAppVersion(config), bump: bumpKinds[0] ?? 'build' }); return; }
125
+ if (command === 'asc-upload') { const path = releasePath(config, requireValue('ipa')); if (execute) await uploadIpa(config, path); else console.log(`Upload IPA: ${path}`); return; }
126
+ if (command === 'play-upload') {
127
+ const path = releasePath(config, requireValue('aab')); const version = requireValue('version'); const track = value('track') ?? 'production';
128
+ if (!['production', 'beta', 'internal'].includes(track)) throw new Error(`Unsupported track: ${track}`);
129
+ if (execute) await uploadAab(config, { aabPath: path, version, track: track as 'production' | 'beta' | 'internal' }); else console.log(`Upload AAB: ${path}, ${version}, ${track}`);
130
+ return;
131
+ }
132
+ if (command === 'asc-submit') {
133
+ const version = requireValue('version'); const build = requireValue('build');
134
+ if (execute) await submitForReview(config, { version, build, attachOnly: has('attach-only'), pushStoreCopy: has('push-store-copy'), replaceSubmission: has('replace-submission'), releaseNotes: config.releaseNotes }); else console.log(`Submit iOS ${version} (${build})`);
135
+ return;
136
+ }
137
+
138
+ const needCopy = () => {
139
+ if (!config.storeCopy) throw new Error('release.config.ts needs `storeCopy` for metadata commands.');
140
+ return config.storeCopy;
141
+ };
142
+ const asc = {
143
+ metadata: (send = execute) => pushAscMetadata({ config, copy: needCopy(), localeMap: localeMap('apple'), execute: send }),
144
+ screenshots: (send = execute) => pushAscScreenshots({ config, execute: send, localeMap: localeMap('apple') }),
145
+ };
146
+ const play = {
147
+ metadata: (send = execute) => pushPlayMetadata({ config, copy: needCopy(), contact: config.contact, localeMap: localeMap('play'), execute: send }),
148
+ screenshots: (send = execute) => pushPlayScreenshots({ config, execute: send, localeMap: localeMap('play') }),
149
+ graphics: (send = execute) => pushPlayGraphics({ config, execute: send, localeMap: localeMap('play') }),
150
+ };
151
+
152
+ // What was pushed, for the annotation after a real push.
153
+ const touched: string[] = [];
154
+ const s = stores(config);
155
+ const appleSelected = command.startsWith('asc-') || (['metadata', 'screenshots'].includes(command) && s.asc);
156
+ const playSelected = command.startsWith('play-') || command === 'graphics' || (['metadata', 'screenshots'].includes(command) && s.play);
157
+ if (!appleSelected && !playSelected) throw new Error('Configure appId/ascAppId or play.packageName.');
158
+ if (appleSelected && !config.appId && !config.ascAppId) throw new Error('Set appId or ascAppId for App Store commands.');
159
+ if (playSelected && !config.play?.packageName) throw new Error('Set play.packageName for Google Play commands.');
160
+ if (appleSelected) localeMap('apple');
161
+ if (playSelected) localeMap('play');
162
+ // Preflight every selected store's local inputs before the first remote write.
163
+ if (execute) {
164
+ const operation = command.split('-').at(-1);
165
+ if (appleSelected) await asc[operation as keyof typeof asc](false);
166
+ if (playSelected) await play[operation as keyof typeof play](false);
167
+ }
168
+ switch (command) {
169
+ case 'metadata':
170
+ if (s.asc) { await asc.metadata(); touched.push('App Store listing'); }
171
+ if (s.play) { await play.metadata(); touched.push('Play listing'); }
172
+ break;
173
+ case 'screenshots':
174
+ if (s.asc) { await asc.screenshots(); touched.push('App Store screenshots'); }
175
+ if (s.play) { await play.screenshots(); touched.push('Play screenshots'); }
176
+ break;
177
+ case 'graphics':
178
+ case 'play-graphics':
179
+ await play.graphics(); touched.push('Play graphics');
180
+ break;
181
+ case 'asc-metadata':
182
+ await asc.metadata(); touched.push('App Store listing');
183
+ break;
184
+ case 'play-metadata':
185
+ await play.metadata(); touched.push('Play listing');
186
+ break;
187
+ case 'asc-screenshots':
188
+ await asc.screenshots(); touched.push('App Store screenshots');
189
+ break;
190
+ case 'play-screenshots':
191
+ await play.screenshots(); touched.push('Play screenshots');
192
+ break;
193
+ }
194
+
195
+ // Annotate the push in Sprid (best effort, only when logged in), so the
196
+ // Monday mail shows "App Store listing changed (Thu)" next to the numbers.
197
+ if (execute && has('annotate') && touched.length > 0) {
198
+ const kind = /screenshots|graphics/.test(touched.join(' ')) ? 'screenshots' : 'listing';
199
+ const ok = await annotate({ kind, label: `${touched.join(' + ')} changed`, app: appSlugFromRepo(releasePath(config, '.')), meta: { command } });
200
+ if (ok) console.log('\nAnnotated in Sprid: the Monday mail will show this change next to the numbers.');
201
+ }
202
+ }
203
+
204
+ main().catch((err) => {
205
+ console.error(err instanceof Error ? err.message : err);
206
+ process.exit(1);
207
+ });
package/src/config.ts ADDED
@@ -0,0 +1,454 @@
1
+ /**
2
+ * The per-app release configuration — the one object each consuming app supplies
3
+ * (as `release.config.ts` at its repo root). Everything the shared release logic
4
+ * needs that legitimately differs between apps lives here; nothing about a
5
+ * specific app is hardcoded in the rest of the package.
6
+ */
7
+
8
+ import { existsSync, readFileSync, statSync } from 'node:fs';
9
+ import { homedir } from 'node:os';
10
+ import { dirname, resolve } from 'node:path';
11
+ import { pathToFileURL } from 'node:url';
12
+ import type { StoreContact, StoreCopy } from './copy.ts';
13
+
14
+ export interface AscConfig {
15
+ /** ASC API key id (the `.p8` filename stem). Not secret. Env `ASC_KEY_ID` wins. */
16
+ keyId?: string;
17
+ /** ASC API issuer id. Not secret. Env `ASC_ISSUER` wins. */
18
+ issuer?: string;
19
+ /** Explicit `.p8` path. Else resolved from env / install dir / credentialsDir. */
20
+ keyPath?: string;
21
+ /**
22
+ * Durable `.p8` source to install into ~/.appstoreconnect/private_keys for
23
+ * altool (relative to cwd or absolute). Defaults to
24
+ * `<credentialsDir>/ios/AuthKey_<keyId>_ASC_API.p8`. Some apps keep it
25
+ * elsewhere (e.g. `.keys/AuthKey_<keyId>.p8`).
26
+ */
27
+ keySourcePath?: string;
28
+ /** Opt in to mirroring en-US into en-GB when en-GB is not explicitly mapped. */
29
+ englishUkFallback?: boolean;
30
+ }
31
+
32
+ export interface PlayConfig {
33
+ /** Android application id (Play package name). */
34
+ packageName: string;
35
+ /** Explicit service-account JSON path. Else env / credentialsDir. */
36
+ keyPath?: string;
37
+ /** Compatibility alias for keyPath. */
38
+ serviceAccountKeyPath?: string;
39
+ }
40
+
41
+ export interface LocaleMaps {
42
+ /** App Store Connect locale (e.g. `en-US`, `sv`) → canonical copy-locale key (e.g. `en`, `sv`). */
43
+ apple?: Record<string, string>;
44
+ /** Google Play locale (e.g. `en-US`, `sv-SE`) → canonical copy-locale key. */
45
+ play?: Record<string, string>;
46
+ }
47
+
48
+ export interface ConfigFileRef {
49
+ /**
50
+ * Where version + build numbers live. `'split'` = marketing version in
51
+ * `path` (an app.config.ts) but buildNumber/versionCode in `buildConfigPath`
52
+ * (an app.json).
53
+ */
54
+ format: 'app.config.ts' | 'app.json' | 'split';
55
+ /** Path to the version source-of-truth, relative to the repo root (or absolute). */
56
+ path: string;
57
+ /** For `'split'`: the app.json holding ios.buildNumber + android.versionCode. */
58
+ buildConfigPath?: string;
59
+ }
60
+
61
+ export interface RequiredEnvVar {
62
+ name: string;
63
+ /** When false (default), a `localhost`/`127.0.0.1` value hard-fails too. */
64
+ allowLocalhost?: boolean;
65
+ }
66
+
67
+ /**
68
+ * A second signed iOS target inside the app — a share extension, a widget, a
69
+ * Messages app. Each one is its own bundle id with its own provisioning profile,
70
+ * and BOTH halves matter: Xcode resolves an extension's signing during the
71
+ * ARCHIVE (before exportOptions is consulted), and `-exportArchive` under manual
72
+ * signing then refuses any bundle id it has no profile for. Missing either half
73
+ * fails a build that has otherwise already succeeded.
74
+ */
75
+ export interface IosExtensionTarget {
76
+ /** Xcode target name, e.g. "MyAppShare". */
77
+ target: string;
78
+ /** Its bundle id, e.g. "com.example.myapp.share-extension". */
79
+ bundleId: string;
80
+ /**
81
+ * Its App Store provisioning profile, resolved like the paths inside
82
+ * credentials.json (relative to that file's dir, or to `credentialsPathBase`).
83
+ */
84
+ profilePath: string;
85
+ }
86
+
87
+ /**
88
+ * The human Apple rings about a submission. These live on the VERSION record, so
89
+ * a version this tool creates through the API starts with all four null and the
90
+ * review submission is refused with a 409 naming each one. A version created in
91
+ * the ASC web UI never shows the problem, because its submit form collects them
92
+ * — which is why an app only hits this once it starts submitting from here.
93
+ */
94
+ export interface ReviewContact {
95
+ firstName: string;
96
+ lastName: string;
97
+ email: string;
98
+ /** E.164, e.g. "+46701234567" — Apple rejects anything else. */
99
+ phone: string;
100
+ /** Optional free text for the reviewer ("Notes" in App Review Information). */
101
+ notes?: string;
102
+ }
103
+
104
+ /** Everything the local build + sign mechanics need to drive `ship`. */
105
+ export interface BuildConfig {
106
+ /** Explicitly enable Expo native generation. Native projects skip prebuild. */
107
+ framework?: 'expo' | 'native';
108
+ /** Optional build commands and artifact paths for other toolchains (argv, never shell text). */
109
+ commands?: Partial<Record<'ios' | 'android', { command: string[]; artifact: string }>>;
110
+ /** App dir holding ios/, android/, the config file + .env, relative to repo root. */
111
+ appDir: string;
112
+ /** Xcode workspace/scheme/target name (e.g. "MyApp" → ios/MyApp.xcworkspace). */
113
+ xcodeName?: string;
114
+ /** Optional Gradle JVM settings. Existing settings are preserved when omitted. */
115
+ gradleJvmArgs?: string;
116
+ /** Generic dotenv source; allowlisted keys only, relative to the config file. */
117
+ envFile?: { path: string; keys: string[] };
118
+ /**
119
+ * Extra signed iOS targets bundled inside the app (share extension, widget…).
120
+ * Omit when the app is a single target, which is the common case.
121
+ */
122
+ iosExtensions?: IosExtensionTarget[];
123
+ /** Extra gradle -P props for the release bundle (e.g. MAPBOX_DOWNLOADS_TOKEN). */
124
+ gradleProps?: Record<string, string>;
125
+ /** Local env files to hide during prebuild so the committed .env wins. */
126
+ hideEnvFiles?: string[];
127
+ /** File holding `SENTRY_AUTH_TOKEN=…` (for source-map upload). Relative to credentialsDir. */
128
+ sentryTokenFile?: string;
129
+ /**
130
+ * Export `EXPO_PUBLIC_*` from an eas.json build profile's `env` block before
131
+ * prebuild, so the local bundle is wired exactly like an EAS build.
132
+ */
133
+ publicEnvFromEas?: {
134
+ /** Path to eas.json (relative to cwd). */
135
+ path: string;
136
+ /** Build profile to read `env` from. Default `production`. */
137
+ profile?: string;
138
+ };
139
+ /**
140
+ * Load an allowlist of secrets from a Drive `KEY=value` file into the env
141
+ * (skipping keys already set). Subsumes `sentryTokenFile`. `file` is relative
142
+ * to credentialsDir. Used for Mapbox download token, Google client ids, etc.
143
+ */
144
+ driveEnv?: {
145
+ file: string;
146
+ secrets: string[];
147
+ };
148
+ /**
149
+ * Env var names to forward to `gradlew bundleRelease` as `-P<NAME>=<value>`
150
+ * (value read from process.env, populated by driveEnv). e.g. `MAPBOX_DOWNLOADS_TOKEN`.
151
+ */
152
+ gradleEnvProps?: string[];
153
+ /**
154
+ * Explicit path to credentials.json (relative to cwd). Else searched at
155
+ * `<appDir>/credentials.json` then `<credentialsDir>/credentials.json`.
156
+ */
157
+ credentialsJson?: string;
158
+ /**
159
+ * Base dir the keystore/cert/profile paths INSIDE credentials.json are
160
+ * relative to (relative to cwd). Defaults to the credentials.json's own dir.
161
+ * For paths relative to the repo root, set `'.'`.
162
+ */
163
+ credentialsPathBase?: string;
164
+ /**
165
+ * Checks to run in `appDir` BEFORE the version bump, so a failure costs
166
+ * seconds instead of a finished archive sitting on a bad tree.
167
+ *
168
+ * - `true` — the built-in react/react-native/expo peer-dependency compat
169
+ * check (needs `semver` in the app's node_modules).
170
+ * - `PreflightCheck[]` — arbitrary commands. A non-zero exit fails the ship.
171
+ * Give a check a `check(output)` to assert something the exit code cannot
172
+ * see, e.g. that the test TOTAL has not dropped: a suite that fails to
173
+ * *load* still exits 0, it just reports a smaller number.
174
+ *
175
+ * Default off.
176
+ */
177
+ preflight?: boolean | PreflightCheck[];
178
+ /**
179
+ * Tie each release to a commit: refuse to build from a dirty tree, then
180
+ * commit what the release wrote and tag it `v<version>+<build>` once the
181
+ * submit succeeds. Nothing is ever pushed.
182
+ *
183
+ * Default OFF, because consumers run `bunx …@latest` with no pin and a new
184
+ * hard failure on a dirty tree would ambush whoever ships next.
185
+ * `--allow-dirty` skips both halves for a one-off.
186
+ */
187
+ gitProvenance?: boolean;
188
+ }
189
+
190
+ /**
191
+ * One preflight check. A bare string is the command line; the object form adds
192
+ * a label and an output assertion.
193
+ */
194
+ export type PreflightCheck =
195
+ | string
196
+ | {
197
+ /** Command line, run through the user's shell. */
198
+ run: string;
199
+ /**
200
+ * Where to run it. `'root'` (default) is the repo root, where monorepo
201
+ * scripts like `bun run test` live. `'app'` is `build.appDir`, for
202
+ * anything that needs the app's own node_modules.
203
+ *
204
+ * This default matters: running a root turbo script from `appDir`
205
+ * silently resolves to the APP's script of the same name, so a
206
+ * repo-wide `bun run test` quietly shrinks to one workspace and exits 0.
207
+ */
208
+ dir?: 'root' | 'app';
209
+ /** Shown in the log instead of the raw command. */
210
+ label?: string;
211
+ /**
212
+ * Assert something about the combined stdout+stderr. Return a string to
213
+ * FAIL the ship with that message; return nothing to pass. Runs only when
214
+ * the command itself exited 0.
215
+ */
216
+ check?: (output: string) => string | void;
217
+ };
218
+
219
+ /** Play phone-screenshot upload source (for the `play-screenshots` command). */
220
+ export interface PlayScreenshotsConfig {
221
+ /** Base dir holding per-language screenshot folders, relative to cwd. */
222
+ dir: string;
223
+ /**
224
+ * Glob (under `dir`) for one language's ordered phone screenshots, with
225
+ * `{lang}` replaced by the copy-locale key (e.g. `{lang}/aso/app_{lang}_play-phone_*.jpg`).
226
+ */
227
+ glob: string;
228
+ }
229
+
230
+ /** App Store screenshot upload source (for the `asc-screenshots` command). */
231
+ export interface AscScreenshotsConfig {
232
+ /** Base dir, relative to cwd. */
233
+ dir: string;
234
+ /** Glob under `dir`, with `{lang}` (e.g. `{lang}/aso/app_{lang}_iphone-65_*.jpg`). */
235
+ glob: string;
236
+ /** ASC display type, e.g. `APP_IPHONE_65`. */
237
+ displayType: string;
238
+ /** Display types to defensively delete first (deprecated sizes). */
239
+ deprecatedTypes?: string[];
240
+ }
241
+
242
+ /** Play feature-graphic + icon source (for the `play-graphics` command). */
243
+ export interface PlayGraphicsConfig {
244
+ /** Feature graphic PNG (1024×500); may contain `{lang}`. */
245
+ featureGraphic?: string;
246
+ /** App icon PNG (512×512); may contain `{lang}`. */
247
+ icon?: string;
248
+ /** Fallback dir: `<dir>/play-store-feature.png` + `<dir>/play-store-icon.png`. */
249
+ dir?: string;
250
+ }
251
+
252
+ /** Listing-locale maps (apple/play locale → copy-locale key) for metadata pushes. */
253
+ export interface ListingLocales {
254
+ apple?: Record<string, string>;
255
+ play?: Record<string, string>;
256
+ }
257
+
258
+ export interface AppReleaseConfig {
259
+ /**
260
+ * App Review contact, written onto each version before it is submitted.
261
+ * Omit and the version keeps whatever ASC holds — which for an API-created
262
+ * version is nothing, and the submission 409s.
263
+ */
264
+ reviewContact?: ReviewContact;
265
+ /** iOS bundle id. Independent of the Android package name. */
266
+ appId?: string;
267
+ /** App Store app id (numeric). May be used instead of the bundle id. */
268
+ ascAppId?: string;
269
+ /** Apple developer team id (`DEVELOPMENT_TEAM`). */
270
+ appleTeamId?: string;
271
+ asc?: AscConfig;
272
+ play?: PlayConfig;
273
+ /**
274
+ * Durable off-repo credential directory (e.g. a Google Drive folder) holding
275
+ * `ios/AuthKey_<id>_ASC_API.p8` and `android/google-service-account.json`.
276
+ * Used as the fallback when explicit key paths / env overrides are absent.
277
+ */
278
+ credentialsDir?: string;
279
+ /** Where the marketing version + build numbers live (app.config.ts or app.json). */
280
+ configFile?: ConfigFileRef;
281
+ /** True only for apps that commit `ios/` to git. Default false (CNG). */
282
+ nativeDirsCommitted?: boolean;
283
+ locales?: LocaleMaps;
284
+ /**
285
+ * Default "What's New" / release notes per canonical copy-locale key. Used to
286
+ * backfill blank store notes; hand-written notes already on the record win.
287
+ */
288
+ releaseNotes?: Record<string, string>;
289
+ /**
290
+ * Env vars that a production build must carry (and, unless allowLocalhost,
291
+ * must not point at localhost). Strings are shorthand for `{ name }`.
292
+ */
293
+ requiredProdEnv?: (string | RequiredEnvVar)[];
294
+ /** Local build + sign mechanics, needed by the `ship` command. */
295
+ build?: BuildConfig;
296
+ /** Store-listing copy by copy-locale key — lets the metadata commands run with no app script. */
297
+ storeCopy?: Record<string, StoreCopy>;
298
+ /** Play listing contact/default-language details. */
299
+ contact?: StoreContact;
300
+ /** Source for `play-screenshots` (phone screenshot upload). */
301
+ playScreenshots?: PlayScreenshotsConfig;
302
+ /** Source for `asc-screenshots` (App Store screenshot upload). */
303
+ ascScreenshots?: AscScreenshotsConfig;
304
+ /** Source for `play-graphics` (feature graphic + icon upload). */
305
+ playGraphics?: PlayGraphicsConfig;
306
+ /**
307
+ * Listing-locale maps for the metadata pushes (which locales the *listings*
308
+ * ship in — may be narrower than `locales`, which also drives release notes).
309
+ * Defaults to `locales` when omitted.
310
+ */
311
+ listingLocales?: ListingLocales;
312
+ }
313
+
314
+ /**
315
+ * Resolve the signing credentials.json + the base its inner paths resolve against.
316
+ * Explicit `build.credentialsJson` wins; else `<appDir>/credentials.json` then
317
+ * `<credentialsDir>/credentials.json`. The base is `build.credentialsPathBase`
318
+ * (relative to cwd) when set, otherwise the credentials.json's own directory.
319
+ */
320
+ export function resolveCredentialsJson(config: AppReleaseConfig): { path: string; base: string } {
321
+ const baseOverride = config.build?.credentialsPathBase
322
+ ? releasePath(config, config.build.credentialsPathBase)
323
+ : undefined;
324
+
325
+ // Try in preference order; the explicit local path is a preference, not a
326
+ // requirement — a missing local credentials.json falls back to the durable
327
+ // credentialsDir. Paths inside it may use a separate credentialsPathBase.
328
+ const candidates: string[] = [];
329
+ if (config.build?.credentialsJson) candidates.push(releasePath(config, config.build.credentialsJson));
330
+ if (config.build) candidates.push(resolve(releasePath(config, config.build.appDir), 'credentials.json'));
331
+ if (config.credentialsDir) candidates.push(resolve(releasePath(config, config.credentialsDir), 'credentials.json'));
332
+
333
+ for (const path of candidates) {
334
+ if (existsSync(path)) return { path, base: baseOverride ?? dirname(path) };
335
+ }
336
+ throw new Error(
337
+ `No credentials.json found. Looked in:\n - ${candidates.join('\n - ') || '(nowhere — set build.credentialsJson or credentialsDir)'}`,
338
+ );
339
+ }
340
+
341
+ /** Identity helper for typed `release.config.ts` files. */
342
+ export function defineReleaseConfig(config: AppReleaseConfig): AppReleaseConfig {
343
+ return config;
344
+ }
345
+
346
+ /** Effective ASC key id / issuer (env overrides config — they're not secret). */
347
+ export function ascKeyId(config: AppReleaseConfig): string {
348
+ return process.env.ASC_KEY_ID || config.asc?.keyId || '';
349
+ }
350
+ export function ascIssuer(config: AppReleaseConfig): string {
351
+ return process.env.ASC_ISSUER || config.asc?.issuer || '';
352
+ }
353
+
354
+ /**
355
+ * Resolve the ASC `.p8` private key path, in order:
356
+ * 1. config.asc?.keyPath (explicit)
357
+ * 2. $ASC_KEY_PATH (env override)
358
+ * 3. ~/.appstoreconnect/private_keys/AuthKey_<id>.p8 (where release.sh installs it)
359
+ * 4. <credentialsDir>/ios/AuthKey_<id>_ASC_API.p8 (durable GDrive source)
360
+ */
361
+ /**
362
+ * The durable `.p8` source — where the key really lives (Drive / `.keys/`),
363
+ * for installing into ~/.appstoreconnect. Order: asc.keySourcePath →
364
+ * `<credentialsDir>/ios/AuthKey_<id>_ASC_API.p8`. Returns undefined if neither.
365
+ */
366
+ export function ascKeySourcePath(config: AppReleaseConfig): string | undefined {
367
+ const id = ascKeyId(config);
368
+ if (config.asc?.keySourcePath) return releasePath(config, config.asc.keySourcePath);
369
+ if (config.credentialsDir) return resolve(releasePath(config, config.credentialsDir), `ios/AuthKey_${id}_ASC_API.p8`);
370
+ return undefined;
371
+ }
372
+
373
+ export function resolveAscKeyPath(config: AppReleaseConfig): string {
374
+ if (config.asc?.keyPath) return releasePath(config, config.asc.keyPath);
375
+ if (process.env.ASC_KEY_PATH) return process.env.ASC_KEY_PATH;
376
+ const id = ascKeyId(config);
377
+ const installed = resolve(homedir(), `.appstoreconnect/private_keys/AuthKey_${id}.p8`);
378
+ if (existsSync(installed)) return installed;
379
+ const source = ascKeySourcePath(config);
380
+ if (source) return source;
381
+ throw new Error(
382
+ 'Cannot resolve the ASC .p8 key path. Set asc.keyPath, asc.keySourcePath, $ASC_KEY_PATH, or credentialsDir.',
383
+ );
384
+ }
385
+
386
+ /**
387
+ * Resolve the Google Play service-account JSON path, in order:
388
+ * 1. config.play.serviceAccountKeyPath
389
+ * 2. $GOOGLE_SERVICE_ACCOUNT_KEY_PATH
390
+ * 3. <credentialsDir>/android/google-service-account.json
391
+ */
392
+ export function resolvePlayKeyPath(config: AppReleaseConfig): string {
393
+ const keyPath = config.play?.keyPath;
394
+ const legacyPath = config.play?.serviceAccountKeyPath;
395
+ if (keyPath && legacyPath && releasePath(config, keyPath) !== releasePath(config, legacyPath)) {
396
+ throw new Error('play.keyPath and play.serviceAccountKeyPath disagree; choose one key file.');
397
+ }
398
+ if (keyPath || legacyPath) return releasePath(config, (keyPath || legacyPath)!);
399
+ if (process.env.GOOGLE_SERVICE_ACCOUNT_KEY_PATH) return process.env.GOOGLE_SERVICE_ACCOUNT_KEY_PATH;
400
+ if (config.credentialsDir) return resolve(releasePath(config, config.credentialsDir), 'android/google-service-account.json');
401
+ throw new Error(
402
+ 'Cannot resolve the Play service-account key path. Set play.serviceAccountKeyPath, ' +
403
+ '$GOOGLE_SERVICE_ACCOUNT_KEY_PATH, or credentialsDir.',
404
+ );
405
+ }
406
+
407
+ /** Base directory travels with a loaded config without appearing in its public data. */
408
+ const configRoots = new WeakMap<AppReleaseConfig, string>();
409
+ export function releasePath(config: AppReleaseConfig, path: string): string {
410
+ return resolve(configRoots.get(config) ?? process.cwd(), path);
411
+ }
412
+
413
+ /** Apply optional conveniences without changing the caller's object. */
414
+ export function normalizeReleaseConfig(config: AppReleaseConfig): AppReleaseConfig {
415
+ const mirror = (map: Record<string, string> | undefined) => {
416
+ if (!map) return undefined;
417
+ if (config.asc?.englishUkFallback === true && map['en-US'] && !map['en-GB']) {
418
+ return { ...map, 'en-GB': map['en-US'] };
419
+ }
420
+ return { ...map };
421
+ };
422
+ const result = { ...config,
423
+ locales: config.locales && { ...config.locales, apple: mirror(config.locales.apple) },
424
+ listingLocales: config.listingLocales && { ...config.listingLocales, apple: mirror(config.listingLocales.apple) },
425
+ };
426
+ const root = configRoots.get(config);
427
+ if (root) configRoots.set(result, root);
428
+ return result;
429
+ }
430
+
431
+ /** Resolve only the selected store's locales. Empty maps are errors, never successful no-ops. */
432
+ export function listingLocaleMap(config: AppReleaseConfig, store: 'apple' | 'play', override?: Record<string, string>): Record<string, string> {
433
+ const map = override ?? config.listingLocales?.[store] ?? config.locales?.[store];
434
+ if (!map || !Object.keys(map).length) throw new Error(`Configure listingLocales.${store} or pass a non-empty localeMap.`);
435
+ return map;
436
+ }
437
+
438
+ /** Load TS, JS, MJS or JSON from an explicit file or the conventional config in a directory. */
439
+ export async function loadReleaseConfig(from: string = process.cwd()): Promise<AppReleaseConfig> {
440
+ const target = resolve(from);
441
+ const candidates = existsSync(target) && statSync(target).isFile() ? [target]
442
+ : ['ts', 'js', 'mjs', 'json'].map(ext => resolve(target, `release.config.${ext}`));
443
+ for (const path of candidates) {
444
+ if (!existsSync(path)) continue;
445
+ const mod = path.endsWith('.json') ? { default: JSON.parse(readFileSync(path, 'utf8')) }
446
+ : await import(pathToFileURL(path).href);
447
+ const config = mod.default ?? mod.config;
448
+ if (!config || typeof config !== 'object') throw new Error(`${path} must export a configuration object.`);
449
+ const result = normalizeReleaseConfig(config);
450
+ configRoots.set(result, dirname(path));
451
+ return result;
452
+ }
453
+ throw new Error(`No release config found at ${target}. Use --config <file>.`);
454
+ }