runcloud 0.2.251 → 0.2.253

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.
@@ -5,6 +5,7 @@ import { join } from 'node:path';
5
5
  import { ApiClient, ApiError, friendlyApiError } from '../api.js';
6
6
  import { requireCredentials, resolveProject } from '../config.js';
7
7
  import { cachedLiveUpdates, liveUpdatesEnabled, NOT_AVAILABLE, rememberLiveUpdates } from './releases.js';
8
+ const UPDATE_DONE = new Set(['published', 'failed']);
8
9
  const POLL_MS = 3000;
9
10
  const FAILED_SESSION = new Set(['failed', 'timeout', 'lost', 'cancelled', 'done']);
10
11
  const NATIVE_DONE = new Set(['succeeded', 'failed', 'cancelled']);
@@ -93,53 +94,114 @@ export async function runRelease(opts, deps) {
93
94
  log(`Warning: these files hold what looks like a live key: ${snap.keyFiles.join(', ')}`);
94
95
  const session = (await client.post(`${project}/sessions`, { kind: 'interactive', branch: snap.branch }));
95
96
  const sessionPath = `/sessions/${encodeURIComponent(session.id)}`;
97
+ const platforms = opts.platforms?.length ? opts.platforms : ['ios'];
98
+ const result = { commit: snap.commit, updateIds: [] };
99
+ const workspaceRunning = () => until(deps, t.sessionMs, 'the workspace to start', async () => {
100
+ const { status } = (await client.get(sessionPath));
101
+ if (FAILED_SESSION.has(status))
102
+ throw new Error(`The workspace stopped (${status}).`);
103
+ return status === 'running' ? status : null;
104
+ });
96
105
  try {
97
- if (opts.native)
98
- return await nativeRelease(sessionPath, snap.commit, deps, t.nativeMs);
106
+ if (opts.native) {
107
+ if (platforms.includes('ios'))
108
+ result.testflightBuild = await nativeRelease(sessionPath, snap.commit, deps, t.nativeMs);
109
+ if (platforms.includes('android')) {
110
+ await workspaceRunning();
111
+ result.apkBuildId = await androidRelease(sessionPath, snap.commit, opts.apkOut, deps, t.nativeMs);
112
+ }
113
+ return result;
114
+ }
99
115
  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
- });
116
+ await workspaceRunning();
106
117
  const plan = await until(deps, t.planMs, 'the release plan', async () => {
107
118
  const read = (await client.get(`${sessionPath}/publish/plan`));
108
- return read.kind === 'pending' ? null : read;
119
+ const pending = read.kind === 'pending' || platforms.some((platform) => read.platformPlans?.[platform].kind === 'pending');
120
+ return pending ? null : read;
109
121
  });
110
122
  if (plan.kind === 'unavailable')
111
123
  throw new Error(plan.reasons[0] ?? NOT_AVAILABLE);
112
124
  if (plan.sourceCommit !== snap.commit)
