runcloud 0.2.249 → 0.2.250

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,187 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { ApiClient, ApiError, friendlyApiError } from '../api.js';
6
+ import { requireCredentials, resolveProject } from '../config.js';
7
+ import { cachedLiveUpdates, liveUpdatesEnabled, NOT_AVAILABLE, rememberLiveUpdates } from './releases.js';
8
+ const POLL_MS = 3000;
9
+ const FAILED_SESSION = new Set(['failed', 'timeout', 'lost', 'cancelled', 'done']);
10
+ const NATIVE_DONE = new Set(['succeeded', 'failed', 'cancelled']);
11
+ export function platformRequestId(requestId, platform) {
12
+ if (platform === 'ios')
13
+ return requestId;
14
+ const hex = createHash('sha256').update(`ota-${platform}:${requestId}`).digest('hex');
15
+ const variant = (8 | (Number.parseInt(hex[16], 16) & 3)).toString(16);
16
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-${variant}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
17
+ }
18
+ export const ANALYTICS_FILE = 'src/lib/newly-analytics.json';
19
+ const ANALYTICS_EXTRA_KEYS = ['newlyIngestKey', 'newlyApiUrl', 'newlyAnalyticsEnabled', 'newlyAnalyticsSamplingRate'];
20
+ export function analyticsFileContent(projectId, config) {
21
+ return `${JSON.stringify({
22
+ ingestKey: config.ingest_key,
23
+ apiUrl: config.api_url.replace(/\/+$/, ''),
24
+ enabled: config.enabled,
25
+ samplingRate: config.sampling_rate,
26
+ projectId,
27
+ }, null, 2)}\n`;
28
+ }
29
+ export async function analyticsPreflight(dir, projectId, client) {
30
+ const read = (path) => JSON.parse(readFileSync(join(dir, path), 'utf8'));
31
+ if (!existsSync(join(dir, 'package.json')) || !read('package.json').dependencies?.['@newly/sdk-react-native'])
32
+ return null;
33
+ const extra = existsSync(join(dir, 'app.json')) ? (read('app.json').expo?.extra ?? {}) : {};
34
+ const configured = ANALYTICS_EXTRA_KEYS.filter((key) => Object.hasOwn(extra, key)).length;
35
+ if (configured === ANALYTICS_EXTRA_KEYS.length)
36
+ return null;
37
+ if (configured > 0 || !existsSync(join(dir, ANALYTICS_FILE))) {
38
+ return `This app reads its analytics settings from app.json, and they are incomplete. Open it in Newly once so they are saved, then commit app.json.`;
39
+ }
40
+ const config = (await client.get(`/projects/${encodeURIComponent(projectId)}/analytics/config`));
41
+ const desired = analyticsFileContent(projectId, config);
42
+ if (readFileSync(join(dir, ANALYTICS_FILE), 'utf8') === desired)
43
+ return null;
44
+ writeFileSync(join(dir, ANALYTICS_FILE), desired);
45
+ return `Updated ${ANALYTICS_FILE} to this project's analytics settings. Commit it, then run newly release again.`;
46
+ }
47
+ export function gitArchive(dir) {
48
+ const git = (args, maxBuffer = 1024 * 1024) => execFileSync('git', args, { cwd: dir, maxBuffer, stdio: ['ignore', 'pipe', 'pipe'] });
49
+ let prefix;
50
+ try {
51
+ prefix = git(['rev-parse', '--show-prefix']).toString().trim();
52
+ }
53
+ catch {
54
+ throw new Error('Run newly release inside the git repository of your app.');
55
+ }
56
+ if (git(['status', '--porcelain', '--', '.']).toString().trim()) {
57
+ throw new Error('This app has uncommitted changes. Commit them first: a release ships exactly a commit.');
58
+ }
59
+ const commit = git(['rev-parse', 'HEAD']).toString().trim();
60
+ const tree = prefix ? `HEAD:${prefix.replace(/\/$/, '')}` : 'HEAD';
61
+ const root = git(['rev-parse', '--show-toplevel']).toString().trim();
62
+ const tar = execFileSync('git', ['archive', '--format=tar.gz', '--prefix=source/', tree], {
63
+ cwd: root, maxBuffer: 64 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'],
64
+ });
65
+ return { tar, commit };
66
+ }
67
+ async function until(deps, ms, what, read) {
68
+ const deadline = Date.now() + ms;
69
+ for (;;) {
70
+ const value = await read();
71
+ if (value !== null)
72
+ return value;
73
+ if (Date.now() > deadline)
74
+ throw new Error(`Timed out waiting for ${what}.`);
75
+ await deps.sleep(POLL_MS);
76
+ }
77
+ }
78
+ export async function runRelease(opts, deps) {
79
+ const { client, log } = deps;
80
+ const t = { sessionMs: 15 * 60_000, planMs: 15 * 60_000, publishMs: 30 * 60_000, nativeMs: 60 * 60_000, ...deps.timeouts };
81
+ const project = `/projects/${encodeURIComponent(opts.projectId)}`;
82
+ const notReady = await (deps.preflight ?? analyticsPreflight)(opts.dir, opts.projectId, client);
83
+ if (notReady)
84
+ throw new Error(notReady);
85
+ const { tar, commit: localCommit } = deps.archive(opts.dir);
86
+ const query = new URLSearchParams({ sourceCommit: localCommit, ...(opts.message ? { message: opts.message.slice(0, 200) } : {}) });
87
+ log(`Uploading ${localCommit.slice(0, 7)} (${Math.ceil(tar.length / 1024)} KiB)...`);
88
+ const snap = (await client.upload(`${project}/source/snapshot?${query}`, tar, 'application/gzip'));
89
+ log(`Saved as ${snap.commit.slice(0, 7)} on ${snap.branch} (${snap.files} files).`);
90
+ if (snap.dropped.length)
91
+ log(`Left out (credential or signing files): ${snap.dropped.join(', ')}`);
92
+ if (snap.keyFiles.length)
93
+ log(`Warning: these files hold what looks like a live key: ${snap.keyFiles.join(', ')}`);
94
+ const session = (await client.post(`${project}/sessions`, { kind: 'interactive', branch: snap.branch }));
95
+ const sessionPath = `/sessions/${encodeURIComponent(session.id)}`;
96
+ try {
97
+ if (opts.native)
98
+ return await nativeRelease(sessionPath, snap.commit, deps, t.nativeMs);
99
+ log('Starting a workspace to check what changed...');
100
+ await until(deps, t.sessionMs, 'the workspace to start', async () => {
101
+ const { status } = (await client.get(sessionPath));
102
+ if (FAILED_SESSION.has(status))
103
+ throw new Error(`The workspace stopped (${status}).`);
104
+ return status === 'running' ? status : null;
105
+ });
106
+ const plan = await until(deps, t.planMs, 'the release plan', async () => {
107
+ const read = (await client.get(`${sessionPath}/publish/plan`));
108
+ return read.kind === 'pending' ? null : read;
109
+ });
110
+ if (plan.kind === 'unavailable')
111
+ throw new Error(plan.reasons[0] ?? NOT_AVAILABLE);
112
+ if (plan.sourceCommit !== snap.commit)
113
+ throw new Error('The project changed while releasing. Run newly release again.');
114
+ if (plan.kind === 'native') {
115
+ log(`A new native build is needed: ${plan.reasons.join('; ') || 'native code changed'}.`);
116
+ return await nativeRelease(sessionPath, snap.commit, deps, t.nativeMs);
117
+ }
118
+ const requestId = randomUUID();
119
+ log('Only JavaScript and assets changed: publishing a live update...');
120
+ await client.post(`${sessionPath}/publish`, {
121
+ requestId, sourceCommit: snap.commit,
122
+ ...(opts.message ? { message: opts.message.slice(0, 500) } : {}),
123
+ ...(opts.rollout !== undefined ? { rolloutPercent: opts.rollout } : {}),
124
+ });
125
+ const wanted = (plan.platforms?.length ? plan.platforms : ['ios']).map((platform) => ({ platform, id: platformRequestId(requestId, platform) }));
126
+ const rows = await until(deps, t.publishMs, 'the live update', async () => {
127
+ const { entries } = (await client.get(`${project}/versions`));
128
+ const found = wanted.map(({ platform, id }) => ({ platform, row: entries.find((entry) => entry.kind === 'update' && entry.requestId === id) }));
129
+ return found.every(({ row }) => row && row.state !== 'publishing') ? found.map(({ platform, row }) => ({ platform, row: row })) : null;
130
+ });
131
+ const failed = rows.filter(({ row }) => row.state === 'failed');
132
+ if (failed.length) {
133
+ throw new Error(`The live update failed: ${failed.map(({ platform, row }) => `${platform}: ${row.failure ?? 'no reason given'}`).join('; ')}`);
134
+ }
135
+ for (const { platform, row } of rows)
136
+ log(`Live update ${row.id} (${platform}) is ${row.state}. Devices get it on their next launch.`);
137
+ return { kind: 'ota', commit: snap.commit, updateId: rows[0].row.id };
138
+ }
139
+ finally {
140
+ await client.post(`${sessionPath}/cancel`, {}).catch(() => undefined);
141
+ }
142
+ }
143
+ async function nativeRelease(sessionPath, commit, deps, ms) {
144
+ deps.log('Starting a Cloud TestFlight build (usually 10 to 25 minutes)...');
145
+ await deps.client.post(`${sessionPath}/testflight`, { requestId: randomUUID(), sourceCommit: commit, confirm: true });
146
+ let last = '';
147
+ const release = await until(deps, ms, 'the TestFlight build', async () => {
148
+ const { release: current } = (await deps.client.get(`${sessionPath}/testflight`));
149
+ if (current && current.status !== last)
150
+ deps.log(` ${(last = current.status)}`);
151
+ return current && NATIVE_DONE.has(current.status) ? current : null;
152
+ });
153
+ if (release.status !== 'succeeded')
154
+ throw new Error(`The TestFlight build ${release.status}: ${release.failureMessage ?? 'no reason given'}`);
155
+ deps.log(`Build ${release.buildNumber ?? ''} is uploaded to TestFlight.`.replace(' ', ' '));
156
+ return { kind: 'native', commit, buildNumber: release.buildNumber ?? null };
157
+ }
158
+ export function registerRelease(program) {
159
+ program
160
+ .command('release', { hidden: !cachedLiveUpdates() })
161
+ .description('Ship the committed app here: a live update when only JS changed, else a TestFlight build')
162
+ .option('--project <id>', 'project id (defaults to the linked project)')
163
+ .option('--native', 'always build a new native binary for TestFlight', false)
164
+ .option('-m, --message <text>', 'what changed, shown in the version history')
165
+ .option('--rollout <percent>', 'share of devices that get a live update first (1-100)', (value) => {
166
+ const n = Number(value);
167
+ if (!Number.isInteger(n) || n < 1 || n > 100)
168
+ throw new Error('--rollout must be a whole number from 1 to 100.');
169
+ return n;
170
+ })
171
+ .action(async (opts) => {
172
+ try {
173
+ const creds = requireCredentials();
174
+ const client = new ApiClient(creds.apiUrl, creds.token);
175
+ const enabled = await liveUpdatesEnabled(client);
176
+ rememberLiveUpdates(enabled);
177
+ if (!enabled)
178
+ throw new Error(NOT_AVAILABLE);
179
+ const result = await runRelease({ projectId: resolveProject(process.cwd(), opts.project), dir: process.cwd(), native: opts.native, message: opts.message, rollout: opts.rollout }, { client, log: (line) => console.log(line), sleep: (ms) => new Promise((r) => setTimeout(r, ms)), archive: gitArchive });
180
+ console.log(result.kind === 'ota' ? 'Released as a live update.' : 'Released as a new TestFlight build.');
181
+ }
182
+ catch (error) {
183
+ console.error(error instanceof ApiError || !(error instanceof Error) ? friendlyApiError(error) : error.message);
184
+ process.exitCode = 1;
185
+ }
186
+ });
187
+ }
@@ -0,0 +1,111 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { ApiClient, friendlyApiError } from '../api.js';
4
+ import { credentialsHome, requireCredentials, resolveProject } from '../config.js';
5
+ export const LIVE_UPDATES_FLAG = 'ota-live-updates';
6
+ export const NOT_AVAILABLE = 'Live updates are not available for your account yet.';
7
+ const FLAG_CACHE_MS = 7 * 24 * 60 * 60 * 1000;
8
+ export async function liveUpdatesEnabled(client) {
9
+ try {
10
+ const answer = (await client.get(`/feature-flags/${LIVE_UPDATES_FLAG}`));
11
+ return typeof answer === 'object' && answer !== null && answer.enabled === true;
12
+ }
13
+ catch {
14
+ return false;
15
+ }
16
+ }
17
+ const flagCachePath = () => join(credentialsHome(), 'flags.json');
18
+ export function cachedLiveUpdates() {
19
+ try {
20
+ const cache = JSON.parse(readFileSync(flagCachePath(), 'utf8'));
21
+ const entry = cache[LIVE_UPDATES_FLAG];
22
+ return entry?.enabled === true && typeof entry.checkedAt === 'number' && Date.now() - entry.checkedAt < FLAG_CACHE_MS;
23
+ }
24
+ catch {
25
+ return false;
26
+ }
27
+ }
28
+ export function rememberLiveUpdates(enabled) {
29
+ try {
30
+ mkdirSync(credentialsHome(), { recursive: true, mode: 0o700 });
31
+ writeFileSync(flagCachePath(), JSON.stringify({ [LIVE_UPDATES_FLAG]: { enabled, checkedAt: Date.now() } }), { mode: 0o600 });
32
+ }
33
+ catch {
34
+ }
35
+ }
36
+ const platformName = (platform) => (platform === 'ios' ? 'iOS' : 'Android');
37
+ const day = (iso) => iso.slice(0, 16).replace('T', ' ');
38
+ export function formatVersions(entries) {
39
+ if (entries.length === 0)
40
+ return 'No store builds or live updates yet.';
41
+ return entries
42
+ .map((entry) => {
43
+ if (entry.kind === 'store') {
44
+ const updates = entry.liveUpdates ? `, takes live updates (${entry.updateCount})` : '';
45
+ return `${platformName(entry.platform)} build ${entry.buildNumber ?? '?'} ${day(entry.uploadedAt)} ${entry.sourceCommit.slice(0, 7)}${updates}`;
46
+ }
47
+ const state = entry.state === 'failed'
48
+ ? `failed: ${entry.failure ?? 'no reason given'}`
49
+ : entry.state === 'publishing'
50
+ ? `publishing${entry.stage ? ` (${entry.stage})` : ''}`
51
+ : `${entry.state}, ${entry.rolloutPercent}% of devices, on build ${entry.targetBuildNumber ?? '?'}`;
52
+ const message = entry.message ? ` "${entry.message}"` : '';
53
+ return ` Live update ${entry.id} ${day(entry.createdAt)} ${platformName(entry.platform)} ${state}${message}`;
54
+ })
55
+ .join('\n');
56
+ }
57
+ function clientFor() {
58
+ const creds = requireCredentials();
59
+ return new ApiClient(creds.apiUrl, creds.token);
60
+ }
61
+ async function requireLiveUpdates(client) {
62
+ const enabled = await liveUpdatesEnabled(client);
63
+ rememberLiveUpdates(enabled);
64
+ if (!enabled)
65
+ throw new Error(NOT_AVAILABLE);
66
+ }
67
+ async function run(action) {
68
+ try {
69
+ await action();
70
+ }
71
+ catch (error) {
72
+ console.error(error instanceof Error && error.message === NOT_AVAILABLE ? NOT_AVAILABLE : friendlyApiError(error));
73
+ process.exitCode = 1;
74
+ }
75
+ }
76
+ const projectPath = (projectId) => `/projects/${encodeURIComponent(projectId)}`;
77
+ export function registerReleases(program) {
78
+ const releases = program
79
+ .command('releases', { hidden: !cachedLiveUpdates() })
80
+ .description("List the project's store builds and live updates")
81
+ .option('--project <id>', 'project id (defaults to the linked project)')
82
+ .action(async (opts) => run(async () => {
83
+ const client = clientFor();
84
+ await requireLiveUpdates(client);
85
+ const projectId = resolveProject(process.cwd(), opts.project);
86
+ const versions = (await client.get(`${projectPath(projectId)}/versions`));
87
+ console.log(formatVersions(versions.entries));
88
+ if (!versions.liveUpdatesOn)
89
+ console.log('\nLive updates are off for this app.');
90
+ }));
91
+ releases
92
+ .command('pause')
93
+ .argument('<update-id>', 'the live update to stop serving')
94
+ .description('Stop serving a live update; devices on it go back to the previous version')
95
+ .option('--project <id>', 'project id (defaults to the linked project)')
96
+ .action(async (updateId, opts) => run(async () => {
97
+ const projectId = resolveProject(process.cwd(), opts.project);
98
+ await clientFor().patch(`${projectPath(projectId)}/versions/updates/${encodeURIComponent(updateId)}`, { enabled: false });
99
+ console.log(`Paused live update ${updateId}.`);
100
+ }));
101
+ releases
102
+ .command('rollback')
103
+ .argument('<update-id>', 'the live update to make current again')
104
+ .description('Make an earlier live update current again, pausing the newer ones')
105
+ .option('--project <id>', 'project id (defaults to the linked project)')
106
+ .action(async (updateId, opts) => run(async () => {
107
+ const projectId = resolveProject(process.cwd(), opts.project);
108
+ await clientFor().post(`${projectPath(projectId)}/versions/updates/${encodeURIComponent(updateId)}/rollback`, {});
109
+ console.log(`Live update ${updateId} is current again.`);
110
+ }));
111
+ }
package/dist/index.js CHANGED
@@ -27,6 +27,8 @@ import { registerUpdate } from './commands/update.js';
27
27
  import { registerToken } from './commands/token.js';
28
28
  import { registerDogfood } from './commands/dogfood.js';
29
29
  import { registerGoals } from './commands/goals.js';
30
+ import { registerReleases } from './commands/releases.js';
31
+ import { registerRelease } from './commands/release.js';
30
32
  import { CLI_VERSION } from './version.js';
31
33
  const program = new Command('newly')
32
34
  .description('Develop, provision, and deploy Newly backends')
@@ -53,6 +55,8 @@ registerDomains(program);
53
55
  registerDns(program);
54
56
  registerDiagnose(program);
55
57
  registerDesktop(program);
58
+ registerRelease(program);
59
+ registerReleases(program);
56
60
  registerAppStore(program);
57
61
  registerUpdate(program);
58
62
  registerToken(program);
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = '0.2.249';
1
+ export const CLI_VERSION = '0.2.250';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "runcloud",
3
- "version": "0.2.249",
3
+ "version": "0.2.250",
4
4
  "description": "Create and control run.cloud remote mobile simulators and cloud sandboxes",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
Binary file
Binary file