react-native-update-cli 2.21.2 → 2.22.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,718 @@
1
+ // Hermes `-base-bytecode` (delta optimizing mode) support.
2
+ //
3
+ // Hermes re-sorts its string table by identifier frequency on every compile, so
4
+ // any source change renumbers most string IDs and the bytecode diff explodes
5
+ // (see hermes-base-bytecode-方案.md). Compiling with the previous HBC of the
6
+ // same app as `-base-bytecode` keeps old IDs stable and shrinks patches 5-30×.
7
+ // This module resolves that base: gating by hermesc build, HBC version probe,
8
+ // server lookup, a sha256-named local cache, download + verification, and the
9
+ // optional disassembly equivalence check. Every failure degrades to the plain
10
+ // compile — nothing here may block a release.
11
+ import { spawn, spawnSync } from 'child_process';
12
+ import { createHash } from 'crypto';
13
+ import fs from 'fs-extra';
14
+ import os from 'os';
15
+ import path from 'path';
16
+ import { pipeline } from 'stream/promises';
17
+ import { tempDir } from './constants';
18
+ import { getHbcVersion } from './hbcTransform';
19
+ import { t } from './i18n';
20
+ import { enumZipEntries, readEntry } from './zip-entries';
21
+
22
+ export type HermesBaseOption = 'auto' | 'none' | string;
23
+
24
+ export interface HermesBaseSelection {
25
+ /** path of the bundle (HBC) handed to hermesc as -base-bytecode */
26
+ path: string;
27
+ bytecodeVersion: number;
28
+ bundleHash: string;
29
+ /** server version id when the base came from the server */
30
+ versionId?: number;
31
+ /** server object key of the base ppk when known */
32
+ hash?: string;
33
+ source: 'cache' | 'download' | 'local' | 'latest-version';
34
+ }
35
+
36
+ /** Metadata attached to version/create so the server can track the chain. */
37
+ export interface HermesBaseMeta {
38
+ bytecodeVersion: number | null;
39
+ baseVersionId: number | null;
40
+ baseHash: string | null;
41
+ }
42
+
43
+ // ---------------------------------------------------------------------------
44
+ // hermesc gating
45
+ // ---------------------------------------------------------------------------
46
+
47
+ /**
48
+ * Hermes V1 (static_h) builds before 2025-07-11 carried a delta-mode bug when a
49
+ * delta-produced base is reused; every released `hermes-compiler` is newer, and
50
+ * classic hermesc (HBC ≤96, react-native/sdks or hermes-engine) upgrades kinds
51
+ * in place and was never affected. Anything else is refused.
52
+ */
53
+ export const MIN_HERMES_COMPILER_BUILD = 250829098;
54
+ export const MIN_HERMES_COMPILER_COMMITLY_DATE = 20250901;
55
+
56
+ export function classifyHermesCommand(hermesCommand: string): {
57
+ allowed: boolean;
58
+ kind: 'classic' | 'hermes-compiler' | 'unknown';
59
+ version?: string;
60
+ reason?: string;
61
+ } {
62
+ const normalized = hermesCommand.split(path.sep).join('/');
63
+ if (
64
+ /\/react-native\/sdks\/hermesc\//.test(normalized) ||
65
+ /\/hermes-engine\//.test(normalized)
66
+ ) {
67
+ return { allowed: true, kind: 'classic' };
68
+ }
69
+ const match = /\/hermes-compiler\//.exec(normalized);
70
+ if (match) {
71
+ const packageRoot = normalized.slice(0, match.index + match[0].length);
72
+ let version = '';
73
+ try {
74
+ version = String(
75
+ JSON.parse(
76
+ fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8'),
77
+ ).version ?? '',
78
+ );
79
+ } catch {
80
+ return {
81
+ allowed: false,
82
+ kind: 'hermes-compiler',
83
+ reason: 'unreadable hermes-compiler version',
84
+ };
85
+ }
86
+ const build = /^(\d{9})\./.exec(version);
87
+ if (build) {
88
+ const ok = Number(build[1]) >= MIN_HERMES_COMPILER_BUILD;
89
+ return {
90
+ allowed: ok,
91
+ kind: 'hermes-compiler',
92
+ version,
93
+ reason: ok
94
+ ? undefined
95
+ : `hermes-compiler ${version} predates the delta-mode fix`,
96
+ };
97
+ }
98
+ const commitly = /^0\.(\d+)\.\d+-commitly-(\d{8})/.exec(version);
99
+ if (commitly) {
100
+ const ok =
101
+ Number(commitly[1]) >= 14 &&
102
+ Number(commitly[2]) >= MIN_HERMES_COMPILER_COMMITLY_DATE;
103
+ return {
104
+ allowed: ok,
105
+ kind: 'hermes-compiler',
106
+ version,
107
+ reason: ok
108
+ ? undefined
109
+ : `hermes-compiler ${version} predates the delta-mode fix`,
110
+ };
111
+ }
112
+ const stable = /^0\.(\d+)\.\d+$/.exec(version);
113
+ if (stable) {
114
+ const ok = Number(stable[1]) >= 14;
115
+ return {
116
+ allowed: ok,
117
+ kind: 'hermes-compiler',
118
+ version,
119
+ reason: ok
120
+ ? undefined
121
+ : `hermes-compiler ${version} predates the delta-mode fix`,
122
+ };
123
+ }
124
+ return {
125
+ allowed: false,
126
+ kind: 'hermes-compiler',
127
+ version,
128
+ reason: `unrecognized hermes-compiler version ${version}`,
129
+ };
130
+ }
131
+ return {
132
+ allowed: false,
133
+ kind: 'unknown',
134
+ reason: 'hermesc location not recognized',
135
+ };
136
+ }
137
+
138
+ // ---------------------------------------------------------------------------
139
+ // HBC helpers
140
+ // ---------------------------------------------------------------------------
141
+
142
+ export function sha256Hex(data: Buffer): string {
143
+ return createHash('sha256').update(data).digest('hex');
144
+ }
145
+
146
+ /** Compile an empty file to learn which HBC version this hermesc emits. */
147
+ export function probeHbcVersion(hermesCommand: string): number | null {
148
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'rnu-hermes-probe-'));
149
+ try {
150
+ const input = path.join(dir, 'probe.js');
151
+ const output = path.join(dir, 'probe.hbc');
152
+ fs.writeFileSync(input, '');
153
+ const result = spawnSync(
154
+ hermesCommand,
155
+ ['-emit-binary', '-out', output, input, '-O', '-w'],
156
+ { stdio: 'ignore' },
157
+ );
158
+ if (result.status !== 0 || !fs.existsSync(output)) {
159
+ return null;
160
+ }
161
+ const header = Buffer.alloc(128);
162
+ const fd = fs.openSync(output, 'r');
163
+ try {
164
+ fs.readSync(fd, header, 0, 128, 0);
165
+ } finally {
166
+ fs.closeSync(fd);
167
+ }
168
+ return getHbcVersion(header);
169
+ } catch {
170
+ return null;
171
+ } finally {
172
+ fs.removeSync(dir);
173
+ }
174
+ }
175
+
176
+ export const BUNDLE_ENTRY_NAMES = [
177
+ 'index.bundlejs',
178
+ 'main.jsbundle',
179
+ 'bundle.harmony.js',
180
+ ];
181
+ const APK_BUNDLE = /^assets\/index\.android\.bundle$/;
182
+ const IPA_BUNDLE = /^payload\/[^/]+\.app\/main\.jsbundle$/i;
183
+
184
+ /**
185
+ * Extract the JS/HBC bundle from a local artifact: a raw bundle file, a ppk,
186
+ * or a native package (apk / ipa / harmony app). Returns null when not found.
187
+ */
188
+ export async function extractBundleFromArchive(
189
+ filePath: string,
190
+ ): Promise<Buffer | null> {
191
+ const ext = path.extname(filePath).toLowerCase();
192
+ if (
193
+ ext === '.hbc' ||
194
+ ext === '.bundle' ||
195
+ ext === '.jsbundle' ||
196
+ ext === '.bundlejs' ||
197
+ ext === '.js'
198
+ ) {
199
+ return fs.readFile(filePath);
200
+ }
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()),
212
+ );
213
+ }
214
+ if (ext === '.app') {
215
+ // harmony .app wraps .hap archives; reuse the existing parser
216
+ const { default: AppInfoParser } = await import('./app-info-parser');
217
+ const parser = new AppInfoParser(filePath);
218
+ const [bundle] = await parser.parser.getEntriesFromHarmonyApp([
219
+ /^resources\/rawfile\/bundle\.harmony\.js$/,
220
+ ]);
221
+ return bundle ?? null;
222
+ }
223
+ // unknown extension: try as zip, then as raw file
224
+ const fromZip = await readFirstZipEntry(filePath, (name) =>
225
+ BUNDLE_ENTRY_NAMES.includes(name),
226
+ ).catch(() => null);
227
+ return fromZip ?? fs.readFile(filePath);
228
+ }
229
+
230
+ async function readFirstZipEntry(
231
+ zipPath: string,
232
+ matches: (name: string) => boolean,
233
+ ): Promise<Buffer | null> {
234
+ let found: Buffer | null = null;
235
+ await enumZipEntries(zipPath, async (entry, zipFile) => {
236
+ if (!found && matches(entry.fileName)) {
237
+ found = await readEntry(entry, zipFile);
238
+ }
239
+ });
240
+ return found;
241
+ }
242
+
243
+ // ---------------------------------------------------------------------------
244
+ // cache (sha256-named bundles)
245
+ // ---------------------------------------------------------------------------
246
+
247
+ export const DEFAULT_CACHE_MAX_BYTES = 500 * 1024 * 1024;
248
+ export const DEFAULT_CACHE_MAX_FILES = 20;
249
+
250
+ export function cacheDir(): string {
251
+ return process.env.PUSHY_CACHE_DIR || path.join(tempDir, 'cache');
252
+ }
253
+
254
+ export function tmpDir(): string {
255
+ return path.join(tempDir, 'tmp');
256
+ }
257
+
258
+ export function cacheLimits(overrideMaxMb?: number) {
259
+ const envMb = Number(process.env.PUSHY_CACHE_MAX_MB);
260
+ const maxBytes =
261
+ overrideMaxMb && overrideMaxMb > 0
262
+ ? overrideMaxMb * 1024 * 1024
263
+ : Number.isFinite(envMb) && envMb > 0
264
+ ? envMb * 1024 * 1024
265
+ : DEFAULT_CACHE_MAX_BYTES;
266
+ return { maxBytes, maxFiles: DEFAULT_CACHE_MAX_FILES };
267
+ }
268
+
269
+ /** Returns the cached bundle path when present and its sha256 still matches. */
270
+ export async function cacheLookup(bundleHash: string): Promise<string | null> {
271
+ if (!/^[0-9a-f]{64}$/.test(bundleHash)) return null;
272
+ const file = path.join(cacheDir(), bundleHash);
273
+ if (!(await fs.pathExists(file))) return null;
274
+ const data = await fs.readFile(file);
275
+ if (sha256Hex(data) !== bundleHash) {
276
+ // corrupt entry: never trust cache content
277
+ await fs.remove(file).catch(() => {});
278
+ return null;
279
+ }
280
+ const now = new Date();
281
+ await fs.utimes(file, now, now).catch(() => {});
282
+ return file;
283
+ }
284
+
285
+ /** Store a bundle under its sha256 (LRU-evicting to the configured limits). */
286
+ export async function cachePut(
287
+ bundle: Buffer,
288
+ maxMb?: number,
289
+ ): Promise<{ path: string; bundleHash: string }> {
290
+ const bundleHash = sha256Hex(bundle);
291
+ const dir = cacheDir();
292
+ await fs.ensureDir(dir);
293
+ const file = path.join(dir, bundleHash);
294
+ if (!(await fs.pathExists(file))) {
295
+ const tmp = `${file}.${process.pid}.tmp`;
296
+ await fs.writeFile(tmp, bundle);
297
+ await fs.rename(tmp, file);
298
+ } else {
299
+ const now = new Date();
300
+ await fs.utimes(file, now, now).catch(() => {});
301
+ }
302
+ await enforceCacheLimits(maxMb, bundleHash);
303
+ return { path: file, bundleHash };
304
+ }
305
+
306
+ export async function enforceCacheLimits(
307
+ maxMb?: number,
308
+ keep?: string,
309
+ ): Promise<void> {
310
+ const dir = cacheDir();
311
+ if (!(await fs.pathExists(dir))) return;
312
+ const { maxBytes, maxFiles } = cacheLimits(maxMb);
313
+ const entries: { name: string; size: number; mtime: number }[] = [];
314
+ for (const name of await fs.readdir(dir)) {
315
+ if (!/^[0-9a-f]{64}$/.test(name)) continue;
316
+ const stat = await fs.stat(path.join(dir, name)).catch(() => null);
317
+ if (stat?.isFile())
318
+ entries.push({ name, size: stat.size, mtime: stat.mtimeMs });
319
+ }
320
+ entries.sort((a, b) => b.mtime - a.mtime); // newest first
321
+ let total = 0;
322
+ let count = 0;
323
+ for (const entry of entries) {
324
+ total += entry.size;
325
+ count += 1;
326
+ if (entry.name !== keep && (total > maxBytes || count > maxFiles)) {
327
+ await fs.remove(path.join(dir, entry.name)).catch(() => {});
328
+ }
329
+ }
330
+ }
331
+
332
+ export async function cleanCache(): Promise<number> {
333
+ const dir = cacheDir();
334
+ if (!(await fs.pathExists(dir))) return 0;
335
+ const names = (await fs.readdir(dir)).filter((n) => /^[0-9a-f]{64}$/.test(n));
336
+ for (const name of names) await fs.remove(path.join(dir, name));
337
+ return names.length;
338
+ }
339
+
340
+ export async function cacheStats(): Promise<{
341
+ dir: string;
342
+ files: number;
343
+ bytes: number;
344
+ }> {
345
+ const dir = cacheDir();
346
+ let files = 0;
347
+ let bytes = 0;
348
+ if (await fs.pathExists(dir)) {
349
+ for (const name of await fs.readdir(dir)) {
350
+ if (!/^[0-9a-f]{64}$/.test(name)) continue;
351
+ const stat = await fs.stat(path.join(dir, name)).catch(() => null);
352
+ if (stat?.isFile()) {
353
+ files += 1;
354
+ bytes += stat.size;
355
+ }
356
+ }
357
+ }
358
+ return { dir, files, bytes };
359
+ }
360
+
361
+ /** Remove leftovers of interrupted runs (older than 24h) from the tmp dir. */
362
+ export async function cleanStaleTmp(
363
+ maxAgeMs = 24 * 60 * 60 * 1000,
364
+ ): Promise<void> {
365
+ const dir = tmpDir();
366
+ if (!(await fs.pathExists(dir))) return;
367
+ const cutoff = Date.now() - maxAgeMs;
368
+ for (const name of await fs.readdir(dir)) {
369
+ const file = path.join(dir, name);
370
+ const stat = await fs.stat(file).catch(() => null);
371
+ if (stat && stat.mtimeMs < cutoff) await fs.remove(file).catch(() => {});
372
+ }
373
+ }
374
+
375
+ // ---------------------------------------------------------------------------
376
+ // download
377
+ // ---------------------------------------------------------------------------
378
+
379
+ export async function downloadToFile(
380
+ url: string,
381
+ destination: string,
382
+ ): Promise<void> {
383
+ const response = await fetch(url);
384
+ if (!response.ok || !response.body) {
385
+ throw new Error(`download failed: HTTP ${response.status} ${url}`);
386
+ }
387
+ await fs.ensureDir(path.dirname(destination));
388
+ const { Readable } = await import('stream');
389
+ await pipeline(
390
+ Readable.fromWeb(response.body as any),
391
+ fs.createWriteStream(destination),
392
+ );
393
+ }
394
+
395
+ // ---------------------------------------------------------------------------
396
+ // resolution
397
+ // ---------------------------------------------------------------------------
398
+
399
+ export interface HermesBaseServerRecord {
400
+ versionId: number;
401
+ hash: string;
402
+ bundleHash?: string | null;
403
+ bytecodeVersion?: number | null;
404
+ url: string;
405
+ }
406
+
407
+ export interface ResolveHermesBaseParams {
408
+ option: HermesBaseOption;
409
+ hermesCommand: string;
410
+ bytecodeVersion: number;
411
+ appId?: string;
412
+ cacheMaxMb?: number;
413
+ /**
414
+ * server lookup; returns null when the app has no usable base. The server
415
+ * itself falls back to the newest version when the epoch is still unknown
416
+ * (its bytecodeVersion is then null and verified here after download).
417
+ */
418
+ fetchBase: (
419
+ appId: string,
420
+ bytecodeVersion: number,
421
+ ) => Promise<HermesBaseServerRecord | null>;
422
+ log?: (message: string) => void;
423
+ }
424
+
425
+ /**
426
+ * Pick and materialize the base bundle for this compile. Returns null (with
427
+ * the reason logged) whenever a base cannot be used; callers then compile
428
+ * without one.
429
+ */
430
+ export async function resolveHermesBase(
431
+ params: ResolveHermesBaseParams,
432
+ ): Promise<HermesBaseSelection | null> {
433
+ const log = params.log ?? (() => {});
434
+ const { option, bytecodeVersion } = params;
435
+ if (option === 'none') {
436
+ log(t('hermesBaseNone', { reason: 'disabled by option' }));
437
+ return null;
438
+ }
439
+ if (option !== 'auto') {
440
+ // explicit local artifact
441
+ try {
442
+ const bundle = await extractBundleFromArchive(option);
443
+ if (!bundle) throw new Error('bundle entry not found');
444
+ const version = getHbcVersion(bundle);
445
+ if (version !== bytecodeVersion) {
446
+ throw new Error(
447
+ `HBC version ${version ?? 'n/a'} != ${bytecodeVersion}`,
448
+ );
449
+ }
450
+ const cached = await cachePut(bundle, params.cacheMaxMb);
451
+ log(t('hermesBaseUsing', { source: option, version: bytecodeVersion }));
452
+ return {
453
+ path: cached.path,
454
+ bytecodeVersion,
455
+ bundleHash: cached.bundleHash,
456
+ source: 'local',
457
+ };
458
+ } catch (error: any) {
459
+ log(
460
+ t('hermesBaseNone', {
461
+ reason: `${option}: ${error?.message ?? error}`,
462
+ }),
463
+ );
464
+ return null;
465
+ }
466
+ }
467
+ if (!params.appId) {
468
+ log(t('hermesBaseNone', { reason: 'app not selected' }));
469
+ return null;
470
+ }
471
+ let record: HermesBaseServerRecord | null = null;
472
+ try {
473
+ record = await params.fetchBase(params.appId, bytecodeVersion);
474
+ } catch (error: any) {
475
+ log(
476
+ t('hermesBaseNone', {
477
+ reason: `server lookup failed: ${error?.message ?? error}`,
478
+ }),
479
+ );
480
+ return null;
481
+ }
482
+ const source: HermesBaseSelection['source'] =
483
+ record?.bytecodeVersion == null ? 'latest-version' : 'download';
484
+ if (!record) {
485
+ log(t('hermesBaseNone', { reason: 'no published version yet' }));
486
+ return null;
487
+ }
488
+ if (
489
+ record.bytecodeVersion != null &&
490
+ record.bytecodeVersion !== bytecodeVersion
491
+ ) {
492
+ log(
493
+ t('hermesBaseNone', {
494
+ reason: `server base is HBC ${record.bytecodeVersion}, need ${bytecodeVersion}`,
495
+ }),
496
+ );
497
+ return null;
498
+ }
499
+ // 1. cache by bundleHash
500
+ if (record.bundleHash) {
501
+ const hit = await cacheLookup(record.bundleHash);
502
+ if (hit) {
503
+ log(
504
+ t('hermesBaseUsing', {
505
+ source: `cache ${record.bundleHash.slice(0, 12)} (version ${record.versionId})`,
506
+ version: bytecodeVersion,
507
+ }),
508
+ );
509
+ return {
510
+ path: hit,
511
+ bytecodeVersion,
512
+ bundleHash: record.bundleHash,
513
+ versionId: record.versionId,
514
+ hash: record.hash,
515
+ source: 'cache',
516
+ };
517
+ }
518
+ }
519
+ // 2. download, extract, verify, cache — up to two attempts
520
+ for (let attempt = 1; attempt <= 2; attempt++) {
521
+ const dir = tmpDir();
522
+ await fs.ensureDir(dir);
523
+ const archive = path.join(
524
+ dir,
525
+ `base-${process.pid}-${Date.now()}-${attempt}.ppk`,
526
+ );
527
+ try {
528
+ log(t('hermesBaseDownloading', { url: record.url }));
529
+ await downloadToFile(record.url, archive);
530
+ const bundle = await extractBundleFromArchive(archive);
531
+ if (!bundle)
532
+ throw new Error('bundle entry not found in downloaded package');
533
+ const actualHash = sha256Hex(bundle);
534
+ if (record.bundleHash && actualHash !== record.bundleHash) {
535
+ throw new Error(
536
+ `bundleHash mismatch (${actualHash.slice(0, 12)} != ${record.bundleHash.slice(0, 12)})`,
537
+ );
538
+ }
539
+ const version = getHbcVersion(bundle);
540
+ if (version !== bytecodeVersion) {
541
+ log(
542
+ t('hermesBaseNone', {
543
+ reason: `downloaded base is HBC ${version ?? 'n/a'}, need ${bytecodeVersion}`,
544
+ }),
545
+ );
546
+ return null;
547
+ }
548
+ const cached = await cachePut(bundle, params.cacheMaxMb);
549
+ log(
550
+ t('hermesBaseUsing', {
551
+ source: `version ${record.versionId} ${record.hash.slice(0, 8)}`,
552
+ version: bytecodeVersion,
553
+ }),
554
+ );
555
+ return {
556
+ path: cached.path,
557
+ bytecodeVersion,
558
+ bundleHash: cached.bundleHash,
559
+ versionId: record.versionId,
560
+ hash: record.hash,
561
+ source,
562
+ };
563
+ } catch (error: any) {
564
+ if (attempt === 2) {
565
+ log(
566
+ t('hermesBaseNone', {
567
+ reason: `download/verify failed: ${error?.message ?? error}`,
568
+ }),
569
+ );
570
+ return null;
571
+ }
572
+ } finally {
573
+ await fs.remove(archive).catch(() => {});
574
+ }
575
+ }
576
+ return null;
577
+ }
578
+
579
+ export function hermescArgsWithBase(
580
+ baseArgs: string[],
581
+ basePath: string | null,
582
+ ): string[] {
583
+ return basePath ? [...baseArgs, `-base-bytecode=${basePath}`] : baseArgs;
584
+ }
585
+
586
+ export function hermesBaseMeta(
587
+ selection: HermesBaseSelection | null,
588
+ bytecodeVersion: number | null,
589
+ ): HermesBaseMeta {
590
+ return {
591
+ bytecodeVersion,
592
+ baseVersionId: selection?.versionId ?? null,
593
+ baseHash: selection?.hash ?? null,
594
+ };
595
+ }
596
+
597
+ // ---------------------------------------------------------------------------
598
+ // equivalence check (streams two `-dump-bytecode` outputs, never writes them)
599
+ // ---------------------------------------------------------------------------
600
+
601
+ const STRING_TABLE_LINE = /^\s*[is](\d+)\[[^\]]*\](?: #[0-9A-F]+)?: (.*)$/;
602
+
603
+ /**
604
+ * Normalize one disassembly line so that a delta-mode compile and a plain
605
+ * compile of the same source compare equal: string IDs are renumbered, literal
606
+ * buffers are laid out differently (offsets, short/long variants), and jump
607
+ * distances follow instruction widths. Everything else must match exactly.
608
+ */
609
+ export function normalizeDisassemblyLine(
610
+ line: string,
611
+ strings: Map<number, string>,
612
+ ): string | null {
613
+ if (/^Offset in debug table/.test(line)) return null;
614
+ let m =
615
+ /^(\s*New(?:Array|Object)WithBuffer)(?:Long)?(?:AndParent)?\s+(r\d+)(.*)$/.exec(
616
+ line,
617
+ );
618
+ if (m) {
619
+ const nums = m[3].match(/\d+/g) ?? [];
620
+ return `${m[1]} ${m[2]} sizes=${nums.slice(0, 1).join(',')}`;
621
+ }
622
+ m = /^(\s*J[A-Za-z]+?)(Long)?\s+(L\d+|\d+)(.*)$/.exec(line);
623
+ if (m) return `${m[1]} <tgt>${m[4]}`;
624
+ m = /^(\s*DefineOwnById\w*\s+r\d+, r\d+, \d+, )(\d+)$/.exec(line);
625
+ if (m) return `${m[1]}"${strings.get(Number(m[2])) ?? `?${m[2]}`}"`;
626
+ return line;
627
+ }
628
+
629
+ /** Split a readable stream into lines without readline (Bun's readline async iterator misbehaves when pulled manually). */
630
+ async function* streamLines(
631
+ stream: NodeJS.ReadableStream,
632
+ ): AsyncGenerator<string> {
633
+ let rest = '';
634
+ for await (const chunk of stream as AsyncIterable<Buffer | string>) {
635
+ rest += typeof chunk === 'string' ? chunk : chunk.toString('utf8');
636
+ let index = rest.indexOf('\n');
637
+ while (index >= 0) {
638
+ yield rest.slice(0, index);
639
+ rest = rest.slice(index + 1);
640
+ index = rest.indexOf('\n');
641
+ }
642
+ }
643
+ if (rest) yield rest;
644
+ }
645
+
646
+ class DumpReader {
647
+ private iterator: AsyncIterator<string>;
648
+ readonly strings = new Map<number, string>();
649
+ private inFunctions = false;
650
+ private finished = false;
651
+ constructor(readonly proc: ReturnType<typeof spawn>) {
652
+ this.iterator = streamLines(proc.stdout!);
653
+ }
654
+ /** next normalized function-body line, or null at end */
655
+ async next(): Promise<string | null> {
656
+ if (this.finished) return null;
657
+ for (;;) {
658
+ const { value, done } = await this.iterator.next();
659
+ if (done) {
660
+ this.finished = true;
661
+ return null;
662
+ }
663
+ const line = value as string;
664
+ if (!this.inFunctions) {
665
+ if (line.startsWith('Function<')) {
666
+ this.inFunctions = true;
667
+ } else {
668
+ const m = STRING_TABLE_LINE.exec(line);
669
+ if (m) this.strings.set(Number(m[1]), m[2]);
670
+ continue;
671
+ }
672
+ }
673
+ if (line.trim() === '') continue;
674
+ const normalized = normalizeDisassemblyLine(line, this.strings);
675
+ if (normalized !== null) return normalized;
676
+ }
677
+ }
678
+ }
679
+
680
+ /**
681
+ * Compare two HBC files by disassembly (see normalizeDisassemblyLine). `-b`
682
+ * forces hermesc to treat inputs as bytecode whatever their extension. Both
683
+ * hermesc dumps are consumed as streams so the ~100 MB of text never touches
684
+ * the disk. Resolves true when equivalent.
685
+ */
686
+ export async function verifyHermesBaseEquivalence(
687
+ hermesCommand: string,
688
+ withBase: string,
689
+ plain: string,
690
+ ): Promise<boolean> {
691
+ const spawnDump = (file: string) =>
692
+ spawn(
693
+ hermesCommand,
694
+ ['-b', '-dump-bytecode', '-pretty-disassemble', file],
695
+ {
696
+ stdio: ['ignore', 'pipe', 'ignore'],
697
+ },
698
+ );
699
+ const a = new DumpReader(spawnDump(withBase));
700
+ const b = new DumpReader(spawnDump(plain));
701
+ let equal = true;
702
+ let lines = 0;
703
+ try {
704
+ for (;;) {
705
+ const [la, lb] = await Promise.all([a.next(), b.next()]);
706
+ if (la === null && lb === null) break;
707
+ if (la !== lb) {
708
+ equal = false;
709
+ break;
710
+ }
711
+ lines++;
712
+ }
713
+ } finally {
714
+ a.proc.kill();
715
+ b.proc.kill();
716
+ }
717
+ return equal && lines > 0;
718
+ }