113
125
  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('; ')}`);
126
+ const live = plan.platforms ?? (plan.kind === 'ota' ? ['ios'] : []);
127
+ const native = platforms.filter((platform) => !live.includes(platform));
128
+ for (const platform of native) {
129
+ const reasons = plan.platformPlans?.[platform].reasons ?? plan.reasons;
130
+ log(`A new ${platform === 'ios' ? 'iOS' : 'Android'} build is needed: ${reasons.join('; ') || 'native code changed'}.`);
134
131
  }
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 };
132
+ if (platforms.some((platform) => live.includes(platform)))
133
+ result.updateIds = await publishLiveUpdate(sessionPath, project, snap.commit, live, opts, deps, t.publishMs);
134
+ if (native.includes('ios'))
135
+ result.testflightBuild = await nativeRelease(sessionPath, snap.commit, deps, t.nativeMs);
136
+ if (native.includes('android'))
137
+ result.apkBuildId = await androidRelease(sessionPath, snap.commit, opts.apkOut, deps, t.nativeMs);
138
+ return result;
138
139
  }
139
140
  finally {
140
141
  await client.post(`${sessionPath}/cancel`, {}).catch(() => undefined);
141
142
  }
142
143
  }
144
+ async function publishLiveUpdate(sessionPath, project, commit, live, opts, deps, ms) {
145
+ const { client, log } = deps;
146
+ const requestId = randomUUID();
147
+ log(`Publishing a live update (${live.join(', ')})...`);
148
+ await client.post(`${sessionPath}/publish`, {
149
+ requestId, sourceCommit: commit,
150
+ ...(opts.message ? { message: opts.message.slice(0, 500) } : {}),
151
+ ...(opts.rollout !== undefined ? { rolloutPercent: opts.rollout } : {}),
152
+ });
153
+ const wanted = live.map((platform) => ({ platform, id: platformRequestId(requestId, platform) }));
154
+ const rows = await until(deps, ms, 'the live update', async () => {
155
+ const { entries } = (await client.get(`${project}/versions`));
156
+ const found = wanted.map(({ platform, id }) => ({ platform, row: entries.find((entry) => entry.kind === 'update' && entry.requestId === id) }));
157
+ return found.every(({ row }) => row && row.state !== 'publishing') ? found.map(({ platform, row }) => ({ platform, row: row })) : null;
158
+ });
159
+ const failed = rows.filter(({ row }) => row.state === 'failed');
160
+ if (failed.length) {
161
+ throw new Error(`The live update failed: ${failed.map(({ platform, row }) => `${platform}: ${row.failure ?? 'no reason given'}`).join('; ')}`);
162
+ }
163
+ for (const { platform, row } of rows)
164
+ log(`Live update ${row.id} (${platform}) is ${row.state}. Devices get it on their next launch.`);
165
+ return rows.map(({ row }) => row.id);
166
+ }
167
+ async function androidRelease(sessionPath, commit, apkOut, deps, ms) {
168
+ const { client, log } = deps;
169
+ const apks = `${sessionPath}/production-apks`;
170
+ log('Building this version for Android to save its source...');
171
+ await client.post(`${sessionPath}/commands`, { command: 'mobile_preview.build', args: { platform: 'android' }, idempotencyKey: randomUUID() });
172
+ const source = await until(deps, ms, 'the Android source to be saved', async () => {
173
+ const { source: saved } = (await client.get(apks));
174
+ return saved?.available && saved.commit === commit ? saved : null;
175
+ });
176
+ log('Building the production APK (usually 10 to 20 minutes)...');
177
+ const { build: started } = (await client.post(apks, { sourceRequestId: source.requestId }));
178
+ let last = '';
179
+ const build = await until(deps, ms, 'the APK build', async () => {
180
+ const current = (await client.get(apks)).builds.find((row) => row.id === started.id);
181
+ if (current && current.status !== last)
182
+ log(` ${(last = current.status)}`);
183
+ return current && NATIVE_DONE.has(current.status) ? current : null;
184
+ });
185
+ if (build.status !== 'succeeded')
186
+ throw new Error(`The APK build ${build.status}: ${build.failure ?? 'no reason given'}`);
187
+ if (build.artifact?.liveUpdate) {
188
+ log('An APK with the same native code exists: shipping this version to it as a live update...');
189
+ const update = await until(deps, ms, 'the Android live update', async () => {
190
+ const current = (await client.get(apks)).builds.find((row) => row.id === build.id)?.artifact?.liveUpdate;
191
+ return current?.status && UPDATE_DONE.has(current.status) ? current : null;
192
+ });
193
+ if (update.status !== 'published')
194
+ throw new Error(`The Android live update failed: ${update.failure ?? 'no reason given'}`);
195
+ }
196
+ if (apkOut) {
197
+ (deps.writeFile ?? writeFileSync)(apkOut, await client.getBinary(`${apks}/${encodeURIComponent(build.id)}/download`));
198
+ log(`The APK is saved to ${apkOut}.`);
199
+ }
200
+ else {
201
+ log("The APK is ready on the Deploy tab of the project in Newly.");
202
+ }
203
+ return build.id;
204
+ }
143
205
  async function nativeRelease(sessionPath, commit, deps, ms) {
144
206
  deps.log('Starting a Cloud TestFlight build (usually 10 to 25 minutes)...');
145
207
  await deps.client.post(`${sessionPath}/testflight`, { requestId: randomUUID(), sourceCommit: commit, confirm: true });
@@ -153,14 +215,20 @@ async function nativeRelease(sessionPath, commit, deps, ms) {
153
215
  if (release.status !== 'succeeded')
154
216
  throw new Error(`The TestFlight build ${release.status}: ${release.failureMessage ?? 'no reason given'}`);
155
217
  deps.log(`Build ${release.buildNumber ?? ''} is uploaded to TestFlight.`.replace(' ', ' '));
156
- return { kind: 'native', commit, buildNumber: release.buildNumber ?? null };
218
+ return release.buildNumber ?? null;
157
219
  }
158
220
  export function registerRelease(program) {
159
221
  program
160
222
  .command('release', { hidden: !cachedLiveUpdates() })
161
- .description('Ship the committed app here: a live update when only JS changed, else a TestFlight build')
223
+ .description('Ship the committed app here: a live update when only JS changed, else a TestFlight build or an Android APK')
162
224
  .option('--project <id>', 'project id (defaults to the linked project)')
163
- .option('--native', 'always build a new native binary for TestFlight', false)
225
+ .option('--native', 'always build a new native binary', false)
226
+ .option('--platform <name>', 'ios, android or all', (value) => {
227
+ if (value !== 'ios' && value !== 'android' && value !== 'all')
228
+ throw new Error('--platform must be ios, android or all.');
229
+ return value;
230
+ }, 'ios')
231
+ .option('--apk-out <file>', 'save a new Android APK here')
164
232
  .option('-m, --message <text>', 'what changed, shown in the version history')
165
233
  .option('--rollout <percent>', 'share of devices that get a live update first (1-100)', (value) => {
166
234
  const n = Number(value);
@@ -176,8 +244,14 @@ export function registerRelease(program) {
176
244
  rememberLiveUpdates(enabled);
177
245
  if (!enabled)
178
246
  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.');
247
+ const result = await runRelease({ projectId: resolveProject(process.cwd(), opts.project), dir: process.cwd(), native: opts.native, message: opts.message, rollout: opts.rollout,
248
+ platforms: opts.platform === 'all' ? ['ios', 'android'] : [opts.platform], apkOut: opts.apkOut }, { client, log: (line) => console.log(line), sleep: (ms) => new Promise((r) => setTimeout(r, ms)), archive: gitArchive });
249
+ const shipped = [
250
+ ...(result.updateIds.length ? ['a live update'] : []),
251
+ ...(result.testflightBuild !== undefined ? ['a new TestFlight build'] : []),
252
+ ...(result.apkBuildId ? ['a new Android APK'] : []),
253
+ ];
254
+ console.log(`Released as ${shipped.join(' and ')}.`);
181
255
  }
182
256
  catch (error) {
183
257
  console.error(error instanceof ApiError || !(error instanceof Error) ? friendlyApiError(error) : error.message);
@@ -1,16 +1,19 @@
1
1
  import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
- import { ApiClient, friendlyApiError } from '../api.js';
3
+ import { ApiClient, ApiError, friendlyApiError } from '../api.js';
4
4
  import { credentialsHome, requireCredentials, resolveProject } from '../config.js';
5
5
  export const LIVE_UPDATES_FLAG = 'ota-live-updates';
6
6
  export const NOT_AVAILABLE = 'Live updates are not available for your account yet.';
7
+ export const SIGNED_OUT = "You're signed out. Run `newly login`, then try again.";
7
8
  const FLAG_CACHE_MS = 7 * 24 * 60 * 60 * 1000;
8
9
  export async function liveUpdatesEnabled(client) {
9
10
  try {
10
11
  const answer = (await client.get(`/feature-flags/${LIVE_UPDATES_FLAG}`));
11
12
  return typeof answer === 'object' && answer !== null && answer.enabled === true;
12
13
  }
13
- catch {
14
+ catch (error) {
15
+ if (error instanceof ApiError && error.status === 401)
16
+ throw new Error(SIGNED_OUT);
14
17
  return false;
15
18
  }
16
19
  }
@@ -69,7 +72,7 @@ async function run(action) {
69
72
  await action();
70
73
  }
71
74
  catch (error) {
72
- console.error(error instanceof Error && error.message === NOT_AVAILABLE ? NOT_AVAILABLE : friendlyApiError(error));
75
+ console.error(error instanceof Error && (error.message === NOT_AVAILABLE || error.message === SIGNED_OUT) ? error.message : friendlyApiError(error));
73
76
  process.exitCode = 1;
74
77
  }
75
78
  }
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = '0.2.251';
1
+ export const CLI_VERSION = '0.2.253';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "runcloud",
3
- "version": "0.2.251",
3
+ "version": "0.2.253",
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