@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,220 @@
1
+ /** Local build and store release support. All app settings come from the consuming configuration. */
2
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { dirname, resolve } from 'node:path';
4
+
5
+
6
+ export type StageId =
7
+ | 'preflight'
8
+ | 'prebuild'
9
+ | 'ios-archive'
10
+ | 'ios-export'
11
+ | 'ios-upload'
12
+ | 'android-build'
13
+ | 'android-upload'
14
+ | 'asc-processing';
15
+
16
+
17
+ export function stageLogPath(id: StageId, root = process.cwd()): string {
18
+ return resolve(root, '.sprid-release/logs', `${id}.log`);
19
+ }
20
+
21
+
22
+ const SEED_SECONDS: Partial<Record<StageId, number>> = {};
23
+
24
+ const MAX_SAMPLES = 5;
25
+ let pipelineRoot = process.cwd();
26
+ const STORE_PATH = () => resolve(pipelineRoot, '.sprid-release/timings.json');
27
+
28
+ interface Store {
29
+ version: 1;
30
+
31
+ stages: Partial<Record<StageId, number[]>>;
32
+ }
33
+
34
+ function readStore(): Store {
35
+ try {
36
+ const raw = JSON.parse(readFileSync(STORE_PATH(), 'utf8'));
37
+ if (raw?.version === 1 && raw.stages) return raw as Store;
38
+ } catch {
39
+ /* absent or unreadable — first run on this machine */
40
+ }
41
+ return { version: 1, stages: {} };
42
+ }
43
+
44
+ function writeStore(store: Store): void {
45
+ try {
46
+ const path = STORE_PATH();
47
+ mkdirSync(dirname(path), { recursive: true });
48
+ writeFileSync(path, `${JSON.stringify(store, null, 2)}\n`);
49
+ } catch {
50
+ /* a release must never fail because it could not write its own stopwatch */
51
+ }
52
+ }
53
+
54
+ function median(xs: number[]): number {
55
+ const s = [...xs].sort((a, b) => a - b);
56
+ const mid = s.length >> 1;
57
+ return s.length % 2 ? s[mid] : Math.round((s[mid - 1] + s[mid]) / 2);
58
+ }
59
+
60
+
61
+ function expected(id: StageId, store: Store): number | undefined {
62
+ const samples = store.stages[id];
63
+ if (samples?.length) return median(samples);
64
+ return SEED_SECONDS[id];
65
+ }
66
+
67
+ export function formatDuration(seconds: number): string {
68
+ const s = Math.max(0, Math.round(seconds));
69
+ if (s < 60) return `${s}s`;
70
+ const m = Math.floor(s / 60);
71
+ const rest = s % 60;
72
+ if (m < 60) return rest ? `${m}m${String(rest).padStart(2, '0')}s` : `${m}m`;
73
+ const h = Math.floor(m / 60);
74
+ return `${h}h${String(m % 60).padStart(2, '0')}m`;
75
+ }
76
+
77
+ function bar(fraction: number, cells = 16): string {
78
+ const filled = Math.max(0, Math.min(cells, Math.round(fraction * cells)));
79
+ return `${'▓'.repeat(filled)}${'░'.repeat(cells - filled)}`;
80
+ }
81
+
82
+
83
+ function tickInterval(expectedSec: number | undefined): number {
84
+ if (!expectedSec) return 30;
85
+ return Math.round(Math.min(60, Math.max(15, expectedSec / 20)));
86
+ }
87
+
88
+ interface PipelineState {
89
+ planned: StageId[];
90
+ store: Store;
91
+
92
+ doneSeconds: number;
93
+
94
+ totalExpected: number | undefined;
95
+ }
96
+
97
+ let pipeline: PipelineState | undefined;
98
+ let verbose = false;
99
+
100
+
101
+ export function setVerbose(on: boolean): void {
102
+ verbose = on;
103
+ }
104
+
105
+ export function isVerbose(): boolean {
106
+ return verbose;
107
+ }
108
+
109
+
110
+ export function beginPipeline(planned: StageId[], root = process.cwd()): void {
111
+ pipelineRoot = root;
112
+ const store = readStore();
113
+ const each = planned.map((id) => expected(id, store));
114
+ pipeline = {
115
+ planned,
116
+ store,
117
+ doneSeconds: 0,
118
+ totalExpected: each.every((e) => e !== undefined) ? each.reduce((a, b) => a! + b!, 0) : undefined,
119
+ };
120
+ const known = each.filter((e): e is number => e !== undefined).reduce((a, b) => a + b, 0);
121
+ const label = pipeline.totalExpected ? `~${formatDuration(known)}` : `~${formatDuration(known)}+ (some stages unmeasured)`;
122
+ console.log(`\n⟨sprid⟩ pipeline stages=${planned.length} estimate=${label}`);
123
+ }
124
+
125
+ function overallFraction(currentElapsed: number, currentExpected: number | undefined): number | undefined {
126
+ if (!pipeline?.totalExpected) return undefined;
127
+ const current = currentExpected ? Math.min(currentElapsed, currentExpected) : 0;
128
+ return Math.min(0.999, (pipeline.doneSeconds + current) / pipeline.totalExpected);
129
+ }
130
+
131
+ function overallRemaining(currentElapsed: number, currentExpected: number | undefined): number | undefined {
132
+ if (!pipeline?.totalExpected) return undefined;
133
+ const current = currentExpected ? Math.min(currentElapsed, currentExpected) : 0;
134
+ return Math.max(0, pipeline.totalExpected - pipeline.doneSeconds - current);
135
+ }
136
+
137
+
138
+ export async function stage<T>(id: StageId, label: string, fn: () => Promise<T>): Promise<T> {
139
+ const store = pipeline?.store ?? readStore();
140
+ const est = expected(id, store);
141
+ const index = pipeline ? pipeline.planned.indexOf(id) + 1 : 0;
142
+ const position = index > 0 ? `[${index}/${pipeline!.planned.length}] ` : '';
143
+ const startedAt = Date.now();
144
+
145
+ console.log(`\n── ${position}${label}${est ? ` (est ~${formatDuration(est)})` : ''}`);
146
+ console.log(`⟨sprid⟩ stage=${id} event=start est=${est ?? 'unknown'}`);
147
+
148
+ const stop = startRenderer(id, est);
149
+ try {
150
+ const result = await fn();
151
+ stop();
152
+ const took = (Date.now() - startedAt) / 1000;
153
+ record(id, took, store);
154
+ if (pipeline) pipeline.doneSeconds += est ?? took;
155
+ const drift = est ? ` (est ~${formatDuration(est)}, ${took >= est ? '+' : '-'}${formatDuration(Math.abs(took - est))})` : '';
156
+ console.log(` ✓ ${label} in ${formatDuration(took)}${drift}`);
157
+ console.log(`⟨sprid⟩ stage=${id} event=done secs=${Math.round(took)}`);
158
+ return result;
159
+ } catch (err) {
160
+ stop();
161
+ const took = (Date.now() - startedAt) / 1000;
162
+ // Deliberately NOT recorded: a stage that died at minute 3 of a 25-minute
163
+ // archive would poison the median and make every later ETA optimistic.
164
+ console.log(`⟨sprid⟩ stage=${id} event=fail secs=${Math.round(took)}`);
165
+ throw err;
166
+ }
167
+ }
168
+
169
+ function record(id: StageId, seconds: number, store: Store): void {
170
+ const samples = [...(store.stages[id] ?? []), Math.round(seconds)].slice(-MAX_SAMPLES);
171
+ store.stages[id] = samples;
172
+ writeStore(store);
173
+ }
174
+
175
+
176
+ let status = '';
177
+ export function setStageStatus(text: string): void {
178
+ status = text.length > 60 ? `${text.slice(0, 57)}...` : text;
179
+ }
180
+
181
+ function startRenderer(id: StageId, est: number | undefined): () => void {
182
+ status = '';
183
+ if (verbose) return () => {};
184
+ const startedAt = Date.now();
185
+ const tty = process.stdout.isTTY === true;
186
+ const everyMs = tty ? 250 : tickInterval(est) * 1000;
187
+
188
+ const paint = () => {
189
+ const elapsed = (Date.now() - startedAt) / 1000;
190
+ const frac = est ? Math.min(0.999, elapsed / est) : undefined;
191
+ const overall = overallFraction(elapsed, est);
192
+ const left = overallRemaining(elapsed, est);
193
+
194
+ // Past the estimate, a pinned "99%" reads as almost-done and is the one
195
+ // moment the number is actively misleading — say how far over instead.
196
+ const stagePart = !est
197
+ ? `${formatDuration(elapsed)} elapsed (no estimate yet)`
198
+ : elapsed > est
199
+ ? `${formatDuration(elapsed)}/~${formatDuration(est)} (+${formatDuration(elapsed - est)} over)`
200
+ : `${Math.floor(frac! * 100)}% ${formatDuration(elapsed)}/~${formatDuration(est)}`;
201
+ const overallPart = overall !== undefined ? ` | overall ${Math.floor(overall * 100)}% ~${formatDuration(left!)} left` : '';
202
+
203
+ if (tty) {
204
+ const cells = est ? `${bar(frac!)} ` : '';
205
+ process.stdout.write(`\r ${cells}${stagePart}${overallPart}${status ? ` ${status}` : ''}\x1b[K`);
206
+ } else {
207
+ console.log(`⟨sprid⟩ stage=${id} ${stagePart}${overallPart}${status ? ` | ${status}` : ''}`);
208
+ }
209
+ };
210
+
211
+ // A TTY paints immediately; a log does not, or every stage would open with a
212
+ // redundant 0% line right under its own header.
213
+ if (tty) paint();
214
+ const timer = setInterval(paint, everyMs);
215
+ timer.unref?.();
216
+ return () => {
217
+ clearInterval(timer);
218
+ if (tty) process.stdout.write(`\r\x1b[K`);
219
+ };
220
+ }
package/src/ship.ts ADDED
@@ -0,0 +1,194 @@
1
+ /** Local build and store release support. All app settings come from the consuming configuration. */
2
+ import { releasePath } from './config.ts';
3
+ import type { AppReleaseConfig } from './config.ts';
4
+ import type { BumpKind } from './bump.ts';
5
+ import { bumpVersion, readAppVersion } from './bump.ts';
6
+ import { assertRequiredProdEnv } from './env-guard.ts';
7
+ import { loadSigningCredentials } from './build/credentials.ts';
8
+ import { loadSentryToken } from './build/sentry.ts';
9
+ import { exportPublicEnvFromEas, loadBuildEnv } from './build/env-sources.ts';
10
+ import { hideEnvFiles } from './build/env-files.ts';
11
+ import { runPrebuild } from './build/prebuild.ts';
12
+ import { runPreflight } from './build/preflight.ts';
13
+ import { assertCleanTree, commitAndTagRelease } from './build/git.ts';
14
+ import { setupIosSigning, patchXcodeprojSigning, buildIosArchive } from './build/ios.ts';
15
+ import { buildAndroid } from './build/android.ts';
16
+ import { uploadIpa } from './asc/upload.ts';
17
+ import { submitForReview } from './asc/submit.ts';
18
+ import { createAscClient } from './asc/client.ts';
19
+ import { assertVersionTrainOpen } from './asc/version.ts';
20
+ import { PlayConsoleRequiredError, uploadAab, type PlayTrack, type UploadAabOptions } from './play/upload.ts';
21
+ import { beginPipeline, formatDuration, type StageId } from './progress.ts';
22
+ import { resolve } from 'node:path';
23
+ import { existsSync } from 'node:fs';
24
+ import { run } from './build/exec.ts';
25
+
26
+ export interface ShipOptions {
27
+ /** No version changes, builds or network writes unless explicitly true. */
28
+ execute?: boolean;
29
+ ios?: boolean;
30
+ android?: boolean;
31
+ upload?: boolean;
32
+ track?: PlayTrack;
33
+ sendPlayReview?: boolean;
34
+ submitIos?: boolean;
35
+ bumpKind?: BumpKind;
36
+ skipBump?: boolean;
37
+
38
+ submitOnly?: boolean;
39
+
40
+ allowDirty?: boolean;
41
+
42
+ pushStoreCopy?: boolean;
43
+
44
+ replaceSubmission?: boolean;
45
+ }
46
+
47
+ export async function ship(config: AppReleaseConfig, opts: ShipOptions = {}): Promise<void> {
48
+ if (!config.build) throw new Error('release.config.ts needs a `build` section for `ship`.');
49
+ if (!config.build.framework || !['expo', 'native'].includes(config.build.framework)) throw new Error('Set build.framework to expo or native.');
50
+ const ios = opts.ios ?? Boolean(config.appId || config.ascAppId);
51
+ const android = opts.android ?? Boolean(config.play);
52
+ const upload = opts.upload ?? true;
53
+ const track: PlayTrack = opts.track ?? 'production';
54
+ const sendPlayReview = opts.sendPlayReview ?? track === 'production';
55
+ const submitIos = opts.submitIos ?? true;
56
+
57
+ if (!ios && !android) throw new Error('Select at least one configured platform.');
58
+ if (!opts.execute) {
59
+ console.log(JSON.stringify({ dryRun: true, ios, android, upload, track, sendPlayReview, submitIos, bump: opts.skipBump ? false : (opts.bumpKind ?? 'build'), framework: config.build.framework, version: readAppVersion(config) }, null, 2));
60
+ return;
61
+ }
62
+ const shipStartedAt = Date.now();
63
+ console.log('=== Release ===');
64
+ console.log(` iOS: ${ios} | Android: ${android} | Upload: ${upload} | track: ${track} | Play review: ${sendPlayReview}`);
65
+
66
+ // Declare the plan before anything runs, so the overall percentage is against
67
+ // the stages this invocation will actually execute (--ios-only ships fewer).
68
+ // Order matters: it is what the [n/N] counter and the overall bar are read
69
+ // against, so it must match the execution order below exactly.
70
+ const planned: StageId[] = [];
71
+ if (!opts.submitOnly) {
72
+ if (config.build.preflight) planned.push('preflight');
73
+ planned.push('prebuild');
74
+ if (ios) planned.push('ios-archive', 'ios-export');
75
+ }
76
+ if (ios && upload && !opts.submitOnly) planned.push('ios-upload');
77
+ if (android && !opts.submitOnly) planned.push('android-build');
78
+ if (android && upload) planned.push('android-upload');
79
+ if (ios && upload && submitIos) planned.push('asc-processing');
80
+ beginPipeline(planned, releasePath(config, '.'));
81
+
82
+ const aabPath = config.build.commands?.android
83
+ ? releasePath(config, config.build.commands.android.artifact)
84
+ : resolve(releasePath(config, '.'), config.build.appDir, 'android/app/build/outputs/bundle/release/app-release.aab');
85
+ let pendingPlay: PlayConsoleRequiredError | undefined;
86
+ const uploadAndroid = async (options: UploadAabOptions) => {
87
+ try { await uploadAab(config, options); }
88
+ catch (error) {
89
+ if (!(error instanceof PlayConsoleRequiredError)) throw error;
90
+ pendingPlay = error;
91
+ console.warn(` ! ${error.message}`);
92
+ }
93
+ };
94
+
95
+ // Resume mode: artifacts already built; just (re-)upload + submit.
96
+ if (opts.submitOnly) {
97
+ console.log('── Submit-only: skipping bump/prebuild/build.');
98
+ const { version } = readAppVersion(config);
99
+ if (android && upload) await uploadAndroid({ aabPath, version, track, sendForReview: sendPlayReview });
100
+ if (ios && upload && submitIos) {
101
+ console.log('── Submitting iOS build for App Store review...');
102
+ await submitForReview(config, { version, build: readAppVersion(config).buildNumber, releaseNotes: config.releaseNotes, pushStoreCopy: opts.pushStoreCopy, replaceSubmission: opts.replaceSubmission });
103
+ }
104
+ if (pendingPlay) throw pendingPlay;
105
+ console.log(`\n=== Done in ${formatDuration((Date.now() - shipStartedAt) / 1000)} ===`);
106
+ return;
107
+ }
108
+
109
+ // Provenance first: assert clean BEFORE anything writes to the tree, so that
110
+ // whatever is dirty at the end was demonstrably produced by this release.
111
+ const gitProvenance = (config.build.gitProvenance ?? false) && !opts.allowDirty;
112
+ if (config.build.gitProvenance && opts.allowDirty) {
113
+ console.log('── --allow-dirty: skipping the clean-tree check and the release tag.');
114
+ } else if (gitProvenance) {
115
+ console.log('── Checking the working tree is clean...');
116
+ await assertCleanTree(releasePath(config, '.'));
117
+ }
118
+
119
+ if (config.build.preflight) await runPreflight(config);
120
+ // Load configured public settings and allowlisted build secrets before prebuild.
121
+ exportPublicEnvFromEas(config);
122
+ loadBuildEnv(config);
123
+ const creds = !((ios && !config.build.commands?.ios) || (android && !config.build.commands?.android)) ? {} : loadSigningCredentials(config, { ios: ios && !config.build.commands?.ios, android: android && !config.build.commands?.android });
124
+ const sentryToken = loadSentryToken(config);
125
+
126
+ if (opts.skipBump) console.log('── Skipping version bump.');
127
+ else bumpVersion(config, opts.bumpKind);
128
+ const { version } = readAppVersion(config);
129
+
130
+ // Fail fast BEFORE the iOS build if Apple has already approved this marketing
131
+ // version (the train is closed; altool would reject the upload).
132
+ if (ios && upload) {
133
+ console.log('── Checking the iOS version train is open...');
134
+ const client = createAscClient(config);
135
+ await assertVersionTrainOpen(client, (await client.findApp()).id, version, {
136
+ replaceSubmission: opts.replaceSubmission,
137
+ });
138
+ }
139
+
140
+ const envHandle = hideEnvFiles(config);
141
+ try {
142
+ assertRequiredProdEnv(config);
143
+ await runPrebuild(config, { ios, android });
144
+
145
+ let ipaPath: string | undefined;
146
+ if (ios && config.build.commands?.ios) {
147
+ ipaPath = await customBuild(config, 'ios');
148
+ if (upload) await uploadIpa(config, ipaPath);
149
+ } else if (ios) {
150
+ if (!creds.ios) throw new Error('iOS build requested but no ios credentials loaded.');
151
+ const ctx = await setupIosSigning(config, creds.ios);
152
+ await patchXcodeprojSigning(config, ctx);
153
+ ipaPath = await buildIosArchive(config, ctx, sentryToken);
154
+ if (upload) await uploadIpa(config, ipaPath);
155
+ }
156
+
157
+ if (android && config.build.commands?.android) {
158
+ const artifact = await customBuild(config, 'android');
159
+ if (upload) await uploadAndroid({ aabPath: artifact, version, track, sendForReview: sendPlayReview });
160
+ } else if (android) {
161
+ if (!creds.android) throw new Error('Android build requested but no android credentials loaded.');
162
+ const aabPath = await buildAndroid(config, creds.android, sentryToken);
163
+ if (upload) await uploadAndroid({ aabPath, version, track, sendForReview: sendPlayReview });
164
+ }
165
+
166
+ if (ios && upload && submitIos) {
167
+ console.log('── Submitting iOS build for App Store review...');
168
+ await submitForReview(config, { version, build: readAppVersion(config).buildNumber, releaseNotes: config.releaseNotes, pushStoreCopy: opts.pushStoreCopy, replaceSubmission: opts.replaceSubmission });
169
+ }
170
+ } finally {
171
+ envHandle.restore();
172
+ }
173
+ if (pendingPlay) throw pendingPlay;
174
+
175
+ // After `restore()`, so the hidden env files are back and cannot be swept
176
+ // into the release commit as deletions.
177
+ if (gitProvenance) {
178
+ console.log('\n── Recording the release in git...');
179
+ const files = [config.configFile!.path, config.configFile!.buildConfigPath].filter((file): file is string => Boolean(file));
180
+ if (config.nativeDirsCommitted) files.push(`${config.build.appDir}/ios`, `${config.build.appDir}/android`);
181
+ await commitAndTagRelease(releasePath(config, '.'), { version, build: readAppVersion(config).buildNumber, files });
182
+ }
183
+
184
+ console.log(`\n=== Done in ${formatDuration((Date.now() - shipStartedAt) / 1000)} ===`);
185
+ }
186
+
187
+ async function customBuild(config: AppReleaseConfig, platform: 'ios' | 'android'): Promise<string> {
188
+ const spec = config.build!.commands![platform]!;
189
+ if (!spec.command.length || !spec.artifact) throw new Error(`build.commands.${platform} needs command and artifact.`);
190
+ await run(spec.command[0], spec.command.slice(1), { cwd: releasePath(config, config.build!.appDir) });
191
+ const artifact = releasePath(config, spec.artifact);
192
+ if (!existsSync(artifact)) throw new Error(`Build did not produce ${artifact}`);
193
+ return artifact;
194
+ }