react-native-update-cli 2.25.0 → 2.26.1

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.
package/README.md CHANGED
@@ -87,7 +87,7 @@ const publishResult = await provider.publish({
87
87
 
88
88
  Hermes projects: `bundle` always runs hermesc with `-output-source-map`, so the debug info section is stripped from the bytecode (15–40% smaller, same as React Native's own release builds). The Hermes sourcemap stays in the intermediate directory (`.pushy/intermedia/<platform>/<bundle>.map`, never packed into the ppk) and is composed with the packager map — `--sourcemap` is on by default since 2.23 (`--no-sourcemap` opts out). When `bundle` publishes, that final map is uploaded and archived with the version (`sourceMapKey`), so `pushy symbolicate` can map crash stacks — including Hermes `address at` frames — back to source later. `pushy publish <ppk> --sourcemap <file.map>` archives a map for a ppk built elsewhere; publishing without a map prints a warning.
89
89
 
90
- Hermes delta mode (`-base-bytecode`): by default (`--hermesBase auto`) `bundle` compiles against the previous HBC of the same app, which keeps Hermes string IDs stable and makes hot-update patches 5–30× smaller. The base comes from the server (`GET /app/:id/hermesBase`), verified by sha256 and kept in a local cache (`.pushy/cache/<sha256>`, 500 MB / 20 files, `PUSHY_CACHE_DIR` / `--cacheMaxMb` to tune, `pushy cache [clean]` to inspect or clear). `--hermesBase none` disables it; `--hermesBase <file.hbc|.ppk|.apk|.ipa>` uses a local artifact (for example the store build). `--verifyHermesBase` (default on) additionally compiles without the base (concurrently with the base compile) and compares both disassemblies; on any mismatch or failure the CLI silently falls back to the plain compile, so the feature can never block a release. Only hermesc builds that include the upstream delta-mode fix are used (classic `react-native/sdks/hermesc`, or `hermes-compiler` ≥ 250829098). If a base compile fails, the full hermesc output is written to `hermes-base-error.log` next to the intermediate directory. `--resetCache false` skips Metro's `--reset-cache` and reuses its transform cache, which makes repeated bundles much faster.
90
+ Hermes delta mode (`-base-bytecode`): by default (`--hermesBase auto`) `bundle` compiles against the previous HBC of the same app, which keeps Hermes string IDs stable and makes hot-update patches 5–30× smaller. The base comes from the server (`GET /app/:id/hermesBase`), verified by sha256 and kept in a local cache (`.pushy/cache/<sha256>`, 500 MB / 20 files, `PUSHY_CACHE_DIR` / `--cacheMaxMb` to tune, `pushy cache [clean]` to inspect or clear). `--hermesBase none` disables it; `--hermesBase <file.hbc|.ppk|.apk|.ipa>` uses a local artifact (for example the store build). `--verifyHermesBase` (default on) additionally compiles without the base (concurrently with the base compile) and compares both disassemblies — literal buffers by content, then function by function, with only representation differences (string ids, operand widths, jump distances, buffer offsets) folded away; on any mismatch or failure the CLI falls back to the plain compile, so the feature can never block a release. The log names the first difference (function, line, both sides) or, separately, a dump that could not be read; set `PUSHY_HERMES_BASE_DEBUG=1` to keep both disassemblies (`hermes-base-dump-base.txt` / `hermes-base-dump-plain.txt` next to the intermediate directory) for a bug report. What the check covers, what it does not yet, and how to triage a rejection: [docs/hermes-base-verification.md](docs/hermes-base-verification.md). The result is reported at publish (`hermesBaseOutcome`: `used` / `rejected` / `dump-failed` / `none`, plus the first difference) so the server can watch the rejection rate across apps. `HERMESC=<path> bun run fuzz:hermes-base --rounds 300` compiles random programs against random bases and reports any build the check would wrongly reject (differential fuzzing of the normalization rules). Only hermesc builds that include the upstream delta-mode fix are used (classic `react-native/sdks/hermesc`, or `hermes-compiler` ≥ 250829098). If a base compile fails, the full hermesc output is written to `hermes-base-error.log` next to the intermediate directory. `--resetCache false` skips Metro's `--reset-cache` and reuses its transform cache, which makes repeated bundles much faster.
91
91
 
92
92
  ### Version
93
93
 
package/README.zh-CN.md CHANGED
@@ -78,7 +78,7 @@ const publishResult = await provider.publish({
78
78
 
79
79
  Hermes 工程:`bundle` 调用 hermesc 时始终带 `-output-source-map`,因此字节码不含 debug info 段(小 15%~40%,与 React Native 自身 release 构建一致)。Hermes sourcemap 保留在中间目录(`.pushy/intermedia/<platform>/<bundle>.map`,不会打进 ppk),并与 packager map 合成——自 2.23 起 `--sourcemap` 默认开启(`--no-sourcemap` 关闭)。`bundle` 发布时会把这份最终 map 上传并随版本归档(`sourceMapKey`),之后用 `pushy symbolicate` 即可把崩溃堆栈(含 Hermes 的 `address at` 帧)还原到源码。别处打好的 ppk 可用 `pushy publish <ppk> --sourcemap <file.map>` 归档;不带 map 发布会打印警告。
80
80
 
81
- Hermes delta 模式(`-base-bytecode`):默认 `--hermesBase auto`,`bundle` 会以同一应用上一版的 HBC 为 base 编译,让 Hermes 字符串 ID 跨版本稳定,热更 patch 可缩小 5~30 倍。base 由服务端(`GET /app/:id/hermesBase`)给出、按 sha256 校验并存入本地缓存(`.pushy/cache/<sha256>`,默认 500 MB / 20 个,可用 `PUSHY_CACHE_DIR` / `--cacheMaxMb` 调整,`pushy cache [clean]` 查看或清空)。`--hermesBase none` 关闭;`--hermesBase <file.hbc|.ppk|.apk|.ipa>` 指定本地文件(比如商店包)作 base。`--verifyHermesBase`(默认开)会并行再做一次普通编译并比对两份反汇编;任何不一致或失败都静默回退到普通编译,不会阻塞发版。只有包含上游 delta 模式修复的 hermesc 才会启用(经典 `react-native/sdks/hermesc`,或 `hermes-compiler` ≥ 250829098)。base 编译失败时,完整的 hermesc 输出会写到中间目录旁边的 `hermes-base-error.log`。`--resetCache false` 可跳过 Metro 的 `--reset-cache`,复用其转换缓存,重复打包会快很多。
81
+ Hermes delta 模式(`-base-bytecode`):默认 `--hermesBase auto`,`bundle` 会以同一应用上一版的 HBC 为 base 编译,让 Hermes 字符串 ID 跨版本稳定,热更 patch 可缩小 5~30 倍。base 由服务端(`GET /app/:id/hermesBase`)给出、按 sha256 校验并存入本地缓存(`.pushy/cache/<sha256>`,默认 500 MB / 20 个,可用 `PUSHY_CACHE_DIR` / `--cacheMaxMb` 调整,`pushy cache [clean]` 查看或清空)。`--hermesBase none` 关闭;`--hermesBase <file.hbc|.ppk|.apk|.ipa>` 指定本地文件(比如商店包)作 base。`--verifyHermesBase`(默认开)会并行再做一次普通编译并比对两份反汇编——先按内容比对字面量缓冲区,再逐函数比对,只折叠纯表示层差异(字符串 id、操作数宽度、跳转距离、缓冲区偏移);任何不一致或失败都回退到普通编译,不会阻塞发版。日志会给出第一处差异(函数、行、两侧内容),dump 读取失败会单独说明;设置 `PUSHY_HERMES_BASE_DEBUG=1` 可把两份反汇编保留在中间目录旁(`hermes-base-dump-base.txt` / `hermes-base-dump-plain.txt`)用于提 issue。校验覆盖什么、还缺什么、如何排查一次拒绝:见 [docs/hermes-base-verification.md](docs/hermes-base-verification.md)。校验结果会随发布上报(`hermesBaseOutcome`:`used` / `rejected` / `dump-failed` / `none`,附第一处差异),服务端可据此观察全体应用的拒绝率。`HERMESC=<path> bun run fuzz:hermes-base --rounds 300` 会用随机程序配随机 base 编译并报告校验误杀的构建(对归一化规则做差分模糊测试)。只有包含上游 delta 模式修复的 hermesc 才会启用(经典 `react-native/sdks/hermesc`,或 `hermes-compiler` ≥ 250829098)。base 编译失败时,完整的 hermesc 输出会写到中间目录旁边的 `hermes-base-error.log`。`--resetCache false` 可跳过 Metro 的 `--reset-cache`,复用其转换缓存,重复打包会快很多。
82
82
 
83
83
  ### Version
84
84
 
@@ -1,4 +1,4 @@
1
- import { type HermesBaseOption, type HermesBaseSelection } from './utils/hermes-base';
1
+ import { type HermesBaseOption, type HermesBaseOutcome, type HermesBaseSelection } from './utils/hermes-base';
2
2
  export interface BundleCliOptions {
3
3
  taro?: boolean;
4
4
  expo?: boolean;
@@ -31,6 +31,14 @@ export interface HermesCompileResult {
31
31
  base: HermesBaseSelection | null;
32
32
  /** true when --verifyHermesBase ran and passed; false when it failed (base dropped) */
33
33
  verified?: boolean;
34
+ /**
35
+ * What became of the base, for version/create. Kept apart from `base`
36
+ * (null whenever nothing shipped with a base) so a rejected base and "no
37
+ * base found" stay distinguishable on the server.
38
+ */
39
+ outcome: HermesBaseOutcome;
40
+ /** first difference / failure reason behind `outcome`, when there is one */
41
+ outcomeDetail?: string;
34
42
  }
35
43
  /** Outcome of picking a base: what to compile with, plus the log lines. */
36
44
  export interface HermesBaseSelectionResult {
@@ -137,6 +145,15 @@ export interface CompileHermesOptions {
137
145
  export declare function compileHermesByteCode({ bundleName, outputFolder, sourcemapOutput, shouldCleanSourcemap, baseRequest, pendingBase, hermesCommand, }: CompileHermesOptions): Promise<HermesCompileResult>;
138
146
  /** where a failed base attempt's full hermesc output goes (never packed) */
139
147
  export declare function hermesBaseErrorLogPath(outputFolder: string): string;
148
+ /**
149
+ * With PUSHY_HERMES_BASE_DEBUG set, both disassemblies of the equivalence
150
+ * check are kept next to the intermediate directory (never packed) so a
151
+ * rejected base can be reported with the exact difference.
152
+ */
153
+ export declare function hermesBaseDumpPaths(outputFolder: string, env?: NodeJS.ProcessEnv): {
154
+ withBase: string;
155
+ plain: string;
156
+ } | undefined;
140
157
  /**
141
158
  * Begin resolving the base right away (before Metro); the compile phase awaits
142
159
  * the result. Never rejects: any failure is reported there instead.
@@ -47,6 +47,7 @@ exports.summarizeHermescStderr = summarizeHermescStderr;
47
47
  exports.buildHermescArgs = buildHermescArgs;
48
48
  exports.compileHermesByteCode = compileHermesByteCode;
49
49
  exports.hermesBaseErrorLogPath = hermesBaseErrorLogPath;
50
+ exports.hermesBaseDumpPaths = hermesBaseDumpPaths;
50
51
  exports.startHermesBaseSelection = startHermesBaseSelection;
51
52
  exports.copyDebugidForSentry = copyDebugidForSentry;
52
53
  exports.prepareSentryUploadArtifacts = prepareSentryUploadArtifacts;
@@ -807,6 +808,7 @@ async function compileHermesByteCode({ bundleName, outputFolder, sourcemapOutput
807
808
  const result = {
808
809
  bytecodeVersion: selection.bytecodeVersion,
809
810
  base: null,
811
+ outcome: 'none',
810
812
  };
811
813
  const base = selection.base;
812
814
  // the packager + hermes maps merged into sourcemapOutput
@@ -844,6 +846,7 @@ async function compileHermesByteCode({ bundleName, outputFolder, sourcemapOutput
844
846
  console.warn((0, i18n_1.t)('hermesBaseCompileFailed', {
845
847
  reason: reason || `exit ${attempt.status}`,
846
848
  }));
849
+ result.outcomeDetail = `base compile failed: ${reason || `exit ${attempt.status}`}`;
847
850
  if (fullStderr.trim()) {
848
851
  // the summary drops noise; keep everything for bug reports — next to
849
852
  // the intermediate dir, never inside it (its content is packed)
@@ -863,26 +866,56 @@ async function compileHermesByteCode({ bundleName, outputFolder, sourcemapOutput
863
866
  : null;
864
867
  if (usedBase && wantPlain) {
865
868
  if (!plainOk) {
866
- // the check could not run; that is not a verification failure
867
- console.warn((0, i18n_1.t)('hermesBasePlainCompileFailed', {
868
- reason: (plain?.error && String(plain.error.message ?? plain.error)) ||
869
- `exit ${plain?.status}`,
870
- }));
869
+ // The check could not run. That is not evidence against the base,
870
+ // but verification was asked for and did not happen, so the base is
871
+ // dropped exactly like a dump that could not be read: never ship
872
+ // unverified when asked to verify. The plain compile is simply
873
+ // repeated below (compilePlain), which surfaces a real compiler
874
+ // failure as the build error it is.
875
+ const reason = (plain?.error && String(plain.error.message ?? plain.error)) ||
876
+ `exit ${plain?.status}`;
877
+ console.warn((0, i18n_1.t)('hermesBasePlainCompileFailed', { reason }));
878
+ result.outcome = 'dump-failed';
879
+ result.outcomeDetail = `plain compile failed: ${reason}`;
880
+ usedBase = false;
871
881
  }
872
882
  else {
873
- let ok;
883
+ const dumpTo = hermesBaseDumpPaths(outputFolder);
884
+ let outcome;
874
885
  try {
875
- ok = await (0, hermes_base_1.verifyHermesBaseEquivalence)(command, bundlePath, plainPath);
886
+ outcome = await (0, hermes_base_1.compareHermesBytecode)(command, bundlePath, plainPath, {
887
+ dumpTo,
888
+ });
889
+ }
890
+ catch (error) {
891
+ outcome = {
892
+ status: 'dump-failed',
893
+ detail: String(error?.message ?? error),
894
+ functions: 0,
895
+ };
876
896
  }
877
- catch {
878
- ok = false;
897
+ result.verified = outcome.status === 'equivalent';
898
+ if (outcome.status !== 'equivalent') {
899
+ result.outcome =
900
+ outcome.status === 'different' ? 'rejected' : 'dump-failed';
901
+ result.outcomeDetail = outcome.detail;
879
902
  }
880
- result.verified = ok;
881
- if (ok) {
882
- console.log((0, i18n_1.t)('hermesBaseVerified'));
903
+ if (outcome.status === 'equivalent') {
904
+ console.log((0, i18n_1.t)('hermesBaseVerified', { functions: outcome.functions }));
883
905
  }
884
906
  else {
885
- console.warn((0, i18n_1.t)('hermesBaseVerifyFailed'));
907
+ // a dump that could not be read is not evidence either way; the
908
+ // base is still dropped (never ship unverified when asked to
909
+ // verify), but the log says which case this is
910
+ console.warn((0, i18n_1.t)(outcome.status === 'different'
911
+ ? 'hermesBaseVerifyFailed'
912
+ : 'hermesBaseVerifyDumpFailed', { detail: outcome.detail ?? '' }));
913
+ if (dumpTo) {
914
+ console.warn((0, i18n_1.t)('hermesBaseVerifyDumpsWritten', {
915
+ withBase: dumpTo.withBase,
916
+ plain: dumpTo.plain,
917
+ }));
918
+ }
886
919
  usedBase = false;
887
920
  }
888
921
  }
@@ -908,6 +941,8 @@ async function compileHermesByteCode({ bundleName, outputFolder, sourcemapOutput
908
941
  }
909
942
  fs.removeSync(workDir);
910
943
  result.base = usedBase ? base : null;
944
+ if (usedBase)
945
+ result.outcome = 'used';
911
946
  }
912
947
  if (sourcemapOutput && !composed) {
913
948
  await composeSourceMaps(packagerMap, hermesMap, sourcemapOutput);
@@ -921,6 +956,21 @@ async function compileHermesByteCode({ bundleName, outputFolder, sourcemapOutput
921
956
  function hermesBaseErrorLogPath(outputFolder) {
922
957
  return path_1.default.join(path_1.default.dirname(path_1.default.resolve(outputFolder)), 'hermes-base-error.log');
923
958
  }
959
+ /**
960
+ * With PUSHY_HERMES_BASE_DEBUG set, both disassemblies of the equivalence
961
+ * check are kept next to the intermediate directory (never packed) so a
962
+ * rejected base can be reported with the exact difference.
963
+ */
964
+ function hermesBaseDumpPaths(outputFolder, env = process.env) {
965
+ const flag = env.PUSHY_HERMES_BASE_DEBUG?.trim().toLowerCase();
966
+ if (!flag || flag === '0' || flag === 'false')
967
+ return undefined;
968
+ const dir = path_1.default.dirname(path_1.default.resolve(outputFolder));
969
+ return {
970
+ withBase: path_1.default.join(dir, 'hermes-base-dump-base.txt'),
971
+ plain: path_1.default.join(dir, 'hermes-base-dump-plain.txt'),
972
+ };
973
+ }
924
974
  /**
925
975
  * Begin resolving the base right away (before Metro); the compile phase awaits
926
976
  * the result. Never rejects: any failure is reported there instead.
package/lib/bundle.js CHANGED
@@ -172,7 +172,10 @@ exports.bundleCommands = {
172
172
  });
173
173
  await (0, bundle_pack_1.packBundle)(path_1.default.resolve(normalized.intermediaDir), realOutput, normalized.bundleName);
174
174
  const baseMeta = hermesResult
175
- ? (0, hermes_base_1.hermesBaseMeta)(hermesResult.base, hermesResult.bytecodeVersion)
175
+ ? (0, hermes_base_1.hermesBaseMeta)(hermesResult.base, hermesResult.bytecodeVersion, {
176
+ outcome: hermesResult.outcome,
177
+ detail: hermesResult.outcomeDetail,
178
+ })
176
179
  : undefined;
177
180
  if (normalized.name) {
178
181
  await publishBundleVersion(realOutput, platform, {
@@ -164,6 +164,8 @@ declare const _default: {
164
164
  hermesBasePlainCompileFailed: string;
165
165
  hermesBaseVerified: string;
166
166
  hermesBaseVerifyFailed: string;
167
+ hermesBaseVerifyDumpFailed: string;
168
+ hermesBaseVerifyDumpsWritten: string;
167
169
  cacheCleaned: string;
168
170
  cacheStats: string;
169
171
  loginCredentialsRequired: string;
package/lib/locales/en.js CHANGED
@@ -169,9 +169,11 @@ This can reduce the risk of inconsistent dependencies and supply chain attacks.
169
169
  hermesBaseRangeFallback: 'Hermes base: partial download unavailable ({{- reason}}); downloading the whole package',
170
170
  hermesBaseCompileFailed: 'Hermes base compile failed ({{- reason}}); retrying without -base-bytecode',
171
171
  hermesBaseCompileFailedLog: 'Hermes base: full compiler output written to {{- file}}',
172
- hermesBasePlainCompileFailed: 'Hermes base: the plain compile used for verification failed ({{- reason}}); keeping the base compile unverified',
173
- hermesBaseVerified: 'Hermes base: bytecode verified equivalent to a plain compile',
174
- hermesBaseVerifyFailed: 'Hermes base: bytecode differs from a plain compile; dropping the base and recompiling',
172
+ hermesBasePlainCompileFailed: 'Hermes base: the plain compile used for verification failed ({{- reason}}); dropping the base and compiling again without it',
173
+ hermesBaseVerified: 'Hermes base: bytecode verified equivalent to a plain compile ({{functions}} functions)',
174
+ hermesBaseVerifyFailed: 'Hermes base: bytecode differs from a plain compile ({{- detail}}); dropping the base',
175
+ hermesBaseVerifyDumpFailed: 'Hermes base: could not compare the bytecode ({{- detail}}); dropping the base',
176
+ hermesBaseVerifyDumpsWritten: 'Hermes base: disassemblies written to {{- withBase}} and {{- plain}}',
175
177
  cacheCleaned: 'Removed {{count}} cached bundle(s)',
176
178
  cacheStats: 'Bundle cache: {{- dir}} — {{files}} file(s), {{mb}} MB',
177
179
  loginCredentialsRequired: 'Email and password are required. Usage: {{scriptName}} login <email> <password>',
@@ -164,6 +164,8 @@ declare const _default: {
164
164
  hermesBasePlainCompileFailed: string;
165
165
  hermesBaseVerified: string;
166
166
  hermesBaseVerifyFailed: string;
167
+ hermesBaseVerifyDumpFailed: string;
168
+ hermesBaseVerifyDumpsWritten: string;
167
169
  cacheCleaned: string;
168
170
  cacheStats: string;
169
171
  loginCredentialsRequired: string;
package/lib/locales/zh.js CHANGED
@@ -169,9 +169,11 @@ exports.default = {
169
169
  hermesBaseRangeFallback: 'Hermes base:无法按需下载({{- reason}}),改为下载整包',
170
170
  hermesBaseCompileFailed: 'Hermes base 编译失败({{- reason}}),改为不带 -base-bytecode 重编',
171
171
  hermesBaseCompileFailedLog: 'Hermes base:完整编译错误已写入 {{- file}}',
172
- hermesBasePlainCompileFailed: 'Hermes base:用于校验的普通编译失败({{- reason}}),保留 base 编译结果但未校验',
173
- hermesBaseVerified: 'Hermes base:字节码与普通编译等价,校验通过',
174
- hermesBaseVerifyFailed: 'Hermes base:字节码与普通编译不等价,放弃 base 重新编译',
172
+ hermesBasePlainCompileFailed: 'Hermes base:用于校验的普通编译失败({{- reason}}),放弃 base,不带 base 重新编译',
173
+ hermesBaseVerified: 'Hermes base:字节码与普通编译等价,校验通过({{functions}} 个函数)',
174
+ hermesBaseVerifyFailed: 'Hermes base:字节码与普通编译不等价({{- detail}}),放弃 base',
175
+ hermesBaseVerifyDumpFailed: 'Hermes base:无法比对字节码({{- detail}}),放弃 base',
176
+ hermesBaseVerifyDumpsWritten: 'Hermes base:两份反汇编已写入 {{- withBase}} 与 {{- plain}}',
175
177
  cacheCleaned: '已清理 {{count}} 个缓存 bundle',
176
178
  cacheStats: 'bundle 缓存:{{- dir}} — {{files}} 个文件,{{mb}} MB',
177
179
  loginCredentialsRequired: '需要提供邮箱和密码。用法:{{scriptName}} login <邮箱> <密码>',
@@ -57,6 +57,21 @@ export declare function compileLayoutToWire(layout: HbcLayout): HbcLayoutWire;
57
57
  export declare function getHbcVersion(buf: Buffer): number | null;
58
58
  /** 同一版本号可能有多个候选布局(按声明顺序即优先级)。 */
59
59
  export declare function findLayouts(version: number): HbcLayout[];
60
+ /** Byte range of one section of an HBC file (see resolveHbcSections). */
61
+ export type HbcSectionRange = {
62
+ start: number;
63
+ size: number;
64
+ };
65
+ /**
66
+ * Section byte ranges of an HBC file from its 128-byte header and total
67
+ * length, keyed by section name (arrayBuffer, objKeyBuffer, ... for v87–96;
68
+ * literalValueBuffer, objShapeTable, ... for v98). Null when no known layout
69
+ * fits, which callers treat as "cannot read this file structurally".
70
+ */
71
+ export declare function resolveHbcSections(header: Buffer, fileLength: number): {
72
+ version: number;
73
+ sections: Map<string, HbcSectionRange>;
74
+ } | null;
60
75
  /**
61
76
  * 对 HBC buffer 执行变换(inverse=false)或逆变换(inverse=true)。
62
77
  * 同一版本号可能存在多个候选布局(如 v98 早/晚两种头部),按声明顺序
@@ -20,6 +20,7 @@ exports.HBC_TRANSFORM_VERSION = exports.HBC_LAYOUTS = void 0;
20
20
  exports.compileLayoutToWire = compileLayoutToWire;
21
21
  exports.getHbcVersion = getHbcVersion;
22
22
  exports.findLayouts = findLayouts;
23
+ exports.resolveHbcSections = resolveHbcSections;
23
24
  exports.transformHbc = transformHbc;
24
25
  exports.pickLayout = pickLayout;
25
26
  exports.transformHbcWithLayout = transformHbcWithLayout;
@@ -319,6 +320,27 @@ function resolveSectionsFromHeader(header, fileLength, layout) {
319
320
  }
320
321
  return resolved;
321
322
  }
323
+ /**
324
+ * Section byte ranges of an HBC file from its 128-byte header and total
325
+ * length, keyed by section name (arrayBuffer, objKeyBuffer, ... for v87–96;
326
+ * literalValueBuffer, objShapeTable, ... for v98). Null when no known layout
327
+ * fits, which callers treat as "cannot read this file structurally".
328
+ */
329
+ function resolveHbcSections(header, fileLength) {
330
+ const version = getHbcVersion(header);
331
+ if (version === null)
332
+ return null;
333
+ for (const layout of findLayouts(version)) {
334
+ const resolved = resolveSectionsFromHeader(header, fileLength, layout);
335
+ if (resolved) {
336
+ return {
337
+ version,
338
+ sections: new Map(resolved.map((s) => [s.desc.name, { start: s.start, size: s.size }])),
339
+ };
340
+ }
341
+ }
342
+ return null;
343
+ }
322
344
  function applyDelta(out, section, inverse) {
323
345
  const { start, size, desc } = section;
324
346
  for (const f of desc.deltaFields ?? []) {
@@ -1,3 +1,4 @@
1
+ import { LiteralResolver } from './hermes-literals';
1
2
  export type HermesBaseOption = 'auto' | 'none' | string;
2
3
  /**
3
4
  * The base cannot be obtained whatever the transport or how often it is
@@ -20,11 +21,27 @@ export interface HermesBaseSelection {
20
21
  hash?: string;
21
22
  source: 'cache' | 'download' | 'local' | 'latest-version' | 'native-package';
22
23
  }
24
+ /**
25
+ * What became of the base for this build, as reported to the server:
26
+ * - `used`: compiled with -base-bytecode (and, when verification was on,
27
+ * the disassembly matched a plain compile)
28
+ * - `rejected`: the disassembly differed from a plain compile; base dropped
29
+ * - `dump-failed`: the check could not run (dump or plain compile failed);
30
+ * base dropped
31
+ * - `none`: no base (none selected, disabled, or the base compile failed)
32
+ */
33
+ export type HermesBaseOutcome = 'used' | 'rejected' | 'dump-failed' | 'none';
34
+ /** the server column is VARCHAR(500); it truncates too, this just saves bytes */
35
+ export declare const HERMES_BASE_DETAIL_MAX_CHARS = 500;
23
36
  /** Metadata attached to version/create so the server can track the chain. */
24
37
  export interface HermesBaseMeta {
25
38
  bytecodeVersion: number | null;
26
39
  baseVersionId: number | null;
27
40
  baseHash: string | null;
41
+ /** absent (never null) when the bundle step did not run hermesc */
42
+ hermesBaseOutcome?: HermesBaseOutcome;
43
+ /** first difference / failure reason; absent when there is none */
44
+ hermesBaseDetail?: string;
28
45
  }
29
46
  /**
30
47
  * Hermes V1 (static_h) builds before 2025-07-11 carried a delta-mode bug when a
@@ -149,19 +166,57 @@ export interface ResolveHermesBaseParams {
149
166
  */
150
167
  export declare function resolveHermesBase(params: ResolveHermesBaseParams): Promise<HermesBaseSelection | null>;
151
168
  export declare function hermescArgsWithBase(baseArgs: string[], basePath: string | null): string[];
152
- export declare function hermesBaseMeta(selection: HermesBaseSelection | null, bytecodeVersion: number | null): HermesBaseMeta;
169
+ export declare function hermesBaseMeta(selection: HermesBaseSelection | null, bytecodeVersion: number | null, check?: {
170
+ outcome: HermesBaseOutcome;
171
+ detail?: string;
172
+ }): HermesBaseMeta;
173
+ /** one line, at most HERMES_BASE_DETAIL_MAX_CHARS code points; '' when empty */
174
+ export declare function truncateHermesBaseDetail(detail: string | undefined): string;
153
175
  /**
154
176
  * Normalize one disassembly line so that a delta-mode compile and a plain
155
177
  * compile of the same source compare equal: string IDs are renumbered, literal
156
178
  * buffers are laid out differently (offsets, short/long variants), and jump
157
179
  * distances follow instruction widths. Everything else must match exactly.
158
180
  */
159
- export declare function normalizeDisassemblyLine(line: string, strings: Map<number, string>): string | null;
181
+ /** separates rendered literal entries inside one normalized line */
182
+ export declare const LITERAL_SEPARATOR = "\u001F";
183
+ export declare function normalizeDisassemblyLine(line: string, strings: Map<number, string>, literals?: LiteralResolver): string | null;
184
+ /** How an equivalence check ended. */
185
+ export type HermesEquivalenceStatus = 'equivalent' | 'different' | 'dump-failed';
186
+ export interface HermesEquivalenceResult {
187
+ status: HermesEquivalenceStatus;
188
+ /**
189
+ * one line for the log: where the first difference is (function, line,
190
+ * both sides) or why a dump could not be read
191
+ */
192
+ detail?: string;
193
+ /** functions compared on both sides */
194
+ functions: number;
195
+ /**
196
+ * `instruction`: literals decoded from the binary buffers at each
197
+ * New*WithBuffer instruction (HBC v87–96 and v98); `buffer`: the dumped
198
+ * buffers compared as a whole (unknown layout)
199
+ */
200
+ literals?: 'instruction' | 'buffer';
201
+ }
202
+ export interface HermesEquivalenceOptions {
203
+ /** write each side's raw disassembly here (bug reports) */
204
+ dumpTo?: {
205
+ withBase: string;
206
+ plain: string;
207
+ };
208
+ }
160
209
  /**
161
- * Compare two HBC files by disassembly (see normalizeDisassemblyLine). `-b`
162
- * forces hermesc to treat inputs as bytecode whatever their extension. Both
163
- * hermesc dumps are consumed as streams so the ~100 MB of text never touches
164
- * the disk. Resolves true when equivalent.
210
+ * Compare two HBC files by disassembly (see normalizeDisassemblyLine): the
211
+ * literal buffers by content, then function by function. `-b` forces hermesc
212
+ * to treat inputs as bytecode whatever their extension. Both dumps are
213
+ * consumed as streams so the ~100 MB of text never touches the disk (unless
214
+ * `dumpTo` asks for it). A dump process that fails or ends early is reported
215
+ * as `dump-failed`, never as a difference: the two cases need different
216
+ * follow-ups. The detail names the first difference so a rejected base can be
217
+ * turned into a normalization rule or a bug report.
165
218
  */
219
+ export declare function compareHermesBytecode(hermesCommand: string, withBase: string, plain: string, options?: HermesEquivalenceOptions): Promise<HermesEquivalenceResult>;
220
+ /** Resolves true when equivalent; see compareHermesBytecode for the details. */
166
221
  export declare function verifyHermesBaseEquivalence(hermesCommand: string, withBase: string, plain: string): Promise<boolean>;
167
222
  export {};
@@ -36,7 +36,7 @@ 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 = exports.BundleHashMismatchError = exports.PermanentBaseError = void 0;
39
+ exports.LITERAL_SEPARATOR = 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.HERMES_BASE_DETAIL_MAX_CHARS = exports.BundleHashMismatchError = exports.PermanentBaseError = void 0;
40
40
  exports.classifyHermesCommand = classifyHermesCommand;
41
41
  exports.sha256Hex = sha256Hex;
42
42
  exports.sha256File = sha256File;
@@ -58,7 +58,9 @@ exports.fetchBaseBundle = fetchBaseBundle;
58
58
  exports.resolveHermesBase = resolveHermesBase;
59
59
  exports.hermescArgsWithBase = hermescArgsWithBase;
60
60
  exports.hermesBaseMeta = hermesBaseMeta;
61
+ exports.truncateHermesBaseDetail = truncateHermesBaseDetail;
61
62
  exports.normalizeDisassemblyLine = normalizeDisassemblyLine;
63
+ exports.compareHermesBytecode = compareHermesBytecode;
62
64
  exports.verifyHermesBaseEquivalence = verifyHermesBaseEquivalence;
63
65
  // Hermes `-base-bytecode` (delta optimizing mode) support.
64
66
  //
@@ -79,6 +81,7 @@ const stream_1 = require("stream");
79
81
  const promises_1 = require("stream/promises");
80
82
  const constants_1 = require("./constants");
81
83
  const hbcTransform_1 = require("./hbcTransform");
84
+ const hermes_literals_1 = require("./hermes-literals");
82
85
  const i18n_1 = require("./i18n");
83
86
  const runtime_1 = require("./runtime");
84
87
  const zip_entries_1 = require("./zip-entries");
@@ -103,6 +106,8 @@ const FETCH_HEADERS_TIMEOUT_MS = 30_000;
103
106
  const STREAM_IDLE_TIMEOUT_MS = 60_000;
104
107
  /** cachePut leftovers (`<hash>.<pid>.tmp`) older than this are evicted */
105
108
  const STALE_CACHE_TMP_MS = 60 * 60 * 1000;
109
+ /** the server column is VARCHAR(500); it truncates too, this just saves bytes */
110
+ exports.HERMES_BASE_DETAIL_MAX_CHARS = 500;
106
111
  // ---------------------------------------------------------------------------
107
112
  // hermesc gating
108
113
  // ---------------------------------------------------------------------------
@@ -796,12 +801,27 @@ async function retryOnce(action) {
796
801
  function hermescArgsWithBase(baseArgs, basePath) {
797
802
  return basePath ? [...baseArgs, `-base-bytecode=${basePath}`] : baseArgs;
798
803
  }
799
- function hermesBaseMeta(selection, bytecodeVersion) {
800
- return {
804
+ function hermesBaseMeta(selection, bytecodeVersion, check) {
805
+ const meta = {
801
806
  bytecodeVersion,
802
807
  baseVersionId: selection?.versionId ?? null,
803
808
  baseHash: selection?.hash ?? null,
804
809
  };
810
+ if (check) {
811
+ meta.hermesBaseOutcome = check.outcome;
812
+ const detail = truncateHermesBaseDetail(check.detail);
813
+ if (detail)
814
+ meta.hermesBaseDetail = detail;
815
+ }
816
+ return meta;
817
+ }
818
+ /** one line, at most HERMES_BASE_DETAIL_MAX_CHARS code points; '' when empty */
819
+ function truncateHermesBaseDetail(detail) {
820
+ const compact = (detail ?? '').replace(/\s+/g, ' ').trim();
821
+ const chars = Array.from(compact);
822
+ return chars.length <= exports.HERMES_BASE_DETAIL_MAX_CHARS
823
+ ? compact
824
+ : chars.slice(0, exports.HERMES_BASE_DETAIL_MAX_CHARS).join('');
805
825
  }
806
826
  // ---------------------------------------------------------------------------
807
827
  // equivalence check (streams two `-dump-bytecode` outputs, never writes them)
@@ -813,7 +833,51 @@ const STRING_TABLE_LINE = /^\s*[is](\d+)\[[^\]]*\](?: #[0-9A-F]+)?: (.*)$/;
813
833
  * buffers are laid out differently (offsets, short/long variants), and jump
814
834
  * distances follow instruction widths. Everything else must match exactly.
815
835
  */
816
- function normalizeDisassemblyLine(line, strings) {
836
+ /** separates rendered literal entries inside one normalized line */
837
+ exports.LITERAL_SEPARATOR = '\u001f';
838
+ /**
839
+ * `NewArrayWithBuffer rX, sizeHint, count, offset` and
840
+ * `NewObjectWithBuffer rX, sizeHint, count, keyOffset, valueOffset` (HBC
841
+ * v87–96) or `NewObjectWithBuffer[AndParent] rX, [rP,] shapeIndex,
842
+ * valueOffset` (v98) with the literals decoded from the binary buffers at
843
+ * those offsets, so two builds that lay their buffers out differently still
844
+ * compare by what each instruction builds. The shape index is dropped like an
845
+ * offset: it only locates the keys. Null when the operands do not fit the
846
+ * layout; an offset that cannot be decoded is spelled out (and so never
847
+ * equals a decoded one).
848
+ */
849
+ function renderBufferInstruction(opcode, operands, literals) {
850
+ const [sizeHint, count] = operands;
851
+ if (opcode.startsWith('NewArray')) {
852
+ if (operands.length !== 3)
853
+ return null;
854
+ const entries = literals.array(operands[2], count);
855
+ return `size=${sizeHint} n=${count} [${entries ? entries.join(exports.LITERAL_SEPARATOR) : `<undecodable@${operands[2]}>`}]`;
856
+ }
857
+ if (literals.layout === 'shaped') {
858
+ if (operands.length !== 2)
859
+ return null;
860
+ const [shapeIndex, valueOffset] = operands;
861
+ const shape = literals.shape(shapeIndex);
862
+ const keys = shape && literals.objectKeys(shape.keyOffset, shape.count);
863
+ const values = shape && literals.objectValues(valueOffset, shape.count);
864
+ if (!shape || !keys || !values) {
865
+ return `n=${shape?.count ?? '?'} {<undecodable@shape${shapeIndex}/${valueOffset}>}`;
866
+ }
867
+ const pairs = keys.map((k, i) => `${k}: ${values[i]}`);
868
+ return `n=${shape.count} {${pairs.join(exports.LITERAL_SEPARATOR)}}`;
869
+ }
870
+ if (operands.length !== 4)
871
+ return null;
872
+ const keys = literals.objectKeys(operands[2], count);
873
+ const values = literals.objectValues(operands[3], count);
874
+ if (!keys || !values) {
875
+ return `size=${sizeHint} n=${count} {<undecodable@${operands[2]}/${operands[3]}>}`;
876
+ }
877
+ const pairs = keys.map((k, i) => `${k}: ${values[i]}`);
878
+ return `size=${sizeHint} n=${count} {${pairs.join(exports.LITERAL_SEPARATOR)}}`;
879
+ }
880
+ function normalizeDisassemblyLine(line, strings, literals) {
817
881
  // Cheap dispatch on the opcode before touching any regex: dumps run to
818
882
  // millions of lines and only a handful of instructions need rewriting.
819
883
  let indent = 0;
@@ -828,11 +892,22 @@ function normalizeDisassemblyLine(line, strings) {
828
892
  }
829
893
  let m;
830
894
  if (opcode.startsWith('New') && opcode.includes('WithBuffer')) {
895
+ // v98's AndParent form takes the parent object in a second register,
896
+ // which is compared as is (it is not a buffer operand)
831
897
  m =
832
- /^(\s*New(?:Array|Object)WithBuffer)(?:Long)?(?:AndParent)?\s+(r\d+)(.*)$/.exec(line);
898
+ /^(\s*New(?:Array|Object)WithBuffer)(?:Long)?(AndParent)?\s+(r\d+)(?:, (r\d+))?(.*)$/.exec(line);
833
899
  if (m) {
834
- const nums = m[3].match(/\d+/g) ?? [];
835
- return `${m[1]} ${m[2]} sizes=${nums.slice(0, 1).join(',')}`;
900
+ const op = `${m[1]}${m[2] ?? ''}`;
901
+ const regs = m[4] ? `${m[3]} ${m[4]}` : m[3];
902
+ const nums = m[5].match(/\d+/g) ?? [];
903
+ if (literals) {
904
+ const rendered = renderBufferInstruction(m[1].trim(), nums.map(Number), literals);
905
+ if (rendered)
906
+ return `${op} ${regs} ${rendered}`;
907
+ }
908
+ // no binary buffers: only the size hint survives; the buffer content
909
+ // is compared as a whole instead (compareBuffers)
910
+ return `${op} ${regs} sizes=${nums.slice(0, 1).join(',')}`;
836
911
  }
837
912
  }
838
913
  if (opcode.charCodeAt(0) === 0x4a /* J */) {
@@ -907,75 +982,301 @@ async function* streamLines(stream) {
907
982
  if (rest)
908
983
  yield rest;
909
984
  }
985
+ /** `Array Buffer:`, `Object Key Buffer:`, `Debug filename table:`, ... */
986
+ const SECTION_HEADER = /^([A-Z][A-Za-z ]*):$/;
987
+ /** literal buffer entry that refers to the string table by id */
988
+ const BUFFER_STRING_ENTRY = /^\[String (\d+)\]$/;
989
+ /** sections after the functions that only serve debuggers and profilers */
990
+ const TRAILER_SECTION = /^(?:Debug |Textified callees table)/;
991
+ /** stderr kept from a dump process */
992
+ const DUMP_STDERR_KEEP = 4 * 1024;
993
+ /** a diagnostic line is cut to this many characters */
994
+ const DETAIL_LINE_MAX = 120;
995
+ function isFunctionHeader(line) {
996
+ return line.startsWith('Function<') || line.startsWith('NCFunction<');
997
+ }
998
+ /**
999
+ * Structured reader over one `hermesc -dump-bytecode -pretty-disassemble`
1000
+ * stream. Everything before the functions is either the string table (kept
1001
+ * to resolve ids), a literal buffer (kept, with string ids resolved to text,
1002
+ * so buffer *content* is compared) or ignored; the functions come out one at
1003
+ * a time, normalized; the debug tables after them are drained and ignored.
1004
+ */
910
1005
  class DumpReader {
911
1006
  proc;
912
1007
  iterator;
913
1008
  strings = new Map();
1009
+ /** literal buffers by section name, entries with string ids resolved */
1010
+ buffers = new Map();
1011
+ exit;
1012
+ section = null;
1013
+ pending = null;
914
1014
  inFunctions = false;
915
1015
  finished = false;
916
- constructor(proc) {
1016
+ /** set when the binary literal buffers of this side could be read */
1017
+ literals;
1018
+ constructor(proc, dumpTo, buffers) {
917
1019
  this.proc = proc;
918
- this.iterator = streamLines(proc.stdout);
1020
+ // the string table is filled while the preamble streams by, before the
1021
+ // first instruction needs it
1022
+ if (buffers)
1023
+ this.literals = new hermes_literals_1.LiteralResolver(buffers, this.strings);
1024
+ const pass = new stream_1.PassThrough();
1025
+ proc.stdout.pipe(pass);
1026
+ if (dumpTo)
1027
+ proc.stdout.pipe(fs_extra_1.default.createWriteStream(dumpTo));
1028
+ this.iterator = streamLines(pass);
1029
+ let stderr = '';
1030
+ proc.stderr?.on('data', (chunk) => {
1031
+ stderr = (stderr + chunk.toString()).slice(-DUMP_STDERR_KEEP);
1032
+ });
1033
+ this.exit = new Promise((resolve) => {
1034
+ // a spawn failure (ENOENT) may leave stdout open and never 'close'
1035
+ proc.on('error', (error) => {
1036
+ pass.end();
1037
+ resolve({ code: null, signal: null, error, stderr });
1038
+ });
1039
+ proc.on('close', (code, signal) => resolve({ code, signal, stderr }));
1040
+ });
919
1041
  }
920
- /** next normalized function-body line, or null at end */
921
- async next() {
1042
+ async nextLine() {
1043
+ if (this.pending !== null) {
1044
+ const line = this.pending;
1045
+ this.pending = null;
1046
+ return line;
1047
+ }
922
1048
  if (this.finished)
923
1049
  return null;
1050
+ const { value, done } = await this.iterator.next();
1051
+ if (done) {
1052
+ this.finished = true;
1053
+ return null;
1054
+ }
1055
+ return value;
1056
+ }
1057
+ /** consume the preamble up to (and returning) the first function header */
1058
+ async skipPreamble() {
924
1059
  for (;;) {
925
- const { value, done } = await this.iterator.next();
926
- if (done) {
927
- this.finished = true;
1060
+ const line = await this.nextLine();
1061
+ if (line === null)
928
1062
  return null;
1063
+ if (isFunctionHeader(line)) {
1064
+ this.inFunctions = true;
1065
+ return line;
929
1066
  }
930
- const line = value;
931
- if (!this.inFunctions) {
932
- if (line.startsWith('Function<')) {
933
- this.inFunctions = true;
934
- }
935
- else {
936
- const m = STRING_TABLE_LINE.exec(line);
937
- if (m)
938
- this.strings.set(Number(m[1]), m[2]);
939
- continue;
940
- }
1067
+ const header = SECTION_HEADER.exec(line);
1068
+ if (header) {
1069
+ this.section = header[1];
1070
+ if (this.section.endsWith('Buffer'))
1071
+ this.buffers.set(this.section, []);
1072
+ continue;
1073
+ }
1074
+ if (this.section === 'Global String Table') {
1075
+ const m = STRING_TABLE_LINE.exec(line);
1076
+ if (m)
1077
+ this.strings.set(Number(m[1]), m[2]);
1078
+ }
1079
+ else if (this.section?.endsWith('Buffer') && line.trim() !== '') {
1080
+ const entry = line.trim();
1081
+ const ref = BUFFER_STRING_ENTRY.exec(entry);
1082
+ const text = ref ? this.strings.get(Number(ref[1])) : undefined;
1083
+ this.buffers
1084
+ .get(this.section)
1085
+ .push(ref
1086
+ ? `[String ${text === undefined ? `?${ref[1]}` : JSON.stringify(text)}]`
1087
+ : entry);
1088
+ }
1089
+ }
1090
+ }
1091
+ /** next function (header + normalized body), or null after the last one */
1092
+ async nextFunction() {
1093
+ const header = this.inFunctions
1094
+ ? await this.nextLine()
1095
+ : await this.skipPreamble();
1096
+ if (header === null)
1097
+ return null;
1098
+ // a non-function header here is a trailer section: no more functions
1099
+ if (!isFunctionHeader(header))
1100
+ return null;
1101
+ const lines = [];
1102
+ for (;;) {
1103
+ const line = await this.nextLine();
1104
+ if (line === null)
1105
+ break;
1106
+ if (isFunctionHeader(line) || TRAILER_SECTION.test(line)) {
1107
+ this.pending = line;
1108
+ break;
941
1109
  }
942
1110
  if (line.trim() === '')
943
1111
  continue;
944
- const normalized = normalizeDisassemblyLine(line, this.strings);
1112
+ const normalized = normalizeDisassemblyLine(line, this.strings, this.literals);
945
1113
  if (normalized !== null)
946
- return normalized;
1114
+ lines.push(normalized);
947
1115
  }
1116
+ return { header, lines };
948
1117
  }
1118
+ /** drain whatever is left and report how the process ended */
1119
+ async finish() {
1120
+ while ((await this.nextLine()) !== null) { }
1121
+ return this.exit;
1122
+ }
1123
+ kill() {
1124
+ this.proc.kill();
1125
+ }
1126
+ }
1127
+ function describeExit(exit) {
1128
+ if (exit.error)
1129
+ return exit.error.message;
1130
+ const how = exit.signal !== null ? `signal ${exit.signal}` : `exit ${exit.code}`;
1131
+ const stderr = exit.stderr.trim().split('\n').pop()?.trim();
1132
+ return stderr ? `${how}: ${stderr}` : how;
1133
+ }
1134
+ function clip(line) {
1135
+ const s = line.trim().split(exports.LITERAL_SEPARATOR).join(', ');
1136
+ return s.length > DETAIL_LINE_MAX ? `${s.slice(0, DETAIL_LINE_MAX - 1)}…` : s;
949
1137
  }
950
1138
  /**
951
- * Compare two HBC files by disassembly (see normalizeDisassemblyLine). `-b`
952
- * forces hermesc to treat inputs as bytecode whatever their extension. Both
953
- * hermesc dumps are consumed as streams so the ~100 MB of text never touches
954
- * the disk. Resolves true when equivalent.
1139
+ * For two New*WithBuffer lines that differ, the first literal that differs
1140
+ * (the whole line would be clipped before the difference for long literals).
955
1141
  */
956
- async function verifyHermesBaseEquivalence(hermesCommand, withBase, plain) {
957
- const spawnDump = (file) => (0, child_process_1.spawn)(hermesCommand, ['-b', '-dump-bytecode', '-pretty-disassemble', file], {
958
- stdio: ['ignore', 'pipe', 'ignore'],
1142
+ function literalDifference(a, b) {
1143
+ const open = /^(\s*New\w+WithBuffer(?:AndParent)? r\d+(?: r\d+)?(?: size=\d+)? n=\d+ [[{])/;
1144
+ const ma = open.exec(a);
1145
+ const mb = open.exec(b);
1146
+ if (!ma || !mb)
1147
+ return null;
1148
+ const ea = a.slice(ma[1].length, -1).split(exports.LITERAL_SEPARATOR);
1149
+ const eb = b.slice(mb[1].length, -1).split(exports.LITERAL_SEPARATOR);
1150
+ const n = Math.min(ea.length, eb.length);
1151
+ for (let i = 0; i < n; i++) {
1152
+ if (ea[i] !== eb[i]) {
1153
+ return `${clip(ma[1].slice(0, -1))} entry ${i}: ${clip(ea[i])} vs ${clip(eb[i])}`;
1154
+ }
1155
+ }
1156
+ return null;
1157
+ }
1158
+ function compareBuffers(a, b) {
1159
+ for (const name of new Set([...a.keys(), ...b.keys()])) {
1160
+ const ea = a.get(name) ?? [];
1161
+ const eb = b.get(name) ?? [];
1162
+ const n = Math.min(ea.length, eb.length);
1163
+ for (let i = 0; i < n; i++) {
1164
+ if (ea[i] !== eb[i]) {
1165
+ return `${name} entry ${i}: ${clip(ea[i])} vs ${clip(eb[i])}`;
1166
+ }
1167
+ }
1168
+ if (ea.length !== eb.length) {
1169
+ return `${name}: ${ea.length} vs ${eb.length} entries`;
1170
+ }
1171
+ }
1172
+ return null;
1173
+ }
1174
+ function compareFunctions(a, b) {
1175
+ if (a.header !== b.header) {
1176
+ return `${clip(a.header)} vs ${clip(b.header)}`;
1177
+ }
1178
+ const n = Math.min(a.lines.length, b.lines.length);
1179
+ for (let i = 0; i < n; i++) {
1180
+ if (a.lines[i] !== b.lines[i]) {
1181
+ const literal = literalDifference(a.lines[i], b.lines[i]);
1182
+ return literal
1183
+ ? `${clip(a.header)} +${i + 1}: ${literal}`
1184
+ : `${clip(a.header)} +${i + 1}: ${clip(a.lines[i])} vs ${clip(b.lines[i])}`;
1185
+ }
1186
+ }
1187
+ if (a.lines.length !== b.lines.length) {
1188
+ return `${clip(a.header)}: ${a.lines.length} vs ${b.lines.length} lines`;
1189
+ }
1190
+ return null;
1191
+ }
1192
+ /**
1193
+ * Compare two HBC files by disassembly (see normalizeDisassemblyLine): the
1194
+ * literal buffers by content, then function by function. `-b` forces hermesc
1195
+ * to treat inputs as bytecode whatever their extension. Both dumps are
1196
+ * consumed as streams so the ~100 MB of text never touches the disk (unless
1197
+ * `dumpTo` asks for it). A dump process that fails or ends early is reported
1198
+ * as `dump-failed`, never as a difference: the two cases need different
1199
+ * follow-ups. The detail names the first difference so a rejected base can be
1200
+ * turned into a normalization rule or a bug report.
1201
+ */
1202
+ async function compareHermesBytecode(hermesCommand, withBase, plain, options = {}) {
1203
+ const spawnDump = (file) => (0, child_process_1.spawn)(hermesCommand, ['-b', '-dump-bytecode', '-pretty-disassemble', file], { stdio: ['ignore', 'pipe', 'pipe'] });
1204
+ // The literal buffers are read from both files up front (header + three
1205
+ // byte ranges). Only when both sides can be read do the instructions
1206
+ // compare decoded literals; otherwise both fall back to the dumped buffers
1207
+ // as a whole, so the two sides always normalize the same way.
1208
+ const [buffersA, buffersB] = await Promise.all([
1209
+ (0, hermes_literals_1.readLiteralBuffers)(withBase).catch(() => null),
1210
+ (0, hermes_literals_1.readLiteralBuffers)(plain).catch(() => null),
1211
+ ]);
1212
+ const binary = buffersA && buffersB && buffersA.version === buffersB.version;
1213
+ const literals = binary ? 'instruction' : 'buffer';
1214
+ const a = new DumpReader(spawnDump(withBase), options.dumpTo?.withBase, binary ? buffersA : null);
1215
+ const b = new DumpReader(spawnDump(plain), options.dumpTo?.plain, binary ? buffersB : null);
1216
+ let functions = 0;
1217
+ const different = (detail) => ({
1218
+ status: 'different',
1219
+ detail,
1220
+ functions,
1221
+ literals,
1222
+ });
1223
+ const dumpFailed = (side, exit) => ({
1224
+ status: 'dump-failed',
1225
+ detail: `${side} dump: ${describeExit(exit)}`,
1226
+ functions,
1227
+ literals,
959
1228
  });
960
- const a = new DumpReader(spawnDump(withBase));
961
- const b = new DumpReader(spawnDump(plain));
962
- let equal = true;
963
- let lines = 0;
964
1229
  try {
965
1230
  for (;;) {
966
- const [la, lb] = await Promise.all([a.next(), b.next()]);
967
- if (la === null && lb === null)
968
- break;
969
- if (la !== lb) {
970
- equal = false;
971
- break;
1231
+ const [fa, fb] = await Promise.all([a.nextFunction(), b.nextFunction()]);
1232
+ if (fa === null || fb === null) {
1233
+ // whoever ended: was that the end of a good dump or a failure?
1234
+ if (fa === null) {
1235
+ const exit = await a.finish();
1236
+ if (exit.error || exit.code !== 0)
1237
+ return dumpFailed('base', exit);
1238
+ }
1239
+ if (fb === null) {
1240
+ const exit = await b.finish();
1241
+ if (exit.error || exit.code !== 0)
1242
+ return dumpFailed('plain', exit);
1243
+ }
1244
+ if (fa !== null || fb !== null) {
1245
+ const extra = fa ?? fb;
1246
+ return different(`function count: ${clip(extra.header)} only in the ${fa ? 'base' : 'plain'} compile`);
1247
+ }
1248
+ if (functions === 0) {
1249
+ return {
1250
+ status: 'dump-failed',
1251
+ detail: 'no functions in the disassembly',
1252
+ functions,
1253
+ literals,
1254
+ };
1255
+ }
1256
+ return { status: 'equivalent', functions, literals };
1257
+ }
1258
+ if (functions === 0 && !binary) {
1259
+ // buffers precede the functions, so both are complete by now. This
1260
+ // whole-buffer comparison is the fallback: the builder overlaps and
1261
+ // deduplicates serialized literals, so a delta build may lay the same
1262
+ // literals out differently and this can reject a good build.
1263
+ const detail = compareBuffers(a.buffers, b.buffers);
1264
+ if (detail)
1265
+ return different(detail);
972
1266
  }
973
- lines++;
1267
+ const detail = compareFunctions(fa, fb);
1268
+ if (detail)
1269
+ return different(detail);
1270
+ functions++;
974
1271
  }
975
1272
  }
976
1273
  finally {
977
- a.proc.kill();
978
- b.proc.kill();
1274
+ a.kill();
1275
+ b.kill();
979
1276
  }
980
- return equal && lines > 0;
1277
+ }
1278
+ /** Resolves true when equivalent; see compareHermesBytecode for the details. */
1279
+ async function verifyHermesBaseEquivalence(hermesCommand, withBase, plain) {
1280
+ const result = await compareHermesBytecode(hermesCommand, withBase, plain);
1281
+ return result.status === 'equivalent';
981
1282
  }
@@ -0,0 +1,64 @@
1
+ export type LiteralValue = {
2
+ kind: 'null' | 'true' | 'false' | 'undefined';
3
+ } | {
4
+ kind: 'number';
5
+ value: number;
6
+ } | {
7
+ kind: 'int';
8
+ value: number;
9
+ } | {
10
+ kind: 'string';
11
+ id: number;
12
+ };
13
+ /** The literal buffers of an HBC file, in one of the two layouts. */
14
+ export type LiteralBuffers = {
15
+ layout: 'split';
16
+ version: number;
17
+ array: Buffer;
18
+ objectKeys: Buffer;
19
+ objectValues: Buffer;
20
+ } | {
21
+ layout: 'shaped';
22
+ version: number;
23
+ values: Buffer;
24
+ objectKeys: Buffer;
25
+ shapes: Buffer;
26
+ };
27
+ /**
28
+ * Read only the literal buffers of an HBC file (header + three byte ranges,
29
+ * never the whole file). Null for a file whose layout is unknown: the caller
30
+ * then falls back to comparing the dumped buffers as a whole.
31
+ */
32
+ export declare function readLiteralBuffers(file: string): Promise<LiteralBuffers | null>;
33
+ /**
34
+ * Decode `count` literal values starting at byte `offset`. Null when the
35
+ * offset or a run reaches outside the buffer or a tag type is unknown; the
36
+ * caller reports that as a difference rather than guessing. `layout` decides
37
+ * what type 6 means (see the file comment).
38
+ */
39
+ export declare function decodeSerializedLiterals(buffer: Buffer, offset: number, count: number, layout?: LiteralBuffers['layout']): LiteralValue[] | null;
40
+ /**
41
+ * One literal as text, string ids resolved through the dump's string table
42
+ * (an unknown id stays visible as `?id`). Doubles keep their exact bits in
43
+ * the text so -0 and 0, or two NaNs, never collide by accident.
44
+ */
45
+ export declare function renderLiteral(value: LiteralValue, strings: Map<number, string>): string;
46
+ /**
47
+ * Decodes the literals an instruction refers to, for one side of a compare.
48
+ * Returns rendered entries, or null when the offset cannot be decoded.
49
+ */
50
+ export declare class LiteralResolver {
51
+ private readonly buffers;
52
+ private readonly strings;
53
+ constructor(buffers: LiteralBuffers, strings: Map<number, string>);
54
+ private decode;
55
+ get layout(): LiteralBuffers['layout'];
56
+ array(offset: number, count: number): string[] | null;
57
+ objectKeys(offset: number, count: number): string[] | null;
58
+ objectValues(offset: number, count: number): string[] | null;
59
+ /** Shape table entry (HBC v98); null out of range or in the split layout. */
60
+ shape(index: number): {
61
+ keyOffset: number;
62
+ count: number;
63
+ } | null;
64
+ }
@@ -0,0 +1,255 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LiteralResolver = void 0;
4
+ exports.readLiteralBuffers = readLiteralBuffers;
5
+ exports.decodeSerializedLiterals = decodeSerializedLiterals;
6
+ exports.renderLiteral = renderLiteral;
7
+ /**
8
+ * Binary literal buffers of an HBC file, for the Hermes base equivalence
9
+ * check (see docs/hermes-base-verification.md §3.2).
10
+ *
11
+ * `NewArrayWithBuffer` / `NewObjectWithBuffer` reference their literals by
12
+ * *byte offset* into the serialized literal buffers. The text dump prints
13
+ * those buffers entry by entry without byte positions, so the offsets in the
14
+ * instructions cannot be mapped to entries from the dump alone — and a delta
15
+ * build may lay the buffers out differently (deduplicated runs, different
16
+ * order) while every instruction still resolves to the same literals. Reading
17
+ * the buffers from the file and decoding at each instruction's offset
18
+ * compares what the instruction actually builds.
19
+ *
20
+ * Serialized literal format (hermes SerializedLiteralGenerator): runs of
21
+ * same-typed values. Tag byte: bits 6..4 = type, bit 7 = "length continues in
22
+ * the next byte", bits 3..0 = low 4 bits of the run length (high 8 bits in
23
+ * the next byte when bit 7 is set). Values follow the tag, fixed width per
24
+ * type: none (null/true/false), 8-byte little-endian double, 4/2/1-byte
25
+ * string id, 4-byte little-endian int32. HBC v98 reuses type 6 (the 1-byte
26
+ * string id before) for `undefined`, which takes no value bytes; string ids
27
+ * there are always 2 or 4 bytes wide.
28
+ *
29
+ * Two file layouts use that format:
30
+ * - HBC v87–96 (`split`): arrayBuffer, objKeyBuffer, objValueBuffer.
31
+ * `NewArrayWithBuffer dst, sizeHint, count, arrayOffset`;
32
+ * `NewObjectWithBuffer dst, sizeHint, count, keyOffset, valueOffset`.
33
+ * - HBC v98 (`shaped`): literalValueBuffer (array elements and object values
34
+ * alike), objKeyBuffer, objShapeTable (8-byte entries: keyOffset u32,
35
+ * numProps u32). `NewArrayWithBuffer dst, sizeHint, count, valueOffset`;
36
+ * `NewObjectWithBuffer dst, shapeIndex, valueOffset` and
37
+ * `NewObjectWithBufferAndParent dst, parent, shapeIndex, valueOffset`.
38
+ */
39
+ const promises_1 = require("node:fs/promises");
40
+ const hbcTransform_1 = require("./hbcTransform");
41
+ const HBC_HEADER_SIZE = 128;
42
+ const TAG_TYPE_MASK = 0x70;
43
+ const TAG_LENGTH_CONTINUES = 0x80;
44
+ const TAG_LENGTH_LOW = 0x0f;
45
+ var Tag;
46
+ (function (Tag) {
47
+ Tag[Tag["Null"] = 0] = "Null";
48
+ Tag[Tag["True"] = 16] = "True";
49
+ Tag[Tag["False"] = 32] = "False";
50
+ Tag[Tag["Number"] = 48] = "Number";
51
+ Tag[Tag["LongString"] = 64] = "LongString";
52
+ Tag[Tag["ShortString"] = 80] = "ShortString";
53
+ /** HBC ≤96: 1-byte string id; HBC v98: `undefined` */
54
+ Tag[Tag["ByteStringOrUndefined"] = 96] = "ByteStringOrUndefined";
55
+ Tag[Tag["Integer"] = 112] = "Integer";
56
+ })(Tag || (Tag = {}));
57
+ const SHAPE_ENTRY_SIZE = 8;
58
+ /**
59
+ * Read only the literal buffers of an HBC file (header + three byte ranges,
60
+ * never the whole file). Null for a file whose layout is unknown: the caller
61
+ * then falls back to comparing the dumped buffers as a whole.
62
+ */
63
+ async function readLiteralBuffers(file) {
64
+ const handle = await (0, promises_1.open)(file, 'r');
65
+ try {
66
+ const { size } = await handle.stat();
67
+ if (size < HBC_HEADER_SIZE)
68
+ return null;
69
+ const header = Buffer.alloc(HBC_HEADER_SIZE);
70
+ const read = await handle.read(header, 0, HBC_HEADER_SIZE, 0);
71
+ if (read.bytesRead !== HBC_HEADER_SIZE)
72
+ return null;
73
+ const resolved = (0, hbcTransform_1.resolveHbcSections)(header, size);
74
+ if (!resolved)
75
+ return null;
76
+ const readRanges = async (names) => {
77
+ const ranges = names.map((name) => resolved.sections.get(name));
78
+ if (ranges.some((r) => !r))
79
+ return null;
80
+ const bufs = await Promise.all(ranges.map(async (r) => {
81
+ const buf = Buffer.alloc(r.size);
82
+ if (r.size === 0)
83
+ return buf;
84
+ const { bytesRead } = await handle.read(buf, 0, r.size, r.start);
85
+ return bytesRead === r.size ? buf : null;
86
+ }));
87
+ return bufs.some((b) => !b) ? null : bufs;
88
+ };
89
+ const { version } = resolved;
90
+ if (resolved.sections.has('objShapeTable')) {
91
+ const bufs = await readRanges([
92
+ 'literalValueBuffer',
93
+ 'objKeyBuffer',
94
+ 'objShapeTable',
95
+ ]);
96
+ if (!bufs)
97
+ return null;
98
+ const [values, objectKeys, shapes] = bufs;
99
+ return { layout: 'shaped', version, values, objectKeys, shapes };
100
+ }
101
+ const bufs = await readRanges([
102
+ 'arrayBuffer',
103
+ 'objKeyBuffer',
104
+ 'objValueBuffer',
105
+ ]);
106
+ if (!bufs)
107
+ return null;
108
+ const [array, objectKeys, objectValues] = bufs;
109
+ return { layout: 'split', version, array, objectKeys, objectValues };
110
+ }
111
+ finally {
112
+ await handle.close();
113
+ }
114
+ }
115
+ /**
116
+ * Decode `count` literal values starting at byte `offset`. Null when the
117
+ * offset or a run reaches outside the buffer or a tag type is unknown; the
118
+ * caller reports that as a difference rather than guessing. `layout` decides
119
+ * what type 6 means (see the file comment).
120
+ */
121
+ function decodeSerializedLiterals(buffer, offset, count, layout = 'split') {
122
+ const values = [];
123
+ let pos = offset;
124
+ while (values.length < count) {
125
+ if (pos < 0 || pos >= buffer.length)
126
+ return null;
127
+ const tag = buffer[pos++];
128
+ let length = tag & TAG_LENGTH_LOW;
129
+ if (tag & TAG_LENGTH_CONTINUES) {
130
+ if (pos >= buffer.length)
131
+ return null;
132
+ length = (length << 8) | buffer[pos++];
133
+ }
134
+ const type = tag & TAG_TYPE_MASK;
135
+ for (let i = 0; i < length && values.length < count; i++) {
136
+ switch (type) {
137
+ case Tag.Null:
138
+ values.push({ kind: 'null' });
139
+ break;
140
+ case Tag.True:
141
+ values.push({ kind: 'true' });
142
+ break;
143
+ case Tag.False:
144
+ values.push({ kind: 'false' });
145
+ break;
146
+ case Tag.Number:
147
+ if (pos + 8 > buffer.length)
148
+ return null;
149
+ values.push({ kind: 'number', value: buffer.readDoubleLE(pos) });
150
+ pos += 8;
151
+ break;
152
+ case Tag.LongString:
153
+ if (pos + 4 > buffer.length)
154
+ return null;
155
+ values.push({ kind: 'string', id: buffer.readUInt32LE(pos) });
156
+ pos += 4;
157
+ break;
158
+ case Tag.ShortString:
159
+ if (pos + 2 > buffer.length)
160
+ return null;
161
+ values.push({ kind: 'string', id: buffer.readUInt16LE(pos) });
162
+ pos += 2;
163
+ break;
164
+ case Tag.ByteStringOrUndefined:
165
+ if (layout === 'shaped') {
166
+ values.push({ kind: 'undefined' });
167
+ break;
168
+ }
169
+ if (pos + 1 > buffer.length)
170
+ return null;
171
+ values.push({ kind: 'string', id: buffer[pos] });
172
+ pos += 1;
173
+ break;
174
+ case Tag.Integer:
175
+ if (pos + 4 > buffer.length)
176
+ return null;
177
+ values.push({ kind: 'int', value: buffer.readInt32LE(pos) });
178
+ pos += 4;
179
+ break;
180
+ default:
181
+ return null;
182
+ }
183
+ }
184
+ }
185
+ return values;
186
+ }
187
+ /**
188
+ * One literal as text, string ids resolved through the dump's string table
189
+ * (an unknown id stays visible as `?id`). Doubles keep their exact bits in
190
+ * the text so -0 and 0, or two NaNs, never collide by accident.
191
+ */
192
+ function renderLiteral(value, strings) {
193
+ switch (value.kind) {
194
+ case 'null':
195
+ case 'true':
196
+ case 'false':
197
+ case 'undefined':
198
+ return value.kind;
199
+ case 'int':
200
+ return `[int ${value.value}]`;
201
+ case 'number': {
202
+ const bits = Buffer.alloc(8);
203
+ bits.writeDoubleLE(value.value);
204
+ return `[double ${Object.is(value.value, -0) ? '-0' : String(value.value)}#${bits.toString('hex')}]`;
205
+ }
206
+ case 'string': {
207
+ const text = strings.get(value.id);
208
+ return `[String ${text === undefined ? `?${value.id}` : JSON.stringify(text)}]`;
209
+ }
210
+ }
211
+ }
212
+ /**
213
+ * Decodes the literals an instruction refers to, for one side of a compare.
214
+ * Returns rendered entries, or null when the offset cannot be decoded.
215
+ */
216
+ class LiteralResolver {
217
+ buffers;
218
+ strings;
219
+ constructor(buffers, strings) {
220
+ this.buffers = buffers;
221
+ this.strings = strings;
222
+ }
223
+ decode(buffer, offset, count) {
224
+ const values = decodeSerializedLiterals(buffer, offset, count, this.buffers.layout);
225
+ return values ? values.map((v) => renderLiteral(v, this.strings)) : null;
226
+ }
227
+ get layout() {
228
+ return this.buffers.layout;
229
+ }
230
+ array(offset, count) {
231
+ const b = this.buffers;
232
+ return this.decode(b.layout === 'split' ? b.array : b.values, offset, count);
233
+ }
234
+ objectKeys(offset, count) {
235
+ return this.decode(this.buffers.objectKeys, offset, count);
236
+ }
237
+ objectValues(offset, count) {
238
+ const b = this.buffers;
239
+ return this.decode(b.layout === 'split' ? b.objectValues : b.values, offset, count);
240
+ }
241
+ /** Shape table entry (HBC v98); null out of range or in the split layout. */
242
+ shape(index) {
243
+ const b = this.buffers;
244
+ if (b.layout !== 'shaped' || index < 0)
245
+ return null;
246
+ const at = index * SHAPE_ENTRY_SIZE;
247
+ if (at + SHAPE_ENTRY_SIZE > b.shapes.length)
248
+ return null;
249
+ return {
250
+ keyOffset: b.shapes.readUInt32LE(at),
251
+ count: b.shapes.readUInt32LE(at + 4),
252
+ };
253
+ }
254
+ }
255
+ exports.LiteralResolver = LiteralResolver;
package/lib/versions.js CHANGED
@@ -358,6 +358,13 @@ async function describePpkBundle(ppkPath, base) {
358
358
  meta.baseVersionId = base.baseVersionId;
359
359
  if (base?.baseHash)
360
360
  meta.baseHash = base.baseHash;
361
+ // equivalence-check result: the server tells a rejected base from "no base"
362
+ // only through these; a server without the columns ignores the keys
363
+ if (base?.hermesBaseOutcome)
364
+ meta.hermesBaseOutcome = base.hermesBaseOutcome;
365
+ if (base?.hermesBaseDetail) {
366
+ meta.hermesBaseDetail = (0, hermes_base_1.truncateHermesBaseDetail)(base.hermesBaseDetail);
367
+ }
361
368
  return meta;
362
369
  }
363
370
  /** Exported for tests: the version/create fields derived from a ppk + base. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-update-cli",
3
- "version": "2.25.0",
3
+ "version": "2.26.1",
4
4
  "description": "command line tool for react-native-update (remote updates for react native)",
5
5
  "main": "lib/exports.js",
6
6
  "types": "lib/exports.d.ts",
@@ -40,7 +40,8 @@
40
40
  "test": "bun test",
41
41
  "smoke": "node scripts/smoke-lib.js",
42
42
  "test:coverage": "bun test --coverage --coverage-reporter=text --coverage-reporter=lcov",
43
- "benchmark:diff-stream": "bun scripts/benchmark-diff-stream.ts"
43
+ "benchmark:diff-stream": "bun scripts/benchmark-diff-stream.ts",
44
+ "fuzz:hermes-base": "bun scripts/fuzz-hermes-base.ts"
44
45
  },
45
46
  "repository": {
46
47
  "type": "git",