react-native-update-cli 2.22.7 → 2.22.9

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 (65) hide show
  1. package/README.md +1 -1
  2. package/README.zh-CN.md +1 -1
  3. package/cli.json +5 -0
  4. package/lib/api.d.ts +7 -0
  5. package/lib/api.js +106 -38
  6. package/lib/app.js +3 -2
  7. package/lib/bin.js +16 -2
  8. package/lib/bundle-runner.d.ts +11 -4
  9. package/lib/bundle-runner.js +176 -90
  10. package/lib/bundle.d.ts +1 -0
  11. package/lib/bundle.js +2 -0
  12. package/lib/diff.d.ts +9 -0
  13. package/lib/diff.js +162 -120
  14. package/lib/locales/en.d.ts +1 -0
  15. package/lib/locales/en.js +1 -0
  16. package/lib/locales/zh.d.ts +1 -0
  17. package/lib/locales/zh.js +1 -0
  18. package/lib/native-package.d.ts +5 -1
  19. package/lib/native-package.js +145 -84
  20. package/lib/package.d.ts +7 -3
  21. package/lib/package.js +22 -12
  22. package/lib/types.d.ts +2 -0
  23. package/lib/utils/dep-versions.d.ts +7 -0
  24. package/lib/utils/dep-versions.js +66 -31
  25. package/lib/utils/hbcTransform.d.ts +21 -0
  26. package/lib/utils/hbcTransform.js +146 -5
  27. package/lib/utils/hermes-base.d.ts +21 -4
  28. package/lib/utils/hermes-base.js +146 -37
  29. package/lib/utils/http-helper.d.ts +6 -1
  30. package/lib/utils/http-helper.js +23 -11
  31. package/lib/utils/index.d.ts +30 -1
  32. package/lib/utils/index.js +98 -24
  33. package/lib/utils/latest-version/index.d.ts +11 -8
  34. package/lib/utils/latest-version/index.js +91 -25
  35. package/lib/utils/zip-entries.js +20 -15
  36. package/lib/utils/zip-options.d.ts +2 -0
  37. package/lib/utils/zip-options.js +9 -4
  38. package/lib/utils/zip-range.d.ts +47 -15
  39. package/lib/utils/zip-range.js +192 -83
  40. package/lib/utils/zip-raw-writer.d.ts +47 -0
  41. package/lib/utils/zip-raw-writer.js +204 -0
  42. package/lib/versions.js +19 -9
  43. package/package.json +10 -12
  44. package/src/api.ts +126 -46
  45. package/src/app.ts +3 -2
  46. package/src/bin.ts +17 -2
  47. package/src/bundle-runner.ts +225 -113
  48. package/src/bundle.ts +3 -0
  49. package/src/diff.ts +210 -153
  50. package/src/locales/en.ts +2 -0
  51. package/src/locales/zh.ts +2 -0
  52. package/src/native-package.ts +186 -96
  53. package/src/package.ts +26 -13
  54. package/src/types.ts +2 -0
  55. package/src/utils/dep-versions.ts +76 -33
  56. package/src/utils/hbcTransform.ts +194 -5
  57. package/src/utils/hermes-base.ts +156 -45
  58. package/src/utils/http-helper.ts +24 -13
  59. package/src/utils/index.ts +136 -26
  60. package/src/utils/latest-version/index.ts +109 -33
  61. package/src/utils/zip-entries.ts +18 -16
  62. package/src/utils/zip-options.ts +8 -3
  63. package/src/utils/zip-range.ts +244 -88
  64. package/src/utils/zip-raw-writer.ts +247 -0
  65. package/src/versions.ts +17 -7
@@ -23,7 +23,11 @@ exports.findLayouts = findLayouts;
23
23
  exports.transformHbc = transformHbc;
24
24
  exports.pickLayout = pickLayout;
25
25
  exports.transformHbcWithLayout = transformHbcWithLayout;
26
+ exports.transformHbcWithLayoutInPlace = transformHbcWithLayoutInPlace;
27
+ exports.transformHbcFile = transformHbcFile;
26
28
  exports.tryTransformPair = tryTransformPair;
29
+ exports.tryTransformPairFiles = tryTransformPairFiles;
30
+ const promises_1 = require("node:fs/promises");
27
31
  const HBC_MAGIC = Buffer.from([0xc6, 0x1f, 0xbc, 0x03, 0xc1, 0x03, 0x19, 0x1f]);
28
32
  const HEADER_COUNTS_OFFSET = 32; // magic(8) + version(4) + sourceHash(20)
29
33
  const HBC_HEADER_SIZE = 128;
@@ -266,19 +270,29 @@ const align4 = (x) => (x + 3) & ~3;
266
270
  * 描述表视为不可信输入,所有算术做显式边界检查。
267
271
  */
