react-native-update-cli 2.22.5 → 2.22.7

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.
@@ -18,6 +18,14 @@ import { tempDir } from './constants';
18
18
  import { getHbcVersion } from './hbcTransform';
19
19
  import { t } from './i18n';
20
20
  import { enumZipEntries, readEntry } from './zip-entries';
21
+ import {
22
+ fetchZipEntryData,
23
+ openRemoteZip,
24
+ RangeUnsupportedError,
25
+ readRemoteZipEntry,
26
+ ZIP_DEFLATED,
27
+ ZIP_STORED,
28
+ } from './zip-range';
21
29
 
22
30
  export type HermesBaseOption = 'auto' | 'none' | string;
23
31
 
@@ -143,8 +151,68 @@ export function sha256Hex(data: Buffer): string {
143
151
  return createHash('sha256').update(data).digest('hex');
144
152
  }
145
153
 
146
- /** Compile an empty file to learn which HBC version this hermesc emits. */
154
+ const PROBE_CACHE_FILE = 'hbc-versions.json';
155
+ const PROBE_CACHE_ENTRIES = 16;
156
+
157
+ /** identity of a hermesc binary for the probe cache: path + size + mtime */
158
+ function probeCacheKey(hermesCommand: string): string | null {
159
+ try {
160
+ const stat = fs.statSync(hermesCommand);
161
+ return `${path.resolve(hermesCommand)}|${stat.size}|${Math.floor(stat.mtimeMs)}`;
162
+ } catch {
163
+ return null;
164
+ }
165
+ }
166
+
167
+ function readProbeCache(): Record<string, number> {
168
+ try {
169
+ const parsed = JSON.parse(
170
+ fs.readFileSync(path.join(cacheDir(), PROBE_CACHE_FILE), 'utf8'),
171
+ );
172
+ return parsed && typeof parsed === 'object' ? parsed : {};
173
+ } catch {
174
+ return {};
175
+ }
176
+ }
177
+
178
+ function writeProbeCache(entries: Record<string, number>): void {
179
+ try {
180
+ const keys = Object.keys(entries);
181
+ // keep the most recently inserted entries only
182
+ const trimmed = Object.fromEntries(
183
+ keys.slice(-PROBE_CACHE_ENTRIES).map((key) => [key, entries[key]]),
184
+ );
185
+ fs.ensureDirSync(cacheDir());
186
+ fs.writeFileSync(
187
+ path.join(cacheDir(), PROBE_CACHE_FILE),
188
+ JSON.stringify(trimmed),
189
+ );
190
+ } catch {
191
+ // the cache is a convenience; probing again next time is fine
192
+ }
193
+ }
194
+
195
+ /**
196
+ * Which HBC version this hermesc emits. The answer is remembered per binary
197
+ * (path, size, mtime) in the cache dir so only the first run of a given
198
+ * hermesc pays for the empty-file compile.
199
+ */
147
200
  export function probeHbcVersion(hermesCommand: string): number | null {
201
+ const key = probeCacheKey(hermesCommand);
202
+ if (key) {
203
+ const cached = readProbeCache()[key];
204
+ if (Number.isInteger(cached) && cached > 0) return cached;
205
+ }
206
+ const version = compileProbe(hermesCommand);
207
+ if (key && version !== null) {
208
+ const { [key]: _stale, ...others } = readProbeCache();
209
+ writeProbeCache({ ...others, [key]: version });
210
+ }
211
+ return version;
212
+ }
213
+
214
+ /** Compile an empty file to learn which HBC version this hermesc emits. */
215
+ function compileProbe(hermesCommand: string): number | null {
148
216
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'rnu-hermes-probe-'));
149
217
  try {
150
218
  const input = path.join(dir, 'probe.js');
@@ -181,6 +249,22 @@ export const BUNDLE_ENTRY_NAMES = [
181
249
  const APK_BUNDLE = /^assets\/index\.android\.bundle$/;
182
250
  const IPA_BUNDLE = /^payload\/[^/]+\.app\/main\.jsbundle$/i;
183
251
 
252
+ export type BaseArtifactType = 'ppk' | 'apk' | 'ipa' | 'app';
253
+
254
+ /** Which zip entry holds the JS/HBC bundle in each kind of artifact. */
255
+ export function bundleEntryMatcher(
256
+ artifactType: BaseArtifactType,
257
+ ): (name: string) => boolean {
258
+ switch (artifactType) {
259
+ case 'apk':
260
+ return (name) => APK_BUNDLE.test(name);
261
+ case 'ipa':
262
+ return (name) => IPA_BUNDLE.test(name.toLowerCase());
263
+ default:
264
+ return (name) => BUNDLE_ENTRY_NAMES.includes(name);
265
+ }
266
+ }
267
+
184
268
  /**
185
269
  * Extract the JS/HBC bundle from a local artifact: a raw bundle file, a ppk,
186
270
  * or a native package (apk / ipa / harmony app). Returns null when not found.
@@ -198,17 +282,10 @@ export async function extractBundleFromArchive(
198
282
  ) {
199
283
  return fs.readFile(filePath);
200
284
  }
201
- if (ext === '.ppk') {
202
- return readFirstZipEntry(filePath, (name) =>
203
- BUNDLE_ENTRY_NAMES.includes(name),
204
- );
205
- }
206
- if (ext === '.apk') {
207
- return readFirstZipEntry(filePath, (name) => APK_BUNDLE.test(name));
208
- }
209
- if (ext === '.ipa') {
210
- return readFirstZipEntry(filePath, (name) =>
211
- IPA_BUNDLE.test(name.toLowerCase()),
285
+ if (ext === '.ppk' || ext === '.apk' || ext === '.ipa') {
286
+ return readFirstZipEntry(
287
+ filePath,
288
+ bundleEntryMatcher(ext.slice(1) as BaseArtifactType),
212
289
  );
213
290
  }
214
291
  if (ext === '.app') {
@@ -286,8 +363,9 @@ export async function cacheLookup(bundleHash: string): Promise<string | null> {
286
363
  export async function cachePut(
287
364
  bundle: Buffer,
288
365
  maxMb?: number,
366
+ knownHash?: string,
289
367
  ): Promise<{ path: string; bundleHash: string }> {
290
- const bundleHash = sha256Hex(bundle);
368
+ const bundleHash = knownHash ?? sha256Hex(bundle);
291
369
  const dir = cacheDir();
292
370
  await fs.ensureDir(dir);
293
371
  const file = path.join(dir, bundleHash);
@@ -399,10 +477,155 @@ export async function downloadToFile(
399
477
  export interface HermesBaseServerRecord {
400
478
  versionId?: number | null;
401
479
  hash: string;
402
- artifactType?: 'ppk' | 'apk' | 'ipa' | 'app';
480
+ artifactType?: BaseArtifactType;
403
481
  bundleHash?: string | null;
404
482
  bytecodeVersion?: number | null;
405
483
  url: string;
484
+ /**
485
+ * Location of the bundle's compressed bytes inside the ppk, reported by the
486
+ * publishing CLI; lets the base be fetched with a single HTTP Range request.
487
+ */
488
+ bundleOffset?: number | null;
489
+ bundleCompressedSize?: number | null;
490
+ /** zip compression method: 0 stored, 8 deflate */
491
+ bundleCompression?: number | null;
492
+ }
493
+
494
+ interface FetchedBaseBundle {
495
+ bundle: Buffer;
496
+ /** sha256 of `bundle`, computed once here */
497
+ bundleHash: string;
498
+ /** how the bytes were obtained, for the log line */
499
+ transport: 'range-entry' | 'range-zip' | 'full';
500
+ fetchedBytes?: number;
501
+ totalBytes?: number;
502
+ }
503
+
504
+ function hasBundleLocation(record: HermesBaseServerRecord): boolean {
505
+ return (
506
+ record.bundleOffset != null &&
507
+ record.bundleCompressedSize != null &&
508
+ record.bundleCompression != null &&
509
+ (record.bundleCompression === ZIP_STORED ||
510
+ record.bundleCompression === ZIP_DEFLATED)
511
+ );
512
+ }
513
+
514
+ async function saveResponse(
515
+ response: Response,
516
+ destination: string,
517
+ ): Promise<void> {
518
+ if (!response.body) throw new Error('empty response body');
519
+ await fs.ensureDir(path.dirname(destination));
520
+ const { Readable } = await import('stream');
521
+ await pipeline(
522
+ Readable.fromWeb(response.body as any),
523
+ fs.createWriteStream(destination),
524
+ );
525
+ }
526
+
527
+ /**
528
+ * Obtain the base bundle with as little traffic as possible, in order:
529
+ * 1. one Range request for the bundle's compressed bytes when the server
530
+ * knows their location (ppk / apk / ipa published by a CLI that
531
+ * reported it);
532
+ * 2. the archive's central directory over Range, then just the bundle
533
+ * entry (any zip: ppk, apk, ipa — harmony .app nests a second zip and
534
+ * is skipped);
535
+ * 3. the whole archive, as before.
536
+ * A server that ignores Range (HTTP 200) streams the full archive into
537
+ * `archive` without a second request. Range results are verified against
538
+ * `record.bundleHash` here; a mismatch (e.g. re-packaged object) falls
539
+ * through to the next transport instead of failing the resolution.
540
+ */
541
+ export async function fetchBaseBundle(
542
+ record: HermesBaseServerRecord,
543
+ artifactType: BaseArtifactType,
544
+ archive: string,
545
+ log: (message: string) => void = () => {},
546
+ ): Promise<FetchedBaseBundle | null> {
547
+ const matches = bundleEntryMatcher(artifactType);
548
+ const verified = (
549
+ bundle: Buffer | null,
550
+ ): { bundle: Buffer; bundleHash: string } => {
551
+ if (!bundle) throw new Error('bundle entry not found');
552
+ const bundleHash = sha256Hex(bundle);
553
+ if (record.bundleHash && bundleHash !== record.bundleHash) {
554
+ throw new Error('bundleHash mismatch');
555
+ }
556
+ return { bundle, bundleHash };
557
+ };
558
+ const fromFullResponse = async (
559
+ response: Response,
560
+ ): Promise<FetchedBaseBundle | null> => {
561
+ await saveResponse(response, archive);
562
+ const bundle = await extractBundleFromArchive(archive);
563
+ return bundle
564
+ ? { bundle, bundleHash: sha256Hex(bundle), transport: 'full' }
565
+ : null;
566
+ };
567
+ const skip = (reason: string) =>
568
+ log(t('hermesBaseRangeFallback', { reason }));
569
+
570
+ // harmony .app nests the bundle in a second zip, so a location inside the
571
+ // outer archive is never reported for it
572
+ if (artifactType !== 'app' && hasBundleLocation(record)) {
573
+ try {
574
+ const { data, fetchedBytes, totalBytes } = await fetchZipEntryData(
575
+ record.url,
576
+ {
577
+ dataOffset: record.bundleOffset as number,
578
+ compressedSize: record.bundleCompressedSize as number,
579
+ compressionMethod: record.bundleCompression as number,
580
+ },
581
+ );
582
+ return {
583
+ ...verified(data),
584
+ transport: 'range-entry',
585
+ fetchedBytes,
586
+ totalBytes,
587
+ };
588
+ } catch (error: any) {
589
+ if (error instanceof RangeUnsupportedError) {
590
+ skip('server ignores Range');
591
+ return fromFullResponse(error.response);
592
+ }
593
+ skip(`entry range: ${error?.message ?? error}`);
594
+ }
595
+ }
596
+
597
+ if (artifactType !== 'app') {
598
+ try {
599
+ const remote = await openRemoteZip(record.url);
600
+ if (remote.kind === 'full') {
601
+ skip('server ignores Range');
602
+ return fromFullResponse(remote.response);
603
+ }
604
+ const bundle = await readRemoteZipEntry(
605
+ remote.zipFile,
606
+ matches,
607
+ remote.reader,
608
+ );
609
+ return {
610
+ ...verified(bundle),
611
+ transport: 'range-zip',
612
+ fetchedBytes: remote.reader.fetchedBytes,
613
+ totalBytes: remote.reader.totalSize,
614
+ };
615
+ } catch (error: any) {
616
+ if (error instanceof RangeUnsupportedError) {
617
+ skip('server ignores Range');
618
+ return fromFullResponse(error.response);
619
+ }
620
+ skip(`zip range: ${error?.message ?? error}`);
621
+ }
622
+ }
623
+
624
+ await downloadToFile(record.url, archive);
625
+ const bundle = await extractBundleFromArchive(archive);
626
+ return bundle
627
+ ? { bundle, bundleHash: sha256Hex(bundle), transport: 'full' }
628
+ : null;
406
629
  }
407
630
 
408
631
  export interface ResolveHermesBaseParams {
@@ -525,10 +748,13 @@ export async function resolveHermesBase(
525
748
  for (let attempt = 1; attempt <= 2; attempt++) {
526
749
  const dir = tmpDir();
527
750
  await fs.ensureDir(dir);
528
- const artifactType = ['ppk', 'apk', 'ipa', 'app'].includes(
529
- record.artifactType ?? '',
530
- )
531
- ? record.artifactType
751
+ const artifactType: BaseArtifactType = [
752
+ 'ppk',
753
+ 'apk',
754
+ 'ipa',
755
+ 'app',
756
+ ].includes(record.artifactType ?? '')
757
+ ? (record.artifactType as BaseArtifactType)
532
758
  : 'ppk';
533
759
  const archive = path.join(
534
760
  dir,
@@ -536,11 +762,18 @@ export async function resolveHermesBase(
536
762
  );
537
763
  try {
538
764
  log(t('hermesBaseDownloading', { url: record.url }));
539
- await downloadToFile(record.url, archive);
540
- const bundle = await extractBundleFromArchive(archive);
541
- if (!bundle)
765
+ const fetched = await fetchBaseBundle(record, artifactType, archive, log);
766
+ if (!fetched)
542
767
  throw new Error('bundle entry not found in downloaded package');
543
- const actualHash = sha256Hex(bundle);
768
+ const { bundle, bundleHash: actualHash } = fetched;
769
+ if (fetched.transport !== 'full') {
770
+ log(
771
+ t('hermesBaseRangeFetched', {
772
+ fetchedKb: Math.ceil((fetched.fetchedBytes ?? 0) / 1024),
773
+ totalKb: Math.ceil((fetched.totalBytes ?? 0) / 1024),
774
+ }),
775
+ );
776
+ }
544
777
  if (record.bundleHash && actualHash !== record.bundleHash) {
545
778
  throw new Error(
546
779
  `bundleHash mismatch (${actualHash.slice(0, 12)} != ${record.bundleHash.slice(0, 12)})`,
@@ -555,7 +788,7 @@ export async function resolveHermesBase(
555
788
  );
556
789
  return null;
557
790
  }
558
- const cached = await cachePut(bundle, params.cacheMaxMb);
791
+ const cached = await cachePut(bundle, params.cacheMaxMb, actualHash);
559
792
  log(
560
793
  t('hermesBaseUsing', {
561
794
  source:
@@ -623,41 +856,84 @@ export function normalizeDisassemblyLine(
623
856
  line: string,
624
857
  strings: Map<number, string>,
625
858
  ): string | null {
626
- if (/^Offset in debug table/.test(line)) return null;
627
- let m =
628
- /^(\s*New(?:Array|Object)WithBuffer)(?:Long)?(?:AndParent)?\s+(r\d+)(.*)$/.exec(
629
- line,
630
- );
631
- if (m) {
632
- const nums = m[3].match(/\d+/g) ?? [];
633
- return `${m[1]} ${m[2]} sizes=${nums.slice(0, 1).join(',')}`;
634
- }
635
- m = /^(\s*J[A-Za-z]+?)(Long)?\s+(L\d+|\d+)(.*)$/.exec(line);
636
- if (m) return `${m[1]} <tgt>${m[4]}`;
637
- m = /^(\s*DefineOwnById\w*\s+r\d+, r\d+, \d+, )(\d+)$/.exec(line);
638
- if (m) line = `${m[1]}"${strings.get(Number(m[2])) ?? `?${m[2]}`}"`;
859
+ // Cheap dispatch on the opcode before touching any regex: dumps run to
860
+ // millions of lines and only a handful of instructions need rewriting.
861
+ let indent = 0;
862
+ while (indent < line.length && isSpace(line.charCodeAt(indent))) indent++;
863
+ let opEnd = indent;
864
+ while (opEnd < line.length && isLetter(line.charCodeAt(opEnd))) opEnd++;
865
+ const opcode = line.slice(indent, opEnd);
866
+ if (opcode === 'Offset' && line.startsWith('Offset in debug table', indent)) {
867
+ return null;
868
+ }
869
+ let m: RegExpExecArray | null;
870
+ if (opcode.startsWith('New') && opcode.includes('WithBuffer')) {
871
+ m =
872
+ /^(\s*New(?:Array|Object)WithBuffer)(?:Long)?(?:AndParent)?\s+(r\d+)(.*)$/.exec(
873
+ line,
874
+ );
875
+ if (m) {
876
+ const nums = m[3].match(/\d+/g) ?? [];
877
+ return `${m[1]} ${m[2]} sizes=${nums.slice(0, 1).join(',')}`;
878
+ }
879
+ }
880
+ if (opcode.charCodeAt(0) === 0x4a /* J */) {
881
+ m = /^(\s*J[A-Za-z]+?)(Long)?\s+(L\d+|\d+)(.*)$/.exec(line);
882
+ if (m) return `${m[1]} <tgt>${m[4]}`;
883
+ }
884
+ if (opcode.startsWith('DefineOwnById')) {
885
+ m = /^(\s*DefineOwnById\w*\s+r\d+, r\d+, \d+, )(\d+)$/.exec(line);
886
+ if (m) line = `${m[1]}"${strings.get(Number(m[2])) ?? `?${m[2]}`}"`;
887
+ }
639
888
  // Operand-width variants of one instruction (GetByIdShort/GetById/GetByIdLong,
640
889
  // LoadConstString/LoadConstStringLongIndex, ...) only differ by how wide a
641
890
  // string/function id or offset is encoded — a foreign base hands the new
642
891
  // code's hot strings large ids, so the delta build legitimately picks the
643
892
  // wider form. Fold the suffix and the column padding that follows it.
644
- m = /^(\s*)([A-Za-z]+?)(?:LongIndex|Long|Short)?(\s+.*|)$/.exec(line);
645
- if (m) line = `${m[1]}${m[2]}${m[3].replace(/\s+/g, ' ')}`;
646
- // Switch jump tables sit after the instructions; their relative offset (and
647
- // the table header hermesc prints for them) moves with instruction widths.
648
- // The two switch instructions carry that offset in different operands:
649
- // StringSwitchImm rX, <id>, <jtOffset>, <defaultLabel>, <count>
650
- // UIntSwitchImm rX, <jtOffset>, <defaultLabel>, <min>, <max>
651
- // Folding only the first shape let a shifted UIntSwitchImm offset read as a
652
- // real difference and drop an otherwise good delta build.
653
- m = /^(\s*StringSwitchImm r\d+, \d+, )\d+(, L\d+, \d+)$/.exec(line);
654
- if (m) line = `${m[1]}<jt>${m[2]}`;
655
- m = /^(\s*UIntSwitchImm r\d+, )\d+(, L\d+, \d+, \d+)$/.exec(line);
656
- if (m) line = `${m[1]}<jt>${m[2]}`;
657
- if (/^\s*offset \d+$/.test(line)) line = line.replace(/\d+$/, '<jt>');
893
+ if (
894
+ opEnd > indent &&
895
+ (opEnd === line.length || isSpace(line.charCodeAt(opEnd)))
896
+ ) {
897
+ const folded = foldWidthSuffix(opcode);
898
+ line = `${line.slice(0, indent)}${folded}${line.slice(opEnd).replace(/\s+/g, ' ')}`;
899
+ // Switch jump tables sit after the instructions; their relative offset (and
900
+ // the table header hermesc prints for them) moves with instruction widths.
901
+ // The two switch instructions carry that offset in different operands:
902
+ // StringSwitchImm rX, <id>, <jtOffset>, <defaultLabel>, <count>
903
+ // UIntSwitchImm rX, <jtOffset>, <defaultLabel>, <min>, <max>
904
+ // Folding only the first shape let a shifted UIntSwitchImm offset read as a
905
+ // real difference and drop an otherwise good delta build.
906
+ if (folded === 'StringSwitchImm') {
907
+ m = /^(\s*StringSwitchImm r\d+, \d+, )\d+(, L\d+, \d+)$/.exec(line);
908
+ if (m) line = `${m[1]}<jt>${m[2]}`;
909
+ } else if (folded === 'UIntSwitchImm') {
910
+ m = /^(\s*UIntSwitchImm r\d+, )\d+(, L\d+, \d+, \d+)$/.exec(line);
911
+ if (m) line = `${m[1]}<jt>${m[2]}`;
912
+ } else if (folded === 'offset' && /^\s*offset \d+$/.test(line)) {
913
+ line = line.replace(/\d+$/, '<jt>');
914
+ }
915
+ }
658
916
  return line;
659
917
  }
660
918
 
919
+ function isSpace(code: number): boolean {
920
+ return code === 0x20 || code === 0x09 || code === 0x0d;
921
+ }
922
+
923
+ function isLetter(code: number): boolean {
924
+ return (code >= 0x41 && code <= 0x5a) || (code >= 0x61 && code <= 0x7a);
925
+ }
926
+
927
+ /** strip one operand-width suffix (LongIndex, Long, Short) off an opcode */
928
+ function foldWidthSuffix(opcode: string): string {
929
+ for (const suffix of ['LongIndex', 'Long', 'Short']) {
930
+ if (opcode.length > suffix.length && opcode.endsWith(suffix)) {
931
+ return opcode.slice(0, -suffix.length);
932
+ }
933
+ }
934
+ return opcode;
935
+ }
936
+
661
937
  /** Split a readable stream into lines without readline (Bun's readline async iterator misbehaves when pulled manually). */
662
938
  async function* streamLines(
663
939
  stream: NodeJS.ReadableStream,