react-native-update-cli 2.24.2 → 2.26.0

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.
Files changed (98) hide show
  1. package/README.md +12 -5
  2. package/README.zh-CN.md +12 -5
  3. package/cli.json +7 -1
  4. package/lib/api.d.ts +2 -0
  5. package/lib/api.js +63 -18
  6. package/lib/app.js +25 -3
  7. package/lib/bin.js +39 -45
  8. package/lib/bundle-runner.d.ts +45 -1
  9. package/lib/bundle-runner.js +303 -34
  10. package/lib/bundle.d.ts +1 -1
  11. package/lib/bundle.js +23 -7
  12. package/lib/commands.d.ts +6 -0
  13. package/lib/commands.js +65 -0
  14. package/lib/locales/en.d.ts +7 -14
  15. package/lib/locales/en.js +10 -17
  16. package/lib/locales/zh.d.ts +7 -13
  17. package/lib/locales/zh.js +10 -16
  18. package/lib/package.js +4 -0
  19. package/lib/provider.d.ts +1 -1
  20. package/lib/provider.js +3 -1
  21. package/lib/symbolicate.js +7 -2
  22. package/lib/types.d.ts +1 -0
  23. package/lib/user.js +6 -0
  24. package/lib/utils/add-gitignore.js +7 -1
  25. package/lib/utils/dep-versions.d.ts +7 -0
  26. package/lib/utils/dep-versions.js +78 -26
  27. package/lib/utils/git.js +9 -6
  28. package/lib/utils/hbcTransform.d.ts +15 -0
  29. package/lib/utils/hbcTransform.js +22 -0
  30. package/lib/utils/hermes-base.d.ts +61 -6
  31. package/lib/utils/hermes-base.js +328 -46
  32. package/lib/utils/hermes-literals.d.ts +51 -0
  33. package/lib/utils/hermes-literals.js +210 -0
  34. package/lib/utils/i18n.d.ts +5 -0
  35. package/lib/utils/i18n.js +14 -1
  36. package/lib/utils/index.d.ts +2 -1
  37. package/lib/utils/index.js +9 -4
  38. package/lib/utils/latest-version/index.js +8 -0
  39. package/lib/utils/runtime.d.ts +21 -0
  40. package/lib/utils/runtime.js +138 -5
  41. package/lib/utils/zip-range.js +3 -2
  42. package/lib/versions.js +14 -4
  43. package/package.json +6 -3
  44. package/lib/index.d.ts +0 -1
  45. package/lib/index.js +0 -17
  46. package/src/api.ts +0 -470
  47. package/src/app.ts +0 -241
  48. package/src/auto-update.ts +0 -647
  49. package/src/bin-cresc.ts +0 -8
  50. package/src/bin.ts +0 -115
  51. package/src/bundle-pack.ts +0 -61
  52. package/src/bundle-runner.ts +0 -1430
  53. package/src/bundle.ts +0 -371
  54. package/src/cache.ts +0 -20
  55. package/src/diff.ts +0 -1010
  56. package/src/exports.ts +0 -17
  57. package/src/index.ts +0 -1
  58. package/src/install.ts +0 -50
  59. package/src/locales/en.ts +0 -257
  60. package/src/locales/zh.ts +0 -234
  61. package/src/native-package.ts +0 -338
  62. package/src/package.ts +0 -482
  63. package/src/provider.ts +0 -294
  64. package/src/symbolicate.ts +0 -164
  65. package/src/types.ts +0 -150
  66. package/src/user.ts +0 -39
  67. package/src/utils/add-gitignore.ts +0 -35
  68. package/src/utils/app-info-parser/aab.ts +0 -241
  69. package/src/utils/app-info-parser/apk.ts +0 -92
  70. package/src/utils/app-info-parser/app.ts +0 -7
  71. package/src/utils/app-info-parser/index.ts +0 -54
  72. package/src/utils/app-info-parser/ipa.ts +0 -109
  73. package/src/utils/app-info-parser/resource-finder.ts +0 -508
  74. package/src/utils/app-info-parser/utils.ts +0 -161
  75. package/src/utils/app-info-parser/xml-parser/binary.ts +0 -693
  76. package/src/utils/app-info-parser/xml-parser/manifest.ts +0 -228
  77. package/src/utils/app-info-parser/zip.ts +0 -108
  78. package/src/utils/check-lockfile.ts +0 -93
  79. package/src/utils/check-plugin.ts +0 -38
  80. package/src/utils/command-result.ts +0 -24
  81. package/src/utils/constants.ts +0 -25
  82. package/src/utils/dep-versions.ts +0 -83
  83. package/src/utils/git.ts +0 -71
  84. package/src/utils/hbcTransform.ts +0 -649
  85. package/src/utils/hermes-base.ts +0 -1137
  86. package/src/utils/http-helper.ts +0 -152
  87. package/src/utils/i18n.ts +0 -39
  88. package/src/utils/index.ts +0 -698
  89. package/src/utils/latest-version/index.ts +0 -573
  90. package/src/utils/options.ts +0 -78
  91. package/src/utils/plugin-config.ts +0 -32
  92. package/src/utils/runtime.ts +0 -187
  93. package/src/utils/slim-sourcemap.ts +0 -105
  94. package/src/utils/zip-entries.ts +0 -209
  95. package/src/utils/zip-options.ts +0 -178
  96. package/src/utils/zip-range.ts +0 -727
  97. package/src/utils/zip-raw-writer.ts +0 -247
  98. package/src/versions.ts +0 -892