268
272
  function resolveSections(buf, layout) {
273
+ return resolveSectionsFromHeader(buf, buf.length, layout);
274
+ }
275
+ /**
276
+ * 只依赖头部 128 字节与文件总长即可解析段边界(表偏移全部来自头部计数),
277
+ * 文件版变换据此无需把整个 bundle 读进内存。
278
+ */
279
+ function resolveSectionsFromHeader(header, fileLength, layout) {
269
280
  const headerEnd = HEADER_COUNTS_OFFSET + layout.headerFields.length * 4;
270
- if (buf.length < HBC_HEADER_SIZE || headerEnd > HBC_HEADER_SIZE)
281
+ if (header.length < HBC_HEADER_SIZE ||
282
+ fileLength < HBC_HEADER_SIZE ||
283
+ headerEnd > HBC_HEADER_SIZE) {
271
284
  return null;
285
+ }
272
286
  const counts = {};
273
287
  layout.headerFields.forEach((name, i) => {
274
- counts[name] = buf.readUInt32LE(HEADER_COUNTS_OFFSET + i * 4);
288
+ counts[name] = header.readUInt32LE(HEADER_COUNTS_OFFSET + i * 4);
275
289
  });
276
- if (counts.fileLength !== buf.length)
290
+ if (counts.fileLength !== fileLength)
277
291
  return null;
278
292
  const debugInfoOffset = counts.debugInfoOffset;
279
293
  if (!Number.isInteger(debugInfoOffset) ||
280
294
  debugInfoOffset < HBC_HEADER_SIZE ||
281
- debugInfoOffset > buf.length) {
295
+ debugInfoOffset > fileLength) {
282
296
  return null;
283
297
  }
284
298
  const resolved = [];
@@ -356,11 +370,99 @@ function transformHbcWithLayout(buf, layout, inverse) {
356
370
  if (!sections)
357
371
  return null;
358
372
  const out = Buffer.from(buf);
373
+ applyDeltaSections(out, sections, inverse);
374
+ return out;
375
+ }
376
+ /**
377
+ * 原地变换:直接改写 buf,不再分配整块副本。调用方须持有 buf 的所有权
378
+ * (例如 patch() 刚返回的新 Buffer)。结构不匹配时返回 false 且 buf 不变。
379
+ */
380
+ function transformHbcWithLayoutInPlace(buf, layout, inverse) {
381
+ const sections = resolveSections(buf, layout);
382
+ if (!sections)
383
+ return false;
384
+ applyDeltaSections(buf, sections, inverse);
385
+ return true;
386
+ }
387
+ function applyDeltaSections(out, sections, inverse) {
359
388
  for (const s of sections) {
360
389
  if (s.desc.deltaFields?.length)
361
390
  applyDelta(out, s, inverse);
362
391
  }
363
- return out;
392
+ }
393
+ /** 读取文件头 128 字节与总长;文件过短或非 HBC 时返回 null。 */
394
+ async function readHbcFileHeader(filePath) {
395
+ const { size } = await (0, promises_1.stat)(filePath);
396
+ if (size < HBC_HEADER_SIZE)
397
+ return null;
398
+ const header = Buffer.alloc(HBC_HEADER_SIZE);
399
+ const handle = await (0, promises_1.open)(filePath, 'r');
400
+ try {
401
+ await readExact(handle, header, 0);
402
+ }
403
+ finally {
404
+ await handle.close();
405
+ }
406
+ if (getHbcVersion(header) === null)
407
+ return null;
408
+ return { header, size };
409
+ }
410
+ async function readExact(handle, buffer, position) {
411
+ let done = 0;
412
+ while (done < buffer.length) {
413
+ const { bytesRead } = await handle.read(buffer, done, buffer.length - done, position + done);
414
+ if (bytesRead <= 0) {
415
+ throw new Error('unexpected end of file while reading HBC section');
416
+ }
417
+ done += bytesRead;
418
+ }
419
+ }
420
+ async function writeExact(handle, buffer, position) {
421
+ let done = 0;
422
+ while (done < buffer.length) {
423
+ const { bytesWritten } = await handle.write(buffer, done, buffer.length - done, position + done);
424
+ if (bytesWritten <= 0) {
425
+ throw new Error('short write while rewriting HBC section');
426
+ }
427
+ done += bytesWritten;
428
+ }
429
+ }
430
+ /**
431
+ * 文件版 transformHbcWithLayout:把 src 复制到 dst,再仅对含差分字段的
432
+ * 段(位于 [128, 最后一段末尾) 区间内)做定位读写改写。任一时刻内存中
433
+ * 只有一个段的内容,不会持有整个 bundle。输出与内存版逐字节一致。
434
+ * 结构不匹配时返回 false 并清理 dst。
435
+ */
436
+ async function transformHbcFile(src, dst, layout, inverse) {
437
+ const info = await readHbcFileHeader(src);
438
+ const sections = info
439
+ ? resolveSectionsFromHeader(info.header, info.size, layout)
440
+ : null;
441
+ if (!sections) {
442
+ return false;
443
+ }
444
+ await (0, promises_1.copyFile)(src, dst);
445
+ try {
446
+ const handle = await (0, promises_1.open)(dst, 'r+');
447
+ try {
448
+ for (const s of sections) {
449
+ if (!s.desc.deltaFields?.length || s.size === 0)
450
+ continue;
451
+ const chunk = Buffer.alloc(s.size);
452
+ await readExact(handle, chunk, s.start);
453
+ applyDelta(chunk, { start: 0, size: s.size, desc: s.desc }, inverse);
454
+ await writeExact(handle, chunk, s.start);
455
+ }
456
+ }
457
+ finally {
458
+ await handle.close();
459
+ }
460
+ }
461
+ catch (error) {
462
+ await (0, promises_1.rm)(dst, { force: true });
463
+ throw error;
464
+ }
465
+ return true;
364
466
  }
365
467
  exports.HBC_TRANSFORM_VERSION = 1;
366
468
  /**
@@ -391,3 +493,42 @@ function tryTransformPair(oldBuf, newBuf) {
391
493
  }
392
494
  return null;
393
495
  }
496
+ /**
497
+ * tryTransformPair 的文件版:只读两侧头部即可选定布局,变换结果直接写到
498
+ * tOldPath / tNewPath,全程不把 bundle 读进内存。无可用布局时返回 null
499
+ * (不产生输出文件)。
500
+ */
501
+ async function tryTransformPairFiles(oldPath, newPath, tOldPath, tNewPath) {
502
+ const [oldInfo, newInfo] = await Promise.all([
503
+ readHbcFileHeader(oldPath),
504
+ readHbcFileHeader(newPath),
505
+ ]);
506
+ if (!oldInfo || !newInfo)
507
+ return null;
508
+ const oldVersion = getHbcVersion(oldInfo.header);
509
+ const newVersion = getHbcVersion(newInfo.header);
510
+ if (oldVersion === null || newVersion === null || oldVersion !== newVersion) {
511
+ return null;
512
+ }
513
+ for (const layout of findLayouts(newVersion)) {
514
+ if (!resolveSectionsFromHeader(oldInfo.header, oldInfo.size, layout) ||
515
+ !resolveSectionsFromHeader(newInfo.header, newInfo.size, layout)) {
516
+ continue;
517
+ }
518
+ const [tOld, tNew] = await Promise.all([
519
+ transformHbcFile(oldPath, tOldPath, layout, false),
520
+ transformHbcFile(newPath, tNewPath, layout, false),
521
+ ]);
522
+ if (!tOld || !tNew)
523
+ continue;
524
+ return {
525
+ layout,
526
+ meta: {
527
+ v: exports.HBC_TRANSFORM_VERSION,
528
+ hbcVersion: newVersion,
529
+ layout: compileLayoutToWire(layout),
530
+ },
531
+ };
532
+ }
533
+ return null;
534
+ }
@@ -1,4 +1,14 @@
1
1
  export type HermesBaseOption = 'auto' | 'none' | string;
2
+ /**
3
+ * The base cannot be obtained whatever the transport or how often it is
4
+ * retried (wrong content on the server, no bundle in the package, ...).
5
+ */
6
+ export declare class PermanentBaseError extends Error {
7
+ }
8
+ /** The fetched bundle's sha256 differs from what the server recorded. */
9
+ export declare class BundleHashMismatchError extends PermanentBaseError {
10
+ constructor(actual: string, expected: string);
11
+ }
2
12
  export interface HermesBaseSelection {
3
13
  /** path of the bundle (HBC) handed to hermesc as -base-bytecode */
4
14
  path: string;
@@ -31,6 +41,10 @@ export declare function classifyHermesCommand(hermesCommand: string): {
31
41
  reason?: string;
32
42
  };
33
43
  export declare function sha256Hex(data: Buffer): string;
44
+ /** sha256 of a file, streamed (a cached base can be tens of MB) */
45
+ export declare function sha256File(file: string): Promise<string>;
46
+ /** HBC version from the first bytes of a file, without reading the rest */
47
+ export declare function readFileHbcVersion(file: string): Promise<number | null>;
34
48
  /**
35
49
  * Which HBC version this hermesc emits. The answer is remembered per binary
36
50
  * (path, size, mtime) in the cache dir so only the first run of a given
@@ -62,6 +76,7 @@ export declare function cachePut(bundle: Buffer, maxMb?: number, knownHash?: str
62
76
  bundleHash: string;
63
77
  }>;
64
78
  export declare function enforceCacheLimits(maxMb?: number, keep?: string): Promise<void>;
79
+ /** Remove every cached bundle (and staging leftovers); returns the bundle count. */
65
80
  export declare function cleanCache(): Promise<number>;
66
81
  export declare function cacheStats(): Promise<{
67
82
  dir: string;
@@ -106,11 +121,13 @@ interface FetchedBaseBundle {
106
121
  * is skipped);
107
122
  * 3. the whole archive, as before.
108
123
  * A server that ignores Range (HTTP 200) streams the full archive into
109
- * `archive` without a second request. Range results are verified against
110
- * `record.bundleHash` here; a mismatch (e.g. re-packaged object) falls
111
- * through to the next transport instead of failing the resolution.
124
+ * `archive` without a second request. Every result is verified against
125
+ * `record.bundleHash`. A mismatch of the located bytes (1) may only mean the
126
+ * recorded location is stale, so the directory transport (2) still runs; a
127
+ * mismatch of the entry itself (2, 3) is final — the same bytes would come
128
+ * back however they are fetched — and raises BundleHashMismatchError.
112
129
  */
113
- export declare function fetchBaseBundle(record: HermesBaseServerRecord, artifactType: BaseArtifactType, archive: string, log?: (message: string) => void): Promise<FetchedBaseBundle | null>;
130
+ export declare function fetchBaseBundle(record: HermesBaseServerRecord, artifactType: BaseArtifactType, archive: string, log?: (message: string) => void): Promise<FetchedBaseBundle>;
114
131
  export interface ResolveHermesBaseParams {
115
132
  option: HermesBaseOption;
116
133
  hermesCommand: string;
@@ -36,9 +36,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.DEFAULT_CACHE_MAX_FILES = exports.DEFAULT_CACHE_MAX_BYTES = exports.BUNDLE_ENTRY_NAMES = exports.MIN_HERMES_COMPILER_COMMITLY_DATE = exports.MIN_HERMES_COMPILER_BUILD = void 0;
39
+ exports.DEFAULT_CACHE_MAX_FILES = exports.DEFAULT_CACHE_MAX_BYTES = exports.BUNDLE_ENTRY_NAMES = exports.MIN_HERMES_COMPILER_COMMITLY_DATE = exports.MIN_HERMES_COMPILER_BUILD = exports.BundleHashMismatchError = exports.PermanentBaseError = void 0;
40
40
  exports.classifyHermesCommand = classifyHermesCommand;
41
41
  exports.sha256Hex = sha256Hex;
42
+ exports.sha256File = sha256File;
43
+ exports.readFileHbcVersion = readFileHbcVersion;
42
44
  exports.probeHbcVersion = probeHbcVersion;
43
45
  exports.bundleEntryMatcher = bundleEntryMatcher;
44
46
  exports.extractBundleFromArchive = extractBundleFromArchive;
@@ -73,12 +75,33 @@ const crypto_1 = require("crypto");
73
75
  const fs_extra_1 = __importDefault(require("fs-extra"));
74
76
  const os_1 = __importDefault(require("os"));
75
77
  const path_1 = __importDefault(require("path"));
78
+ const stream_1 = require("stream");
76
79
  const promises_1 = require("stream/promises");
77
80
  const constants_1 = require("./constants");
78
81
  const hbcTransform_1 = require("./hbcTransform");
79
82
  const i18n_1 = require("./i18n");
80
83
  const zip_entries_1 = require("./zip-entries");
81
84
  const zip_range_1 = require("./zip-range");
85
+ /**
86
+ * The base cannot be obtained whatever the transport or how often it is
87
+ * retried (wrong content on the server, no bundle in the package, ...).
88
+ */
89
+ class PermanentBaseError extends Error {
90
+ }
91
+ exports.PermanentBaseError = PermanentBaseError;
92
+ /** The fetched bundle's sha256 differs from what the server recorded. */
93
+ class BundleHashMismatchError extends PermanentBaseError {
94
+ constructor(actual, expected) {
95
+ super(`bundleHash mismatch (${actual.slice(0, 12)} != ${expected.slice(0, 12)})`);
96
+ }
97
+ }
98
+ exports.BundleHashMismatchError = BundleHashMismatchError;
99
+ /** time allowed for a response to start (headers) */
100
+ const FETCH_HEADERS_TIMEOUT_MS = 30_000;
101
+ /** a download that receives nothing for this long is abandoned */
102
+ const STREAM_IDLE_TIMEOUT_MS = 60_000;
103
+ /** cachePut leftovers (`<hash>.<pid>.tmp`) older than this are evicted */
104
+ const STALE_CACHE_TMP_MS = 60 * 60 * 1000;
82
105
  // ---------------------------------------------------------------------------
83
106
  // hermesc gating
84
107
  // ---------------------------------------------------------------------------
@@ -166,6 +189,28 @@ function classifyHermesCommand(hermesCommand) {
166
189
  function sha256Hex(data) {
167
190
  return (0, crypto_1.createHash)('sha256').update(data).digest('hex');
168
191
  }
192
+ /** sha256 of a file, streamed (a cached base can be tens of MB) */
193
+ async function sha256File(file) {
194
+ const hash = (0, crypto_1.createHash)('sha256');
195
+ for await (const chunk of fs_extra_1.default.createReadStream(file))
196
+ hash.update(chunk);
197
+ return hash.digest('hex');
198
+ }
199
+ /** HBC version from the first bytes of a file, without reading the rest */
200
+ async function readFileHbcVersion(file) {
201
+ const header = Buffer.alloc(128);
202
+ const fd = await fs_extra_1.default.open(file, 'r');
203
+ try {
204
+ const { bytesRead } = await fs_extra_1.default.read(fd, header, 0, 128, 0);
205
+ return (0, hbcTransform_1.getHbcVersion)(header.subarray(0, bytesRead));
206
+ }
207
+ catch {
208
+ return null;
209
+ }
210
+ finally {
211
+ await fs_extra_1.default.close(fd);
212
+ }
213
+ }
169
214
  const PROBE_CACHE_FILE = 'hbc-versions.json';
170
215
  const PROBE_CACHE_ENTRIES = 16;
171
216
  /** identity of a hermesc binary for the probe cache: path + size + mtime */
@@ -329,8 +374,7 @@ async function cacheLookup(bundleHash) {
329
374
  const file = path_1.default.join(cacheDir(), bundleHash);
330
375
  if (!(await fs_extra_1.default.pathExists(file)))
331
376
  return null;
332
- const data = await fs_extra_1.default.readFile(file);
333
- if (sha256Hex(data) !== bundleHash) {
377
+ if ((await sha256File(file).catch(() => '')) !== bundleHash) {
334
378
  // corrupt entry: never trust cache content
335
379
  await fs_extra_1.default.remove(file).catch(() => { });
336
380
  return null;
@@ -363,12 +407,21 @@ async function enforceCacheLimits(maxMb, keep) {
363
407
  return;
364
408
  const { maxBytes, maxFiles } = cacheLimits(maxMb);
365
409
  const entries = [];
410
+ const staleTmpCutoff = Date.now() - STALE_CACHE_TMP_MS;
366
411
  for (const name of await fs_extra_1.default.readdir(dir)) {
367
- if (!/^[0-9a-f]{64}$/.test(name))
412
+ const isTmp = isCacheTmpName(name);
413
+ if (!isTmp && !/^[0-9a-f]{64}$/.test(name))
368
414
  continue;
369
415
  const stat = await fs_extra_1.default.stat(path_1.default.join(dir, name)).catch(() => null);
370
- if (stat?.isFile())
371
- entries.push({ name, size: stat.size, mtime: stat.mtimeMs });
416
+ if (!stat?.isFile())
417
+ continue;
418
+ if (isTmp) {
419
+ // an interrupted cachePut; nothing will ever rename it into place
420
+ if (stat.mtimeMs < staleTmpCutoff)
421
+ await fs_extra_1.default.remove(path_1.default.join(dir, name)).catch(() => { });
422
+ continue;
423
+ }
424
+ entries.push({ name, size: stat.size, mtime: stat.mtimeMs });
372
425
  }
373
426
  entries.sort((a, b) => b.mtime - a.mtime); // newest first
374
427
  let total = 0;
@@ -381,14 +434,25 @@ async function enforceCacheLimits(maxMb, keep) {
381
434
  }
382
435
  }
383
436
  }
437
+ /** `<sha256>.<pid>.tmp`, the staging name cachePut writes before renaming */
438
+ function isCacheTmpName(name) {
439
+ return /^[0-9a-f]{64}\.\d+\.tmp$/.test(name);
440
+ }
441
+ /** Remove every cached bundle (and staging leftovers); returns the bundle count. */
384
442
  async function cleanCache() {
385
443
  const dir = cacheDir();
386
444
  if (!(await fs_extra_1.default.pathExists(dir)))
387
445
  return 0;
388
- const names = (await fs_extra_1.default.readdir(dir)).filter((n) => /^[0-9a-f]{64}$/.test(n));
389
- for (const name of names)
446
+ let bundles = 0;
447
+ for (const name of await fs_extra_1.default.readdir(dir)) {
448
+ const isBundle = /^[0-9a-f]{64}$/.test(name);
449
+ if (!isBundle && !isCacheTmpName(name))
450
+ continue;
390
451
  await fs_extra_1.default.remove(path_1.default.join(dir, name));
391
- return names.length;
452
+ if (isBundle)
453
+ bundles += 1;
454
+ }
455
+ return bundles;
392
456
  }
393
457
  async function cacheStats() {
394
458
  const dir = cacheDir();
@@ -424,13 +488,19 @@ async function cleanStaleTmp(maxAgeMs = 24 * 60 * 60 * 1000) {
424
488
  // download
425
489
  // ---------------------------------------------------------------------------
426
490
  async function downloadToFile(url, destination) {
427
- const response = await fetch(url);
491
+ const controller = new AbortController();
492
+ const headersTimer = setTimeout(() => controller.abort(new Error('timeout waiting for response')), FETCH_HEADERS_TIMEOUT_MS);
493
+ let response;
494
+ try {
495
+ response = await fetch(url, { signal: controller.signal });
496
+ }
497
+ finally {
498
+ clearTimeout(headersTimer);
499
+ }
428
500
  if (!response.ok || !response.body) {
429
501
  throw new Error(`download failed: HTTP ${response.status} ${url}`);
430
502
  }
431
- await fs_extra_1.default.ensureDir(path_1.default.dirname(destination));
432
- const { Readable } = await Promise.resolve().then(() => __importStar(require('stream')));
433
- await (0, promises_1.pipeline)(Readable.fromWeb(response.body), fs_extra_1.default.createWriteStream(destination));
503
+ await saveResponse(response, destination, controller);
434
504
  }
435
505
  function hasBundleLocation(record) {
436
506
  return (record.bundleOffset != null &&
@@ -439,12 +509,30 @@ function hasBundleLocation(record) {
439
509
  (record.bundleCompression === zip_range_1.ZIP_STORED ||
440
510
  record.bundleCompression === zip_range_1.ZIP_DEFLATED));
441
511
  }
442
- async function saveResponse(response, destination) {
512
+ /**
513
+ * Stream a response body to disk, giving up when no bytes arrive for
514
+ * STREAM_IDLE_TIMEOUT_MS. `controller` is the one the request was made with
515
+ * (aborting it also tears down the socket); a foreign response gets its own.
516
+ */
517
+ async function saveResponse(response, destination, controller = new AbortController()) {
443
518
  if (!response.body)
444
519
  throw new Error('empty response body');
445
520
  await fs_extra_1.default.ensureDir(path_1.default.dirname(destination));
446
- const { Readable } = await Promise.resolve().then(() => __importStar(require('stream')));
447
- await (0, promises_1.pipeline)(Readable.fromWeb(response.body), fs_extra_1.default.createWriteStream(destination));
521
+ const abort = () => controller.abort(new Error(`download stalled for ${STREAM_IDLE_TIMEOUT_MS / 1000}s`));
522
+ let idle = setTimeout(abort, STREAM_IDLE_TIMEOUT_MS);
523
+ const watchdog = new stream_1.PassThrough({
524
+ transform(chunk, _encoding, callback) {
525
+ clearTimeout(idle);
526
+ idle = setTimeout(abort, STREAM_IDLE_TIMEOUT_MS);
527
+ callback(null, chunk);
528
+ },
529
+ });
530
+ try {
531
+ await (0, promises_1.pipeline)(stream_1.Readable.fromWeb(response.body), watchdog, fs_extra_1.default.createWriteStream(destination), { signal: controller.signal });
532
+ }
533
+ finally {
534
+ clearTimeout(idle);
535
+ }
448
536
  }
449
537
  /**
450
538
  * Obtain the base bundle with as little traffic as possible, in order:
@@ -456,27 +544,29 @@ async function saveResponse(response, destination) {
456
544
  * is skipped);
457
545
  * 3. the whole archive, as before.
458
546
  * A server that ignores Range (HTTP 200) streams the full archive into
459
- * `archive` without a second request. Range results are verified against
460
- * `record.bundleHash` here; a mismatch (e.g. re-packaged object) falls
461
- * through to the next transport instead of failing the resolution.
547
+ * `archive` without a second request. Every result is verified against
548
+ * `record.bundleHash`. A mismatch of the located bytes (1) may only mean the
549
+ * recorded location is stale, so the directory transport (2) still runs; a
550
+ * mismatch of the entry itself (2, 3) is final — the same bytes would come
551
+ * back however they are fetched — and raises BundleHashMismatchError.
462
552
  */
463
553
  async function fetchBaseBundle(record, artifactType, archive, log = () => { }) {
464
554
  const matches = bundleEntryMatcher(artifactType);
465
555
  const verified = (bundle) => {
466
556
  if (!bundle)
467
- throw new Error('bundle entry not found');
557
+ throw new PermanentBaseError('bundle entry not found');
468
558
  const bundleHash = sha256Hex(bundle);
469
559
  if (record.bundleHash && bundleHash !== record.bundleHash) {
470
- throw new Error('bundleHash mismatch');
560
+ throw new BundleHashMismatchError(bundleHash, record.bundleHash);
471
561
  }
472
562
  return { bundle, bundleHash };
473
563
  };
474
564
  const fromFullResponse = async (response) => {
475
565
  await saveResponse(response, archive);
476
- const bundle = await extractBundleFromArchive(archive);
477
- return bundle
478
- ? { bundle, bundleHash: sha256Hex(bundle), transport: 'full' }
479
- : null;
566
+ return {
567
+ ...verified(await extractBundleFromArchive(archive)),
568
+ transport: 'full',
569
+ };
480
570
  };
481
571
  const skip = (reason) => log((0, i18n_1.t)('hermesBaseRangeFallback', { reason }));
482
572
  // harmony .app nests the bundle in a second zip, so a location inside the
@@ -523,14 +613,17 @@ async function fetchBaseBundle(record, artifactType, archive, log = () => { }) {
523
613
  skip('server ignores Range');
524
614
  return fromFullResponse(error.response);
525
615
  }
616
+ // the real entry was read and is not the recorded one: final
617
+ if (error instanceof PermanentBaseError)
618
+ throw error;
526
619
  skip(`zip range: ${error?.message ?? error}`);
527
620
  }
528
621
  }
529
622
  await downloadToFile(record.url, archive);
530
- const bundle = await extractBundleFromArchive(archive);
531
- return bundle
532
- ? { bundle, bundleHash: sha256Hex(bundle), transport: 'full' }
533
- : null;
623
+ return {
624
+ ...verified(await extractBundleFromArchive(archive)),
625
+ transport: 'full',
626
+ };
534
627
  }
535
628
  /**
536
629
  * Pick and materialize the base bundle for this compile. Returns null (with
@@ -576,7 +669,7 @@ async function resolveHermesBase(params) {
576
669
  }
577
670
  let record = null;
578
671
  try {
579
- record = await params.fetchBase(params.appId, bytecodeVersion);
672
+ record = await retryOnce(() => params.fetchBase(params.appId, bytecodeVersion));
580
673
  }
581
674
  catch (error) {
582
675
  log((0, i18n_1.t)('hermesBaseNone', {
@@ -603,6 +696,17 @@ async function resolveHermesBase(params) {
603
696
  // 1. cache by bundleHash
604
697
  if (record.bundleHash) {
605
698
  const hit = await cacheLookup(record.bundleHash);
699
+ if (hit && record.bytecodeVersion == null) {
700
+ // the server does not know the HBC version (legacy version, native
701
+ // package): the download path checks it, the cache path must too
702
+ const version = await readFileHbcVersion(hit);
703
+ if (version !== bytecodeVersion) {
704
+ log((0, i18n_1.t)('hermesBaseNone', {
705
+ reason: `cached base is HBC ${version ?? 'n/a'}, need ${bytecodeVersion}`,
706
+ }));
707
+ return null;
708
+ }
709
+ }
606
710
  if (hit) {
607
711
  log((0, i18n_1.t)('hermesBaseUsing', {
608
712
  source: `cache ${record.bundleHash.slice(0, 12)}${record.versionId == null ? '' : ` (version ${record.versionId})`}`,
@@ -618,7 +722,7 @@ async function resolveHermesBase(params) {
618
722
  };
619
723
  }
620
724
  }
621
- // 2. download, extract, verify, cache — up to two attempts
725
+ // 2. download, extract, verify, cache — transport errors get a second try
622
726
  for (let attempt = 1; attempt <= 2; attempt++) {
623
727
  const dir = tmpDir();
624
728
  await fs_extra_1.default.ensureDir(dir);
@@ -634,8 +738,6 @@ async function resolveHermesBase(params) {
634
738
  try {
635
739
  log((0, i18n_1.t)('hermesBaseDownloading', { url: record.url }));
636
740
  const fetched = await fetchBaseBundle(record, artifactType, archive, log);
637
- if (!fetched)
638
- throw new Error('bundle entry not found in downloaded package');
639
741
  const { bundle, bundleHash: actualHash } = fetched;
640
742
  if (fetched.transport !== 'full') {
641
743
  log((0, i18n_1.t)('hermesBaseRangeFetched', {
@@ -643,9 +745,6 @@ async function resolveHermesBase(params) {
643
745
  totalKb: Math.ceil((fetched.totalBytes ?? 0) / 1024),
644
746
  }));
645
747
  }
646
- if (record.bundleHash && actualHash !== record.bundleHash) {
647
- throw new Error(`bundleHash mismatch (${actualHash.slice(0, 12)} != ${record.bundleHash.slice(0, 12)})`);
648
- }
649
748
  const version = (0, hbcTransform_1.getHbcVersion)(bundle);
650
749
  if (version !== bytecodeVersion) {
651
750
  log((0, i18n_1.t)('hermesBaseNone', {
@@ -670,7 +769,7 @@ async function resolveHermesBase(params) {
670
769
  };
671
770
  }
672
771
  catch (error) {
673
- if (attempt === 2) {
772
+ if (attempt === 2 || error instanceof PermanentBaseError) {
674
773
  log((0, i18n_1.t)('hermesBaseNone', {
675
774
  reason: `download/verify failed: ${error?.message ?? error}`,
676
775
  }));
@@ -683,6 +782,16 @@ async function resolveHermesBase(params) {
683
782
  }
684
783
  return null;
685
784
  }
785
+ /** one retry after a short pause, for transient network failures */
786
+ async function retryOnce(action) {
787
+ try {
788
+ return await action();
789
+ }
790
+ catch {
791
+ await new Promise((resolve) => setTimeout(resolve, 500));
792
+ return action();
793
+ }
794
+ }
686
795
  function hermescArgsWithBase(baseArgs, basePath) {
687
796
  return basePath ? [...baseArgs, `-base-bytecode=${basePath}`] : baseArgs;
688
797
  }
@@ -1,4 +1,9 @@
1
1
  export declare function promiseAny<T>(promises: Promise<T>[]): Promise<T>;
2
2
  export declare const ping: (url: string, signal?: AbortSignal) => Promise<string | null>;
3
3
  export declare const testUrls: (urls?: string[], hedgeDelayMs?: number) => Promise<string | null>;
4
- export declare const getBaseUrl: Promise<string>;
4
+ /**
5
+ * The API base url: the env override, or the first default endpoint that
6
+ * answers a HEAD ping. Resolved lazily on the first API call (offline commands
7
+ * such as `hdiff`/`help` never ping) and memoized for the process lifetime.
8
+ */
9
+ export declare const getBaseUrl: () => Promise<string>;
@@ -111,18 +111,30 @@ const testUrls = async (urls, hedgeDelayMs = HEDGE_DELAY_MS) => {
111
111
  });
112
112
  };
113
113
  exports.testUrls = testUrls;
114
- exports.getBaseUrl = (async () => {
114
+ let baseUrlPromise;
115
+ async function resolveBaseUrl() {
115
116
  const testEndpoint = process.env.PUSHY_REGISTRY || process.env.RNU_API;
116
117
  if (testEndpoint) {
117
118
  return testEndpoint;
118
119
  }
119
- return (0, exports.testUrls)(constants_1.defaultEndpoints.map((url) => `${url}/status`)).then((ret) => {
120
- let baseUrl = constants_1.defaultEndpoints[0];
121
- if (ret) {
122
- // remove /status
123
- baseUrl = ret.replace('/status', '');
124
- }
125
- // console.log('baseUrl', baseUrl);
126
- return baseUrl;
127
- });
128
- })();
120
+ const ret = await (0, exports.testUrls)(constants_1.defaultEndpoints.map((url) => `${url}/status`));
121
+ let baseUrl = constants_1.defaultEndpoints[0];
122
+ if (ret) {
123
+ // remove /status
124
+ baseUrl = ret.replace('/status', '');
125
+ }
126
+ // console.log('baseUrl', baseUrl);
127
+ return baseUrl;
128
+ }
129
+ /**
130
+ * The API base url: the env override, or the first default endpoint that
131
+ * answers a HEAD ping. Resolved lazily on the first API call (offline commands
132
+ * such as `hdiff`/`help` never ping) and memoized for the process lifetime.
133
+ */
134
+ const getBaseUrl = () => {
135
+ if (!baseUrlPromise) {
136
+ baseUrlPromise = resolveBaseUrl();
137
+ }
138
+ return baseUrlPromise;
139
+ };
140
+ exports.getBaseUrl = getBaseUrl;
@@ -1,4 +1,9 @@
1
1
  import { checkPlugins } from './check-plugin';
2
+ /**
3
+ * tty-table (~25 ms to load) only when a table is rendered. Bun's require of
4
+ * a CJS module can hand back a namespace object, so unwrap `default`.
5
+ */
6
+ export declare function loadTtyTable(): typeof import('tty-table');
2
7
  export declare function isNonInteractive(): boolean;
3
8
  export declare function question(query: string, password?: boolean): Promise<string>;
4
9
  export declare function translateOptions<T extends Record<string, unknown>>(options: T, map?: Record<string, string>): T & Record<string, unknown>;
@@ -27,5 +32,29 @@ export declare function getAabInfo(fn: string): Promise<{
27
32
  buildTime: number;
28
33
  bundleHash?: string | undefined;
29
34
  }>;
30
- export declare function printVersionCommand(): Promise<void>;
35
+ export interface VersionCheck {
36
+ /** settles once the registry check has finished (or failed); never rejects */
37
+ done: Promise<void>;
38
+ /** wait for the check, but never longer than `graceMs` */
39
+ settle: (graceMs: number) => Promise<void>;
40
+ /**
41
+ * Print the "newer version available" hints if the check has completed by
42
+ * now; a no-op while it is still pending, when nothing is newer, and after
43
+ * the first call. Safe to call from a process 'exit' handler.
44
+ */
45
+ printHints: () => void;
46
+ }
47
+ /**
48
+ * Print the installed CLI / react-native-update versions (and refuse or warn
49
+ * about unsupported client versions) immediately, without touching the
50
+ * network.
51
+ *
52
+ * With `wait: true` (the `-v`/`version` command) the registry is queried
53
+ * first and the latest versions are printed inline. Otherwise the registry
54
+ * check runs in the background and the returned `printHints` shows what is
55
+ * newer once the command is done — the command itself is never delayed by it.
56
+ */
57
+ export declare function printVersionCommand({ wait, }?: {
58
+ wait?: boolean;
59
+ }): Promise<VersionCheck>;
31
60
  export { checkPlugins };