react-native-update-cli 2.23.0 → 2.24.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.
@@ -0,0 +1,502 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.detectGlobalPackageManager = detectGlobalPackageManager;
7
+ exports.buildUpdateCommand = buildUpdateCommand;
8
+ exports.launchAutoUpdate = launchAutoUpdate;
9
+ exports.consumeAutoUpdateNotice = consumeAutoUpdateNotice;
10
+ const child_process_1 = require("child_process");
11
+ const fs_1 = require("fs");
12
+ const os_1 = require("os");
13
+ const path_1 = __importDefault(require("path"));
14
+ const PACKAGE_NAME = 'react-native-update-cli';
15
+ const WORKER_ENV = 'RNU_AUTO_UPDATE_WORKER';
16
+ const CANDIDATE_ENV = 'RNU_AUTO_UPDATE_CANDIDATE';
17
+ const LOCK_STALE_MS = 10 * 60 * 1000;
18
+ const UPDATE_TIMEOUT_MS = 2 * 60 * 1000;
19
+ const NETWORK_RETRY_MS = 6 * 60 * 60 * 1000;
20
+ const FAILURE_RETRY_MS = 24 * 60 * 60 * 1000;
21
+ const PERMISSION_RETRY_MS = 7 * 24 * 60 * 60 * 1000;
22
+ const OUTPUT_LIMIT = 32 * 1024;
23
+ function cacheDir() {
24
+ if (process.env.XDG_CACHE_HOME) {
25
+ return path_1.default.join(process.env.XDG_CACHE_HOME, PACKAGE_NAME);
26
+ }
27
+ switch (process.platform) {
28
+ case 'darwin':
29
+ return path_1.default.join((0, os_1.homedir)(), 'Library', 'Caches', PACKAGE_NAME);
30
+ case 'win32':
31
+ return path_1.default.join(process.env.LOCALAPPDATA ?? path_1.default.join((0, os_1.homedir)(), 'AppData', 'Local'), PACKAGE_NAME, 'Cache');
32
+ default:
33
+ return path_1.default.join((0, os_1.homedir)(), '.cache', PACKAGE_NAME);
34
+ }
35
+ }
36
+ function stateFile() {
37
+ return path_1.default.join(cacheDir(), 'auto-update.json');
38
+ }
39
+ function lockDir() {
40
+ return path_1.default.join(cacheDir(), 'auto-update.lock');
41
+ }
42
+ function readState() {
43
+ try {
44
+ const parsed = JSON.parse((0, fs_1.readFileSync)(stateFile(), 'utf8'));
45
+ if (!parsed ||
46
+ !['running', 'updated', 'failed'].includes(parsed.status) ||
47
+ typeof parsed.targetVersion !== 'string' ||
48
+ typeof parsed.attemptedAt !== 'number') {
49
+ return undefined;
50
+ }
51
+ return parsed;
52
+ }
53
+ catch {
54
+ return undefined;
55
+ }
56
+ }
57
+ function writeState(state) {
58
+ try {
59
+ (0, fs_1.mkdirSync)(cacheDir(), { recursive: true });
60
+ const temporary = `${stateFile()}.${process.pid}.tmp`;
61
+ (0, fs_1.writeFileSync)(temporary, JSON.stringify(state));
62
+ (0, fs_1.renameSync)(temporary, stateFile());
63
+ }
64
+ catch {
65
+ // A read-only cache must never interfere with the CLI or the update.
66
+ }
67
+ }
68
+ function normalizePath(value) {
69
+ let resolved = path_1.default.resolve(value);
70
+ try {
71
+ resolved = fs_1.realpathSync.native(resolved);
72
+ }
73
+ catch {
74
+ // The caller may supply a path that was replaced during an update.
75
+ }
76
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
77
+ }
78
+ function isWithin(child, parent) {
79
+ const relative = path_1.default.relative(normalizePath(parent), normalizePath(child));
80
+ return (relative === '' ||
81
+ (!relative.startsWith('..') && !path_1.default.isAbsolute(relative)));
82
+ }
83
+ function managerFromUserAgent(env) {
84
+ const value = `${env.npm_config_user_agent ?? ''} ${env.npm_execpath ?? ''}`.toLowerCase();
85
+ if (/\bbun(?:\/|\s|$)/.test(value))
86
+ return 'bun';
87
+ if (/\bpnpm(?:\/|\s|$)/.test(value))
88
+ return 'pnpm';
89
+ if (/\byarn(?:\/|\s|$)/.test(value))
90
+ return 'yarn';
91
+ if (/\bnpm(?:\/|\s|$)/.test(value))
92
+ return 'npm';
93
+ return undefined;
94
+ }
95
+ function parseManager(value) {
96
+ const manager = value?.trim().toLowerCase();
97
+ return manager === 'npm' ||
98
+ manager === 'pnpm' ||
99
+ manager === 'yarn' ||
100
+ manager === 'bun'
101
+ ? manager
102
+ : undefined;
103
+ }
104
+ /**
105
+ * Identify the package manager that owns this global installation. Project
106
+ * lockfiles are deliberately ignored: they say how the app is installed, not
107
+ * how this CLI was installed.
108
+ */
109
+ function detectGlobalPackageManager({ packageRoot, env = process.env, npmGlobalDir, yarnGlobalDir, }) {
110
+ const root = normalizePath(packageRoot);
111
+ const normalized = root.replaceAll('\\', '/').toLowerCase();
112
+ if (yarnGlobalDir && isWithin(root, yarnGlobalDir))
113
+ return 'yarn';
114
+ if (npmGlobalDir && isWithin(root, npmGlobalDir))
115
+ return 'npm';
116
+ if (/\/(?:\.bun|bun)\/install\/global\/node_modules\//.test(normalized)) {
117
+ return 'bun';
118
+ }
119
+ if (/\/pnpm\/global\/[^/]+\//.test(normalized))
120
+ return 'pnpm';
121
+ if (/\/(?:\.config\/yarn\/global|yarn\/data\/global)\/node_modules\//.test(normalized)) {
122
+ return 'yarn';
123
+ }
124
+ // Custom npm prefixes conventionally use <prefix>/lib/node_modules on
125
+ // Unix and <prefix>/node_modules on Windows. Only accept the generic form
126
+ // when the package is outside the current project, so npx and local installs
127
+ // are never self-modified.
128
+ const cwdNodeModules = path_1.default.join(normalizePath(process.cwd()), 'node_modules');
129
+ const configuredPrefixModules = env.npm_config_prefix
130
+ ? path_1.default.join(normalizePath(env.npm_config_prefix), 'node_modules')
131
+ : undefined;
132
+ const looksGlobal = normalized.includes('/lib/node_modules/') ||
133
+ (process.platform === 'win32' &&
134
+ (normalized.includes('/npm/node_modules/') ||
135
+ (configuredPrefixModules && isWithin(root, configuredPrefixModules))));
136
+ if (looksGlobal && !isWithin(root, cwdNodeModules)) {
137
+ return (parseManager(env.RNU_AUTO_UPDATE_PACKAGE_MANAGER) ??
138
+ managerFromUserAgent(env) ??
139
+ 'npm');
140
+ }
141
+ return undefined;
142
+ }
143
+ function globalDirectories() {
144
+ try {
145
+ const dirs = require('global-dirs');
146
+ return {
147
+ npmGlobalDir: dirs.npm?.packages,
148
+ npmPrefix: dirs.npm?.prefix,
149
+ yarnGlobalDir: dirs.yarn?.packages,
150
+ };
151
+ }
152
+ catch {
153
+ return {};
154
+ }
155
+ }
156
+ function sanitizeRegistryUrl(value) {
157
+ try {
158
+ const registry = new URL(value);
159
+ if (registry.protocol !== 'http:' && registry.protocol !== 'https:') {
160
+ return 'https://registry.npmjs.org/';
161
+ }
162
+ // Credentials belong in the user's package-manager configuration, not in
163
+ // a process argument or our state file.
164
+ registry.username = '';
165
+ registry.password = '';
166
+ return registry.toString();
167
+ }
168
+ catch {
169
+ return 'https://registry.npmjs.org/';
170
+ }
171
+ }
172
+ function buildUpdateCommand(manager, targetVersion, registryUrl, installPrefix) {
173
+ const target = `${PACKAGE_NAME}@${targetVersion}`;
174
+ const registry = sanitizeRegistryUrl(registryUrl);
175
+ // Windows package managers are .cmd shims and therefore run through
176
+ // cmd.exe. Keep the URL out of that command line (it may contain shell
177
+ // metacharacters); runPackageManager supplies the same value through the
178
+ // environment instead.
179
+ const registryArgs = process.platform === 'win32' ? [] : [`--registry=${registry}`];
180
+ switch (manager) {
181
+ case 'pnpm':
182
+ return {
183
+ command: process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm',
184
+ args: ['add', '--global', target, '--reporter=silent', ...registryArgs],
185
+ };
186
+ case 'yarn':
187
+ return {
188
+ command: process.platform === 'win32' ? 'yarn.cmd' : 'yarn',
189
+ args: [
190
+ 'global',
191
+ 'add',
192
+ target,
193
+ '--non-interactive',
194
+ '--silent',
195
+ ...registryArgs,
196
+ ],
197
+ };
198
+ case 'bun':
199
+ return {
200
+ command: process.platform === 'win32' ? 'bun.exe' : 'bun',
201
+ args: ['add', '--global', target, '--no-progress', ...registryArgs],
202
+ };
203
+ default:
204
+ return {
205
+ command: process.platform === 'win32' ? 'npm.cmd' : 'npm',
206
+ args: [
207
+ 'install',
208
+ '--global',
209
+ target,
210
+ ...(installPrefix && process.platform !== 'win32'
211
+ ? [`--prefix=${installPrefix}`]
212
+ : []),
213
+ '--no-audit',
214
+ '--no-fund',
215
+ '--loglevel=error',
216
+ ...registryArgs,
217
+ ],
218
+ };
219
+ }
220
+ }
221
+ function inferNpmPrefix(packageRoot, npmGlobalDir, npmPrefix) {
222
+ if (npmGlobalDir && npmPrefix && isWithin(packageRoot, npmGlobalDir)) {
223
+ return normalizePath(npmPrefix);
224
+ }
225
+ const modules = path_1.default.dirname(normalizePath(packageRoot));
226
+ if (path_1.default.basename(modules).toLowerCase() !== 'node_modules') {
227
+ return undefined;
228
+ }
229
+ const modulesParent = path_1.default.dirname(modules);
230
+ return path_1.default.basename(modulesParent).toLowerCase() === 'lib'
231
+ ? path_1.default.dirname(modulesParent)
232
+ : modulesParent;
233
+ }
234
+ function isDisabled(env) {
235
+ const disabled = (value) => value === '0' || value?.toLowerCase() === 'false';
236
+ const enabled = (value) => value === '1' || value?.toLowerCase() === 'true';
237
+ return (disabled(env.RNU_AUTO_UPDATE) ||
238
+ enabled(env.RNU_DISABLE_AUTO_UPDATE) ||
239
+ enabled(env.NO_UPDATE_NOTIFIER) ||
240
+ enabled(env.CI));
241
+ }
242
+ function shouldRetry(state, target) {
243
+ if (!state || state.targetVersion !== target)
244
+ return true;
245
+ if (state.status === 'updated')
246
+ return false;
247
+ if (state.status === 'running') {
248
+ return Date.now() - state.attemptedAt >= LOCK_STALE_MS;
249
+ }
250
+ return !state.retryAt || state.retryAt <= Date.now();
251
+ }
252
+ /**
253
+ * Start a detached updater after the foreground command has completed. This
254
+ * function is synchronous on purpose: it is safe to call from process.exit.
255
+ */
256
+ function launchAutoUpdate(currentVersion, targetVersion, env = process.env) {
257
+ if (!targetVersion ||
258
+ targetVersion === currentVersion ||
259
+ isDisabled(env) ||
260
+ !shouldRetry(readState(), targetVersion)) {
261
+ return false;
262
+ }
263
+ const packageRoot = path_1.default.resolve(__dirname, '..');
264
+ const directories = globalDirectories();
265
+ const detected = detectGlobalPackageManager({
266
+ packageRoot,
267
+ env,
268
+ npmGlobalDir: directories.npmGlobalDir,
269
+ yarnGlobalDir: directories.yarnGlobalDir,
270
+ });
271
+ if (!detected)
272
+ return false;
273
+ const packageManager = parseManager(env.RNU_AUTO_UPDATE_PACKAGE_MANAGER) ?? detected;
274
+ let registryUrl = 'https://registry.npmjs.org/';
275
+ try {
276
+ const registryModule = require('registry-auth-token/registry-url');
277
+ const getRegistryUrl = (registryModule.default ?? registryModule);
278
+ registryUrl = getRegistryUrl('');
279
+ }
280
+ catch {
281
+ // Keep the public npm registry fallback when config parsing fails.
282
+ }
283
+ const candidate = {
284
+ currentVersion,
285
+ targetVersion,
286
+ packageRoot: normalizePath(packageRoot),
287
+ packageManager,
288
+ registryUrl: sanitizeRegistryUrl(registryUrl),
289
+ installPrefix: packageManager === 'npm' && detected === 'npm'
290
+ ? inferNpmPrefix(packageRoot, directories.npmGlobalDir, directories.npmPrefix)
291
+ : undefined,
292
+ };
293
+ try {
294
+ const worker = (0, child_process_1.spawn)(process.execPath, [__filename], {
295
+ detached: true,
296
+ env: {
297
+ ...env,
298
+ [WORKER_ENV]: '1',
299
+ [CANDIDATE_ENV]: JSON.stringify(candidate),
300
+ },
301
+ stdio: 'ignore',
302
+ windowsHide: true,
303
+ });
304
+ worker.once('error', () => { });
305
+ worker.unref();
306
+ return true;
307
+ }
308
+ catch {
309
+ return false;
310
+ }
311
+ }
312
+ function acquireLock() {
313
+ try {
314
+ (0, fs_1.mkdirSync)(cacheDir(), { recursive: true });
315
+ try {
316
+ (0, fs_1.mkdirSync)(lockDir());
317
+ return true;
318
+ }
319
+ catch {
320
+ if ((0, fs_1.existsSync)(lockDir()) &&
321
+ Date.now() - (0, fs_1.statSync)(lockDir()).mtimeMs >= LOCK_STALE_MS) {
322
+ (0, fs_1.rmSync)(lockDir(), { force: true, recursive: true });
323
+ (0, fs_1.mkdirSync)(lockDir());
324
+ return true;
325
+ }
326
+ return false;
327
+ }
328
+ }
329
+ catch {
330
+ return false;
331
+ }
332
+ }
333
+ function appendBounded(current, chunk) {
334
+ const combined = `${current}${chunk.toString()}`;
335
+ return combined.length > OUTPUT_LIMIT
336
+ ? combined.slice(combined.length - OUTPUT_LIMIT)
337
+ : combined;
338
+ }
339
+ function classifyFailure(error) {
340
+ if (/eacces|eperm|permission denied|access is denied/i.test(error)) {
341
+ return 'permission';
342
+ }
343
+ if (/econn|enet|eai_again|enotfound|timed?\s*out|timeout|certificate|socket|network|fetch/i.test(error)) {
344
+ return 'network';
345
+ }
346
+ if (/enoent|not recognized|command not found/i.test(error)) {
347
+ return 'package-manager';
348
+ }
349
+ return 'unknown';
350
+ }
351
+ function retryDelay(kind) {
352
+ if (kind === 'permission')
353
+ return PERMISSION_RETRY_MS;
354
+ if (kind === 'network')
355
+ return NETWORK_RETRY_MS;
356
+ return FAILURE_RETRY_MS;
357
+ }
358
+ function compactMessage(value) {
359
+ return value
360
+ .split(String.fromCharCode(27))
361
+ .map((part, index) => index === 0 ? part : part.replace(/^\[[0-9;]*m/, ''))
362
+ .join('')
363
+ .trim()
364
+ .slice(-2000);
365
+ }
366
+ async function runPackageManager(command, args, registryUrl, installPrefix) {
367
+ return new Promise((resolve) => {
368
+ let output = '';
369
+ let settled = false;
370
+ const child = (0, child_process_1.spawn)(command, args, {
371
+ env: {
372
+ ...process.env,
373
+ npm_config_audit: 'false',
374
+ npm_config_fund: 'false',
375
+ ...(installPrefix
376
+ ? {
377
+ NPM_CONFIG_PREFIX: installPrefix,
378
+ npm_config_prefix: installPrefix,
379
+ }
380
+ : {}),
381
+ npm_config_registry: sanitizeRegistryUrl(registryUrl),
382
+ npm_config_update_notifier: 'false',
383
+ },
384
+ shell: process.platform === 'win32' && command.endsWith('.cmd'),
385
+ stdio: ['ignore', 'pipe', 'pipe'],
386
+ windowsHide: true,
387
+ });
388
+ const finish = (code, extra = '') => {
389
+ if (settled)
390
+ return;
391
+ settled = true;
392
+ clearTimeout(timer);
393
+ resolve({ code, output: appendBounded(output, extra) });
394
+ };
395
+ child.stdout?.on('data', (chunk) => {
396
+ output = appendBounded(output, chunk);
397
+ });
398
+ child.stderr?.on('data', (chunk) => {
399
+ output = appendBounded(output, chunk);
400
+ });
401
+ child.once('error', (error) => finish(127, error.message));
402
+ child.once('close', (code, signal) => finish(code ?? 1, signal ? `\nTerminated by ${signal}` : ''));
403
+ const timer = setTimeout(() => {
404
+ child.kill('SIGTERM');
405
+ finish(124, '\nUpdate timed out');
406
+ }, UPDATE_TIMEOUT_MS);
407
+ });
408
+ }
409
+ async function runWorker(candidate) {
410
+ if (!acquireLock())
411
+ return;
412
+ const previous = readState();
413
+ const running = {
414
+ ...candidate,
415
+ status: 'running',
416
+ attemptedAt: Date.now(),
417
+ failureCount: previous?.targetVersion === candidate.targetVersion
418
+ ? (previous.failureCount ?? 0) + 1
419
+ : 1,
420
+ };
421
+ writeState(running);
422
+ try {
423
+ if (process.platform !== 'win32') {
424
+ (0, fs_1.accessSync)(path_1.default.dirname(candidate.packageRoot), fs_1.constants.W_OK);
425
+ }
426
+ }
427
+ catch (error) {
428
+ const failureKind = 'permission';
429
+ writeState({
430
+ ...running,
431
+ status: 'failed',
432
+ finishedAt: Date.now(),
433
+ retryAt: Date.now() + retryDelay(failureKind),
434
+ failureKind,
435
+ message: compactMessage(String(error)),
436
+ });
437
+ (0, fs_1.rmSync)(lockDir(), { force: true, recursive: true });
438
+ return;
439
+ }
440
+ const update = buildUpdateCommand(candidate.packageManager, candidate.targetVersion, candidate.registryUrl, candidate.installPrefix);
441
+ const result = await runPackageManager(update.command, update.args, candidate.registryUrl, candidate.installPrefix);
442
+ if (result.code === 0) {
443
+ writeState({
444
+ ...running,
445
+ status: 'updated',
446
+ finishedAt: Date.now(),
447
+ message: undefined,
448
+ });
449
+ }
450
+ else {
451
+ const detail = compactMessage(result.output);
452
+ const failureKind = classifyFailure(detail);
453
+ writeState({
454
+ ...running,
455
+ status: 'failed',
456
+ finishedAt: Date.now(),
457
+ retryAt: Date.now() + retryDelay(failureKind),
458
+ failureKind,
459
+ message: detail,
460
+ });
461
+ }
462
+ (0, fs_1.rmSync)(lockDir(), { force: true, recursive: true });
463
+ }
464
+ function consumeAutoUpdateNotice(currentVersion) {
465
+ const state = readState();
466
+ if (!state || state.reportedAt)
467
+ return undefined;
468
+ if (state.status === 'updated' && currentVersion === state.targetVersion) {
469
+ writeState({ ...state, reportedAt: Date.now() });
470
+ return {
471
+ kind: 'updated',
472
+ currentVersion: state.currentVersion,
473
+ targetVersion: state.targetVersion,
474
+ };
475
+ }
476
+ if (state.status === 'failed' && state.failureKind === 'permission') {
477
+ writeState({ ...state, reportedAt: Date.now() });
478
+ const update = buildUpdateCommand(state.packageManager, state.targetVersion, state.registryUrl, state.installPrefix);
479
+ return {
480
+ kind: 'permission',
481
+ currentVersion,
482
+ targetVersion: state.targetVersion,
483
+ command: [update.command, ...update.args].join(' '),
484
+ };
485
+ }
486
+ return undefined;
487
+ }
488
+ if (process.env[WORKER_ENV] === '1') {
489
+ try {
490
+ const candidate = JSON.parse(process.env[CANDIDATE_ENV] ?? '');
491
+ if (candidate?.packageRoot &&
492
+ candidate.targetVersion &&
493
+ parseManager(candidate.packageManager)) {
494
+ void runWorker(candidate).catch(() => {
495
+ (0, fs_1.rmSync)(lockDir(), { force: true, recursive: true });
496
+ });
497
+ }
498
+ }
499
+ catch {
500
+ // Malformed worker input is ignored; foreground CLI operation is over.
501
+ }
502
+ }
package/lib/bin.js CHANGED
@@ -51,11 +51,13 @@ async function run() {
51
51
  // exit on their own.
52
52
  const versionCheck = await (0, utils_1.printVersionCommand)({ wait: versionOnly });
53
53
  if (versionOnly) {
54
+ versionCheck.startAutoUpdate();
54
55
  process.exit();
55
56
  }
56
57
  process.on('exit', (code) => {
57
58
  if (code === 0) {
58
59
  versionCheck.printHints();
60
+ versionCheck.startAutoUpdate();
59
61
  }
60
62
  });
61
63
  const argv = require('cli-arguments').parse(require('../cli.json'));
@@ -79,6 +81,7 @@ async function run() {
79
81
  // registry request itself is unref'd, so exiting never waits on it
80
82
  await versionCheck.settle(500);
81
83
  versionCheck.printHints();
84
+ versionCheck.startAutoUpdate();
82
85
  }
83
86
  else {
84
87
  throw new Error((0, i18n_1.t)('unknownCommand', { command: argv.command }));
package/lib/bundle.d.ts CHANGED
@@ -13,6 +13,8 @@ type NormalizedBundleOptions = {
13
13
  verifyHermesBase: boolean;
14
14
  resetCache: boolean;
15
15
  cacheMaxMb?: number;
16
+ appId?: string;
17
+ config?: string;
16
18
  name?: string;
17
19
  description?: string;
18
20
  metaInfo?: string;
@@ -26,8 +28,10 @@ type NormalizedBundleOptions = {
26
28
  sentryRelease?: string;
27
29
  sentryDist?: string;
28
30
  };
31
+ /** Normalize translated CLI values into the bundle command's typed options. */
29
32
  export declare function normalizeBundleOptions(translatedOptions: Record<string, unknown>, platform: string): NormalizedBundleOptions;
30
33
  export declare const bundleCommands: {
34
+ /** Build a bundle and optionally publish it to one operation-scoped app. */
31
35
  bundle: ({ options, }: {
32
36
  args?: string[];
33
37
  options: Record<string, unknown>;
package/lib/bundle.js CHANGED
@@ -18,14 +18,17 @@ const hermes_base_1 = require("./utils/hermes-base");
18
18
  const i18n_1 = require("./utils/i18n");
19
19
  const options_1 = require("./utils/options");
20
20
  const versions_1 = require("./versions");
21
+ /** Parse a positive cache-size option expressed in megabytes. */
21
22
  function parseCacheMaxMb(value) {
22
23
  const parsed = typeof value === 'string' ? Number(value) : value;
23
24
  return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
24
25
  }
26
+ /** Read either spelling of an aliased optional CLI string option. */
25
27
  function getAliasedOptionalStringOption(options, key, alias) {
26
28
  return ((0, options_1.getOptionalStringOption)(options, key) ??
27
29
  (0, options_1.getOptionalStringOption)(options, alias));
28
30
  }
31
+ /** Normalize translated CLI values into the bundle command's typed options. */
29
32
  function normalizeBundleOptions(translatedOptions, platform) {
30
33
  return {
31
34
  // harmony bundles always use this fixed name (runReactNativeBundleCommand
@@ -48,6 +51,8 @@ function normalizeBundleOptions(translatedOptions, platform) {
48
51
  verifyHermesBase: (0, options_1.getBooleanOption)(translatedOptions, 'verifyHermesBase', true),
49
52
  resetCache: (0, options_1.getBooleanOption)(translatedOptions, 'resetCache', true),
50
53
  cacheMaxMb: parseCacheMaxMb(translatedOptions.cacheMaxMb),
54
+ appId: (0, options_1.getOptionalStringOption)(translatedOptions, 'appId'),
55
+ config: (0, options_1.getOptionalStringOption)(translatedOptions, 'config'),
51
56
  name: (0, options_1.getOptionalStringOption)(translatedOptions, 'name'),
52
57
  description: (0, options_1.getOptionalStringOption)(translatedOptions, 'description'),
53
58
  metaInfo: (0, options_1.getOptionalStringOption)(translatedOptions, 'metaInfo'),
@@ -62,6 +67,7 @@ function normalizeBundleOptions(translatedOptions, platform) {
62
67
  sentryDist: getAliasedOptionalStringOption(translatedOptions, 'sentry-dist', 'sentryDist'),
63
68
  };
64
69
  }
70
+ /** Upload generated Sentry artifacts when the detected plugin requires them. */
65
71
  async function uploadSentryArtifactsIfNeeded(shouldUpload, bundleName, intermediaDir, sourcemapOutput, platform, sentryOptions) {
66
72
  if (!shouldUpload) {
67
73
  return;
@@ -69,6 +75,7 @@ async function uploadSentryArtifactsIfNeeded(shouldUpload, bundleName, intermedi
69
75
  await (0, bundle_runner_1.copyDebugidForSentry)(bundleName, intermediaDir, sourcemapOutput);
70
76
  await (0, bundle_runner_1.uploadSourcemapForSentry)(bundleName, intermediaDir, sourcemapOutput, platform, sentryOptions);
71
77
  }
78
+ /** Publish a packed bundle through the version command implementation. */
72
79
  async function publishBundleVersion(outputPath, platform, payload) {
73
80
  return versions_1.versionCommands.publish({
74
81
  args: [outputPath],
@@ -79,6 +86,7 @@ async function publishBundleVersion(outputPath, platform, payload) {
79
86
  });
80
87
  }
81
88
  exports.bundleCommands = {
89
+ /** Build a bundle and optionally publish it to one operation-scoped app. */
82
90
  bundle: async ({ options, }) => {
83
91
  const platform = await (0, app_1.getPlatform)(typeof options.platform === 'string' ? options.platform : undefined);
84
92
  const translatedOptions = (0, utils_1.translateOptions)({
@@ -87,29 +95,51 @@ exports.bundleCommands = {
87
95
  platform,
88
96
  });
89
97
  const normalized = normalizeBundleOptions(translatedOptions, platform);
98
+ // One app per operation: the Hermes base lookup and the publish step must
99
+ // never see different apps, so the target is resolved once and reused.
100
+ let appId;
101
+ const getAppId = async () => (appId ??= await (0, app_1.resolveAppId)({
102
+ appId: normalized.appId,
103
+ config: normalized.config,
104
+ platform,
105
+ }));
106
+ const hermesBase = normalized.dev === 'true'
107
+ ? undefined
108
+ : {
109
+ option: normalized.hermesBase,
110
+ verify: normalized.verifyHermesBase,
111
+ cacheMaxMb: normalized.cacheMaxMb,
112
+ };
113
+ // Resolve before any side effect or expensive work. A named bundle is
114
+ // published, so a missing app fails right here; a bundle-only run only
115
+ // needs the app for the remote Hermes base lookup and may go on without
116
+ // one (it then compiles a full bundle). Any other config error (e.g.
117
+ // malformed JSON) is reported immediately either way.
118
+ if (normalized.name) {
119
+ await getAppId();
120
+ }
121
+ else if (hermesBase?.option === 'auto') {
122
+ try {
123
+ await getAppId();
124
+ }
125
+ catch (error) {
126
+ if (!(error instanceof app_1.AppNotSelectedError)) {
127
+ throw error;
128
+ }
129
+ }
130
+ }
90
131
  (0, check_lockfile_1.checkLockFiles)();
91
132
  (0, add_gitignore_1.addGitIgnore)();
92
- const bundleParams = await (0, utils_1.checkPlugins)();
133
+ const [bundleParams] = await Promise.all([
134
+ (0, utils_1.checkPlugins)(),
135
+ (0, hermes_base_1.cleanStaleTmp)().catch(() => { }),
136
+ ]);
93
137
  const sourcemapOutput = path_1.default.join(normalized.intermediaDir, `${normalized.bundleName}.map`);
94
138
  const realOutput = normalized.output.replace(/\$\{time\}/g, `${Date.now()}`);
95
139
  if (!platform) {
96
140
  throw new Error((0, i18n_1.t)('platformRequired'));
97
141
  }
98
142
  console.log((0, i18n_1.t)('bundlingWithRN', { version: dep_versions_1.depVersions['react-native'] }));
99
- await (0, hermes_base_1.cleanStaleTmp)().catch(() => { });
100
- // the hermes base lookup needs the app; resolve it up front but never
101
- // fail the bundle over it (publishing resolves it again and reports)
102
- let appIdForBase = typeof options.appId === 'string' && options.appId
103
- ? options.appId
104
- : undefined;
105
- if (!appIdForBase && normalized.hermesBase === 'auto') {
106
- try {
107
- appIdForBase = (await (0, app_1.getSelectedApp)(platform, options.config)).appId;
108
- }
109
- catch {
110
- appIdForBase = undefined;
111
- }
112
- }
113
143
  const hermesResult = await (0, bundle_runner_1.runReactNativeBundleCommand)({
114
144
  bundleName: normalized.bundleName,
115
145
  dev: normalized.dev,
@@ -118,14 +148,7 @@ exports.bundleCommands = {
118
148
  platform,
119
149
  sourcemapOutput: normalized.sourcemap || bundleParams.sourcemap ? sourcemapOutput : '',
120
150
  forceHermes: normalized.hermes,
121
- hermesBase: normalized.dev === 'true'
122
- ? undefined
123
- : {
124
- option: normalized.hermesBase,
125
- appId: appIdForBase,
126
- verify: normalized.verifyHermesBase,
127
- cacheMaxMb: normalized.cacheMaxMb,
128
- },
151
+ hermesBase: hermesBase ? { ...hermesBase, appId } : undefined,
129
152
  resetCache: normalized.resetCache,
130
153
  cli: {
131
154
  taro: normalized.taro,
@@ -140,6 +163,7 @@ exports.bundleCommands = {
140
163
  : undefined;
141
164
  if (normalized.name) {
142
165
  await publishBundleVersion(realOutput, platform, {
166
+ appId: await getAppId(),
143
167
  name: normalized.name,
144
168
  description: normalized.description,
145
169
  metaInfo: normalized.metaInfo,
@@ -165,6 +189,7 @@ exports.bundleCommands = {
165
189
  const v = await (0, utils_1.question)((0, i18n_1.t)('uploadBundlePrompt'));
166
190
  if (v.toLowerCase() === 'y') {
167
191
  await publishBundleVersion(realOutput, platform, {
192
+ appId: await getAppId(),
168
193
  hermesBase: baseMeta,
169
194
  sourcemap: normalized.sourcemap || bundleParams.sourcemap
170
195
  ? sourcemapOutput