package/src/api.ts DELETED
@@ -1,470 +0,0 @@
1
- import filesizeParser from 'filesize-parser';
2
- import fs from 'fs';
3
- import fetch from 'node-fetch';
4
- import path from 'path';
5
- import type ProgressBar from 'progress';
6
- import packageJson from '../package.json';
7
- import type { Package, Session } from './types';
8
- import { credentialFile, IS_CRESC, pricingPageUrl } from './utils/constants';
9
- import type { HermesBaseServerRecord } from './utils/hermes-base';
10
- import { getBaseUrl } from './utils/http-helper';
11
- import { t } from './utils/i18n';
12
- import {
13
- measureTcpLatency,
14
- type RuntimeRequestInit,
15
- type RuntimeResponse,
16
- runtimeFetch,
17
- } from './utils/runtime';
18
-
19
- let session: Session | undefined;
20
- let savedSession: Session | undefined;
21
- let apiToken: string | undefined;
22
-
23
- const userAgent = `react-native-update-cli/${packageJson.version}`;
24
-
25
- export const getSession = () => session;
26
-
27
- export const getApiToken = () => apiToken;
28
-
29
- export const setApiToken = (token: string) => {
30
- apiToken = token;
31
- };
32
-
33
- const loadApiTokenFromEnv = () => {
34
- // Use CRESC_API_TOKEN for cresc, PUSHY_API_TOKEN for pushy
35
- const envToken = IS_CRESC
36
- ? process.env.CRESC_API_TOKEN
37
- : process.env.PUSHY_API_TOKEN;
38
- if (envToken) {
39
- apiToken = envToken;
40
- }
41
- };
42
-
43
- export const replaceSession = (newSession: { token: string }) => {
44
- session = newSession;
45
- };
46
-
47
- export const loadSession = async () => {
48
- loadApiTokenFromEnv();
49
- if (fs.existsSync(credentialFile)) {
50
- try {
51
- replaceSession(JSON.parse(fs.readFileSync(credentialFile, 'utf8')));
52
- savedSession = session;
53
- } catch (e) {
54
- console.error(
55
- `Failed to parse file ${credentialFile}. Try to remove it manually.`,
56
- );
57
- throw e;
58
- }
59
- }
60
- };
61
-
62
- export const saveSession = () => {
63
- // Only save on change.
64
- if (session !== savedSession) {
65
- const current = session;
66
- const data = JSON.stringify(current, null, 4);
67
- fs.writeFileSync(credentialFile, data, { encoding: 'utf8', mode: 0o600 });
68
- try {
69
- // mode above only applies on creation; tighten pre-existing files too
70
- fs.chmodSync(credentialFile, 0o600);
71
- } catch {
72
- // best-effort (e.g. exotic filesystems); the token is still saved
73
- }
74
- savedSession = current;
75
- }
76
- };
77
-
78
- export const closeSession = () => {
79
- if (fs.existsSync(credentialFile)) {
80
- fs.unlinkSync(credentialFile);
81
- savedSession = undefined;
82
- }
83
- session = undefined;
84
- };
85
-
86
- function createRequestError(
87
- error: unknown,
88
- requestUrl: string,
89
- status?: number,
90
- ) {
91
- const message =
92
- typeof error === 'string'
93
- ? error
94
- : error instanceof Error
95
- ? error.message
96
- : String(error);
97
- const requestError = new Error(`${message}\nURL: ${requestUrl}`) as Error & {
98
- status?: number;
99
- };
100
- requestError.status = status;
101
- return requestError;
102
- }
103
-
104
- const PROXY_ERROR_PATTERNS = [
105
- 'socket disconnected before secure TLS connection',
106
- 'ECONNRESET',
107
- 'ECONNREFUSED',
108
- 'DEPTH_ZERO_SELF_SIGNED_CERT',
109
- 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
110
- 'CERT_HAS_EXPIRED',
111
- 'self signed certificate',
112
- 'proxy',
113
- 'ETIMEDOUT',
114
- 'EHOSTUNREACH',
115
- 'ENETUNREACH',
116
- ];
117
-
118
- function isProxyRelatedError(error: unknown): boolean {
119
- const msg =
120
- error instanceof Error
121
- ? error.message
122
- : typeof error === 'string'
123
- ? error
124
- : '';
125
- const lower = msg.toLowerCase();
126
- return PROXY_ERROR_PATTERNS.some((p) => lower.includes(p.toLowerCase()));
127
- }
128
-
129
- async function query(url: string, options: RuntimeRequestInit) {
130
- const baseUrl = await getBaseUrl();
131
- const fullUrl = `${baseUrl}${url}`;
132
- let resp: RuntimeResponse;
133
- try {
134
- resp = await runtimeFetch(fullUrl, options);
135
- } catch (error) {
136
- const baseError = createRequestError(error, fullUrl);
137
- if (isProxyRelatedError(error)) {
138
- throw new Error(
139
- `${baseError.message}\n\n${t('proxyNetworkError')}\n${t('proxyNetworkErrorTips')}`,
140
- );
141
- }
142
- throw baseError;
143
- }
144
- const text = await resp.text();
145
- let json: any;
146
- try {
147
- json = JSON.parse(text);
148
- } catch (_e) {
149
- if (resp.status === 200) {
150
- // a proxy/gateway likely replaced the response; surface it instead of
151
- // returning undefined and crashing callers on destructuring
152
- throw createRequestError(
153
- `API returned 200 with non-JSON body (${text.length} bytes)`,
154
- fullUrl,
155
- resp.status,
156
- );
157
- }
158
- }
159
-
160
- if (resp.status !== 200) {
161
- const message = json?.message || resp.statusText || `HTTP ${resp.status}`;
162
- if (resp.status === 401) {
163
- throw createRequestError(t('loginExpired'), fullUrl, resp.status);
164
- }
165
- throw createRequestError(message, fullUrl, resp.status);
166
- }
167
- return json;
168
- }
169
-
170
- function queryWithoutBody(method: string) {
171
- return (api: string) => {
172
- const headers: Record<string, string> = {
173
- 'User-Agent': userAgent,
174
- };
175
- if (apiToken) {
176
- headers['x-api-token'] = apiToken;
177
- } else if (session?.token) {
178
- headers['X-AccessToken'] = session.token;
179
- }
180
- return query(api, {
181
- method,
182
- headers,
183
- });
184
- };
185
- }
186
-
187
- function queryWithBody(method: string) {
188
- return (api: string, body?: Record<string, any>) => {
189
- const headers: Record<string, string> = {
190
- 'User-Agent': userAgent,
191
- 'Content-Type': 'application/json',
192
- };
193
- if (apiToken) {
194
- headers['x-api-token'] = apiToken;
195
- } else if (session?.token) {
196
- headers['X-AccessToken'] = session.token;
197
- }
198
- return query(api, {
199
- method,
200
- headers,
201
- body: JSON.stringify(body),
202
- });
203
- };
204
- }
205
-
206
- export const get = queryWithoutBody('GET');
207
- export const post = queryWithBody('POST');
208
- export const put = queryWithBody('PUT');
209
- export const doDelete = queryWithBody('DELETE');
210
-
211
- // Upload deadline: generous for a slow link (1 s/MB on top of a 30 s base,
212
- // never below 60 s) but bounded, so a stalled connection cannot hang a CI job
213
- // forever. The bar keeps ticking while bytes flow; the deadline is absolute.
214
- const UPLOAD_TIMEOUT_BASE_MS = 30_000;
215
- const UPLOAD_TIMEOUT_PER_MB_MS = 1_000;
216
- const UPLOAD_TIMEOUT_MIN_MS = 60_000;
217
- const UPLOAD_MAX_RETRIES = 1;
218
-
219
- export function uploadTimeoutMs(fileSize: number): number {
220
- const megabytes = Math.ceil(Math.max(0, fileSize) / 1048576);
221
- return Math.max(
222
- UPLOAD_TIMEOUT_MIN_MS,
223
- UPLOAD_TIMEOUT_BASE_MS + megabytes * UPLOAD_TIMEOUT_PER_MB_MS,
224
- );
225
- }
226
-
227
- const TRANSIENT_UPLOAD_ERROR_CODES = ['ECONNRESET', 'ETIMEDOUT', 'EPIPE'];
228
-
229
- /**
230
- * A network-level failure worth one more attempt: a reset/timed-out/broken
231
- * pipe connection, or our own deadline abort. HTTP responses (4xx/5xx) never
232
- * get here — they are surfaced as-is.
233
- */
234
- export function isTransientUploadError(error: unknown): boolean {
235
- if (!error || typeof error !== 'object') {
236
- return false;
237
- }
238
- const { name, code, type, message } = error as {
239
- name?: string;
240
- code?: string;
241
- type?: string;
242
- message?: string;
243
- };
244
- if (name === 'AbortError' || type === 'aborted' || code === 'ABORT_ERR') {
245
- return true;
246
- }
247
- const text = `${code ?? ''} ${message ?? ''}`;
248
- return TRANSIENT_UPLOAD_ERROR_CODES.some((c) => text.includes(c));
249
- }
250
-
251
- class UploadTimeoutError extends Error {
252
- constructor(timeoutMs: number) {
253
- super(`Upload timed out after ${Math.round(timeoutMs / 1000)}s`);
254
- this.name = 'UploadTimeoutError';
255
- }
256
- }
257
-
258
- /**
259
- * Send the file with a size-scaled deadline and one retry on a transient
260
- * network error. `buildRequest` is invoked per attempt with a fresh file
261
- * stream (a consumed stream/form cannot be replayed).
262
- */
263
- async function sendUpload(
264
- fn: string,
265
- realUrl: string,
266
- fileSize: number,
267
- bar: ProgressBar,
268
- buildRequest: (fileStream: fs.ReadStream) => fetch.RequestInit,
269
- ): Promise<fetch.Response> {
270
- const timeoutMs = uploadTimeoutMs(fileSize);
271
- for (let attempt = 0; ; attempt++) {
272
- const controller = new AbortController();
273
- let timedOut = false;
274
- const timer = setTimeout(() => {
275
- timedOut = true;
276
- controller.abort();
277
- }, timeoutMs);
278
- const fileStream = fs.createReadStream(fn);
279
- fileStream.on('data', (data) => {
280
- bar.tick(data.length);
281
- });
282
- try {
283
- return await fetch(realUrl, {
284
- ...buildRequest(fileStream),
285
- signal: controller.signal,
286
- });
287
- } catch (rawError) {
288
- fileStream.destroy();
289
- const error = timedOut ? new UploadTimeoutError(timeoutMs) : rawError;
290
- if (attempt < UPLOAD_MAX_RETRIES && isTransientUploadError(error)) {
291
- const reason = error instanceof Error ? error.message : String(error);
292
- console.warn(`\nUpload interrupted (${reason}), retrying...`);
293
- // restart the bar from zero for the second pass
294
- bar.curr = 0;
295
- continue;
296
- }
297
- throw error;
298
- } finally {
299
- clearTimeout(timer);
300
- }
301
- }
302
- }
303
-
304
- export async function uploadFile(
305
- fn: string,
306
- key?: string,
307
- appId?: string | number,
308
- ) {
309
- // appId 用于服务端路由:绑定了自托管节点(rnu-node)的应用,
310
- // 上传指令会指向节点或其对象存储
311
- const resp = await post('/upload', {
312
- ext: path.extname(fn),
313
- ...(appId ? { appId: Number(appId) } : {}),
314
- });
315
- const { url, backupUrl, formData, maxSize } = resp;
316
- let realUrl = url;
317
- if (backupUrl) {
318
- if (global.USE_ACC_OSS) {
319
- realUrl = backupUrl;
320
- } else {
321
- const latency = await measureTcpLatency(url, {
322
- attempts: 4,
323
- timeout: 1000,
324
- });
325
- if (!Number.isFinite(latency) || latency > 150) {
326
- realUrl = backupUrl;
327
- }
328
- }
329
- // console.log({realUrl});
330
- }
331
-
332
- const fileSize = fs.statSync(fn).size;
333
- if (maxSize && fileSize > filesizeParser(maxSize)) {
334
- const readableFileSize = `${(fileSize / 1048576).toFixed(1)}m`;
335
- throw new Error(
336
- t('fileSizeExceeded', {
337
- fileSize: readableFileSize,
338
- maxSize,
339
- pricingPageUrl,
340
- }),
341
- );
342
- }
343
-
344
- // progress/form-data are only needed here; keep them off the startup path
345
- const ProgressBarImpl = require('progress') as typeof import('progress');
346
- const bar = new ProgressBarImpl(' Uploading [:bar] :percent :etas', {
347
- complete: '=',
348
- incomplete: ' ',
349
- total: fileSize,
350
- });
351
-
352
- const rethrowUploadError = (error: unknown): never => {
353
- if (isProxyRelatedError(error)) {
354
- const rawMessage = error instanceof Error ? error.message : String(error);
355
- throw new Error(
356
- `${rawMessage}\n\n${t('proxyNetworkError')}\n${t('proxyNetworkErrorTips')}`,
357
- );
358
- }
359
- throw createRequestError(error, realUrl);
360
- };
361
-
362
- // 自托管节点的 s3 直传:服务端下发预签名 PUT,字节直达用户的对象存储
363
- if (resp.method === 'PUT') {
364
- let putRes: fetch.Response;
365
- try {
366
- putRes = await sendUpload(fn, realUrl, fileSize, bar, (fileStream) => ({
367
- method: 'PUT',
368
- body: fileStream,
369
- // 预签名 PUT 不接受 chunked 传输,必须显式声明长度
370
- headers: {
371
- 'content-length': String(fileSize),
372
- ...(resp.headers || {}),
373
- },
374
- }));
375
- } catch (error) {
376
- return rethrowUploadError(error);
377
- }
378
- if (putRes.status > 299) {
379
- throw createRequestError(
380
- `${putRes.status}: ${putRes.statusText || 'Upload failed'}`,
381
- realUrl,
382
- );
383
- }
384
- return { hash: resp.key };
385
- }
386
-
387
- const FormData = require('form-data') as typeof import('form-data');
388
- let res: fetch.Response;
389
- try {
390
- res = await sendUpload(fn, realUrl, fileSize, bar, (fileStream) => {
391
- const form = new FormData();
392
- for (const [k, v] of Object.entries(formData)) {
393
- form.append(k, v);
394
- }
395
- if (key) {
396
- form.append('key', key);
397
- }
398
- form.append('file', fileStream);
399
- // form.append('file', fileStream, {
400
- // contentType: 'application/octet-stream',
401
- // });
402
- return { method: 'POST', body: form };
403
- });
404
- } catch (error) {
405
- return rethrowUploadError(error);
406
- }
407
-
408
- if (res.status > 299) {
409
- throw createRequestError(
410
- `${res.status}: ${res.statusText || 'Upload failed'}`,
411
- realUrl,
412
- );
413
- }
414
-
415
- // const body = await response.json();
416
- return { hash: key || formData.key };
417
- }
418
-
419
- /**
420
- * Ask the server for the Hermes base of (app, HBC version): the earliest
421
- * existing version of that epoch, or the newest version when the epoch is not
422
- * known yet. Old servers answer 404 → treated as "no base".
423
- */
424
- export async function getHermesBase(
425
- appId: string,
426
- bytecodeVersion: number,
427
- ): Promise<HermesBaseServerRecord | null> {
428
- try {
429
- const data = await get(
430
- `/app/${appId}/hermesBase?bytecodeVersion=${bytecodeVersion}`,
431
- );
432
- const record =
433
- data && typeof data === 'object' && 'data' in data ? data.data : data;
434
- if (!record || typeof record !== 'object' || !record.url || !record.hash) {
435
- return null;
436
- }
437
- return record as HermesBaseServerRecord;
438
- } catch (error) {
439
- if ((error as { status?: number })?.status === 404) {
440
- return null;
441
- }
442
- throw error;
443
- }
444
- }
445
-
446
- export const getAllPackages = async (appId: string) => {
447
- // the server caps limit at 100, so page through with offset
448
- const limit = 100;
449
- let offset = 0;
450
- let allPackages: Package[] | undefined | null;
451
- while (true) {
452
- const { data, count } = await get(
453
- `/app/${appId}/package/list?offset=${offset}&limit=${limit}`,
454
- );
455
- const packages = data as Package[] | undefined | null;
456
- if (allPackages === undefined || allPackages === null) {
457
- allPackages = packages;
458
- } else if (packages) {
459
- allPackages.push(...packages);
460
- }
461
- if (!packages || packages.length === 0) {
462
- break;
463
- }
464
- offset += packages.length;
465
- if (offset >= Number(count || 0)) {
466
- break;
467
- }
468
- }
469
- return allPackages;
470
- };
package/src/app.ts DELETED
@@ -1,241 +0,0 @@
1
- import fs from 'fs';
2
- import { doDelete, get, post } from './api';
3
- import type { Platform } from './types';
4
- import { loadTtyTable, question } from './utils';
5
- import { updateJson } from './utils/constants';
6
- import { t } from './utils/i18n';
7
-
8
- interface AppSummary {
9
- id: number;
10
- name: string;
11
- platform: Platform;
12
- }
13
-
14
- export interface AppTargetOptions {
15
- appId?: string;
16
- config?: string;
17
- platform?: Platform | '';
18
- }
19
-
20
- /** The selected-app config file was missing or has no entry for the platform. */
21
- export class AppNotSelectedError extends Error {
22
- readonly code = 'APP_NOT_SELECTED';
23
- constructor(platform: Platform) {
24
- super(t('appNotSelected', { platform }));
25
- this.name = 'AppNotSelectedError';
26
- }
27
- }
28
-
29
- /** Resolve an explicit platform or prompt for one interactively. */
30
- export async function getPlatform(platform?: string) {
31
- return assertPlatform(
32
- platform || (await question(t('platformQuestion'))),
33
- ) as Platform;
34
- }
35
-
36
- /** Validate that a string names a platform supported by the update service. */
37
- export function assertPlatform(platform: string): Platform {
38
- if (platform !== 'ios' && platform !== 'android' && platform !== 'harmony') {
39
- throw new Error(t('unsupportedPlatform', { platform }));
40
- }
41
- return platform as Platform;
42
- }
43
-
44
- /** Read the selected app for a platform from the requested config file. */
45
- export async function getSelectedApp(
46
- platform: Platform,
47
- configPath?: string,
48
- ): Promise<{ appId: string; appKey: string; platform: Platform }> {
49
- assertPlatform(platform);
50
-
51
- const resolvedConfigPath = configPath || updateJson;
52
- let raw: string;
53
- try {
54
- raw = await fs.promises.readFile(resolvedConfigPath, 'utf8');
55
- } catch (e: any) {
56
- if (e.code === 'ENOENT') {
57
- throw new AppNotSelectedError(platform);
58
- }
59
- throw e;
60
- }
61
- let updateInfo: Partial<Record<Platform, { appId: number; appKey: string }>>;
62
- try {
63
- updateInfo = JSON.parse(raw);
64
- } catch {
65
- throw new Error(
66
- t('failedToParseUpdateJson', { configPath: resolvedConfigPath }),
67
- );
68
- }
69
- const info = updateInfo[platform];
70
- if (!info) {
71
- throw new AppNotSelectedError(platform);
72
- }
73
- return {
74
- appId: String(info.appId),
75
- appKey: info.appKey,
76
- platform,
77
- };
78
- }
79
-
80
- /**
81
- * Fail fast when an explicit `--appId` names an app of another platform.
82
- * The server accepts a bundle for any app the account owns and never sees
83
- * the platform it was built for, so this is the only place the mistake can
84
- * be caught before it reaches devices. A missing or foreign app fails here
85
- * too (403/404) instead of after the expensive work.
86
- */
87
- async function assertAppPlatform(appId: string, platform: Platform) {
88
- const app = (await get(`/app/${appId}`)) as { platform?: Platform };
89
- if (app.platform && app.platform !== platform) {
90
- throw new Error(
91
- t('appPlatformMismatch', { appId, appPlatform: app.platform, platform }),
92
- );
93
- }
94
- }
95
-
96
- /**
97
- * Resolve the app an operation targets: an explicit `--appId` wins, otherwise
98
- * the app selected for the platform in `--config` (default: update.json).
99
- * Prompts for the platform only when it is needed and not given.
100
- */
101
- export async function resolveAppId(
102
- options: AppTargetOptions = {},
103
- ): Promise<string> {
104
- if (options.platform) {
105
- assertPlatform(options.platform);
106
- }
107
- if (options.appId) {
108
- const appId = String(options.appId);
109
- if (options.platform) {
110
- await assertAppPlatform(appId, options.platform);
111
- }
112
- return appId;
113
- }
114
- const platform = await getPlatform(options.platform || undefined);
115
- return (await getSelectedApp(platform, options.config)).appId;
116
- }
117
-
118
- /** List apps, optionally filtering them to one platform. */
119
- export async function listApp(platform: Platform | '' = '') {
120
- const { data } = await get('/app/list');
121
- const allApps = data as AppSummary[];
122
- const list = platform
123
- ? allApps.filter((app: AppSummary) => app.platform === platform)
124
- : allApps;
125
-
126
- const header = [
127
- { value: t('appId') },
128
- { value: t('appName') },
129
- { value: t('platform') },
130
- ];
131
- const rows = [];
132
- for (const app of list) {
133
- rows.push([app.id, app.name, app.platform]);
134
- }
135
-
136
- // tty-table is ~25 ms to load; only pay for it when a table is rendered
137
- const Table = loadTtyTable();
138
- console.log(Table(header, rows).render());
139
-
140
- console.log(`\n${t('totalApps', { count: list.length, platform })}`);
141
- return list;
142
- }
143
-
144
- /** Prompt until the user chooses an app belonging to the target platform. */
145
- export async function chooseApp(platform: Platform) {
146
- const list = await listApp(platform);
147
-
148
- while (true) {
149
- const id = await question(t('enterAppIdQuestion'));
150
- const app = list.find((item: AppSummary) => item.id === Number(id));
151
- if (app) {
152
- return app;
153
- }
154
- }
155
- }
156
-
157
- /** Persist an app selection in the requested brand-aware config file. */
158
- async function selectApp({
159
- args,
160
- options,
161
- }: {
162
- args: string[];
163
- options: { platform?: Platform | ''; config?: string };
164
- }) {
165
- const platform = await getPlatform(options.platform);
166
- const id = args[0]
167
- ? Number.parseInt(args[0], 10)
168
- : (await chooseApp(platform)).id;
169
-
170
- const configPath = options.config || updateJson;
171
- let updateInfo: Partial<Record<Platform, { appId: number; appKey: string }>> =
172
- {};
173
- try {
174
- updateInfo = JSON.parse(await fs.promises.readFile(configPath, 'utf8'));
175
- } catch (e: any) {
176
- if (e.code !== 'ENOENT') {
177
- console.error(t('failedToParseUpdateJson', { configPath }));
178
- throw e;
179
- }
180
- }
181
- const { appKey } = await get(`/app/${id}`);
182
- updateInfo[platform] = {
183
- appId: id,
184
- appKey,
185
- };
186
- await fs.promises.writeFile(
187
- configPath,
188
- JSON.stringify(updateInfo, null, 4),
189
- 'utf8',
190
- );
191
- }
192
-
193
- /** Build the application-management command handlers used by the CLI. */
194
- export function getAppCommands() {
195
- return {
196
- /** Create an app and select it in the same configuration file. */
197
- createApp: async ({
198
- options,
199
- }: {
200
- options: {
201
- name: string;
202
- downloadUrl: string;
203
- platform?: Platform | '';
204
- config?: string;
205
- };
206
- }) => {
207
- const name = options.name || (await question(t('appNameQuestion')));
208
- const { downloadUrl } = options;
209
- const platform = await getPlatform(options.platform);
210
- const { id } = await post('/app/create', { name, platform, downloadUrl });
211
- console.log(t('createAppSuccess', { id }));
212
- await selectApp({
213
- args: [String(id)],
214
- options: { platform, config: options.config },
215
- });
216
- },
217
- /** Delete the specified app, or prompt for one when no ID is supplied. */
218
- deleteApp: async ({
219
- args,
220
- options,
221
- }: {
222
- args: string[];
223
- options: { platform: Platform };
224
- }) => {
225
- const { platform } = options;
226
- const id = args[0] || (await chooseApp(platform)).id;
227
- if (!id) {
228
- console.log(t('cancelled'));
229
- return;
230
- }
231
- await doDelete(`/app/${id}`);
232
- console.log(t('operationSuccess'));
233
- },
234
- /** List apps through the command interface. */
235
- apps: async ({ options }: { options: { platform?: Platform | '' } }) => {
236
- const { platform = '' } = options;
237
- return listApp(platform);
238
- },
239
- selectApp,
240
- };
241
- }