@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,141 @@
1
+ /** Local build and store release support. All app settings come from the consuming configuration. */
2
+ import { spawn } from 'node:child_process';
3
+ import { createWriteStream, mkdirSync, readFileSync } from 'node:fs';
4
+ import { dirname } from 'node:path';
5
+ import { isVerbose, setStageStatus } from '../progress.ts';
6
+
7
+ export interface RunOptions {
8
+ cwd?: string;
9
+ env?: NodeJS.ProcessEnv;
10
+ }
11
+
12
+
13
+ const SECRET_FLAGS = new Set(['-P', '-p', '--password', '--apiKey']);
14
+
15
+ const SECRET_KEY = /(password|secret|token|apikey|api_key)/i;
16
+
17
+
18
+ function redactArgs(args: string[]): string {
19
+ return args
20
+ .map((arg, i) => {
21
+ const prev = args[i - 1];
22
+ if (prev && SECRET_FLAGS.has(prev)) return '«redacted»';
23
+ const eq = arg.indexOf('=');
24
+ if (eq > 0 && SECRET_KEY.test(arg.slice(0, eq))) return `${arg.slice(0, eq)}=«redacted»`;
25
+ return arg;
26
+ })
27
+ .join(' ');
28
+ }
29
+
30
+
31
+ export function run(cmd: string, args: string[], opts: RunOptions = {}): Promise<void> {
32
+ return new Promise((resolve, reject) => {
33
+ const child = spawn(cmd, args, { stdio: 'inherit', cwd: opts.cwd, env: opts.env ?? process.env });
34
+ child.on('error', reject);
35
+ child.on('close', (code) => {
36
+ if (code === 0) resolve();
37
+ else reject(new Error(`${cmd} ${redactArgs(args)} exited with code ${code}`));
38
+ });
39
+ });
40
+ }
41
+
42
+ export interface RunLoggedOptions extends RunOptions {
43
+
44
+ logFile: string;
45
+
46
+ surface?: RegExp;
47
+
48
+ status?: (line: string) => string | undefined;
49
+
50
+ tailOnFailure?: number;
51
+ }
52
+
53
+
54
+ export function runLogged(cmd: string, args: string[], opts: RunLoggedOptions): Promise<void> {
55
+ if (isVerbose()) return run(cmd, args, opts);
56
+ return new Promise((resolve, reject) => {
57
+ mkdirSync(dirname(opts.logFile), { recursive: true });
58
+ const log = createWriteStream(opts.logFile);
59
+ const child = spawn(cmd, args, { stdio: ['inherit', 'pipe', 'pipe'], cwd: opts.cwd, env: opts.env ?? process.env });
60
+
61
+ let pending = '';
62
+ const consume = (chunk: Buffer) => {
63
+ log.write(chunk);
64
+ pending += chunk.toString();
65
+ const lines = pending.split('\n');
66
+ pending = lines.pop() ?? '';
67
+ for (const line of lines) {
68
+ if (opts.surface?.test(line)) console.log(` ${line.trim()}`);
69
+ const s = opts.status?.(line);
70
+ if (s) setStageStatus(s);
71
+ }
72
+ };
73
+ child.stdout.on('data', consume);
74
+ child.stderr.on('data', consume);
75
+
76
+ child.on('error', reject);
77
+ child.on('close', (code) => {
78
+ // Read the tail only after the stream has actually flushed. `end()`
79
+ // returns before the last writes land, so reading here would show a
80
+ // truncated tail — precisely on the big logs where the tail is the point.
81
+ log.end(() => {
82
+ if (code === 0) return resolve();
83
+ const tail = opts.tailOnFailure ?? 40;
84
+ try {
85
+ const lines = readFileSync(opts.logFile, 'utf8').trimEnd().split('\n');
86
+ console.log(`\n Last ${tail} lines of ${opts.logFile}:`);
87
+ for (const l of lines.slice(-tail)) console.log(` ${l}`);
88
+ } catch {
89
+ /* the log itself is best-effort */
90
+ }
91
+ reject(new Error(`${cmd} ${redactArgs(args)} exited with code ${code} — full output: ${opts.logFile}`));
92
+ });
93
+ });
94
+ });
95
+ }
96
+
97
+ export interface CaptureOptions extends RunOptions {
98
+
99
+ input?: string | Buffer;
100
+
101
+ allowFail?: boolean;
102
+ }
103
+
104
+
105
+ export function tee(commandLine: string, opts: RunOptions = {}): Promise<{ code: number; output: string }> {
106
+ return new Promise((resolve, reject) => {
107
+ const child = spawn(commandLine, {
108
+ shell: true,
109
+ stdio: ['inherit', 'pipe', 'pipe'],
110
+ cwd: opts.cwd,
111
+ env: opts.env ?? process.env,
112
+ });
113
+ let output = '';
114
+ child.stdout.on('data', (d) => {
115
+ output += d.toString();
116
+ process.stdout.write(d);
117
+ });
118
+ child.stderr.on('data', (d) => {
119
+ output += d.toString();
120
+ process.stderr.write(d);
121
+ });
122
+ child.on('error', reject);
123
+ child.on('close', (code) => resolve({ code: code ?? 1, output }));
124
+ });
125
+ }
126
+
127
+
128
+ export function capture(cmd: string, args: string[], opts: CaptureOptions = {}): Promise<string> {
129
+ return new Promise((resolve, reject) => {
130
+ const child = spawn(cmd, args, { stdio: ['pipe', 'pipe', 'inherit'], cwd: opts.cwd, env: opts.env ?? process.env });
131
+ let out = '';
132
+ child.stdout.on('data', (d) => (out += d.toString()));
133
+ child.on('error', reject);
134
+ child.on('close', (code) => {
135
+ if (code === 0 || opts.allowFail) resolve(out);
136
+ else reject(new Error(`${cmd} ${redactArgs(args)} exited with code ${code}`));
137
+ });
138
+ if (opts.input !== undefined) child.stdin.write(opts.input);
139
+ child.stdin.end();
140
+ });
141
+ }
@@ -0,0 +1,64 @@
1
+ /** Local build and store release support. All app settings come from the consuming configuration. */
2
+ import { capture, run } from './exec.ts';
3
+
4
+
5
+ export async function dirtyPaths(cwd: string): Promise<string[]> {
6
+ const out = await capture('git', ['status', '--porcelain'], { cwd });
7
+ return out
8
+ .split('\n')
9
+ .map((l) => l.trim())
10
+ .filter(Boolean);
11
+ }
12
+
13
+
14
+ export async function assertCleanTree(cwd: string): Promise<void> {
15
+ const dirty = await dirtyPaths(cwd);
16
+ if (dirty.length === 0) {
17
+ console.log(' ✓ working tree is clean');
18
+ return;
19
+ }
20
+ const shown = dirty.slice(0, 10).join('\n ');
21
+ const more = dirty.length > 10 ? `\n …and ${dirty.length - 10} more` : '';
22
+ throw new Error(
23
+ `Working tree is not clean (${dirty.length} path${dirty.length === 1 ? '' : 's'}):\n ${shown}${more}\n` +
24
+ 'A release built from a dirty tree cannot be reproduced from its tag. ' +
25
+ 'Commit or stash first, or pass --allow-dirty to ship anyway (no tag will be written).',
26
+ );
27
+ }
28
+
29
+ export async function currentBranch(cwd: string): Promise<string> {
30
+ return (await capture('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd })).trim();
31
+ }
32
+
33
+ async function tagExists(cwd: string, tag: string): Promise<boolean> {
34
+ const out = await capture('git', ['tag', '--list', tag], { cwd, allowFail: true });
35
+ return out.trim() === tag;
36
+ }
37
+
38
+
39
+ export async function commitAndTagRelease(
40
+ cwd: string,
41
+ opts: { version: string; build: string; files: string[] },
42
+ ): Promise<string | undefined> {
43
+ const tag = `v${opts.version}+${opts.build}`;
44
+
45
+ if (await tagExists(cwd, tag)) {
46
+ console.log(` · tag ${tag} already exists — leaving it alone`);
47
+ return undefined;
48
+ }
49
+
50
+ if ((await dirtyPaths(cwd)).length > 0) {
51
+ if (!opts.files.length) throw new Error('No version files configured for the release commit.');
52
+ await run('git', ['add', '--update', '--', ...opts.files], { cwd });
53
+ const staged = await capture('git', ['diff', '--cached', '--name-only'], { cwd });
54
+ if (staged.trim()) {
55
+ const files = staged.trim().split('\n');
56
+ await run('git', ['commit', '-m', `chore(release): ${opts.version} (build ${opts.build})`], { cwd });
57
+ console.log(` ✓ committed ${files.length} release file${files.length === 1 ? '' : 's'}`);
58
+ }
59
+ }
60
+
61
+ await run('git', ['tag', '-a', tag, '-m', `${opts.version} (build ${opts.build})`], { cwd });
62
+ console.log(` ✓ tagged ${tag} (not pushed — \`git push origin ${tag}\` when ready)`);
63
+ return tag;
64
+ }
@@ -0,0 +1,200 @@
1
+ /** Local build and store release support. All app settings come from the consuming configuration. */
2
+ import { createHash } from 'node:crypto';
3
+ import { mkdirSync, mkdtempSync, copyFileSync, writeFileSync } from 'node:fs';
4
+ import { homedir, tmpdir } from 'node:os';
5
+ import { resolve } from 'node:path';
6
+ import { releasePath } from '../config.ts';
7
+ import type { AppReleaseConfig } from '../config.ts';
8
+ import { resolveCredentialsJson } from '../config.ts';
9
+ import type { IosSigning } from './credentials.ts';
10
+ import { capture, run, runLogged } from './exec.ts';
11
+ import { stage, stageLogPath } from '../progress.ts';
12
+
13
+ const KEYCHAIN = resolve(homedir(), 'Library/Keychains/login.keychain-db');
14
+
15
+
16
+ const XCODE_SURFACE = /^(\*\* .+ \*\*|(?:[^\s:]+:\d+:\d+: )?error: |ld: error|clang: error)/;
17
+
18
+
19
+ function xcodeStatus(line: string): string | undefined {
20
+ const target = line.match(/\(in target '([^']+)' from project/)?.[1];
21
+ if (!target) return undefined;
22
+ const verb = /^(?:CompileC|CompileSwift|SwiftCompile|SwiftDriver|CompileXIB|CompileStoryboard)\b/.test(line)
23
+ ? 'compiling'
24
+ : /^Ld\b/.test(line)
25
+ ? 'linking'
26
+ : /^CodeSign\b/.test(line)
27
+ ? 'signing'
28
+ : /^(?:Copy|CpResource|PBXCp|ProcessInfoPlistFile)\b/.test(line)
29
+ ? 'copying'
30
+ : undefined;
31
+ return verb ? `${verb} ${target}` : undefined;
32
+ }
33
+
34
+ function quotedName(line: string): string {
35
+ return line.replace(/.*"(.*)".*/, '$1');
36
+ }
37
+
38
+ export interface IosSignContext {
39
+ profileUuid: string;
40
+ signIdentity: string;
41
+
42
+ extensions: { target: string; bundleId: string; profileUuid: string }[];
43
+ }
44
+
45
+
46
+ async function installProfile(path: string, label: string): Promise<string> {
47
+ const decoded = resolve(mkdtempSync(resolve(tmpdir(), 'sprid-profile-')), 'profile.plist');
48
+ await run('security', ['cms', '-D', '-i', path, '-o', decoded]);
49
+ const uuid = (await capture('plutil', ['-extract', 'UUID', 'raw', '-o', '-', decoded])).trim();
50
+ const profilesDir = resolve(homedir(), 'Library/MobileDevice/Provisioning Profiles');
51
+ mkdirSync(profilesDir, { recursive: true });
52
+ copyFileSync(path, resolve(profilesDir, `${uuid}.mobileprovision`));
53
+ return uuid;
54
+ }
55
+
56
+
57
+ export async function setupIosSigning(config: AppReleaseConfig, signing: IosSigning): Promise<IosSignContext> {
58
+ console.log('── Setting up iOS signing...');
59
+ const decoded = resolve(mkdtempSync(resolve(tmpdir(), 'sprid-signing-')), 'profile.plist');
60
+ await run('security', ['cms', '-D', '-i', signing.provisioningProfilePath, '-o', decoded]);
61
+
62
+ const profileUuid = await installProfile(signing.provisioningProfilePath, 'app');
63
+ console.log(` Profile UUID: ${profileUuid}`);
64
+
65
+ // Extension profiles are installed here too, so the archive can resolve every
66
+ // target's signing without ever asking Apple for one.
67
+ const base = resolveCredentialsJson(config).base;
68
+ const extensions: IosSignContext['extensions'] = [];
69
+ for (const ext of config.build?.iosExtensions ?? []) {
70
+ const path = resolve(base, ext.profilePath);
71
+ const uuid = await installProfile(path, ext.target);
72
+ console.log(` Profile UUID (${ext.target} / ${ext.bundleId}): ${uuid}`);
73
+ extensions.push({ target: ext.target, bundleId: ext.bundleId, profileUuid: uuid });
74
+ }
75
+
76
+ await run(
77
+ 'security',
78
+ ['import', signing.distCertPath, '-k', KEYCHAIN, '-P', signing.distCertPassword, '-T', '/usr/bin/codesign', '-T', '/usr/bin/security'],
79
+ {},
80
+ ).catch(() => {}); // already-imported cert is fine
81
+
82
+ const identities = await capture('security', ['find-identity', '-v', '-p', 'codesigning', KEYCHAIN]);
83
+ // The profile's DeveloperCertificates are DER `<data>` blobs — JSON can't hold
84
+ // binary, so extract as XML (base64 <data>) and decode here (the python plistlib
85
+ // step the bash used, reimplemented). SHA-1 each → match against find-identity.
86
+ const certsXml = await capture('plutil', ['-extract', 'DeveloperCertificates', 'xml1', '-o', '-', decoded]);
87
+ const profileHashes: string[] = [...certsXml.matchAll(/<data>([\s\S]*?)<\/data>/g)].map((m) =>
88
+ createHash('sha1').update(Buffer.from(m[1].replace(/\s/g, ''), 'base64')).digest('hex').toUpperCase(),
89
+ );
90
+ if (!profileHashes.length) throw new Error('No DeveloperCertificates found in the provisioning profile.');
91
+
92
+ let signIdentity = '';
93
+ for (const h of profileHashes) {
94
+ const line = identities.split('\n').find((l) => l.includes(h));
95
+ if (line) {
96
+ signIdentity = quotedName(line);
97
+ break;
98
+ }
99
+ }
100
+ if (!signIdentity) throw new Error('No keychain signing identity matches the selected provisioning profile.');
101
+ console.log(` Signing identity: ${signIdentity}`);
102
+
103
+ return { profileUuid, signIdentity, extensions };
104
+ }
105
+
106
+
107
+ export async function patchXcodeprojSigning(config: AppReleaseConfig, ctx: IosSignContext): Promise<void> {
108
+ console.log('── Patching Xcode project signing...');
109
+ const name = config.build!.xcodeName;
110
+ if (!name || !config.appId || !config.appleTeamId) throw new Error('iOS native builds need build.xcodeName, appId and appleTeamId.');
111
+ const proj = resolve(releasePath(config, '.'), config.build!.appDir, `ios/${name}.xcodeproj`);
112
+ // Every signed target, app first. An extension left on automatic signing stops
113
+ // the ARCHIVE — Xcode resolves it there, long before exportOptions is read.
114
+ const targets = [
115
+ { name, profileUuid: ctx.profileUuid },
116
+ ...ctx.extensions.map((e) => ({ name: e.target, profileUuid: e.profileUuid })),
117
+ ];
118
+ const script = `
119
+ require 'xcodeproj'
120
+ require 'json'
121
+ spec = JSON.parse(ARGV.fetch(0))
122
+ project = Xcodeproj::Project.open(spec.fetch('project'))
123
+ spec.fetch('targets').each do |entry|
124
+ target = project.targets.find { |t| t.name == entry.fetch('name') }
125
+ raise "Signing target not found: #{entry.fetch('name')}" if target.nil?
126
+ target.build_configurations.each do |c|
127
+ c.build_settings['CODE_SIGN_STYLE'] = 'Manual'
128
+ c.build_settings['CODE_SIGN_IDENTITY'] = spec.fetch('identity')
129
+ c.build_settings['PROVISIONING_PROFILE_SPECIFIER'] = entry.fetch('profileUuid')
130
+ c.build_settings['DEVELOPMENT_TEAM'] = spec.fetch('team')
131
+ end
132
+ end
133
+ project.save
134
+ `;
135
+ await run('ruby', ['-e', script, JSON.stringify({ project: proj, targets, identity: ctx.signIdentity, team: config.appleTeamId })]);
136
+ }
137
+
138
+
139
+ export async function buildIosArchive(
140
+ config: AppReleaseConfig,
141
+ ctx: IosSignContext,
142
+ sentryToken: string | undefined,
143
+ ): Promise<string> {
144
+ const name = config.build!.xcodeName;
145
+ if (!name || !config.appId || !config.appleTeamId) throw new Error('iOS native builds need build.xcodeName, appId and appleTeamId.');
146
+ const iosDir = resolve(releasePath(config, '.'), config.build!.appDir, 'ios');
147
+ const artifacts = releasePath(config, '.sprid-release/artifacts');
148
+ mkdirSync(artifacts, { recursive: true });
149
+ const archivePath = resolve(artifacts, `${name}.xcarchive`);
150
+ const exportPath = resolve(artifacts, `${name}Export`);
151
+ const exportOptions = resolve(artifacts, `${name}-ExportOptions.plist`);
152
+
153
+ const env = { ...process.env };
154
+ if (!sentryToken) env.SENTRY_DISABLE_AUTO_UPLOAD = 'true';
155
+
156
+ await stage('ios-archive', 'Building iOS archive', () =>
157
+ runLogged(
158
+ 'xcodebuild',
159
+ ['-workspace', `${name}.xcworkspace`, '-scheme', name, '-configuration', 'Release', '-archivePath', archivePath, 'archive'],
160
+ { cwd: iosDir, env, logFile: stageLogPath('ios-archive', releasePath(config, '.')), surface: XCODE_SURFACE, status: xcodeStatus },
161
+ ),
162
+ );
163
+
164
+ writeFileSync(
165
+ exportOptions,
166
+ `<?xml version="1.0" encoding="UTF-8"?>
167
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
168
+ <plist version="1.0">
169
+ <dict>
170
+ <key>method</key><string>app-store-connect</string>
171
+ <key>teamID</key><string>${xml(config.appleTeamId)}</string>
172
+ <key>signingStyle</key><string>manual</string>
173
+ <key>provisioningProfiles</key>
174
+ <dict>
175
+ <key>${xml(config.appId)}</key><string>${xml(ctx.profileUuid)}</string>${ctx.extensions
176
+ .map((e) => `\n <key>${xml(e.bundleId)}</key><string>${xml(e.profileUuid)}</string>`)
177
+ .join('')}
178
+ </dict>
179
+ <key>signingCertificate</key><string>${xml(ctx.signIdentity)}</string>
180
+ <key>uploadSymbols</key><false/>
181
+ <key>destination</key><string>export</string>
182
+ </dict>
183
+ </plist>
184
+ `,
185
+ );
186
+
187
+ await stage('ios-export', 'Exporting IPA', () =>
188
+ runLogged(
189
+ 'xcodebuild',
190
+ ['-exportArchive', '-archivePath', archivePath, '-exportPath', exportPath, '-exportOptionsPlist', exportOptions],
191
+ { cwd: iosDir, env, logFile: stageLogPath('ios-export', releasePath(config, '.')), surface: XCODE_SURFACE },
192
+ ),
193
+ );
194
+
195
+ const ipa = resolve(exportPath, `${name}.ipa`);
196
+ console.log(` IPA: ${ipa}`);
197
+ return ipa;
198
+ }
199
+
200
+ function xml(value: string): string { return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('\"', '&quot;').replaceAll("'", '&apos;'); }
@@ -0,0 +1,26 @@
1
+ /** Local build and store release support. All app settings come from the consuming configuration. */
2
+ import { resolve } from 'node:path';
3
+ import { releasePath } from '../config.ts';
4
+ import type { AppReleaseConfig } from '../config.ts';
5
+ import { runLogged } from './exec.ts';
6
+ import { stage, stageLogPath } from '../progress.ts';
7
+
8
+ export async function runPrebuild(
9
+ config: AppReleaseConfig,
10
+ platforms: { ios: boolean; android: boolean },
11
+ ): Promise<void> {
12
+ if (config.build?.framework !== 'expo') return;
13
+ const cwd = resolve(releasePath(config, '.'), config.build!.appDir);
14
+ const args = ['expo', 'prebuild', '--clean'];
15
+ if (platforms.ios && !platforms.android) args.push('--platform', 'ios');
16
+ else if (platforms.android && !platforms.ios) args.push('--platform', 'android');
17
+ await stage('prebuild', `Running ${args.join(' ')}`, () =>
18
+ runLogged('npx', args, {
19
+ cwd,
20
+ logFile: stageLogPath('prebuild', releasePath(config, '.')),
21
+ // Prebuild's own progress lines are few and worth keeping; the volume is
22
+ // in the pod install underneath it.
23
+ surface: /^(✔|✖|›|Error|error:|\[stderr\])/,
24
+ }),
25
+ );
26
+ }
@@ -0,0 +1,58 @@
1
+ /** Local build and store release support. All app settings come from the consuming configuration. */
2
+ import { resolve } from 'node:path';
3
+ import { releasePath } from '../config.ts';
4
+ import type { AppReleaseConfig, PreflightCheck } from '../config.ts';
5
+ import { run, tee } from './exec.ts';
6
+ import { stage } from '../progress.ts';
7
+
8
+ const CHECK = `
9
+ const semver = require('semver');
10
+ const errors = [];
11
+ const ver = (p) => require(p + '/package.json').version;
12
+ const reactVer = ver('react');
13
+ const rnPkg = require('react-native/package.json');
14
+ const expoPkg = require('expo/package.json');
15
+ const rnPeer = rnPkg.peerDependencies && rnPkg.peerDependencies.react;
16
+ if (rnPeer && !semver.satisfies(reactVer, rnPeer)) errors.push('react@' + reactVer + ' does not satisfy react-native peer ' + rnPeer);
17
+ try {
18
+ const reactDomVer = ver('react-dom');
19
+ if (reactVer.split('.').slice(0,2).join('.') !== reactDomVer.split('.').slice(0,2).join('.'))
20
+ errors.push('react@' + reactVer + ' and react-dom@' + reactDomVer + ' differ in minor');
21
+ } catch {}
22
+ const expoPeer = expoPkg.peerDependencies && expoPkg.peerDependencies.react;
23
+ if (expoPeer && !semver.satisfies(reactVer, expoPeer)) errors.push('react@' + reactVer + ' does not satisfy expo peer ' + expoPeer);
24
+ if (errors.length) { errors.forEach(e => console.error('FAIL: ' + e)); process.exit(1); }
25
+ console.log(' react@' + reactVer + ' + react-native@' + rnPkg.version + ' + expo@' + expoPkg.version + ' ✓');
26
+ `;
27
+
28
+ export async function runPreflight(config: AppReleaseConfig): Promise<void> {
29
+ const appDir = resolve(releasePath(config, '.'), config.build!.appDir);
30
+ const preflight = config.build!.preflight;
31
+
32
+ if (preflight === true) {
33
+ console.log('── Dependency compatibility check...');
34
+ await run('node', ['-e', CHECK], { cwd: appDir });
35
+ return;
36
+ }
37
+ if (!Array.isArray(preflight)) return;
38
+
39
+ await stage('preflight', `Preflight (${preflight.length} check${preflight.length === 1 ? '' : 's'})`, async () => {
40
+ for (const entry of preflight) {
41
+ const spec: Exclude<PreflightCheck, string> = typeof entry === 'string' ? { run: entry } : entry;
42
+ const label = spec.label ?? spec.run;
43
+ const cwd = spec.dir === 'app' ? appDir : releasePath(config, '.');
44
+ console.log(`\n→ ${label}`);
45
+
46
+ const { code, output } = await tee(spec.run, { cwd });
47
+ if (code !== 0) throw new Error(`Preflight failed: ${label} exited with code ${code}`);
48
+
49
+ // Exit 0 is not proof the check did its job — a test suite that fails to
50
+ // LOAD still exits 0 and simply reports fewer tests. That is what `check`
51
+ // is for.
52
+ const complaint = spec.check?.(output);
53
+ if (complaint) throw new Error(`Preflight failed: ${label} — ${complaint}`);
54
+
55
+ console.log(` ✓ ${label}`);
56
+ }
57
+ });
58
+ }
@@ -0,0 +1,31 @@
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
+ export function loadSentryToken(config: AppReleaseConfig): string | undefined {
8
+ if (process.env.SENTRY_AUTH_TOKEN) {
9
+ console.log('── Sentry: using SENTRY_AUTH_TOKEN from environment.');
10
+ return process.env.SENTRY_AUTH_TOKEN;
11
+ }
12
+ const file = config.build?.sentryTokenFile;
13
+ if (file && config.credentialsDir) {
14
+ const path = resolve(releasePath(config, config.credentialsDir), file);
15
+ try {
16
+ const line = readFileSync(path, 'utf8')
17
+ .split('\n')
18
+ .find((l) => l.startsWith('SENTRY_AUTH_TOKEN='));
19
+ if (line) {
20
+ const token = line.slice('SENTRY_AUTH_TOKEN='.length).trim();
21
+ process.env.SENTRY_AUTH_TOKEN = token;
22
+ console.log(`── Sentry: loaded SENTRY_AUTH_TOKEN from ${path}`);
23
+ return token;
24
+ }
25
+ } catch {
26
+ /* fall through */
27
+ }
28
+ }
29
+ console.log('── Sentry: no SENTRY_AUTH_TOKEN found — source maps will NOT upload.');
30
+ return undefined;
31
+ }
package/src/bump.ts ADDED
@@ -0,0 +1,101 @@
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
+
7
+ export type BumpKind = 'patch' | 'minor' | 'major';
8
+
9
+ export interface AppVersion {
10
+ version: string;
11
+ buildNumber: string;
12
+ versionCode: number;
13
+ }
14
+
15
+ function configPath(config: AppReleaseConfig): string {
16
+ if (!config.configFile) throw new Error('Set configFile to read or bump versions.');
17
+ return resolve(releasePath(config, '.'), config.configFile!.path);
18
+ }
19
+
20
+ function readVersionFromConfigTs(src: string, path: string): string {
21
+ const version = src.match(/^\s*version:\s*["']([^"']+)["']/m)?.[1];
22
+ if (!version) throw new Error(`Could not parse version from ${path}`);
23
+ return version;
24
+ }
25
+
26
+ function readBuildFromAppJson(src: string): { buildNumber: string; versionCode: number } {
27
+ const expo = (JSON.parse(src).expo ?? JSON.parse(src)) as any;
28
+ return { buildNumber: String(expo.ios?.buildNumber ?? '0'), versionCode: Number(expo.android?.versionCode ?? 0) };
29
+ }
30
+
31
+ export function readAppVersion(config: AppReleaseConfig): AppVersion {
32
+ const path = configPath(config);
33
+ const src = readFileSync(path, 'utf8');
34
+
35
+ if (config.configFile!.format === 'split') {
36
+ const buildSrc = readFileSync(resolve(releasePath(config, '.'), config.configFile!.buildConfigPath!), 'utf8');
37
+ return { version: readVersionFromConfigTs(src, path), ...readBuildFromAppJson(buildSrc) };
38
+ }
39
+ if (config.configFile!.format === 'app.json') {
40
+ const expo = (JSON.parse(src).expo ?? JSON.parse(src)) as any;
41
+ return {
42
+ version: String(expo.version),
43
+ buildNumber: String(expo.ios?.buildNumber ?? '0'),
44
+ versionCode: Number(expo.android?.versionCode ?? 0),
45
+ };
46
+ }
47
+ // app.config.ts — line-anchored literals.
48
+ const buildNumber = src.match(/buildNumber:\s*["']([^"']+)["']/)?.[1];
49
+ const versionCode = src.match(/versionCode:\s*(\d+)/)?.[1];
50
+ if (!buildNumber || !versionCode) throw new Error(`Could not parse buildNumber/versionCode from ${path}`);
51
+ return { version: readVersionFromConfigTs(src, path), buildNumber, versionCode: Number(versionCode) };
52
+ }
53
+
54
+ function nextVersion(version: string, kind: BumpKind): string {
55
+ const [major, minor, patch] = version.split('.').map(Number);
56
+ if (kind === 'major') return `${major + 1}.0.0`;
57
+ if (kind === 'minor') return `${major}.${minor + 1}.0`;
58
+ return `${major}.${minor}.${patch + 1}`;
59
+ }
60
+
61
+ export function bumpVersion(config: AppReleaseConfig, kind?: BumpKind): AppVersion {
62
+ const path = configPath(config);
63
+ const current = readAppVersion(config);
64
+ const next: AppVersion = {
65
+ version: kind ? nextVersion(current.version, kind) : current.version,
66
+ buildNumber: String(Number(current.buildNumber) + 1),
67
+ versionCode: current.versionCode + 1,
68
+ };
69
+
70
+ const writeAppJsonBuild = (jsonPath: string, alsoVersion: boolean) => {
71
+ const json = JSON.parse(readFileSync(jsonPath, 'utf8'));
72
+ const expo = json.expo ?? json;
73
+ if (alsoVersion) expo.version = next.version;
74
+ expo.ios = { ...expo.ios, buildNumber: next.buildNumber };
75
+ expo.android = { ...expo.android, versionCode: next.versionCode };
76
+ writeFileSync(jsonPath, JSON.stringify(json, null, 2) + '\n');
77
+ };
78
+
79
+ if (config.configFile!.format === 'app.json') {
80
+ writeAppJsonBuild(path, true);
81
+ } else if (config.configFile!.format === 'split') {
82
+ // version → app.config.ts (regex); build/versionCode → app.json
83
+ if (kind) {
84
+ let src = readFileSync(path, 'utf8');
85
+ src = src.replace(/(^\s*version:\s*["'])[^"']+(["'])/m, `$1${next.version}$2`);
86
+ writeFileSync(path, src);
87
+ }
88
+ writeAppJsonBuild(resolve(releasePath(config, '.'), config.configFile!.buildConfigPath!), false);
89
+ } else {
90
+ let src = readFileSync(path, 'utf8');
91
+ if (kind) src = src.replace(/(^\s*version:\s*["'])[^"']+(["'])/m, `$1${next.version}$2`);
92
+ src = src.replace(/(buildNumber:\s*["'])[^"']+(["'])/, `$1${next.buildNumber}$2`);
93
+ src = src.replace(/(versionCode:\s*)\d+/, `$1${next.versionCode}`);
94
+ writeFileSync(path, src);
95
+ }
96
+
97
+ console.log(
98
+ ` version=${current.version} → ${next.version} build=${current.buildNumber} → ${next.buildNumber} versionCode=${current.versionCode} → ${next.versionCode}`,
99
+ );
100
+ return next;
101
+ }