react-native-update-cli 2.24.2 → 2.25.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.
- package/README.md +11 -4
- package/README.zh-CN.md +11 -4
- package/cli.json +7 -1
- package/lib/api.d.ts +2 -0
- package/lib/api.js +63 -18
- package/lib/app.js +25 -3
- package/lib/bin.js +39 -45
- package/lib/bundle-runner.d.ts +27 -0
- package/lib/bundle-runner.js +240 -21
- package/lib/bundle.d.ts +1 -1
- package/lib/bundle.js +19 -6
- package/lib/commands.d.ts +6 -0
- package/lib/commands.js +65 -0
- package/lib/locales/en.d.ts +5 -14
- package/lib/locales/en.js +5 -14
- package/lib/locales/zh.d.ts +5 -13
- package/lib/locales/zh.js +5 -13
- package/lib/package.js +4 -0
- package/lib/provider.d.ts +1 -1
- package/lib/provider.js +3 -1
- package/lib/symbolicate.js +7 -2
- package/lib/types.d.ts +1 -0
- package/lib/user.js +6 -0
- package/lib/utils/add-gitignore.js +7 -1
- package/lib/utils/dep-versions.d.ts +7 -0
- package/lib/utils/dep-versions.js +78 -26
- package/lib/utils/git.js +9 -6
- package/lib/utils/hermes-base.js +2 -1
- package/lib/utils/i18n.d.ts +5 -0
- package/lib/utils/i18n.js +14 -1
- package/lib/utils/index.d.ts +2 -1
- package/lib/utils/index.js +9 -4
- package/lib/utils/latest-version/index.js +8 -0
- package/lib/utils/runtime.d.ts +21 -0
- package/lib/utils/runtime.js +138 -5
- package/lib/utils/zip-range.js +3 -2
- package/lib/versions.js +7 -4
- package/package.json +4 -2
- package/lib/index.d.ts +0 -1
- package/lib/index.js +0 -17
- package/src/api.ts +0 -470
- package/src/app.ts +0 -241
- package/src/auto-update.ts +0 -647
- package/src/bin-cresc.ts +0 -8
- package/src/bin.ts +0 -115
- package/src/bundle-pack.ts +0 -61
- package/src/bundle-runner.ts +0 -1430
- package/src/bundle.ts +0 -371
- package/src/cache.ts +0 -20
- package/src/diff.ts +0 -1010
- package/src/exports.ts +0 -17
- package/src/index.ts +0 -1
- package/src/install.ts +0 -50
- package/src/locales/en.ts +0 -257
- package/src/locales/zh.ts +0 -234
- package/src/native-package.ts +0 -338
- package/src/package.ts +0 -482
- package/src/provider.ts +0 -294
- package/src/symbolicate.ts +0 -164
- package/src/types.ts +0 -150
- package/src/user.ts +0 -39
- package/src/utils/add-gitignore.ts +0 -35
- package/src/utils/app-info-parser/aab.ts +0 -241
- package/src/utils/app-info-parser/apk.ts +0 -92
- package/src/utils/app-info-parser/app.ts +0 -7
- package/src/utils/app-info-parser/index.ts +0 -54
- package/src/utils/app-info-parser/ipa.ts +0 -109
- package/src/utils/app-info-parser/resource-finder.ts +0 -508
- package/src/utils/app-info-parser/utils.ts +0 -161
- package/src/utils/app-info-parser/xml-parser/binary.ts +0 -693
- package/src/utils/app-info-parser/xml-parser/manifest.ts +0 -228
- package/src/utils/app-info-parser/zip.ts +0 -108
- package/src/utils/check-lockfile.ts +0 -93
- package/src/utils/check-plugin.ts +0 -38
- package/src/utils/command-result.ts +0 -24
- package/src/utils/constants.ts +0 -25
- package/src/utils/dep-versions.ts +0 -83
- package/src/utils/git.ts +0 -71
- package/src/utils/hbcTransform.ts +0 -649
- package/src/utils/hermes-base.ts +0 -1137
- package/src/utils/http-helper.ts +0 -152
- package/src/utils/i18n.ts +0 -39
- package/src/utils/index.ts +0 -698
- package/src/utils/latest-version/index.ts +0 -573
- package/src/utils/options.ts +0 -78
- package/src/utils/plugin-config.ts +0 -32
- package/src/utils/runtime.ts +0 -187
- package/src/utils/slim-sourcemap.ts +0 -105
- package/src/utils/zip-entries.ts +0 -209
- package/src/utils/zip-options.ts +0 -178
- package/src/utils/zip-range.ts +0 -727
- package/src/utils/zip-raw-writer.ts +0 -247
- package/src/versions.ts +0 -892
package/src/utils/hermes-base.ts
DELETED
|
@@ -1,1137 +0,0 @@
|
|
|
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 { PassThrough, Readable } from 'stream';
|
|
17
|
-
import { pipeline } from 'stream/promises';
|
|
18
|
-
import { tempDir } from './constants';
|
|
19
|
-
import { getHbcVersion } from './hbcTransform';
|
|
20
|
-
import { t } from './i18n';
|
|
21
|
-
import { enumZipEntries, readEntry } from './zip-entries';
|
|
22
|
-
import {
|
|
23
|
-
fetchZipEntryData,
|
|
24
|
-
openRemoteZip,
|
|
25
|
-
RangeUnsupportedError,
|
|
26
|
-
readRemoteZipEntry,
|
|
27
|
-
ZIP_DEFLATED,
|
|
28
|
-
ZIP_STORED,
|
|
29
|
-
} from './zip-range';
|
|
30
|
-
|
|
31
|
-
export type HermesBaseOption = 'auto' | 'none' | string;
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* The base cannot be obtained whatever the transport or how often it is
|
|
35
|
-
* retried (wrong content on the server, no bundle in the package, ...).
|
|
36
|
-
*/
|
|
37
|
-
export class PermanentBaseError extends Error {}
|
|
38
|
-
/** The fetched bundle's sha256 differs from what the server recorded. */
|
|
39
|
-
export class BundleHashMismatchError extends PermanentBaseError {
|
|
40
|
-
constructor(actual: string, expected: string) {
|
|
41
|
-
super(
|
|
42
|
-
`bundleHash mismatch (${actual.slice(0, 12)} != ${expected.slice(0, 12)})`,
|
|
43
|
-
);
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/** time allowed for a response to start (headers) */
|
|
48
|
-
const FETCH_HEADERS_TIMEOUT_MS = 30_000;
|
|
49
|
-
/** a download that receives nothing for this long is abandoned */
|
|
50
|
-
const STREAM_IDLE_TIMEOUT_MS = 60_000;
|
|
51
|
-
/** cachePut leftovers (`<hash>.<pid>.tmp`) older than this are evicted */
|
|
52
|
-
const STALE_CACHE_TMP_MS = 60 * 60 * 1000;
|
|
53
|
-
|
|
54
|
-
export interface HermesBaseSelection {
|
|
55
|
-
/** path of the bundle (HBC) handed to hermesc as -base-bytecode */
|
|
56
|
-
path: string;
|
|
57
|
-
bytecodeVersion: number;
|
|
58
|
-
bundleHash: string;
|
|
59
|
-
/** server version id when the base came from the server */
|
|
60
|
-
versionId?: number;
|
|
61
|
-
/** server object key of the base artifact when known */
|
|
62
|
-
hash?: string;
|
|
63
|
-
source: 'cache' | 'download' | 'local' | 'latest-version' | 'native-package';
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
/** Metadata attached to version/create so the server can track the chain. */
|
|
67
|
-
export interface HermesBaseMeta {
|
|
68
|
-
bytecodeVersion: number | null;
|
|
69
|
-
baseVersionId: number | null;
|
|
70
|
-
baseHash: string | null;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
// ---------------------------------------------------------------------------
|
|
74
|
-
// hermesc gating
|
|
75
|
-
// ---------------------------------------------------------------------------
|
|
76
|
-
|
|
77
|
-
/**
|
|
78
|
-
* Hermes V1 (static_h) builds before 2025-07-11 carried a delta-mode bug when a
|
|
79
|
-
* delta-produced base is reused; every released `hermes-compiler` is newer, and
|
|
80
|
-
* classic hermesc (HBC ≤96, react-native/sdks or hermes-engine) upgrades kinds
|
|
81
|
-
* in place and was never affected. Anything else is refused.
|
|
82
|
-
*/
|
|
83
|
-
export const MIN_HERMES_COMPILER_BUILD = 250829098;
|
|
84
|
-
export const MIN_HERMES_COMPILER_COMMITLY_DATE = 20250901;
|
|
85
|
-
|
|
86
|
-
export function classifyHermesCommand(hermesCommand: string): {
|
|
87
|
-
allowed: boolean;
|
|
88
|
-
kind: 'classic' | 'hermes-compiler' | 'unknown';
|
|
89
|
-
version?: string;
|
|
90
|
-
reason?: string;
|
|
91
|
-
} {
|
|
92
|
-
const normalized = hermesCommand.split(path.sep).join('/');
|
|
93
|
-
if (
|
|
94
|
-
/\/react-native\/sdks\/hermesc\//.test(normalized) ||
|
|
95
|
-
/\/hermes-engine\//.test(normalized)
|
|
96
|
-
) {
|
|
97
|
-
return { allowed: true, kind: 'classic' };
|
|
98
|
-
}
|
|
99
|
-
const match = /\/hermes-compiler\//.exec(normalized);
|
|
100
|
-
if (match) {
|
|
101
|
-
const packageRoot = normalized.slice(0, match.index + match[0].length);
|
|
102
|
-
let version = '';
|
|
103
|
-
try {
|
|
104
|
-
version = String(
|
|
105
|
-
JSON.parse(
|
|
106
|
-
fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8'),
|
|
107
|
-
).version ?? '',
|
|
108
|
-
);
|
|
109
|
-
} catch {
|
|
110
|
-
return {
|
|
111
|
-
allowed: false,
|
|
112
|
-
kind: 'hermes-compiler',
|
|
113
|
-
reason: 'unreadable hermes-compiler version',
|
|
114
|
-
};
|
|
115
|
-
}
|
|
116
|
-
const build = /^(\d{9})\./.exec(version);
|
|
117
|
-
if (build) {
|
|
118
|
-
const ok = Number(build[1]) >= MIN_HERMES_COMPILER_BUILD;
|
|
119
|
-
return {
|
|
120
|
-
allowed: ok,
|
|
121
|
-
kind: 'hermes-compiler',
|
|
122
|
-
version,
|
|
123
|
-
reason: ok
|
|
124
|
-
? undefined
|
|
125
|
-
: `hermes-compiler ${version} predates the delta-mode fix`,
|
|
126
|
-
};
|
|
127
|
-
}
|
|
128
|
-
const commitly = /^0\.(\d+)\.\d+-commitly-(\d{8})/.exec(version);
|
|
129
|
-
if (commitly) {
|
|
130
|
-
const ok =
|
|
131
|
-
Number(commitly[1]) >= 14 &&
|
|
132
|
-
Number(commitly[2]) >= MIN_HERMES_COMPILER_COMMITLY_DATE;
|
|
133
|
-
return {
|
|
134
|
-
allowed: ok,
|
|
135
|
-
kind: 'hermes-compiler',
|
|
136
|
-
version,
|
|
137
|
-
reason: ok
|
|
138
|
-
? undefined
|
|
139
|
-
: `hermes-compiler ${version} predates the delta-mode fix`,
|
|
140
|
-
};
|
|
141
|
-
}
|
|
142
|
-
const stable = /^0\.(\d+)\.\d+$/.exec(version);
|
|
143
|
-
if (stable) {
|
|
144
|
-
const ok = Number(stable[1]) >= 14;
|
|
145
|
-
return {
|
|
146
|
-
allowed: ok,
|
|
147
|
-
kind: 'hermes-compiler',
|
|
148
|
-
version,
|
|
149
|
-
reason: ok
|
|
150
|
-
? undefined
|
|
151
|
-
: `hermes-compiler ${version} predates the delta-mode fix`,
|
|
152
|
-
};
|
|
153
|
-
}
|
|
154
|
-
return {
|
|
155
|
-
allowed: false,
|
|
156
|
-
kind: 'hermes-compiler',
|
|
157
|
-
version,
|
|
158
|
-
reason: `unrecognized hermes-compiler version ${version}`,
|
|
159
|
-
};
|
|
160
|
-
}
|
|
161
|
-
return {
|
|
162
|
-
allowed: false,
|
|
163
|
-
kind: 'unknown',
|
|
164
|
-
reason: 'hermesc location not recognized',
|
|
165
|
-
};
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
// ---------------------------------------------------------------------------
|
|
169
|
-
// HBC helpers
|
|
170
|
-
// ---------------------------------------------------------------------------
|
|
171
|
-
|
|
172
|
-
export function sha256Hex(data: Buffer): string {
|
|
173
|
-
return createHash('sha256').update(data).digest('hex');
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
/** sha256 of a file, streamed (a cached base can be tens of MB) */
|
|
177
|
-
export async function sha256File(file: string): Promise<string> {
|
|
178
|
-
const hash = createHash('sha256');
|
|
179
|
-
for await (const chunk of fs.createReadStream(file)) hash.update(chunk);
|
|
180
|
-
return hash.digest('hex');
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
/** HBC version from the first bytes of a file, without reading the rest */
|
|
184
|
-
export async function readFileHbcVersion(file: string): Promise<number | null> {
|
|
185
|
-
const header = Buffer.alloc(128);
|
|
186
|
-
const fd = await fs.open(file, 'r');
|
|
187
|
-
try {
|
|
188
|
-
const { bytesRead } = await fs.read(fd, header, 0, 128, 0);
|
|
189
|
-
return getHbcVersion(header.subarray(0, bytesRead));
|
|
190
|
-
} catch {
|
|
191
|
-
return null;
|
|
192
|
-
} finally {
|
|
193
|
-
await fs.close(fd);
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
const PROBE_CACHE_FILE = 'hbc-versions.json';
|
|
198
|
-
const PROBE_CACHE_ENTRIES = 16;
|
|
199
|
-
|
|
200
|
-
/** identity of a hermesc binary for the probe cache: path + size + mtime */
|
|
201
|
-
function probeCacheKey(hermesCommand: string): string | null {
|
|
202
|
-
try {
|
|
203
|
-
const stat = fs.statSync(hermesCommand);
|
|
204
|
-
return `${path.resolve(hermesCommand)}|${stat.size}|${Math.floor(stat.mtimeMs)}`;
|
|
205
|
-
} catch {
|
|
206
|
-
return null;
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
function readProbeCache(): Record<string, number> {
|
|
211
|
-
try {
|
|
212
|
-
const parsed = JSON.parse(
|
|
213
|
-
fs.readFileSync(path.join(cacheDir(), PROBE_CACHE_FILE), 'utf8'),
|
|
214
|
-
);
|
|
215
|
-
return parsed && typeof parsed === 'object' ? parsed : {};
|
|
216
|
-
} catch {
|
|
217
|
-
return {};
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
function writeProbeCache(entries: Record<string, number>): void {
|
|
222
|
-
try {
|
|
223
|
-
const keys = Object.keys(entries);
|
|
224
|
-
// keep the most recently inserted entries only
|
|
225
|
-
const trimmed = Object.fromEntries(
|
|
226
|
-
keys.slice(-PROBE_CACHE_ENTRIES).map((key) => [key, entries[key]]),
|
|
227
|
-
);
|
|
228
|
-
fs.ensureDirSync(cacheDir());
|
|
229
|
-
fs.writeFileSync(
|
|
230
|
-
path.join(cacheDir(), PROBE_CACHE_FILE),
|
|
231
|
-
JSON.stringify(trimmed),
|
|
232
|
-
);
|
|
233
|
-
} catch {
|
|
234
|
-
// the cache is a convenience; probing again next time is fine
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
/**
|
|
239
|
-
* Which HBC version this hermesc emits. The answer is remembered per binary
|
|
240
|
-
* (path, size, mtime) in the cache dir so only the first run of a given
|
|
241
|
-
* hermesc pays for the empty-file compile.
|
|
242
|
-
*/
|
|
243
|
-
export function probeHbcVersion(hermesCommand: string): number | null {
|
|
244
|
-
const key = probeCacheKey(hermesCommand);
|
|
245
|
-
if (key) {
|
|
246
|
-
const cached = readProbeCache()[key];
|
|
247
|
-
if (Number.isInteger(cached) && cached > 0) return cached;
|
|
248
|
-
}
|
|
249
|
-
const version = compileProbe(hermesCommand);
|
|
250
|
-
if (key && version !== null) {
|
|
251
|
-
const { [key]: _stale, ...others } = readProbeCache();
|
|
252
|
-
writeProbeCache({ ...others, [key]: version });
|
|
253
|
-
}
|
|
254
|
-
return version;
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
/** Compile an empty file to learn which HBC version this hermesc emits. */
|
|
258
|
-
function compileProbe(hermesCommand: string): number | null {
|
|
259
|
-
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'rnu-hermes-probe-'));
|
|
260
|
-
try {
|
|
261
|
-
const input = path.join(dir, 'probe.js');
|
|
262
|
-
const output = path.join(dir, 'probe.hbc');
|
|
263
|
-
fs.writeFileSync(input, '');
|
|
264
|
-
const result = spawnSync(
|
|
265
|
-
hermesCommand,
|
|
266
|
-
['-emit-binary', '-out', output, input, '-O', '-w'],
|
|
267
|
-
{ stdio: 'ignore' },
|
|
268
|
-
);
|
|
269
|
-
if (result.status !== 0 || !fs.existsSync(output)) {
|
|
270
|
-
return null;
|
|
271
|
-
}
|
|
272
|
-
const header = Buffer.alloc(128);
|
|
273
|
-
const fd = fs.openSync(output, 'r');
|
|
274
|
-
try {
|
|
275
|
-
fs.readSync(fd, header, 0, 128, 0);
|
|
276
|
-
} finally {
|
|
277
|
-
fs.closeSync(fd);
|
|
278
|
-
}
|
|
279
|
-
return getHbcVersion(header);
|
|
280
|
-
} catch {
|
|
281
|
-
return null;
|
|
282
|
-
} finally {
|
|
283
|
-
fs.removeSync(dir);
|
|
284
|
-
}
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
export const BUNDLE_ENTRY_NAMES = [
|
|
288
|
-
'index.bundlejs',
|
|
289
|
-
'main.jsbundle',
|
|
290
|
-
'bundle.harmony.js',
|
|
291
|
-
];
|
|
292
|
-
const APK_BUNDLE = /^assets\/index\.android\.bundle$/;
|
|
293
|
-
const IPA_BUNDLE = /^payload\/[^/]+\.app\/main\.jsbundle$/i;
|
|
294
|
-
|
|
295
|
-
export type BaseArtifactType = 'ppk' | 'apk' | 'ipa' | 'app';
|
|
296
|
-
|
|
297
|
-
/** Which zip entry holds the JS/HBC bundle in each kind of artifact. */
|
|
298
|
-
export function bundleEntryMatcher(
|
|
299
|
-
artifactType: BaseArtifactType,
|
|
300
|
-
): (name: string) => boolean {
|
|
301
|
-
switch (artifactType) {
|
|
302
|
-
case 'apk':
|
|
303
|
-
return (name) => APK_BUNDLE.test(name);
|
|
304
|
-
case 'ipa':
|
|
305
|
-
return (name) => IPA_BUNDLE.test(name.toLowerCase());
|
|
306
|
-
default:
|
|
307
|
-
return (name) => BUNDLE_ENTRY_NAMES.includes(name);
|
|
308
|
-
}
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
/**
|
|
312
|
-
* Extract the JS/HBC bundle from a local artifact: a raw bundle file, a ppk,
|
|
313
|
-
* or a native package (apk / ipa / harmony app). Returns null when not found.
|
|
314
|
-
*/
|
|
315
|
-
export async function extractBundleFromArchive(
|
|
316
|
-
filePath: string,
|
|
317
|
-
): Promise<Buffer | null> {
|
|
318
|
-
const ext = path.extname(filePath).toLowerCase();
|
|
319
|
-
if (
|
|
320
|
-
ext === '.hbc' ||
|
|
321
|
-
ext === '.bundle' ||
|
|
322
|
-
ext === '.jsbundle' ||
|
|
323
|
-
ext === '.bundlejs' ||
|
|
324
|
-
ext === '.js'
|
|
325
|
-
) {
|
|
326
|
-
return fs.readFile(filePath);
|
|
327
|
-
}
|
|
328
|
-
if (ext === '.ppk' || ext === '.apk' || ext === '.ipa') {
|
|
329
|
-
return readFirstZipEntry(
|
|
330
|
-
filePath,
|
|
331
|
-
bundleEntryMatcher(ext.slice(1) as BaseArtifactType),
|
|
332
|
-
);
|
|
333
|
-
}
|
|
334
|
-
if (ext === '.app') {
|
|
335
|
-
// harmony .app wraps .hap archives; reuse the existing parser
|
|
336
|
-
const { default: AppInfoParser } = await import('./app-info-parser');
|
|
337
|
-
const parser = new AppInfoParser(filePath);
|
|
338
|
-
const [bundle] = await parser.parser.getEntriesFromHarmonyApp([
|
|
339
|
-
/^resources\/rawfile\/bundle\.harmony\.js$/,
|
|
340
|
-
]);
|
|
341
|
-
return bundle ?? null;
|
|
342
|
-
}
|
|
343
|
-
// unknown extension: try as zip, then as raw file
|
|
344
|
-
const fromZip = await readFirstZipEntry(filePath, (name) =>
|
|
345
|
-
BUNDLE_ENTRY_NAMES.includes(name),
|
|
346
|
-
).catch(() => null);
|
|
347
|
-
return fromZip ?? fs.readFile(filePath);
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
async function readFirstZipEntry(
|
|
351
|
-
zipPath: string,
|
|
352
|
-
matches: (name: string) => boolean,
|
|
353
|
-
): Promise<Buffer | null> {
|
|
354
|
-
let found: Buffer | null = null;
|
|
355
|
-
await enumZipEntries(zipPath, async (entry, zipFile) => {
|
|
356
|
-
if (!found && matches(entry.fileName)) {
|
|
357
|
-
found = await readEntry(entry, zipFile);
|
|
358
|
-
}
|
|
359
|
-
});
|
|
360
|
-
return found;
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
// ---------------------------------------------------------------------------
|
|
364
|
-
// cache (sha256-named bundles)
|
|
365
|
-
// ---------------------------------------------------------------------------
|
|
366
|
-
|
|
367
|
-
export const DEFAULT_CACHE_MAX_BYTES = 500 * 1024 * 1024;
|
|
368
|
-
export const DEFAULT_CACHE_MAX_FILES = 20;
|
|
369
|
-
|
|
370
|
-
export function cacheDir(): string {
|
|
371
|
-
return process.env.PUSHY_CACHE_DIR || path.join(tempDir, 'cache');
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
export function tmpDir(): string {
|
|
375
|
-
return path.join(tempDir, 'tmp');
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
export function cacheLimits(overrideMaxMb?: number) {
|
|
379
|
-
const envMb = Number(process.env.PUSHY_CACHE_MAX_MB);
|
|
380
|
-
const maxBytes =
|
|
381
|
-
overrideMaxMb && overrideMaxMb > 0
|
|
382
|
-
? overrideMaxMb * 1024 * 1024
|
|
383
|
-
: Number.isFinite(envMb) && envMb > 0
|
|
384
|
-
? envMb * 1024 * 1024
|
|
385
|
-
: DEFAULT_CACHE_MAX_BYTES;
|
|
386
|
-
return { maxBytes, maxFiles: DEFAULT_CACHE_MAX_FILES };
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
/** Returns the cached bundle path when present and its sha256 still matches. */
|
|
390
|
-
export async function cacheLookup(bundleHash: string): Promise<string | null> {
|
|
391
|
-
if (!/^[0-9a-f]{64}$/.test(bundleHash)) return null;
|
|
392
|
-
const file = path.join(cacheDir(), bundleHash);
|
|
393
|
-
if (!(await fs.pathExists(file))) return null;
|
|
394
|
-
if ((await sha256File(file).catch(() => '')) !== bundleHash) {
|
|
395
|
-
// corrupt entry: never trust cache content
|
|
396
|
-
await fs.remove(file).catch(() => {});
|
|
397
|
-
return null;
|
|
398
|
-
}
|
|
399
|
-
const now = new Date();
|
|
400
|
-
await fs.utimes(file, now, now).catch(() => {});
|
|
401
|
-
return file;
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
/** Store a bundle under its sha256 (LRU-evicting to the configured limits). */
|
|
405
|
-
export async function cachePut(
|
|
406
|
-
bundle: Buffer,
|
|
407
|
-
maxMb?: number,
|
|
408
|
-
knownHash?: string,
|
|
409
|
-
): Promise<{ path: string; bundleHash: string }> {
|
|
410
|
-
const bundleHash = knownHash ?? sha256Hex(bundle);
|
|
411
|
-
const dir = cacheDir();
|
|
412
|
-
await fs.ensureDir(dir);
|
|
413
|
-
const file = path.join(dir, bundleHash);
|
|
414
|
-
if (!(await fs.pathExists(file))) {
|
|
415
|
-
const tmp = `${file}.${process.pid}.tmp`;
|
|
416
|
-
await fs.writeFile(tmp, bundle);
|
|
417
|
-
await fs.rename(tmp, file);
|
|
418
|
-
} else {
|
|
419
|
-
const now = new Date();
|
|
420
|
-
await fs.utimes(file, now, now).catch(() => {});
|
|
421
|
-
}
|
|
422
|
-
await enforceCacheLimits(maxMb, bundleHash);
|
|
423
|
-
return { path: file, bundleHash };
|
|
424
|
-
}
|
|
425
|
-
|
|
426
|
-
export async function enforceCacheLimits(
|
|
427
|
-
maxMb?: number,
|
|
428
|
-
keep?: string,
|
|
429
|
-
): Promise<void> {
|
|
430
|
-
const dir = cacheDir();
|
|
431
|
-
if (!(await fs.pathExists(dir))) return;
|
|
432
|
-
const { maxBytes, maxFiles } = cacheLimits(maxMb);
|
|
433
|
-
const entries: { name: string; size: number; mtime: number }[] = [];
|
|
434
|
-
const staleTmpCutoff = Date.now() - STALE_CACHE_TMP_MS;
|
|
435
|
-
for (const name of await fs.readdir(dir)) {
|
|
436
|
-
const isTmp = isCacheTmpName(name);
|
|
437
|
-
if (!isTmp && !/^[0-9a-f]{64}$/.test(name)) continue;
|
|
438
|
-
const stat = await fs.stat(path.join(dir, name)).catch(() => null);
|
|
439
|
-
if (!stat?.isFile()) continue;
|
|
440
|
-
if (isTmp) {
|
|
441
|
-
// an interrupted cachePut; nothing will ever rename it into place
|
|
442
|
-
if (stat.mtimeMs < staleTmpCutoff)
|
|
443
|
-
await fs.remove(path.join(dir, name)).catch(() => {});
|
|
444
|
-
continue;
|
|
445
|
-
}
|
|
446
|
-
entries.push({ name, size: stat.size, mtime: stat.mtimeMs });
|
|
447
|
-
}
|
|
448
|
-
entries.sort((a, b) => b.mtime - a.mtime); // newest first
|
|
449
|
-
let total = 0;
|
|
450
|
-
let count = 0;
|
|
451
|
-
for (const entry of entries) {
|
|
452
|
-
total += entry.size;
|
|
453
|
-
count += 1;
|
|
454
|
-
if (entry.name !== keep && (total > maxBytes || count > maxFiles)) {
|
|
455
|
-
await fs.remove(path.join(dir, entry.name)).catch(() => {});
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
/** `<sha256>.<pid>.tmp`, the staging name cachePut writes before renaming */
|
|
461
|
-
function isCacheTmpName(name: string): boolean {
|
|
462
|
-
return /^[0-9a-f]{64}\.\d+\.tmp$/.test(name);
|
|
463
|
-
}
|
|
464
|
-
|
|
465
|
-
/** Remove every cached bundle (and staging leftovers); returns the bundle count. */
|
|
466
|
-
export async function cleanCache(): Promise<number> {
|
|
467
|
-
const dir = cacheDir();
|
|
468
|
-
if (!(await fs.pathExists(dir))) return 0;
|
|
469
|
-
let bundles = 0;
|
|
470
|
-
for (const name of await fs.readdir(dir)) {
|
|
471
|
-
const isBundle = /^[0-9a-f]{64}$/.test(name);
|
|
472
|
-
if (!isBundle && !isCacheTmpName(name)) continue;
|
|
473
|
-
await fs.remove(path.join(dir, name));
|
|
474
|
-
if (isBundle) bundles += 1;
|
|
475
|
-
}
|
|
476
|
-
return bundles;
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
export async function cacheStats(): Promise<{
|
|
480
|
-
dir: string;
|
|
481
|
-
files: number;
|
|
482
|
-
bytes: number;
|
|
483
|
-
}> {
|
|
484
|
-
const dir = cacheDir();
|
|
485
|
-
let files = 0;
|
|
486
|
-
let bytes = 0;
|
|
487
|
-
if (await fs.pathExists(dir)) {
|
|
488
|
-
for (const name of await fs.readdir(dir)) {
|
|
489
|
-
if (!/^[0-9a-f]{64}$/.test(name)) continue;
|
|
490
|
-
const stat = await fs.stat(path.join(dir, name)).catch(() => null);
|
|
491
|
-
if (stat?.isFile()) {
|
|
492
|
-
files += 1;
|
|
493
|
-
bytes += stat.size;
|
|
494
|
-
}
|
|
495
|
-
}
|
|
496
|
-
}
|
|
497
|
-
return { dir, files, bytes };
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
/** Remove leftovers of interrupted runs (older than 24h) from the tmp dir. */
|
|
501
|
-
export async function cleanStaleTmp(
|
|
502
|
-
maxAgeMs = 24 * 60 * 60 * 1000,
|
|
503
|
-
): Promise<void> {
|
|
504
|
-
const dir = tmpDir();
|
|
505
|
-
if (!(await fs.pathExists(dir))) return;
|
|
506
|
-
const cutoff = Date.now() - maxAgeMs;
|
|
507
|
-
for (const name of await fs.readdir(dir)) {
|
|
508
|
-
const file = path.join(dir, name);
|
|
509
|
-
const stat = await fs.stat(file).catch(() => null);
|
|
510
|
-
if (stat && stat.mtimeMs < cutoff) await fs.remove(file).catch(() => {});
|
|
511
|
-
}
|
|
512
|
-
}
|
|
513
|
-
|
|
514
|
-
// ---------------------------------------------------------------------------
|
|
515
|
-
// download
|
|
516
|
-
// ---------------------------------------------------------------------------
|
|
517
|
-
|
|
518
|
-
export async function downloadToFile(
|
|
519
|
-
url: string,
|
|
520
|
-
destination: string,
|
|
521
|
-
): Promise<void> {
|
|
522
|
-
const controller = new AbortController();
|
|
523
|
-
const headersTimer = setTimeout(
|
|
524
|
-
() => controller.abort(new Error('timeout waiting for response')),
|
|
525
|
-
FETCH_HEADERS_TIMEOUT_MS,
|
|
526
|
-
);
|
|
527
|
-
let response: Response;
|
|
528
|
-
try {
|
|
529
|
-
response = await fetch(url, { signal: controller.signal });
|
|
530
|
-
} finally {
|
|
531
|
-
clearTimeout(headersTimer);
|
|
532
|
-
}
|
|
533
|
-
if (!response.ok || !response.body) {
|
|
534
|
-
throw new Error(`download failed: HTTP ${response.status} ${url}`);
|
|
535
|
-
}
|
|
536
|
-
await saveResponse(response, destination, controller);
|
|
537
|
-
}
|
|
538
|
-
|
|
539
|
-
// ---------------------------------------------------------------------------
|
|
540
|
-
// resolution
|
|
541
|
-
// ---------------------------------------------------------------------------
|
|
542
|
-
|
|
543
|
-
export interface HermesBaseServerRecord {
|
|
544
|
-
versionId?: number | null;
|
|
545
|
-
hash: string;
|
|
546
|
-
artifactType?: BaseArtifactType;
|
|
547
|
-
bundleHash?: string | null;
|
|
548
|
-
bytecodeVersion?: number | null;
|
|
549
|
-
url: string;
|
|
550
|
-
/**
|
|
551
|
-
* Location of the bundle's compressed bytes inside the ppk, reported by the
|
|
552
|
-
* publishing CLI; lets the base be fetched with a single HTTP Range request.
|
|
553
|
-
*/
|
|
554
|
-
bundleOffset?: number | null;
|
|
555
|
-
bundleCompressedSize?: number | null;
|
|
556
|
-
/** zip compression method: 0 stored, 8 deflate */
|
|
557
|
-
bundleCompression?: number | null;
|
|
558
|
-
}
|
|
559
|
-
|
|
560
|
-
interface FetchedBaseBundle {
|
|
561
|
-
bundle: Buffer;
|
|
562
|
-
/** sha256 of `bundle`, computed once here */
|
|
563
|
-
bundleHash: string;
|
|
564
|
-
/** how the bytes were obtained, for the log line */
|
|
565
|
-
transport: 'range-entry' | 'range-zip' | 'full';
|
|
566
|
-
fetchedBytes?: number;
|
|
567
|
-
totalBytes?: number;
|
|
568
|
-
}
|
|
569
|
-
|
|
570
|
-
function hasBundleLocation(record: HermesBaseServerRecord): boolean {
|
|
571
|
-
return (
|
|
572
|
-
record.bundleOffset != null &&
|
|
573
|
-
record.bundleCompressedSize != null &&
|
|
574
|
-
record.bundleCompression != null &&
|
|
575
|
-
(record.bundleCompression === ZIP_STORED ||
|
|
576
|
-
record.bundleCompression === ZIP_DEFLATED)
|
|
577
|
-
);
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
/**
|
|
581
|
-
* Stream a response body to disk, giving up when no bytes arrive for
|
|
582
|
-
* STREAM_IDLE_TIMEOUT_MS. `controller` is the one the request was made with
|
|
583
|
-
* (aborting it also tears down the socket); a foreign response gets its own.
|
|
584
|
-
*/
|
|
585
|
-
async function saveResponse(
|
|
586
|
-
response: Response,
|
|
587
|
-
destination: string,
|
|
588
|
-
controller = new AbortController(),
|
|
589
|
-
): Promise<void> {
|
|
590
|
-
if (!response.body) throw new Error('empty response body');
|
|
591
|
-
await fs.ensureDir(path.dirname(destination));
|
|
592
|
-
const abort = () =>
|
|
593
|
-
controller.abort(
|
|
594
|
-
new Error(`download stalled for ${STREAM_IDLE_TIMEOUT_MS / 1000}s`),
|
|
595
|
-
);
|
|
596
|
-
let idle = setTimeout(abort, STREAM_IDLE_TIMEOUT_MS);
|
|
597
|
-
const watchdog = new PassThrough({
|
|
598
|
-
transform(chunk, _encoding, callback) {
|
|
599
|
-
clearTimeout(idle);
|
|
600
|
-
idle = setTimeout(abort, STREAM_IDLE_TIMEOUT_MS);
|
|
601
|
-
callback(null, chunk);
|
|
602
|
-
},
|
|
603
|
-
});
|
|
604
|
-
try {
|
|
605
|
-
await pipeline(
|
|
606
|
-
Readable.fromWeb(response.body as any),
|
|
607
|
-
watchdog,
|
|
608
|
-
fs.createWriteStream(destination),
|
|
609
|
-
{ signal: controller.signal },
|
|
610
|
-
);
|
|
611
|
-
} finally {
|
|
612
|
-
clearTimeout(idle);
|
|
613
|
-
}
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
/**
|
|
617
|
-
* Obtain the base bundle with as little traffic as possible, in order:
|
|
618
|
-
* 1. one Range request for the bundle's compressed bytes when the server
|
|
619
|
-
* knows their location (ppk / apk / ipa published by a CLI that
|
|
620
|
-
* reported it);
|
|
621
|
-
* 2. the archive's central directory over Range, then just the bundle
|
|
622
|
-
* entry (any zip: ppk, apk, ipa — harmony .app nests a second zip and
|
|
623
|
-
* is skipped);
|
|
624
|
-
* 3. the whole archive, as before.
|
|
625
|
-
* A server that ignores Range (HTTP 200) streams the full archive into
|
|
626
|
-
* `archive` without a second request. Every result is verified against
|
|
627
|
-
* `record.bundleHash`. A mismatch of the located bytes (1) may only mean the
|
|
628
|
-
* recorded location is stale, so the directory transport (2) still runs; a
|
|
629
|
-
* mismatch of the entry itself (2, 3) is final — the same bytes would come
|
|
630
|
-
* back however they are fetched — and raises BundleHashMismatchError.
|
|
631
|
-
*/
|
|
632
|
-
export async function fetchBaseBundle(
|
|
633
|
-
record: HermesBaseServerRecord,
|
|
634
|
-
artifactType: BaseArtifactType,
|
|
635
|
-
archive: string,
|
|
636
|
-
log: (message: string) => void = () => {},
|
|
637
|
-
): Promise<FetchedBaseBundle> {
|
|
638
|
-
const matches = bundleEntryMatcher(artifactType);
|
|
639
|
-
const verified = (
|
|
640
|
-
bundle: Buffer | null,
|
|
641
|
-
): { bundle: Buffer; bundleHash: string } => {
|
|
642
|
-
if (!bundle) throw new PermanentBaseError('bundle entry not found');
|
|
643
|
-
const bundleHash = sha256Hex(bundle);
|
|
644
|
-
if (record.bundleHash && bundleHash !== record.bundleHash) {
|
|
645
|
-
throw new BundleHashMismatchError(bundleHash, record.bundleHash);
|
|
646
|
-
}
|
|
647
|
-
return { bundle, bundleHash };
|
|
648
|
-
};
|
|
649
|
-
const fromFullResponse = async (
|
|
650
|
-
response: Response,
|
|
651
|
-
): Promise<FetchedBaseBundle> => {
|
|
652
|
-
await saveResponse(response, archive);
|
|
653
|
-
return {
|
|
654
|
-
...verified(await extractBundleFromArchive(archive)),
|
|
655
|
-
transport: 'full',
|
|
656
|
-
};
|
|
657
|
-
};
|
|
658
|
-
const skip = (reason: string) =>
|
|
659
|
-
log(t('hermesBaseRangeFallback', { reason }));
|
|
660
|
-
|
|
661
|
-
// harmony .app nests the bundle in a second zip, so a location inside the
|
|
662
|
-
// outer archive is never reported for it
|
|
663
|
-
if (artifactType !== 'app' && hasBundleLocation(record)) {
|
|
664
|
-
try {
|
|
665
|
-
const { data, fetchedBytes, totalBytes } = await fetchZipEntryData(
|
|
666
|
-
record.url,
|
|
667
|
-
{
|
|
668
|
-
dataOffset: record.bundleOffset as number,
|
|
669
|
-
compressedSize: record.bundleCompressedSize as number,
|
|
670
|
-
compressionMethod: record.bundleCompression as number,
|
|
671
|
-
},
|
|
672
|
-
);
|
|
673
|
-
return {
|
|
674
|
-
...verified(data),
|
|
675
|
-
transport: 'range-entry',
|
|
676
|
-
fetchedBytes,
|
|
677
|
-
totalBytes,
|
|
678
|
-
};
|
|
679
|
-
} catch (error: any) {
|
|
680
|
-
if (error instanceof RangeUnsupportedError) {
|
|
681
|
-
skip('server ignores Range');
|
|
682
|
-
return fromFullResponse(error.response);
|
|
683
|
-
}
|
|
684
|
-
skip(`entry range: ${error?.message ?? error}`);
|
|
685
|
-
}
|
|
686
|
-
}
|
|
687
|
-
|
|
688
|
-
if (artifactType !== 'app') {
|
|
689
|
-
try {
|
|
690
|
-
const remote = await openRemoteZip(record.url);
|
|
691
|
-
if (remote.kind === 'full') {
|
|
692
|
-
skip('server ignores Range');
|
|
693
|
-
return fromFullResponse(remote.response);
|
|
694
|
-
}
|
|
695
|
-
const bundle = await readRemoteZipEntry(
|
|
696
|
-
remote.zipFile,
|
|
697
|
-
matches,
|
|
698
|
-
remote.reader,
|
|
699
|
-
);
|
|
700
|
-
return {
|
|
701
|
-
...verified(bundle),
|
|
702
|
-
transport: 'range-zip',
|
|
703
|
-
fetchedBytes: remote.reader.fetchedBytes,
|
|
704
|
-
totalBytes: remote.reader.totalSize,
|
|
705
|
-
};
|
|
706
|
-
} catch (error: any) {
|
|
707
|
-
if (error instanceof RangeUnsupportedError) {
|
|
708
|
-
skip('server ignores Range');
|
|
709
|
-
return fromFullResponse(error.response);
|
|
710
|
-
}
|
|
711
|
-
// the real entry was read and is not the recorded one: final
|
|
712
|
-
if (error instanceof PermanentBaseError) throw error;
|
|
713
|
-
skip(`zip range: ${error?.message ?? error}`);
|
|
714
|
-
}
|
|
715
|
-
}
|
|
716
|
-
|
|
717
|
-
await downloadToFile(record.url, archive);
|
|
718
|
-
return {
|
|
719
|
-
...verified(await extractBundleFromArchive(archive)),
|
|
720
|
-
transport: 'full',
|
|
721
|
-
};
|
|
722
|
-
}
|
|
723
|
-
|
|
724
|
-
export interface ResolveHermesBaseParams {
|
|
725
|
-
option: HermesBaseOption;
|
|
726
|
-
hermesCommand: string;
|
|
727
|
-
bytecodeVersion: number;
|
|
728
|
-
appId?: string;
|
|
729
|
-
cacheMaxMb?: number;
|
|
730
|
-
/**
|
|
731
|
-
* server lookup; returns null when the app has no usable base. The server
|
|
732
|
-
* itself falls back to the newest legacy version, then the newest native
|
|
733
|
-
* package (bytecodeVersion is null and verified here after download).
|
|
734
|
-
*/
|
|
735
|
-
fetchBase: (
|
|
736
|
-
appId: string,
|
|
737
|
-
bytecodeVersion: number,
|
|
738
|
-
) => Promise<HermesBaseServerRecord | null>;
|
|
739
|
-
log?: (message: string) => void;
|
|
740
|
-
}
|
|
741
|
-
|
|
742
|
-
/**
|
|
743
|
-
* Pick and materialize the base bundle for this compile. Returns null (with
|
|
744
|
-
* the reason logged) whenever a base cannot be used; callers then compile
|
|
745
|
-
* without one.
|
|
746
|
-
*/
|
|
747
|
-
export async function resolveHermesBase(
|
|
748
|
-
params: ResolveHermesBaseParams,
|
|
749
|
-
): Promise<HermesBaseSelection | null> {
|
|
750
|
-
const log = params.log ?? (() => {});
|
|
751
|
-
const { option, bytecodeVersion } = params;
|
|
752
|
-
if (option === 'none') {
|
|
753
|
-
log(t('hermesBaseNone', { reason: 'disabled by option' }));
|
|
754
|
-
return null;
|
|
755
|
-
}
|
|
756
|
-
if (option !== 'auto') {
|
|
757
|
-
// explicit local artifact
|
|
758
|
-
try {
|
|
759
|
-
const bundle = await extractBundleFromArchive(option);
|
|
760
|
-
if (!bundle) throw new Error('bundle entry not found');
|
|
761
|
-
const version = getHbcVersion(bundle);
|
|
762
|
-
if (version !== bytecodeVersion) {
|
|
763
|
-
throw new Error(
|
|
764
|
-
`HBC version ${version ?? 'n/a'} != ${bytecodeVersion}`,
|
|
765
|
-
);
|
|
766
|
-
}
|
|
767
|
-
const cached = await cachePut(bundle, params.cacheMaxMb);
|
|
768
|
-
log(t('hermesBaseUsing', { source: option, version: bytecodeVersion }));
|
|
769
|
-
return {
|
|
770
|
-
path: cached.path,
|
|
771
|
-
bytecodeVersion,
|
|
772
|
-
bundleHash: cached.bundleHash,
|
|
773
|
-
source: 'local',
|
|
774
|
-
};
|
|
775
|
-
} catch (error: any) {
|
|
776
|
-
log(
|
|
777
|
-
t('hermesBaseNone', {
|
|
778
|
-
reason: `${option}: ${error?.message ?? error}`,
|
|
779
|
-
}),
|
|
780
|
-
);
|
|
781
|
-
return null;
|
|
782
|
-
}
|
|
783
|
-
}
|
|
784
|
-
if (!params.appId) {
|
|
785
|
-
log(t('hermesBaseNone', { reason: 'app not selected' }));
|
|
786
|
-
return null;
|
|
787
|
-
}
|
|
788
|
-
let record: HermesBaseServerRecord | null = null;
|
|
789
|
-
try {
|
|
790
|
-
record = await retryOnce(() =>
|
|
791
|
-
params.fetchBase(params.appId as string, bytecodeVersion),
|
|
792
|
-
);
|
|
793
|
-
} catch (error: any) {
|
|
794
|
-
log(
|
|
795
|
-
t('hermesBaseNone', {
|
|
796
|
-
reason: `server lookup failed: ${error?.message ?? error}`,
|
|
797
|
-
}),
|
|
798
|
-
);
|
|
799
|
-
return null;
|
|
800
|
-
}
|
|
801
|
-
const source: HermesBaseSelection['source'] =
|
|
802
|
-
record?.artifactType && record.artifactType !== 'ppk'
|
|
803
|
-
? 'native-package'
|
|
804
|
-
: record?.bytecodeVersion == null
|
|
805
|
-
? 'latest-version'
|
|
806
|
-
: 'download';
|
|
807
|
-
if (!record) {
|
|
808
|
-
log(t('hermesBaseNone', { reason: 'no published version yet' }));
|
|
809
|
-
return null;
|
|
810
|
-
}
|
|
811
|
-
if (
|
|
812
|
-
record.bytecodeVersion != null &&
|
|
813
|
-
record.bytecodeVersion !== bytecodeVersion
|
|
814
|
-
) {
|
|
815
|
-
log(
|
|
816
|
-
t('hermesBaseNone', {
|
|
817
|
-
reason: `server base is HBC ${record.bytecodeVersion}, need ${bytecodeVersion}`,
|
|
818
|
-
}),
|
|
819
|
-
);
|
|
820
|
-
return null;
|
|
821
|
-
}
|
|
822
|
-
// 1. cache by bundleHash
|
|
823
|
-
if (record.bundleHash) {
|
|
824
|
-
const hit = await cacheLookup(record.bundleHash);
|
|
825
|
-
if (hit && record.bytecodeVersion == null) {
|
|
826
|
-
// the server does not know the HBC version (legacy version, native
|
|
827
|
-
// package): the download path checks it, the cache path must too
|
|
828
|
-
const version = await readFileHbcVersion(hit);
|
|
829
|
-
if (version !== bytecodeVersion) {
|
|
830
|
-
log(
|
|
831
|
-
t('hermesBaseNone', {
|
|
832
|
-
reason: `cached base is HBC ${version ?? 'n/a'}, need ${bytecodeVersion}`,
|
|
833
|
-
}),
|
|
834
|
-
);
|
|
835
|
-
return null;
|
|
836
|
-
}
|
|
837
|
-
}
|
|
838
|
-
if (hit) {
|
|
839
|
-
log(
|
|
840
|
-
t('hermesBaseUsing', {
|
|
841
|
-
source: `cache ${record.bundleHash.slice(0, 12)}${record.versionId == null ? '' : ` (version ${record.versionId})`}`,
|
|
842
|
-
version: bytecodeVersion,
|
|
843
|
-
}),
|
|
844
|
-
);
|
|
845
|
-
return {
|
|
846
|
-
path: hit,
|
|
847
|
-
bytecodeVersion,
|
|
848
|
-
bundleHash: record.bundleHash,
|
|
849
|
-
versionId: record.versionId ?? undefined,
|
|
850
|
-
hash: record.hash,
|
|
851
|
-
source: 'cache',
|
|
852
|
-
};
|
|
853
|
-
}
|
|
854
|
-
}
|
|
855
|
-
// 2. download, extract, verify, cache — transport errors get a second try
|
|
856
|
-
for (let attempt = 1; attempt <= 2; attempt++) {
|
|
857
|
-
const dir = tmpDir();
|
|
858
|
-
await fs.ensureDir(dir);
|
|
859
|
-
const artifactType: BaseArtifactType = [
|
|
860
|
-
'ppk',
|
|
861
|
-
'apk',
|
|
862
|
-
'ipa',
|
|
863
|
-
'app',
|
|
864
|
-
].includes(record.artifactType ?? '')
|
|
865
|
-
? (record.artifactType as BaseArtifactType)
|
|
866
|
-
: 'ppk';
|
|
867
|
-
const archive = path.join(
|
|
868
|
-
dir,
|
|
869
|
-
`base-${process.pid}-${Date.now()}-${attempt}.${artifactType}`,
|
|
870
|
-
);
|
|
871
|
-
try {
|
|
872
|
-
log(t('hermesBaseDownloading', { url: record.url }));
|
|
873
|
-
const fetched = await fetchBaseBundle(record, artifactType, archive, log);
|
|
874
|
-
const { bundle, bundleHash: actualHash } = fetched;
|
|
875
|
-
if (fetched.transport !== 'full') {
|
|
876
|
-
log(
|
|
877
|
-
t('hermesBaseRangeFetched', {
|
|
878
|
-
fetchedKb: Math.ceil((fetched.fetchedBytes ?? 0) / 1024),
|
|
879
|
-
totalKb: Math.ceil((fetched.totalBytes ?? 0) / 1024),
|
|
880
|
-
}),
|
|
881
|
-
);
|
|
882
|
-
}
|
|
883
|
-
const version = getHbcVersion(bundle);
|
|
884
|
-
if (version !== bytecodeVersion) {
|
|
885
|
-
log(
|
|
886
|
-
t('hermesBaseNone', {
|
|
887
|
-
reason: `downloaded base is HBC ${version ?? 'n/a'}, need ${bytecodeVersion}`,
|
|
888
|
-
}),
|
|
889
|
-
);
|
|
890
|
-
return null;
|
|
891
|
-
}
|
|
892
|
-
const cached = await cachePut(bundle, params.cacheMaxMb, actualHash);
|
|
893
|
-
log(
|
|
894
|
-
t('hermesBaseUsing', {
|
|
895
|
-
source:
|
|
896
|
-
record.versionId == null
|
|
897
|
-
? `native package ${record.hash.slice(0, 8)}`
|
|
898
|
-
: `version ${record.versionId} ${record.hash.slice(0, 8)}`,
|
|
899
|
-
version: bytecodeVersion,
|
|
900
|
-
}),
|
|
901
|
-
);
|
|
902
|
-
return {
|
|
903
|
-
path: cached.path,
|
|
904
|
-
bytecodeVersion,
|
|
905
|
-
bundleHash: cached.bundleHash,
|
|
906
|
-
versionId: record.versionId ?? undefined,
|
|
907
|
-
hash: record.hash,
|
|
908
|
-
source,
|
|
909
|
-
};
|
|
910
|
-
} catch (error: any) {
|
|
911
|
-
if (attempt === 2 || error instanceof PermanentBaseError) {
|
|
912
|
-
log(
|
|
913
|
-
t('hermesBaseNone', {
|
|
914
|
-
reason: `download/verify failed: ${error?.message ?? error}`,
|
|
915
|
-
}),
|
|
916
|
-
);
|
|
917
|
-
return null;
|
|
918
|
-
}
|
|
919
|
-
} finally {
|
|
920
|
-
await fs.remove(archive).catch(() => {});
|
|
921
|
-
}
|
|
922
|
-
}
|
|
923
|
-
return null;
|
|
924
|
-
}
|
|
925
|
-
|
|
926
|
-
/** one retry after a short pause, for transient network failures */
|
|
927
|
-
async function retryOnce<T>(action: () => Promise<T>): Promise<T> {
|
|
928
|
-
try {
|
|
929
|
-
return await action();
|
|
930
|
-
} catch {
|
|
931
|
-
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
932
|
-
return action();
|
|
933
|
-
}
|
|
934
|
-
}
|
|
935
|
-
|
|
936
|
-
export function hermescArgsWithBase(
|
|
937
|
-
baseArgs: string[],
|
|
938
|
-
basePath: string | null,
|
|
939
|
-
): string[] {
|
|
940
|
-
return basePath ? [...baseArgs, `-base-bytecode=${basePath}`] : baseArgs;
|
|
941
|
-
}
|
|
942
|
-
|
|
943
|
-
export function hermesBaseMeta(
|
|
944
|
-
selection: HermesBaseSelection | null,
|
|
945
|
-
bytecodeVersion: number | null,
|
|
946
|
-
): HermesBaseMeta {
|
|
947
|
-
return {
|
|
948
|
-
bytecodeVersion,
|
|
949
|
-
baseVersionId: selection?.versionId ?? null,
|
|
950
|
-
baseHash: selection?.hash ?? null,
|
|
951
|
-
};
|
|
952
|
-
}
|
|
953
|
-
|
|
954
|
-
// ---------------------------------------------------------------------------
|
|
955
|
-
// equivalence check (streams two `-dump-bytecode` outputs, never writes them)
|
|
956
|
-
// ---------------------------------------------------------------------------
|
|
957
|
-
|
|
958
|
-
const STRING_TABLE_LINE = /^\s*[is](\d+)\[[^\]]*\](?: #[0-9A-F]+)?: (.*)$/;
|
|
959
|
-
|
|
960
|
-
/**
|
|
961
|
-
* Normalize one disassembly line so that a delta-mode compile and a plain
|
|
962
|
-
* compile of the same source compare equal: string IDs are renumbered, literal
|
|
963
|
-
* buffers are laid out differently (offsets, short/long variants), and jump
|
|
964
|
-
* distances follow instruction widths. Everything else must match exactly.
|
|
965
|
-
*/
|
|
966
|
-
export function normalizeDisassemblyLine(
|
|
967
|
-
line: string,
|
|
968
|
-
strings: Map<number, string>,
|
|
969
|
-
): string | null {
|
|
970
|
-
// Cheap dispatch on the opcode before touching any regex: dumps run to
|
|
971
|
-
// millions of lines and only a handful of instructions need rewriting.
|
|
972
|
-
let indent = 0;
|
|
973
|
-
while (indent < line.length && isSpace(line.charCodeAt(indent))) indent++;
|
|
974
|
-
let opEnd = indent;
|
|
975
|
-
while (opEnd < line.length && isLetter(line.charCodeAt(opEnd))) opEnd++;
|
|
976
|
-
const opcode = line.slice(indent, opEnd);
|
|
977
|
-
if (opcode === 'Offset' && line.startsWith('Offset in debug table', indent)) {
|
|
978
|
-
return null;
|
|
979
|
-
}
|
|
980
|
-
let m: RegExpExecArray | null;
|
|
981
|
-
if (opcode.startsWith('New') && opcode.includes('WithBuffer')) {
|
|
982
|
-
m =
|
|
983
|
-
/^(\s*New(?:Array|Object)WithBuffer)(?:Long)?(?:AndParent)?\s+(r\d+)(.*)$/.exec(
|
|
984
|
-
line,
|
|
985
|
-
);
|
|
986
|
-
if (m) {
|
|
987
|
-
const nums = m[3].match(/\d+/g) ?? [];
|
|
988
|
-
return `${m[1]} ${m[2]} sizes=${nums.slice(0, 1).join(',')}`;
|
|
989
|
-
}
|
|
990
|
-
}
|
|
991
|
-
if (opcode.charCodeAt(0) === 0x4a /* J */) {
|
|
992
|
-
m = /^(\s*J[A-Za-z]+?)(Long)?\s+(L\d+|\d+)(.*)$/.exec(line);
|
|
993
|
-
if (m) return `${m[1]} <tgt>${m[4]}`;
|
|
994
|
-
}
|
|
995
|
-
if (opcode.startsWith('DefineOwnById')) {
|
|
996
|
-
m = /^(\s*DefineOwnById\w*\s+r\d+, r\d+, \d+, )(\d+)$/.exec(line);
|
|
997
|
-
if (m) line = `${m[1]}"${strings.get(Number(m[2])) ?? `?${m[2]}`}"`;
|
|
998
|
-
}
|
|
999
|
-
// Operand-width variants of one instruction (GetByIdShort/GetById/GetByIdLong,
|
|
1000
|
-
// LoadConstString/LoadConstStringLongIndex, ...) only differ by how wide a
|
|
1001
|
-
// string/function id or offset is encoded — a foreign base hands the new
|
|
1002
|
-
// code's hot strings large ids, so the delta build legitimately picks the
|
|
1003
|
-
// wider form. Fold the suffix and the column padding that follows it.
|
|
1004
|
-
if (
|
|
1005
|
-
opEnd > indent &&
|
|
1006
|
-
(opEnd === line.length || isSpace(line.charCodeAt(opEnd)))
|
|
1007
|
-
) {
|
|
1008
|
-
const folded = foldWidthSuffix(opcode);
|
|
1009
|
-
line = `${line.slice(0, indent)}${folded}${line.slice(opEnd).replace(/\s+/g, ' ')}`;
|
|
1010
|
-
// Switch jump tables sit after the instructions; their relative offset (and
|
|
1011
|
-
// the table header hermesc prints for them) moves with instruction widths.
|
|
1012
|
-
// The two switch instructions carry that offset in different operands:
|
|
1013
|
-
// StringSwitchImm rX, <id>, <jtOffset>, <defaultLabel>, <count>
|
|
1014
|
-
// UIntSwitchImm rX, <jtOffset>, <defaultLabel>, <min>, <max>
|
|
1015
|
-
// Folding only the first shape let a shifted UIntSwitchImm offset read as a
|
|
1016
|
-
// real difference and drop an otherwise good delta build.
|
|
1017
|
-
if (folded === 'StringSwitchImm') {
|
|
1018
|
-
m = /^(\s*StringSwitchImm r\d+, \d+, )\d+(, L\d+, \d+)$/.exec(line);
|
|
1019
|
-
if (m) line = `${m[1]}<jt>${m[2]}`;
|
|
1020
|
-
} else if (folded === 'UIntSwitchImm') {
|
|
1021
|
-
m = /^(\s*UIntSwitchImm r\d+, )\d+(, L\d+, \d+, \d+)$/.exec(line);
|
|
1022
|
-
if (m) line = `${m[1]}<jt>${m[2]}`;
|
|
1023
|
-
} else if (folded === 'offset' && /^\s*offset \d+$/.test(line)) {
|
|
1024
|
-
line = line.replace(/\d+$/, '<jt>');
|
|
1025
|
-
}
|
|
1026
|
-
}
|
|
1027
|
-
return line;
|
|
1028
|
-
}
|
|
1029
|
-
|
|
1030
|
-
function isSpace(code: number): boolean {
|
|
1031
|
-
return code === 0x20 || code === 0x09 || code === 0x0d;
|
|
1032
|
-
}
|
|
1033
|
-
|
|
1034
|
-
function isLetter(code: number): boolean {
|
|
1035
|
-
return (code >= 0x41 && code <= 0x5a) || (code >= 0x61 && code <= 0x7a);
|
|
1036
|
-
}
|
|
1037
|
-
|
|
1038
|
-
/** strip one operand-width suffix (LongIndex, Long, Short) off an opcode */
|
|
1039
|
-
function foldWidthSuffix(opcode: string): string {
|
|
1040
|
-
for (const suffix of ['LongIndex', 'Long', 'Short']) {
|
|
1041
|
-
if (opcode.length > suffix.length && opcode.endsWith(suffix)) {
|
|
1042
|
-
return opcode.slice(0, -suffix.length);
|
|
1043
|
-
}
|
|
1044
|
-
}
|
|
1045
|
-
return opcode;
|
|
1046
|
-
}
|
|
1047
|
-
|
|
1048
|
-
/** Split a readable stream into lines without readline (Bun's readline async iterator misbehaves when pulled manually). */
|
|
1049
|
-
async function* streamLines(
|
|
1050
|
-
stream: NodeJS.ReadableStream,
|
|
1051
|
-
): AsyncGenerator<string> {
|
|
1052
|
-
let rest = '';
|
|
1053
|
-
for await (const chunk of stream as AsyncIterable<Buffer | string>) {
|
|
1054
|
-
rest += typeof chunk === 'string' ? chunk : chunk.toString('utf8');
|
|
1055
|
-
let index = rest.indexOf('\n');
|
|
1056
|
-
while (index >= 0) {
|
|
1057
|
-
yield rest.slice(0, index);
|
|
1058
|
-
rest = rest.slice(index + 1);
|
|
1059
|
-
index = rest.indexOf('\n');
|
|
1060
|
-
}
|
|
1061
|
-
}
|
|
1062
|
-
if (rest) yield rest;
|
|
1063
|
-
}
|
|
1064
|
-
|
|
1065
|
-
class DumpReader {
|
|
1066
|
-
private iterator: AsyncIterator<string>;
|
|
1067
|
-
readonly strings = new Map<number, string>();
|
|
1068
|
-
private inFunctions = false;
|
|
1069
|
-
private finished = false;
|
|
1070
|
-
constructor(readonly proc: ReturnType<typeof spawn>) {
|
|
1071
|
-
this.iterator = streamLines(proc.stdout!);
|
|
1072
|
-
}
|
|
1073
|
-
/** next normalized function-body line, or null at end */
|
|
1074
|
-
async next(): Promise<string | null> {
|
|
1075
|
-
if (this.finished) return null;
|
|
1076
|
-
for (;;) {
|
|
1077
|
-
const { value, done } = await this.iterator.next();
|
|
1078
|
-
if (done) {
|
|
1079
|
-
this.finished = true;
|
|
1080
|
-
return null;
|
|
1081
|
-
}
|
|
1082
|
-
const line = value as string;
|
|
1083
|
-
if (!this.inFunctions) {
|
|
1084
|
-
if (line.startsWith('Function<')) {
|
|
1085
|
-
this.inFunctions = true;
|
|
1086
|
-
} else {
|
|
1087
|
-
const m = STRING_TABLE_LINE.exec(line);
|
|
1088
|
-
if (m) this.strings.set(Number(m[1]), m[2]);
|
|
1089
|
-
continue;
|
|
1090
|
-
}
|
|
1091
|
-
}
|
|
1092
|
-
if (line.trim() === '') continue;
|
|
1093
|
-
const normalized = normalizeDisassemblyLine(line, this.strings);
|
|
1094
|
-
if (normalized !== null) return normalized;
|
|
1095
|
-
}
|
|
1096
|
-
}
|
|
1097
|
-
}
|
|
1098
|
-
|
|
1099
|
-
/**
|
|
1100
|
-
* Compare two HBC files by disassembly (see normalizeDisassemblyLine). `-b`
|
|
1101
|
-
* forces hermesc to treat inputs as bytecode whatever their extension. Both
|
|
1102
|
-
* hermesc dumps are consumed as streams so the ~100 MB of text never touches
|
|
1103
|
-
* the disk. Resolves true when equivalent.
|
|
1104
|
-
*/
|
|
1105
|
-
export async function verifyHermesBaseEquivalence(
|
|
1106
|
-
hermesCommand: string,
|
|
1107
|
-
withBase: string,
|
|
1108
|
-
plain: string,
|
|
1109
|
-
): Promise<boolean> {
|
|
1110
|
-
const spawnDump = (file: string) =>
|
|
1111
|
-
spawn(
|
|
1112
|
-
hermesCommand,
|
|
1113
|
-
['-b', '-dump-bytecode', '-pretty-disassemble', file],
|
|
1114
|
-
{
|
|
1115
|
-
stdio: ['ignore', 'pipe', 'ignore'],
|
|
1116
|
-
},
|
|
1117
|
-
);
|
|
1118
|
-
const a = new DumpReader(spawnDump(withBase));
|
|
1119
|
-
const b = new DumpReader(spawnDump(plain));
|
|
1120
|
-
let equal = true;
|
|
1121
|
-
let lines = 0;
|
|
1122
|
-
try {
|
|
1123
|
-
for (;;) {
|
|
1124
|
-
const [la, lb] = await Promise.all([a.next(), b.next()]);
|
|
1125
|
-
if (la === null && lb === null) break;
|
|
1126
|
-
if (la !== lb) {
|
|
1127
|
-
equal = false;
|
|
1128
|
-
break;
|
|
1129
|
-
}
|
|
1130
|
-
lines++;
|
|
1131
|
-
}
|
|
1132
|
-
} finally {
|
|
1133
|
-
a.proc.kill();
|
|
1134
|
-
b.proc.kill();
|
|
1135
|
-
}
|
|
1136
|
-
return equal && lines > 0;
|
|
1137
|
-
}
|