@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.
@@ -0,0 +1,367 @@
1
+ /**
2
+ * App Store version operations: wait for a build to process, resolve the version
3
+ * record to MATCH the build (find-or-create-or-rename), attach the build, set
4
+ * export compliance, and backfill blank release notes.
5
+ */
6
+
7
+ import type { AscClient } from './client.ts';
8
+ import {
9
+ ACTIVE_SUBMISSION_STATE,
10
+ QUEUED_SUBMISSION_STATE,
11
+ cancelSubmission,
12
+ listSubmissions,
13
+ } from './submissions.ts';
14
+
15
+ /** App Store version states we can still edit / submit from. */
16
+ export const EDITABLE_STATES = new Set([
17
+ 'PREPARE_FOR_SUBMISSION',
18
+ 'DEVELOPER_REJECTED',
19
+ 'REJECTED',
20
+ 'METADATA_REJECTED',
21
+ 'INVALID_BINARY',
22
+ ]);
23
+
24
+ /**
25
+ * Version states where the record EXISTS but a pending review has it locked. It
26
+ * can't take a new build, and Apple refuses to create a second version beside
27
+ * it — `POST /appStoreVersions` answers 409 with *"You cannot create a new
28
+ * version of the App in the current state"* + *"The version number has been
29
+ * previously used"*, which reads like a version-numbering problem and isn't.
30
+ *
31
+ * Not the same thing as a closed train: those versions are approved and the fix
32
+ * is `--patch`. These are versions still waiting, where the fix is to cancel the
33
+ * submission and reuse the record — see `--replace-submission`.
34
+ */
35
+ export const IN_FLIGHT_STATES = new Set([QUEUED_SUBMISSION_STATE, ACTIVE_SUBMISSION_STATE]);
36
+
37
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
38
+
39
+ /** Numeric dotted-version compare ("1.0.6" vs "1.0.10" → negative). */
40
+ const cmpVersion = (a: string, b: string): number => {
41
+ const pa = a.split('.').map(Number);
42
+ const pb = b.split('.').map(Number);
43
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
44
+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);
45
+ if (d) return d;
46
+ }
47
+ return 0;
48
+ };
49
+
50
+ // Once Apple APPROVES a version, its train is closed: a new upload's
51
+ // CFBundleShortVersionString must be STRICTLY higher (altool errors 90062 +
52
+ // 90186 — which otherwise land ~25 build-minutes in). These are the
53
+ // approved-side appStoreStates.
54
+ const APPROVED_STATES = 'READY_FOR_SALE,PENDING_DEVELOPER_RELEASE,PENDING_APPLE_RELEASE,PROCESSING_FOR_APP_STORE,REPLACED_WITH_NEW_VERSION';
55
+
56
+ /**
57
+ * Fail fast (BEFORE building) when `version` is not above the highest approved
58
+ * App Store version. Lenient on API/network errors — this is a guard, not a
59
+ * gate; a real problem resurfaces at upload.
60
+ */
61
+ export async function assertVersionTrainOpen(
62
+ client: AscClient,
63
+ appId: string,
64
+ version: string,
65
+ opts: { replaceSubmission?: boolean } = {},
66
+ ): Promise<void> {
67
+ let approved: string[];
68
+ try {
69
+ const res = await client.api(
70
+ `/apps/${appId}/appStoreVersions?filter[platform]=IOS&filter[appStoreState]=${APPROVED_STATES}` +
71
+ `&limit=20&fields[appStoreVersions]=versionString,appStoreState`,
72
+ );
73
+ approved = (res.data ?? []).map((v: any) => v.attributes.versionString as string);
74
+ } catch (err) {
75
+ console.warn(` ! could not check approved App Store versions (${err instanceof Error ? err.message.split('\n')[0] : err}) — continuing`);
76
+ return;
77
+ }
78
+ const highest = approved.sort(cmpVersion).at(-1);
79
+ if (highest && cmpVersion(version, highest) <= 0) {
80
+ throw new Error(
81
+ `iOS version train ${version} is closed — ${highest} is already approved on the App Store.\n` +
82
+ ` Apple requires a strictly higher CFBundleShortVersionString: re-run with --patch (or --minor/--major).`,
83
+ );
84
+ }
85
+ console.log(` ✓ iOS version ${version} is above the latest approved (${highest ?? 'none yet'})`);
86
+ await assertVersionNotInFlight(client, appId, version, opts);
87
+ }
88
+
89
+ /**
90
+ * Fail fast (BEFORE building) when a version record for this exact version is
91
+ * already sitting in Apple's review queue.
92
+ *
93
+ * The train check above only looks at APPROVED versions, so a version that has
94
+ * been submitted but not yet reviewed sails straight past it — and the build,
95
+ * the upload and the Android leg all succeed before `resolveVersion` walks into
96
+ * a 409 it can do nothing with. Twenty-odd minutes to learn something knowable
97
+ * in one request.
98
+ *
99
+ * Lenient on API/network errors, like its neighbour: this is a guard, not a gate.
100
+ */
101
+ async function assertVersionNotInFlight(
102
+ client: AscClient,
103
+ appId: string,
104
+ version: string,
105
+ opts: { replaceSubmission?: boolean } = {},
106
+ ): Promise<void> {
107
+ let inFlight: { versionString: string; state: string } | undefined;
108
+ try {
109
+ const res = await client.api(
110
+ `/apps/${appId}/appStoreVersions?filter[platform]=IOS` +
111
+ `&filter[appStoreState]=${[...IN_FLIGHT_STATES].join(',')}` +
112
+ `&limit=10&fields[appStoreVersions]=versionString,appStoreState`,
113
+ );
114
+ inFlight = (res.data ?? [])
115
+ .map((v: any) => ({ versionString: v.attributes.versionString as string, state: v.attributes.appStoreState as string }))
116
+ .find((v: { versionString: string }) => v.versionString === version);
117
+ } catch (err) {
118
+ console.warn(` ! could not check in-flight App Store versions (${err instanceof Error ? err.message.split('\n')[0] : err}) — continuing`);
119
+ return;
120
+ }
121
+ if (!inFlight) return;
122
+
123
+ if (inFlight.state === ACTIVE_SUBMISSION_STATE) {
124
+ throw new Error(
125
+ `iOS version ${version} is already IN REVIEW.\n` +
126
+ ` A reviewer has it open — a new build cannot be attached, and cancelling that is a\n` +
127
+ ` decision for a person. Wait for the outcome, or bump: re-run with --patch.`,
128
+ );
129
+ }
130
+ if (!opts.replaceSubmission) {
131
+ throw new Error(
132
+ `iOS version ${version} is already submitted and ${inFlight.state}.\n` +
133
+ ` Apple locks the version record while it waits, so this build cannot be attached to it\n` +
134
+ ` and no second ${version} can be created. Two ways on:\n` +
135
+ ` --replace-submission cancel the queued submission and ship this build as ${version}\n` +
136
+ ` (loses its place in the review queue — nothing has been reviewed yet)\n` +
137
+ ` --patch leave it queued and ship this build as the next version`,
138
+ );
139
+ }
140
+ console.log(` ! version ${version} is queued (${inFlight.state}); --replace-submission will cancel it before submitting`);
141
+ }
142
+
143
+ /**
144
+ * Find the build for (marketingVersion, buildNumber). `filter[version]` is the
145
+ * CFBundleVersion (build number); we additionally confirm the marketing version
146
+ * via the included preReleaseVersion so we never grab a same-numbered build from
147
+ * a different train.
148
+ */
149
+ async function findBuild(client: AscClient, appId: string, version: string, build: string) {
150
+ const res = await client.api(
151
+ `/builds?filter[app]=${appId}&filter[version]=${build}` +
152
+ `&include=preReleaseVersion&limit=10&sort=-uploadedDate` +
153
+ // `preReleaseVersion` MUST be in fields[builds] or the sparse fieldset omits
154
+ // the relationship entirely, leaving the train undefined (and the marketing-
155
+ // version cross-check below silently never matching).
156
+ `&fields[builds]=version,processingState,usesNonExemptEncryption,expired,preReleaseVersion` +
157
+ `&fields[preReleaseVersions]=version`,
158
+ );
159
+ const prById = new Map<string, string>(
160
+ (res.included ?? [])
161
+ .filter((i: any) => i.type === 'preReleaseVersions')
162
+ .map((i: any) => [i.id, i.attributes.version]),
163
+ );
164
+ // `filter[version]` already scopes to this build number for this app. Prefer
165
+ // the one whose train matches the marketing version (guards against a same-
166
+ // numbered build from another train), but fall back to the build-number match
167
+ // if the train relationship is absent — never poll forever over a missing rel.
168
+ const candidates = (res.data ?? []).filter((b: any) => b.attributes.version === build);
169
+ return (
170
+ candidates.find((b: any) => prById.get(b.relationships?.preReleaseVersion?.data?.id) === version) ??
171
+ candidates[0]
172
+ );
173
+ }
174
+
175
+ /** Poll until the build reaches processingState VALID (or throw on FAILED/INVALID/timeout). */
176
+ export async function waitForBuild(
177
+ client: AscClient,
178
+ appId: string,
179
+ version: string,
180
+ build: string,
181
+ timeoutMin = 45,
182
+ ): Promise<any> {
183
+ const deadline = Date.now() + timeoutMin * 60_000;
184
+ let announced = false;
185
+ for (;;) {
186
+ const b = await findBuild(client, appId, version, build);
187
+ if (b) {
188
+ if (!announced) {
189
+ console.log(` ✓ build ${version} (${build}) registered (id=${b.id})`);
190
+ announced = true;
191
+ }
192
+ const st = b.attributes.processingState;
193
+ if (st === 'VALID') return b;
194
+ if (st === 'FAILED' || st === 'INVALID') {
195
+ throw new Error(`Build ${version} (${build}) processing ${st} — cannot submit.`);
196
+ }
197
+ console.log(` … processing=${st}, waiting…`);
198
+ } else {
199
+ console.log(` … build ${version} (${build}) not visible in ASC yet, waiting…`);
200
+ }
201
+ if (Date.now() > deadline) {
202
+ throw new Error(`Timed out after ${timeoutMin} min waiting for build ${version} (${build}) to become VALID.`);
203
+ }
204
+ await sleep(30_000);
205
+ }
206
+ }
207
+
208
+ /**
209
+ * Resolve the App Store version record, NAMED to match this build. The record's
210
+ * versionString must equal the build's marketing version or ASC won't accept the
211
+ * attach. Rather than fail on a mismatch, we make it match:
212
+ * - an editable record with the wrong name (e.g. a leftover DEVELOPER_REJECTED
213
+ * 1.0.2) → rename it in place, keeping its metadata/screenshots;
214
+ * - none → create a fresh one.
215
+ * Apple allows only ONE editable version at a time, so we never create a second
216
+ * alongside an open one — we rename the open one.
217
+ */
218
+ export async function resolveVersion(
219
+ client: AscClient,
220
+ appId: string,
221
+ version: string,
222
+ opts: { replaceSubmission?: boolean } = {},
223
+ ): Promise<string> {
224
+ const versions = await client.api(
225
+ `/apps/${appId}/appStoreVersions?limit=10&filter[platform]=IOS&fields[appStoreVersions]=versionString,appStoreState,appVersionState`,
226
+ );
227
+ const state = (v: any) => (v.attributes.appStoreState ?? v.attributes.appVersionState) as string;
228
+ const editable = (versions.data ?? []).find((v: any) => EDITABLE_STATES.has(state(v)));
229
+
230
+ if (editable) {
231
+ const vState = editable.attributes.appStoreState ?? editable.attributes.appVersionState;
232
+ if (editable.attributes.versionString === version) {
233
+ console.log(` ✓ version ${version} already present (state=${vState}, id=${editable.id})`);
234
+ return editable.id;
235
+ }
236
+ console.log(` · renaming editable ${editable.attributes.versionString} (state=${vState}) → ${version}`);
237
+ await client.api(`/appStoreVersions/${editable.id}`, {
238
+ method: 'PATCH',
239
+ body: JSON.stringify({
240
+ data: { type: 'appStoreVersions', id: editable.id, attributes: { versionString: version } },
241
+ }),
242
+ });
243
+ console.log(` ✓ renamed to ${version}`);
244
+ return editable.id;
245
+ }
246
+
247
+ // No editable record. Before creating one, check whether THIS version is
248
+ // simply locked by a submission still waiting in the queue — creating a second
249
+ // one is impossible in that state, and the 409 that comes back names the
250
+ // version string, so it reads as a numbering mistake. Cancel and reuse instead.
251
+ const queued = (versions.data ?? []).find(
252
+ (v: any) => v.attributes.versionString === version && IN_FLIGHT_STATES.has(state(v)),
253
+ );
254
+ if (queued) {
255
+ const qState = state(queued);
256
+ if (qState === ACTIVE_SUBMISSION_STATE) {
257
+ throw new Error(`Version ${version} is IN REVIEW — a build cannot be attached to it. Wait for the outcome, or ship the next version.`);
258
+ }
259
+ if (!opts.replaceSubmission) {
260
+ throw new Error(
261
+ `Version ${version} is already submitted and ${qState}, so it is locked and no second ${version} can be created.\n` +
262
+ ` Re-run with --replace-submission to cancel the queued submission and ship this build as ${version},\n` +
263
+ ` or bump the version instead.`,
264
+ );
265
+ }
266
+ const open = (await listSubmissions(client, appId)).find(
267
+ (s) => s.state === QUEUED_SUBMISSION_STATE || s.state === 'READY_FOR_REVIEW',
268
+ );
269
+ if (open) await cancelSubmission(client, open.id, `version ${version} is queued (${qState}) and --replace-submission was given`);
270
+ // Cancelling settles the submission first and the VERSION a moment later, so
271
+ // re-read the record rather than trusting the state we listed before.
272
+ const settled = await waitForEditableVersion(client, queued.id);
273
+ console.log(` ✓ reusing ${version} (state=${settled}, id=${queued.id})`);
274
+ return queued.id;
275
+ }
276
+
277
+ console.log(` · no editable version — creating ${version}`);
278
+ const created = await client.api(`/appStoreVersions`, {
279
+ method: 'POST',
280
+ body: JSON.stringify({
281
+ data: {
282
+ type: 'appStoreVersions',
283
+ attributes: { versionString: version, platform: 'IOS' },
284
+ relationships: { app: { data: { type: 'apps', id: appId } } },
285
+ },
286
+ }),
287
+ });
288
+ console.log(` ✓ created ${version} (id=${created.data.id})`);
289
+ return created.data.id;
290
+ }
291
+
292
+ /** Poll a version record until it is editable again (after a submission was cancelled). */
293
+ async function waitForEditableVersion(client: AscClient, versionId: string, timeoutMin = 10): Promise<string> {
294
+ const deadline = Date.now() + timeoutMin * 60_000;
295
+ for (;;) {
296
+ const res = await client.api(`/appStoreVersions/${versionId}?fields[appStoreVersions]=appStoreState,appVersionState`);
297
+ const st = (res?.data?.attributes?.appStoreState ?? res?.data?.attributes?.appVersionState) as string;
298
+ if (EDITABLE_STATES.has(st)) return st;
299
+ if (Date.now() > deadline) {
300
+ throw new Error(`Timed out after ${timeoutMin} min waiting for version ${versionId} to become editable (state=${st}).`);
301
+ }
302
+ await sleep(10_000);
303
+ }
304
+ }
305
+
306
+ /** Attach a build to a version record. */
307
+ export async function attachBuild(client: AscClient, versionId: string, buildId: string): Promise<void> {
308
+ await client.api(`/appStoreVersions/${versionId}/relationships/build`, {
309
+ method: 'PATCH',
310
+ body: JSON.stringify({ data: { type: 'builds', id: buildId } }),
311
+ });
312
+ }
313
+
314
+ /** Resolve export compliance if ASC left `usesNonExemptEncryption` null. */
315
+ export async function ensureExportCompliance(client: AscClient, build: any): Promise<void> {
316
+ if (build.attributes.usesNonExemptEncryption === null) {
317
+ await client.api(`/builds/${build.id}`, {
318
+ method: 'PATCH',
319
+ body: JSON.stringify({
320
+ data: { type: 'builds', id: build.id, attributes: { usesNonExemptEncryption: false } },
321
+ }),
322
+ });
323
+ console.log(' ✓ export compliance set (usesNonExemptEncryption=false)');
324
+ } else {
325
+ console.log(` ✓ export compliance already resolved (usesNonExemptEncryption=${build.attributes.usesNonExemptEncryption})`);
326
+ }
327
+ }
328
+
329
+ /**
330
+ * Fill blank `whatsNew` on each version localization. `notesByAscLocale` maps an
331
+ * ASC locale (e.g. `en-US`, `sv`) → text. Hand-written notes already on the
332
+ * record win; only empty ones are filled (default falls back to the first entry).
333
+ */
334
+ export async function backfillWhatsNew(
335
+ client: AscClient,
336
+ versionId: string,
337
+ notesByAscLocale: Record<string, string>,
338
+ ): Promise<void> {
339
+ // Apple does not expose What's New for an app's first version. Determine this
340
+ // from its version records, never from a particular marketing version number.
341
+ // https://developer.apple.com/help/app-store-connect/reference/app-information/platform-version-information
342
+ const app = await client.findApp();
343
+ const versions = await client.api(`/apps/${app.id}/appStoreVersions?filter[platform]=IOS&limit=2&fields[appStoreVersions]=versionString`);
344
+ if (versions.data?.length === 1 && versions.data[0].id === versionId) {
345
+ console.log(' ✓ first App Store version: What’s New is unavailable');
346
+ return;
347
+ }
348
+ const fallback = Object.values(notesByAscLocale)[0] ?? 'Bug fixes and improvements.';
349
+ const locs = await client.api(
350
+ `/appStoreVersions/${versionId}/appStoreVersionLocalizations?fields[appStoreVersionLocalizations]=locale,whatsNew&limit=50`,
351
+ );
352
+ for (const loc of locs.data ?? []) {
353
+ const locale = loc.attributes.locale as string;
354
+ if ((loc.attributes.whatsNew ?? '').trim()) {
355
+ console.log(` ✓ ${locale}: keeping existing notes`);
356
+ continue;
357
+ }
358
+ const text = notesByAscLocale[locale] ?? fallback;
359
+ await client.api(`/appStoreVersionLocalizations/${loc.id}`, {
360
+ method: 'PATCH',
361
+ body: JSON.stringify({
362
+ data: { type: 'appStoreVersionLocalizations', id: loc.id, attributes: { whatsNew: text } },
363
+ }),
364
+ });
365
+ console.log(` ✓ ${locale}: set "${text}"`);
366
+ }
367
+ }
@@ -0,0 +1,122 @@
1
+ /** Local build and store release support. All app settings come from the consuming configuration. */
2
+ import { readFileSync, writeFileSync } from 'node:fs';
3
+ import { resolve } from 'node:path';
4
+ import { releasePath } from '../config.ts';
5
+ import type { AppReleaseConfig } from '../config.ts';
6
+ import type { AndroidSigning } from './credentials.ts';
7
+ import { run, runLogged } from './exec.ts';
8
+ import { stage, stageLogPath } from '../progress.ts';
9
+
10
+
11
+ const GRADLE_SURFACE = /^(FAILURE:|\* What went wrong:|\* Try:|Caused by:|e: |BUILD (?:SUCCESSFUL|FAILED))/;
12
+
13
+
14
+ function gradleStatus(line: string): string | undefined {
15
+ const task = line.match(/^> Task (\S+)/);
16
+ if (task) return task[1].replace(/^:/, '');
17
+ const transform = line.match(/^> Transform (\S+)/);
18
+ if (transform) return `transform ${transform[1]}`;
19
+ return undefined;
20
+ }
21
+
22
+ const RELEASE_BLOCK = ` release {
23
+ storeFile file(property('RELEASE_STORE_FILE'))
24
+ storePassword property('RELEASE_STORE_PASSWORD')
25
+ keyAlias property('RELEASE_KEY_ALIAS')
26
+ keyPassword property('RELEASE_KEY_PASSWORD')
27
+ }`;
28
+
29
+ // Apply only the consuming app's explicit memory settings after native generation.
30
+
31
+
32
+ function patchGradleJvmArgs(appDir: string, args?: string): void {
33
+ if (!args) return;
34
+ const GRADLE_JVMARGS = `org.gradle.jvmargs=${args}`;
35
+ const file = resolve(appDir, 'android/gradle.properties');
36
+ let content = readFileSync(file, 'utf8');
37
+ if (/^org\.gradle\.jvmargs=/m.test(content)) {
38
+ content = content.replace(/^org\.gradle\.jvmargs=.*$/m, GRADLE_JVMARGS);
39
+ } else {
40
+ content += `\n${GRADLE_JVMARGS}\n`;
41
+ }
42
+ writeFileSync(file, content);
43
+ console.log(` gradle.properties: ${GRADLE_JVMARGS}`);
44
+ }
45
+
46
+ export function patchGradleSigning(appDir: string): void {
47
+ const gradle = resolve(appDir, 'android/app/build.gradle');
48
+ let content = readFileSync(gradle, 'utf8');
49
+ if (content.includes('signingConfigs.release')) {
50
+ console.log(' Release signingConfig already present.');
51
+ return;
52
+ }
53
+ console.log(' Patching build.gradle with release signingConfig...');
54
+ // Insert the release block right after the debug { … } block inside signingConfigs.
55
+ const withBlock = content.replace(/(signingConfigs\s*\{[^}]*debug\s*\{[^}]*\})/, `$1\n${RELEASE_BLOCK}`);
56
+ if (withBlock === content) throw new Error('Unrecognized Expo signingConfigs template. Configure release signing before building.');
57
+ content = withBlock;
58
+ // Point the release buildType at it.
59
+ content = content.replace(/(release\s*\{[^}]*signingConfig\s+)signingConfigs\.debug/, '$1signingConfigs.release');
60
+ if (!content.includes('signingConfig signingConfigs.release')) throw new Error('Unrecognized Expo release buildType. Refusing to build with debug signing.');
61
+ writeFileSync(gradle, content);
62
+ console.log(' Patched successfully.');
63
+ }
64
+
65
+
66
+ export async function buildAndroid(
67
+ config: AppReleaseConfig,
68
+ signing: AndroidSigning,
69
+ sentryToken: string | undefined,
70
+ ): Promise<string> {
71
+ const appDir = resolve(releasePath(config, '.'), config.build!.appDir);
72
+ if (config.build?.framework === 'expo') patchGradleSigning(appDir);
73
+ patchGradleJvmArgs(appDir, config.build?.gradleJvmArgs);
74
+
75
+ const props: Record<string, string> = {
76
+ RELEASE_STORE_FILE: signing.keystorePath,
77
+ RELEASE_STORE_PASSWORD: signing.keystorePassword,
78
+ RELEASE_KEY_ALIAS: signing.keyAlias,
79
+ RELEASE_KEY_PASSWORD: signing.keyPassword,
80
+ ...(config.build!.gradleProps ?? {}),
81
+ };
82
+ // Props sourced from env (e.g. MAPBOX_DOWNLOADS_TOKEN from driveEnv).
83
+ for (const name of config.build!.gradleEnvProps ?? []) {
84
+ props[name] = process.env[name] ?? '';
85
+ }
86
+
87
+ // Pass props as ORG_GRADLE_PROJECT_* env vars, NOT `-P` argv. Gradle resolves
88
+ // these to identical project properties for findProperty(...), but the values
89
+ // (keystore + key passwords, Mapbox download token) stay out of the process
90
+ // table AND out of run()'s on-failure error string (which joins argv) — gradle
91
+ // build failures are common, and a `-P<PASSWORD>=…` argv would leak there.
92
+ const env = { ...process.env };
93
+ for (const [k, v] of Object.entries(props)) env[`ORG_GRADLE_PROJECT_${k}`] = v;
94
+ if (!sentryToken) env.SENTRY_DISABLE_AUTO_UPLOAD = 'true';
95
+
96
+ // Stop leftover daemons first: one from a crashed/OOM'd build (running with
97
+ // the OLD jvmargs) holds the journal-cache lock, which fails the next build
98
+ // with "Timeout waiting to lock journal cache". Cheap; a fresh daemon also
99
+ // guarantees the jvmargs patched above actually apply.
100
+ try {
101
+ await run('./gradlew', ['--stop'], { cwd: resolve(appDir, 'android'), env });
102
+ } catch {
103
+ /* no daemon registry yet — nothing to stop */
104
+ }
105
+
106
+ await stage('android-build', 'Building Android AAB', () =>
107
+ runLogged('./gradlew', ['bundleRelease'], {
108
+ cwd: resolve(appDir, 'android'),
109
+ env,
110
+ logFile: stageLogPath('android-build', releasePath(config, '.')),
111
+ surface: GRADLE_SURFACE,
112
+ status: gradleStatus,
113
+ // Gradle prints the actual cause well above the last line (the tail is
114
+ // "BUILD FAILED" plus the --stacktrace hint), so it needs a longer tail
115
+ // than xcodebuild's.
116
+ tailOnFailure: 60,
117
+ }),
118
+ );
119
+ const aab = resolve(appDir, 'android/app/build/outputs/bundle/release/app-release.aab');
120
+ console.log(` AAB: ${aab}`);
121
+ return aab;
122
+ }
@@ -0,0 +1,57 @@
1
+ /** Local build and store release support. All app settings come from the consuming configuration. */
2
+ import { readFileSync } from 'node:fs';
3
+ import { resolve } from 'node:path';
4
+ import { releasePath } from '../config.ts';
5
+ import type { AppReleaseConfig } from '../config.ts';
6
+ import { resolveCredentialsJson } from '../config.ts';
7
+
8
+ export interface AndroidSigning {
9
+ keystorePath: string;
10
+ keystorePassword: string;
11
+ keyAlias: string;
12
+ keyPassword: string;
13
+ }
14
+ export interface IosSigning {
15
+ distCertPath: string;
16
+ distCertPassword: string;
17
+ provisioningProfilePath: string;
18
+ }
19
+
20
+ export interface SigningCredentials {
21
+ android?: AndroidSigning;
22
+ ios?: IosSigning;
23
+ }
24
+
25
+
26
+ export function loadSigningCredentials(
27
+ config: AppReleaseConfig,
28
+ want: { ios: boolean; android: boolean },
29
+ ): SigningCredentials {
30
+ const { path, base } = resolveCredentialsJson(config);
31
+ console.log(`Using credentials from: ${path}`);
32
+ const j = JSON.parse(readFileSync(path, 'utf8'));
33
+ const creds: SigningCredentials = {};
34
+
35
+ if (want.android) {
36
+ const k = j.android?.keystore;
37
+ if (!k) throw new Error(`credentials.json has no android.keystore section (${path}).`);
38
+ creds.android = {
39
+ keystorePath: resolve(base, k.keystorePath),
40
+ keystorePassword: k.keystorePassword,
41
+ keyAlias: k.keyAlias,
42
+ keyPassword: k.keyPassword,
43
+ };
44
+ }
45
+ if (want.ios) {
46
+ const cert = j.ios?.distributionCertificate;
47
+ if (!cert || !j.ios?.provisioningProfilePath) {
48
+ throw new Error(`credentials.json has no ios.distributionCertificate / provisioningProfilePath (${path}).`);
49
+ }
50
+ creds.ios = {
51
+ distCertPath: resolve(base, cert.path),
52
+ distCertPassword: cert.password,
53
+ provisioningProfilePath: resolve(base, j.ios.provisioningProfilePath),
54
+ };
55
+ }
56
+ return creds;
57
+ }
@@ -0,0 +1,60 @@
1
+ /** Local build and store release support. All app settings come from the consuming configuration. */
2
+ import { existsSync, renameSync } from 'node:fs';
3
+ import { resolve } from 'node:path';
4
+ import { releasePath } from '../config.ts';
5
+ import type { AppReleaseConfig } from '../config.ts';
6
+
7
+ const SUFFIX = '.release-bak';
8
+
9
+ export interface EnvHideHandle {
10
+ restore(): void;
11
+ }
12
+
13
+
14
+ export function hideEnvFiles(config: AppReleaseConfig): EnvHideHandle {
15
+ const appDir = resolve(releasePath(config, '.'), config.build?.appDir ?? '.');
16
+ const names = config.build?.hideEnvFiles ?? [];
17
+
18
+ // Self-heal leftovers from a SIGKILL'd / power-lost prior run.
19
+ for (const name of names) {
20
+ const orig = resolve(appDir, name);
21
+ const bak = orig + SUFFIX;
22
+ if (existsSync(bak) && !existsSync(orig)) {
23
+ console.log(` Found leftover ${name}${SUFFIX} from a crashed run — restoring.`);
24
+ renameSync(bak, orig);
25
+ }
26
+ }
27
+
28
+ const hidden: string[] = [];
29
+ for (const name of names) {
30
+ const orig = resolve(appDir, name);
31
+ const bak = orig + SUFFIX;
32
+ if (existsSync(orig)) {
33
+ if (existsSync(bak)) throw new Error(`Backup already exists for ${orig}`);
34
+ renameSync(orig, bak);
35
+ hidden.push(orig);
36
+ console.log(` Moved ${name} aside (production build)`);
37
+ }
38
+ }
39
+
40
+ let restored = false;
41
+ const restore = () => {
42
+ if (restored) return;
43
+ restored = true;
44
+ for (const orig of hidden) {
45
+ const bak = orig + SUFFIX;
46
+ if (existsSync(bak)) renameSync(bak, orig);
47
+ }
48
+ };
49
+
50
+ // EXIT-equivalent coverage: normal exit + signals.
51
+ process.once('exit', restore);
52
+ for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP'] as const) {
53
+ process.once(sig, () => {
54
+ restore();
55
+ process.exit(1);
56
+ });
57
+ }
58
+
59
+ return { restore };
60
+ }
@@ -0,0 +1,41 @@
1
+ /** Local build and store release support. All app settings come from the consuming configuration. */
2
+ import { readFileSync } from 'node:fs';
3
+ import { resolve } from 'node:path';
4
+ import { releasePath } from '../config.ts';
5
+ import type { AppReleaseConfig } from '../config.ts';
6
+
7
+
8
+ export function exportPublicEnvFromEas(config: AppReleaseConfig): void {
9
+ const ref = config.build?.publicEnvFromEas;
10
+ if (!ref) return;
11
+ const profile = ref.profile ?? 'production';
12
+ console.log(`── Exporting env from eas.json (${profile} profile)...`);
13
+ const eas = JSON.parse(readFileSync(releasePath(config, ref.path), 'utf8'));
14
+ const env = eas?.build?.[profile]?.env ?? {};
15
+ for (const [k, v] of Object.entries(env)) {
16
+ process.env[k] = String(v);
17
+ }
18
+ const keys = Object.keys(env);
19
+ if (keys.length) console.log(` exported ${keys.length}: ${keys.join(', ')}`);
20
+ }
21
+
22
+
23
+ export function loadBuildEnv(config: AppReleaseConfig): void {
24
+ const legacy = config.build?.driveEnv;
25
+ const ref = config.build?.envFile ?? (legacy && config.credentialsDir ? { path: resolve(releasePath(config, config.credentialsDir), legacy.file), keys: legacy.secrets } : undefined);
26
+ if (!ref) return;
27
+ const path = releasePath(config, ref.path);
28
+ let text = '';
29
+ try {
30
+ text = readFileSync(path, 'utf8');
31
+ } catch {
32
+ throw new Error(`Build environment file not found: ${path}`);
33
+ }
34
+ for (const key of ref.keys) {
35
+ if (process.env[key]) continue; // env wins
36
+ const line = text.split('\n').find((l) => l.startsWith(`${key}=`));
37
+ if (line) process.env[key] = line.slice(key.length + 1).trim().replace(/^["']|["']$/g, '');
38
+ }
39
+ const loaded = ref.keys.filter((k) => process.env[k]);
40
+ console.log(`── Build environment: ${loaded.length}/${ref.keys.length} present (${loaded.join(', ') || 'none'}).`);
41
+ }