react-native-update-cli 2.22.5 → 2.22.6
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/lib/locales/en.d.ts +2 -0
- package/lib/locales/en.js +2 -0
- package/lib/locales/zh.d.ts +2 -0
- package/lib/locales/zh.js +2 -0
- package/lib/utils/hermes-base.d.ts +34 -1
- package/lib/utils/hermes-base.js +123 -12
- package/lib/utils/zip-range.d.ts +72 -0
- package/lib/utils/zip-range.js +275 -0
- package/lib/versions.js +12 -0
- package/package.json +1 -1
- package/src/locales/en.ts +4 -0
- package/src/locales/zh.ts +4 -0
- package/src/utils/hermes-base.ts +176 -19
- package/src/utils/zip-range.ts +358 -0
- package/src/versions.ts +17 -0
package/lib/locales/en.d.ts
CHANGED
|
@@ -160,6 +160,8 @@ declare const _default: {
|
|
|
160
160
|
hermesBaseNone: string;
|
|
161
161
|
hermesBaseUsing: string;
|
|
162
162
|
hermesBaseDownloading: string;
|
|
163
|
+
hermesBaseRangeFetched: string;
|
|
164
|
+
hermesBaseRangeFallback: string;
|
|
163
165
|
hermesBaseCompileFailed: string;
|
|
164
166
|
hermesBaseCompileFailedLog: string;
|
|
165
167
|
hermesBaseVerified: string;
|
package/lib/locales/en.js
CHANGED
|
@@ -168,6 +168,8 @@ This can reduce the risk of inconsistent dependencies and supply chain attacks.
|
|
|
168
168
|
hermesBaseNone: 'Hermes base: none ({{- reason}}); compiling without -base-bytecode',
|
|
169
169
|
hermesBaseUsing: 'Hermes base: {{- source}} (HBC v{{version}})',
|
|
170
170
|
hermesBaseDownloading: 'Hermes base: downloading {{- url}}',
|
|
171
|
+
hermesBaseRangeFetched: 'Hermes base: fetched only the bundle via HTTP Range ({{fetchedKb}} KB of {{totalKb}} KB)',
|
|
172
|
+
hermesBaseRangeFallback: 'Hermes base: partial download unavailable ({{- reason}}); downloading the whole package',
|
|
171
173
|
hermesBaseCompileFailed: 'Hermes base compile failed ({{- reason}}); retrying without -base-bytecode',
|
|
172
174
|
hermesBaseCompileFailedLog: 'Hermes base: full compiler output written to {{- file}}',
|
|
173
175
|
hermesBaseVerified: 'Hermes base: bytecode verified equivalent to a plain compile',
|
package/lib/locales/zh.d.ts
CHANGED
|
@@ -159,6 +159,8 @@ declare const _default: {
|
|
|
159
159
|
hermesBaseNone: string;
|
|
160
160
|
hermesBaseUsing: string;
|
|
161
161
|
hermesBaseDownloading: string;
|
|
162
|
+
hermesBaseRangeFetched: string;
|
|
163
|
+
hermesBaseRangeFallback: string;
|
|
162
164
|
hermesBaseCompileFailed: string;
|
|
163
165
|
hermesBaseCompileFailedLog: string;
|
|
164
166
|
hermesBaseVerified: string;
|
package/lib/locales/zh.js
CHANGED
|
@@ -167,6 +167,8 @@ exports.default = {
|
|
|
167
167
|
hermesBaseNone: 'Hermes base:未使用({{- reason}}),按普通方式编译',
|
|
168
168
|
hermesBaseUsing: 'Hermes base:{{- source}}(HBC v{{version}})',
|
|
169
169
|
hermesBaseDownloading: 'Hermes base:下载 {{- url}}',
|
|
170
|
+
hermesBaseRangeFetched: 'Hermes base:已通过 HTTP Range 仅下载 bundle({{fetchedKb}} KB / 整包 {{totalKb}} KB)',
|
|
171
|
+
hermesBaseRangeFallback: 'Hermes base:无法按需下载({{- reason}}),改为下载整包',
|
|
170
172
|
hermesBaseCompileFailed: 'Hermes base 编译失败({{- reason}}),改为不带 -base-bytecode 重编',
|
|
171
173
|
hermesBaseCompileFailedLog: 'Hermes base:完整编译错误已写入 {{- file}}',
|
|
172
174
|
hermesBaseVerified: 'Hermes base:字节码与普通编译等价,校验通过',
|
|
@@ -34,6 +34,9 @@ export declare function sha256Hex(data: Buffer): string;
|
|
|
34
34
|
/** Compile an empty file to learn which HBC version this hermesc emits. */
|
|
35
35
|
export declare function probeHbcVersion(hermesCommand: string): number | null;
|
|
36
36
|
export declare const BUNDLE_ENTRY_NAMES: string[];
|
|
37
|
+
export type BaseArtifactType = 'ppk' | 'apk' | 'ipa' | 'app';
|
|
38
|
+
/** Which zip entry holds the JS/HBC bundle in each kind of artifact. */
|
|
39
|
+
export declare function bundleEntryMatcher(artifactType: BaseArtifactType): (name: string) => boolean;
|
|
37
40
|
/**
|
|
38
41
|
* Extract the JS/HBC bundle from a local artifact: a raw bundle file, a ppk,
|
|
39
42
|
* or a native package (apk / ipa / harmony app). Returns null when not found.
|
|
@@ -67,11 +70,40 @@ export declare function downloadToFile(url: string, destination: string): Promis
|
|
|
67
70
|
export interface HermesBaseServerRecord {
|
|
68
71
|
versionId?: number | null;
|
|
69
72
|
hash: string;
|
|
70
|
-
artifactType?:
|
|
73
|
+
artifactType?: BaseArtifactType;
|
|
71
74
|
bundleHash?: string | null;
|
|
72
75
|
bytecodeVersion?: number | null;
|
|
73
76
|
url: string;
|
|
77
|
+
/**
|
|
78
|
+
* Location of the bundle's compressed bytes inside the ppk, reported by the
|
|
79
|
+
* publishing CLI; lets the base be fetched with a single HTTP Range request.
|
|
80
|
+
*/
|
|
81
|
+
bundleOffset?: number | null;
|
|
82
|
+
bundleCompressedSize?: number | null;
|
|
83
|
+
/** zip compression method: 0 stored, 8 deflate */
|
|
84
|
+
bundleCompression?: number | null;
|
|
85
|
+
}
|
|
86
|
+
interface FetchedBaseBundle {
|
|
87
|
+
bundle: Buffer;
|
|
88
|
+
/** how the bytes were obtained, for the log line */
|
|
89
|
+
transport: 'range-entry' | 'range-zip' | 'full';
|
|
90
|
+
fetchedBytes?: number;
|
|
91
|
+
totalBytes?: number;
|
|
74
92
|
}
|
|
93
|
+
/**
|
|
94
|
+
* Obtain the base bundle with as little traffic as possible, in order:
|
|
95
|
+
* 1. one Range request for the bundle's compressed bytes when the server
|
|
96
|
+
* knows their location (ppk published by a CLI that reported it);
|
|
97
|
+
* 2. the archive's central directory over Range, then just the bundle
|
|
98
|
+
* entry (any zip: ppk, apk, ipa — harmony .app nests a second zip and
|
|
99
|
+
* is skipped);
|
|
100
|
+
* 3. the whole archive, as before.
|
|
101
|
+
* A server that ignores Range (HTTP 200) streams the full archive into
|
|
102
|
+
* `archive` without a second request. Range results are verified against
|
|
103
|
+
* `record.bundleHash` here; a mismatch (e.g. re-packaged object) falls
|
|
104
|
+
* through to the next transport instead of failing the resolution.
|
|
105
|
+
*/
|
|
106
|
+
export declare function fetchBaseBundle(record: HermesBaseServerRecord, artifactType: BaseArtifactType, archive: string, log?: (message: string) => void): Promise<FetchedBaseBundle | null>;
|
|
75
107
|
export interface ResolveHermesBaseParams {
|
|
76
108
|
option: HermesBaseOption;
|
|
77
109
|
hermesCommand: string;
|
|
@@ -108,3 +140,4 @@ export declare function normalizeDisassemblyLine(line: string, strings: Map<numb
|
|
|
108
140
|
* the disk. Resolves true when equivalent.
|
|
109
141
|
*/
|
|
110
142
|
export declare function verifyHermesBaseEquivalence(hermesCommand: string, withBase: string, plain: string): Promise<boolean>;
|
|
143
|
+
export {};
|
package/lib/utils/hermes-base.js
CHANGED
|
@@ -40,6 +40,7 @@ exports.DEFAULT_CACHE_MAX_FILES = exports.DEFAULT_CACHE_MAX_BYTES = exports.BUND
|
|
|
40
40
|
exports.classifyHermesCommand = classifyHermesCommand;
|
|
41
41
|
exports.sha256Hex = sha256Hex;
|
|
42
42
|
exports.probeHbcVersion = probeHbcVersion;
|
|
43
|
+
exports.bundleEntryMatcher = bundleEntryMatcher;
|
|
43
44
|
exports.extractBundleFromArchive = extractBundleFromArchive;
|
|
44
45
|
exports.cacheDir = cacheDir;
|
|
45
46
|
exports.tmpDir = tmpDir;
|
|
@@ -51,6 +52,7 @@ exports.cleanCache = cleanCache;
|
|
|
51
52
|
exports.cacheStats = cacheStats;
|
|
52
53
|
exports.cleanStaleTmp = cleanStaleTmp;
|
|
53
54
|
exports.downloadToFile = downloadToFile;
|
|
55
|
+
exports.fetchBaseBundle = fetchBaseBundle;
|
|
54
56
|
exports.resolveHermesBase = resolveHermesBase;
|
|
55
57
|
exports.hermescArgsWithBase = hermescArgsWithBase;
|
|
56
58
|
exports.hermesBaseMeta = hermesBaseMeta;
|
|
@@ -76,6 +78,7 @@ const constants_1 = require("./constants");
|
|
|
76
78
|
const hbcTransform_1 = require("./hbcTransform");
|
|
77
79
|
const i18n_1 = require("./i18n");
|
|
78
80
|
const zip_entries_1 = require("./zip-entries");
|
|
81
|
+
const zip_range_1 = require("./zip-range");
|
|
79
82
|
// ---------------------------------------------------------------------------
|
|
80
83
|
// hermesc gating
|
|
81
84
|
// ---------------------------------------------------------------------------
|
|
@@ -198,6 +201,17 @@ exports.BUNDLE_ENTRY_NAMES = [
|
|
|
198
201
|
];
|
|
199
202
|
const APK_BUNDLE = /^assets\/index\.android\.bundle$/;
|
|
200
203
|
const IPA_BUNDLE = /^payload\/[^/]+\.app\/main\.jsbundle$/i;
|
|
204
|
+
/** Which zip entry holds the JS/HBC bundle in each kind of artifact. */
|
|
205
|
+
function bundleEntryMatcher(artifactType) {
|
|
206
|
+
switch (artifactType) {
|
|
207
|
+
case 'apk':
|
|
208
|
+
return (name) => APK_BUNDLE.test(name);
|
|
209
|
+
case 'ipa':
|
|
210
|
+
return (name) => IPA_BUNDLE.test(name.toLowerCase());
|
|
211
|
+
default:
|
|
212
|
+
return (name) => exports.BUNDLE_ENTRY_NAMES.includes(name);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
201
215
|
/**
|
|
202
216
|
* Extract the JS/HBC bundle from a local artifact: a raw bundle file, a ppk,
|
|
203
217
|
* or a native package (apk / ipa / harmony app). Returns null when not found.
|
|
@@ -211,14 +225,8 @@ async function extractBundleFromArchive(filePath) {
|
|
|
211
225
|
ext === '.js') {
|
|
212
226
|
return fs_extra_1.default.readFile(filePath);
|
|
213
227
|
}
|
|
214
|
-
if (ext === '.ppk') {
|
|
215
|
-
return readFirstZipEntry(filePath, (
|
|
216
|
-
}
|
|
217
|
-
if (ext === '.apk') {
|
|
218
|
-
return readFirstZipEntry(filePath, (name) => APK_BUNDLE.test(name));
|
|
219
|
-
}
|
|
220
|
-
if (ext === '.ipa') {
|
|
221
|
-
return readFirstZipEntry(filePath, (name) => IPA_BUNDLE.test(name.toLowerCase()));
|
|
228
|
+
if (ext === '.ppk' || ext === '.apk' || ext === '.ipa') {
|
|
229
|
+
return readFirstZipEntry(filePath, bundleEntryMatcher(ext.slice(1)));
|
|
222
230
|
}
|
|
223
231
|
if (ext === '.app') {
|
|
224
232
|
// harmony .app wraps .hap archives; reuse the existing parser
|
|
@@ -372,6 +380,98 @@ async function downloadToFile(url, destination) {
|
|
|
372
380
|
const { Readable } = await Promise.resolve().then(() => __importStar(require('stream')));
|
|
373
381
|
await (0, promises_1.pipeline)(Readable.fromWeb(response.body), fs_extra_1.default.createWriteStream(destination));
|
|
374
382
|
}
|
|
383
|
+
function hasBundleLocation(record) {
|
|
384
|
+
return (record.bundleOffset != null &&
|
|
385
|
+
record.bundleCompressedSize != null &&
|
|
386
|
+
record.bundleCompression != null &&
|
|
387
|
+
(record.bundleCompression === zip_range_1.ZIP_STORED ||
|
|
388
|
+
record.bundleCompression === zip_range_1.ZIP_DEFLATED));
|
|
389
|
+
}
|
|
390
|
+
async function saveResponse(response, destination) {
|
|
391
|
+
if (!response.body)
|
|
392
|
+
throw new Error('empty response body');
|
|
393
|
+
await fs_extra_1.default.ensureDir(path_1.default.dirname(destination));
|
|
394
|
+
const { Readable } = await Promise.resolve().then(() => __importStar(require('stream')));
|
|
395
|
+
await (0, promises_1.pipeline)(Readable.fromWeb(response.body), fs_extra_1.default.createWriteStream(destination));
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* Obtain the base bundle with as little traffic as possible, in order:
|
|
399
|
+
* 1. one Range request for the bundle's compressed bytes when the server
|
|
400
|
+
* knows their location (ppk published by a CLI that reported it);
|
|
401
|
+
* 2. the archive's central directory over Range, then just the bundle
|
|
402
|
+
* entry (any zip: ppk, apk, ipa — harmony .app nests a second zip and
|
|
403
|
+
* is skipped);
|
|
404
|
+
* 3. the whole archive, as before.
|
|
405
|
+
* A server that ignores Range (HTTP 200) streams the full archive into
|
|
406
|
+
* `archive` without a second request. Range results are verified against
|
|
407
|
+
* `record.bundleHash` here; a mismatch (e.g. re-packaged object) falls
|
|
408
|
+
* through to the next transport instead of failing the resolution.
|
|
409
|
+
*/
|
|
410
|
+
async function fetchBaseBundle(record, artifactType, archive, log = () => { }) {
|
|
411
|
+
const matches = bundleEntryMatcher(artifactType);
|
|
412
|
+
const verified = (bundle) => {
|
|
413
|
+
if (!bundle)
|
|
414
|
+
throw new Error('bundle entry not found');
|
|
415
|
+
if (record.bundleHash && sha256Hex(bundle) !== record.bundleHash) {
|
|
416
|
+
throw new Error('bundleHash mismatch');
|
|
417
|
+
}
|
|
418
|
+
return bundle;
|
|
419
|
+
};
|
|
420
|
+
const fromFullResponse = async (response) => {
|
|
421
|
+
await saveResponse(response, archive);
|
|
422
|
+
const bundle = await extractBundleFromArchive(archive);
|
|
423
|
+
return bundle ? { bundle, transport: 'full' } : null;
|
|
424
|
+
};
|
|
425
|
+
const skip = (reason) => log((0, i18n_1.t)('hermesBaseRangeFallback', { reason }));
|
|
426
|
+
if (artifactType === 'ppk' && hasBundleLocation(record)) {
|
|
427
|
+
try {
|
|
428
|
+
const { data, fetchedBytes, totalBytes } = await (0, zip_range_1.fetchZipEntryData)(record.url, {
|
|
429
|
+
dataOffset: record.bundleOffset,
|
|
430
|
+
compressedSize: record.bundleCompressedSize,
|
|
431
|
+
compressionMethod: record.bundleCompression,
|
|
432
|
+
});
|
|
433
|
+
return {
|
|
434
|
+
bundle: verified(data),
|
|
435
|
+
transport: 'range-entry',
|
|
436
|
+
fetchedBytes,
|
|
437
|
+
totalBytes,
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
catch (error) {
|
|
441
|
+
if (error instanceof zip_range_1.RangeUnsupportedError) {
|
|
442
|
+
skip('server ignores Range');
|
|
443
|
+
return fromFullResponse(error.response);
|
|
444
|
+
}
|
|
445
|
+
skip(`entry range: ${error?.message ?? error}`);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
if (artifactType !== 'app') {
|
|
449
|
+
try {
|
|
450
|
+
const remote = await (0, zip_range_1.openRemoteZip)(record.url);
|
|
451
|
+
if (remote.kind === 'full') {
|
|
452
|
+
skip('server ignores Range');
|
|
453
|
+
return fromFullResponse(remote.response);
|
|
454
|
+
}
|
|
455
|
+
const bundle = await (0, zip_range_1.readRemoteZipEntry)(remote.zipFile, matches);
|
|
456
|
+
return {
|
|
457
|
+
bundle: verified(bundle),
|
|
458
|
+
transport: 'range-zip',
|
|
459
|
+
fetchedBytes: remote.reader.fetchedBytes,
|
|
460
|
+
totalBytes: remote.reader.totalSize,
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
catch (error) {
|
|
464
|
+
if (error instanceof zip_range_1.RangeUnsupportedError) {
|
|
465
|
+
skip('server ignores Range');
|
|
466
|
+
return fromFullResponse(error.response);
|
|
467
|
+
}
|
|
468
|
+
skip(`zip range: ${error?.message ?? error}`);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
await downloadToFile(record.url, archive);
|
|
472
|
+
const bundle = await extractBundleFromArchive(archive);
|
|
473
|
+
return bundle ? { bundle, transport: 'full' } : null;
|
|
474
|
+
}
|
|
375
475
|
/**
|
|
376
476
|
* Pick and materialize the base bundle for this compile. Returns null (with
|
|
377
477
|
* the reason logged) whenever a base cannot be used; callers then compile
|
|
@@ -462,16 +562,27 @@ async function resolveHermesBase(params) {
|
|
|
462
562
|
for (let attempt = 1; attempt <= 2; attempt++) {
|
|
463
563
|
const dir = tmpDir();
|
|
464
564
|
await fs_extra_1.default.ensureDir(dir);
|
|
465
|
-
const artifactType = [
|
|
565
|
+
const artifactType = [
|
|
566
|
+
'ppk',
|
|
567
|
+
'apk',
|
|
568
|
+
'ipa',
|
|
569
|
+
'app',
|
|
570
|
+
].includes(record.artifactType ?? '')
|
|
466
571
|
? record.artifactType
|
|
467
572
|
: 'ppk';
|
|
468
573
|
const archive = path_1.default.join(dir, `base-${process.pid}-${Date.now()}-${attempt}.${artifactType}`);
|
|
469
574
|
try {
|
|
470
575
|
log((0, i18n_1.t)('hermesBaseDownloading', { url: record.url }));
|
|
471
|
-
await
|
|
472
|
-
|
|
473
|
-
if (!bundle)
|
|
576
|
+
const fetched = await fetchBaseBundle(record, artifactType, archive, log);
|
|
577
|
+
if (!fetched)
|
|
474
578
|
throw new Error('bundle entry not found in downloaded package');
|
|
579
|
+
const { bundle } = fetched;
|
|
580
|
+
if (fetched.transport !== 'full') {
|
|
581
|
+
log((0, i18n_1.t)('hermesBaseRangeFetched', {
|
|
582
|
+
fetchedKb: Math.ceil((fetched.fetchedBytes ?? 0) / 1024),
|
|
583
|
+
totalKb: Math.ceil((fetched.totalBytes ?? 0) / 1024),
|
|
584
|
+
}));
|
|
585
|
+
}
|
|
475
586
|
const actualHash = sha256Hex(bundle);
|
|
476
587
|
if (record.bundleHash && actualHash !== record.bundleHash) {
|
|
477
588
|
throw new Error(`bundleHash mismatch (${actualHash.slice(0, 12)} != ${record.bundleHash.slice(0, 12)})`);
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { Readable } from 'stream';
|
|
2
|
+
import { RandomAccessReader, type ZipFile } from 'yauzl';
|
|
3
|
+
export declare const ZIP_STORED = 0;
|
|
4
|
+
export declare const ZIP_DEFLATED = 8;
|
|
5
|
+
export interface ZipEntryLocation {
|
|
6
|
+
fileName: string;
|
|
7
|
+
/** absolute offset of the compressed data, past the local file header */
|
|
8
|
+
dataOffset: number;
|
|
9
|
+
compressedSize: number;
|
|
10
|
+
uncompressedSize: number;
|
|
11
|
+
/** 0 = stored, 8 = deflate; anything else cannot be inflated here */
|
|
12
|
+
compressionMethod: number;
|
|
13
|
+
}
|
|
14
|
+
/** Data location of the first entry matching `matches` in a local zip. */
|
|
15
|
+
export declare function locateZipEntry(zipPath: string, matches: (name: string) => boolean): Promise<ZipEntryLocation | null>;
|
|
16
|
+
/** The server answered a Range request with the whole body (HTTP 200). */
|
|
17
|
+
export declare class RangeUnsupportedError extends Error {
|
|
18
|
+
readonly response: Response;
|
|
19
|
+
constructor(response: Response);
|
|
20
|
+
}
|
|
21
|
+
interface ContentRange {
|
|
22
|
+
start: number;
|
|
23
|
+
end: number;
|
|
24
|
+
total: number;
|
|
25
|
+
}
|
|
26
|
+
export declare function parseContentRange(header: string | null): ContentRange | null;
|
|
27
|
+
/**
|
|
28
|
+
* Fetch one entry whose compressed bytes are already located (the ppk's own
|
|
29
|
+
* publish-time report) and decompress it. Returns the raw entry content.
|
|
30
|
+
*/
|
|
31
|
+
export declare function fetchZipEntryData(url: string, location: Pick<ZipEntryLocation, 'dataOffset' | 'compressedSize' | 'compressionMethod'>): Promise<{
|
|
32
|
+
data: Buffer;
|
|
33
|
+
fetchedBytes: number;
|
|
34
|
+
totalBytes: number;
|
|
35
|
+
}>;
|
|
36
|
+
/**
|
|
37
|
+
* yauzl reader over HTTP Range. Header reads (EOCD, central directory, local
|
|
38
|
+
* file headers) are widened to CHUNK_BYTES and cached so a small archive costs
|
|
39
|
+
* one request; entry data streams straight from its own request.
|
|
40
|
+
*/
|
|
41
|
+
export declare class HttpRangeReader extends RandomAccessReader {
|
|
42
|
+
private readonly url;
|
|
43
|
+
readonly totalSize: number;
|
|
44
|
+
private readonly chunks;
|
|
45
|
+
requests: number;
|
|
46
|
+
fetchedBytes: number;
|
|
47
|
+
constructor(url: string, totalSize: number, tail?: {
|
|
48
|
+
start: number;
|
|
49
|
+
data: Buffer;
|
|
50
|
+
});
|
|
51
|
+
private cached;
|
|
52
|
+
_readStreamForRange(start: number, end: number): Readable;
|
|
53
|
+
read(buffer: Buffer, offset: number, length: number, position: number, callback: (err: Error | null, bytesRead?: number) => void): void;
|
|
54
|
+
}
|
|
55
|
+
export type RemoteZip = {
|
|
56
|
+
kind: 'zip';
|
|
57
|
+
zipFile: ZipFile;
|
|
58
|
+
reader: HttpRangeReader;
|
|
59
|
+
}
|
|
60
|
+
/** the server ignored Range: the whole archive is streaming in `response` */
|
|
61
|
+
| {
|
|
62
|
+
kind: 'full';
|
|
63
|
+
response: Response;
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* Open a remote zip by fetching its tail (EOCD + central directory for
|
|
67
|
+
* typical archives) and letting yauzl read the rest on demand.
|
|
68
|
+
*/
|
|
69
|
+
export declare function openRemoteZip(url: string): Promise<RemoteZip>;
|
|
70
|
+
/** Read the first matching entry of an opened remote zip, then close it. */
|
|
71
|
+
export declare function readRemoteZipEntry(zipFile: ZipFile, matches: (name: string) => boolean): Promise<Buffer | null>;
|
|
72
|
+
export {};
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.HttpRangeReader = exports.RangeUnsupportedError = exports.ZIP_DEFLATED = exports.ZIP_STORED = void 0;
|
|
7
|
+
exports.locateZipEntry = locateZipEntry;
|
|
8
|
+
exports.parseContentRange = parseContentRange;
|
|
9
|
+
exports.fetchZipEntryData = fetchZipEntryData;
|
|
10
|
+
exports.openRemoteZip = openRemoteZip;
|
|
11
|
+
exports.readRemoteZipEntry = readRemoteZipEntry;
|
|
12
|
+
// Byte-range access to zip archives.
|
|
13
|
+
//
|
|
14
|
+
// Two halves of the same trick: at publish time `locateZipEntry` records where
|
|
15
|
+
// the bundle's compressed bytes sit inside the ppk (so the server can hand
|
|
16
|
+
// that location to the next build), and at build time `fetchZipEntryData` /
|
|
17
|
+
// `openRemoteZip` read just the bundle of a remote archive through HTTP Range
|
|
18
|
+
// requests instead of downloading the whole ppk / apk / ipa. Every helper
|
|
19
|
+
// throws on anything unexpected; callers fall back to a full download.
|
|
20
|
+
const fs_extra_1 = __importDefault(require("fs-extra"));
|
|
21
|
+
const stream_1 = require("stream");
|
|
22
|
+
const yauzl_1 = require("yauzl");
|
|
23
|
+
const zlib_1 = require("zlib");
|
|
24
|
+
const zip_entries_1 = require("./zip-entries");
|
|
25
|
+
exports.ZIP_STORED = 0;
|
|
26
|
+
exports.ZIP_DEFLATED = 8;
|
|
27
|
+
const LOCAL_HEADER_SIGNATURE = 0x04034b50;
|
|
28
|
+
const LOCAL_HEADER_SIZE = 30;
|
|
29
|
+
/** covers the EOCD (≤ 22 + 65535 bytes) and, for small archives, everything */
|
|
30
|
+
const TAIL_BYTES = 64 * 1024;
|
|
31
|
+
/** minimum span fetched for header reads, so header + directory share a request */
|
|
32
|
+
const CHUNK_BYTES = 64 * 1024;
|
|
33
|
+
/** Data location of the first entry matching `matches` in a local zip. */
|
|
34
|
+
async function locateZipEntry(zipPath, matches) {
|
|
35
|
+
const entry = await findEntry(zipPath, matches);
|
|
36
|
+
if (!entry)
|
|
37
|
+
return null;
|
|
38
|
+
const header = Buffer.alloc(LOCAL_HEADER_SIZE);
|
|
39
|
+
const fd = await fs_extra_1.default.open(zipPath, 'r');
|
|
40
|
+
try {
|
|
41
|
+
const { bytesRead } = await fs_extra_1.default.read(fd, header, 0, LOCAL_HEADER_SIZE, entry.relativeOffsetOfLocalHeader);
|
|
42
|
+
if (bytesRead !== LOCAL_HEADER_SIZE) {
|
|
43
|
+
throw new Error('truncated local file header');
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
await fs_extra_1.default.close(fd);
|
|
48
|
+
}
|
|
49
|
+
if (header.readUInt32LE(0) !== LOCAL_HEADER_SIGNATURE) {
|
|
50
|
+
throw new Error('invalid local file header signature');
|
|
51
|
+
}
|
|
52
|
+
const fileNameLength = header.readUInt16LE(26);
|
|
53
|
+
const extraFieldLength = header.readUInt16LE(28);
|
|
54
|
+
return {
|
|
55
|
+
fileName: entry.fileName,
|
|
56
|
+
dataOffset: entry.relativeOffsetOfLocalHeader +
|
|
57
|
+
LOCAL_HEADER_SIZE +
|
|
58
|
+
fileNameLength +
|
|
59
|
+
extraFieldLength,
|
|
60
|
+
compressedSize: entry.compressedSize,
|
|
61
|
+
uncompressedSize: entry.uncompressedSize,
|
|
62
|
+
compressionMethod: entry.compressionMethod,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
function findEntry(zipPath, matches) {
|
|
66
|
+
return new Promise((resolve, reject) => {
|
|
67
|
+
(0, yauzl_1.open)(zipPath, { lazyEntries: true }, (err, zipFile) => {
|
|
68
|
+
if (err)
|
|
69
|
+
return reject(err);
|
|
70
|
+
let found = null;
|
|
71
|
+
zipFile.on('error', reject);
|
|
72
|
+
zipFile.on('end', () => resolve(found));
|
|
73
|
+
zipFile.on('entry', (entry) => {
|
|
74
|
+
if (!found && matches(entry.fileName)) {
|
|
75
|
+
found = entry;
|
|
76
|
+
zipFile.close();
|
|
77
|
+
resolve(found);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
zipFile.readEntry();
|
|
81
|
+
});
|
|
82
|
+
zipFile.readEntry();
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
// ---------------------------------------------------------------------------
|
|
87
|
+
// HTTP Range
|
|
88
|
+
// ---------------------------------------------------------------------------
|
|
89
|
+
/** The server answered a Range request with the whole body (HTTP 200). */
|
|
90
|
+
class RangeUnsupportedError extends Error {
|
|
91
|
+
response;
|
|
92
|
+
constructor(response) {
|
|
93
|
+
super(`HTTP ${response.status} without Content-Range`);
|
|
94
|
+
this.response = response;
|
|
95
|
+
this.name = 'RangeUnsupportedError';
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
exports.RangeUnsupportedError = RangeUnsupportedError;
|
|
99
|
+
function parseContentRange(header) {
|
|
100
|
+
const match = /^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(header?.trim() ?? '');
|
|
101
|
+
if (!match)
|
|
102
|
+
return null;
|
|
103
|
+
const [start, end, total] = match.slice(1).map(Number);
|
|
104
|
+
if (end < start || end >= total)
|
|
105
|
+
return null;
|
|
106
|
+
return { start, end, total };
|
|
107
|
+
}
|
|
108
|
+
/** One Range request; `end` is exclusive. Resolves with a 206 response. */
|
|
109
|
+
async function fetchRange(url, start, end) {
|
|
110
|
+
const response = await fetch(url, {
|
|
111
|
+
headers: {
|
|
112
|
+
Range: `bytes=${start}-${end - 1}`,
|
|
113
|
+
'Accept-Encoding': 'identity',
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
if (response.status === 200)
|
|
117
|
+
throw new RangeUnsupportedError(response);
|
|
118
|
+
if (response.status !== 206 || !response.body) {
|
|
119
|
+
await response.body?.cancel().catch(() => { });
|
|
120
|
+
throw new Error(`HTTP ${response.status} for bytes=${start}-${end - 1}`);
|
|
121
|
+
}
|
|
122
|
+
const range = parseContentRange(response.headers.get('content-range'));
|
|
123
|
+
if (!range || range.start !== start || range.end !== end - 1) {
|
|
124
|
+
await response.body.cancel().catch(() => { });
|
|
125
|
+
throw new Error(`unexpected Content-Range ${response.headers.get('content-range')}`);
|
|
126
|
+
}
|
|
127
|
+
return Object.assign(response, { range });
|
|
128
|
+
}
|
|
129
|
+
async function fetchRangeBuffer(url, start, end) {
|
|
130
|
+
const response = await fetchRange(url, start, end);
|
|
131
|
+
const data = Buffer.from(await response.arrayBuffer());
|
|
132
|
+
if (data.length !== end - start) {
|
|
133
|
+
throw new Error(`range returned ${data.length} bytes, expected ${end - start}`);
|
|
134
|
+
}
|
|
135
|
+
return { data, total: response.range.total };
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Fetch one entry whose compressed bytes are already located (the ppk's own
|
|
139
|
+
* publish-time report) and decompress it. Returns the raw entry content.
|
|
140
|
+
*/
|
|
141
|
+
async function fetchZipEntryData(url, location) {
|
|
142
|
+
const { dataOffset, compressedSize, compressionMethod } = location;
|
|
143
|
+
if (compressionMethod !== exports.ZIP_STORED && compressionMethod !== exports.ZIP_DEFLATED) {
|
|
144
|
+
throw new Error(`unsupported compression method ${compressionMethod}`);
|
|
145
|
+
}
|
|
146
|
+
if (!Number.isInteger(dataOffset) ||
|
|
147
|
+
!Number.isInteger(compressedSize) ||
|
|
148
|
+
dataOffset < 0 ||
|
|
149
|
+
compressedSize <= 0) {
|
|
150
|
+
throw new Error('invalid bundle location');
|
|
151
|
+
}
|
|
152
|
+
const { data, total } = await fetchRangeBuffer(url, dataOffset, dataOffset + compressedSize);
|
|
153
|
+
return {
|
|
154
|
+
data: compressionMethod === exports.ZIP_DEFLATED ? (0, zlib_1.inflateRawSync)(data) : data,
|
|
155
|
+
fetchedBytes: compressedSize,
|
|
156
|
+
totalBytes: total,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* yauzl reader over HTTP Range. Header reads (EOCD, central directory, local
|
|
161
|
+
* file headers) are widened to CHUNK_BYTES and cached so a small archive costs
|
|
162
|
+
* one request; entry data streams straight from its own request.
|
|
163
|
+
*/
|
|
164
|
+
class HttpRangeReader extends yauzl_1.RandomAccessReader {
|
|
165
|
+
url;
|
|
166
|
+
totalSize;
|
|
167
|
+
chunks = [];
|
|
168
|
+
requests = 0;
|
|
169
|
+
fetchedBytes = 0;
|
|
170
|
+
constructor(url, totalSize, tail) {
|
|
171
|
+
super();
|
|
172
|
+
this.url = url;
|
|
173
|
+
this.totalSize = totalSize;
|
|
174
|
+
if (tail)
|
|
175
|
+
this.chunks.push(tail);
|
|
176
|
+
}
|
|
177
|
+
cached(start, end) {
|
|
178
|
+
for (const chunk of this.chunks) {
|
|
179
|
+
if (start >= chunk.start && end <= chunk.start + chunk.data.length) {
|
|
180
|
+
return chunk.data.subarray(start - chunk.start, end - chunk.start);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
_readStreamForRange(start, end) {
|
|
186
|
+
const hit = this.cached(start, end);
|
|
187
|
+
if (hit)
|
|
188
|
+
return stream_1.Readable.from([hit]);
|
|
189
|
+
const out = new stream_1.PassThrough();
|
|
190
|
+
this.requests++;
|
|
191
|
+
fetchRange(this.url, start, end)
|
|
192
|
+
.then((response) => {
|
|
193
|
+
this.fetchedBytes += end - start;
|
|
194
|
+
const body = stream_1.Readable.fromWeb(response.body);
|
|
195
|
+
body.on('error', (error) => out.destroy(error));
|
|
196
|
+
body.pipe(out);
|
|
197
|
+
})
|
|
198
|
+
.catch((error) => out.destroy(error));
|
|
199
|
+
return out;
|
|
200
|
+
}
|
|
201
|
+
read(buffer, offset, length, position, callback) {
|
|
202
|
+
const hit = this.cached(position, position + length);
|
|
203
|
+
if (hit) {
|
|
204
|
+
hit.copy(buffer, offset);
|
|
205
|
+
setImmediate(() => callback(null, length));
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
const end = Math.min(this.totalSize, Math.max(position + length, position + CHUNK_BYTES));
|
|
209
|
+
this.requests++;
|
|
210
|
+
fetchRangeBuffer(this.url, position, end).then(({ data }) => {
|
|
211
|
+
this.fetchedBytes += data.length;
|
|
212
|
+
this.chunks.push({ start: position, data });
|
|
213
|
+
data.copy(buffer, offset, 0, length);
|
|
214
|
+
callback(null, length);
|
|
215
|
+
}, (error) => callback(error));
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
exports.HttpRangeReader = HttpRangeReader;
|
|
219
|
+
/**
|
|
220
|
+
* Open a remote zip by fetching its tail (EOCD + central directory for
|
|
221
|
+
* typical archives) and letting yauzl read the rest on demand.
|
|
222
|
+
*/
|
|
223
|
+
async function openRemoteZip(url) {
|
|
224
|
+
const response = await fetch(url, {
|
|
225
|
+
headers: { Range: `bytes=-${TAIL_BYTES}`, 'Accept-Encoding': 'identity' },
|
|
226
|
+
});
|
|
227
|
+
if (!response.ok || !response.body) {
|
|
228
|
+
await response.body?.cancel().catch(() => { });
|
|
229
|
+
throw new Error(`HTTP ${response.status}`);
|
|
230
|
+
}
|
|
231
|
+
if (response.status !== 206)
|
|
232
|
+
return { kind: 'full', response };
|
|
233
|
+
const range = parseContentRange(response.headers.get('content-range'));
|
|
234
|
+
if (!range) {
|
|
235
|
+
await response.body.cancel().catch(() => { });
|
|
236
|
+
throw new Error(`unexpected Content-Range ${response.headers.get('content-range')}`);
|
|
237
|
+
}
|
|
238
|
+
const data = Buffer.from(await response.arrayBuffer());
|
|
239
|
+
if (data.length !== range.end - range.start + 1) {
|
|
240
|
+
throw new Error(`tail returned ${data.length} bytes, expected ${range.end - range.start + 1}`);
|
|
241
|
+
}
|
|
242
|
+
const reader = new HttpRangeReader(url, range.total, {
|
|
243
|
+
start: range.start,
|
|
244
|
+
data,
|
|
245
|
+
});
|
|
246
|
+
reader.requests = 1;
|
|
247
|
+
reader.fetchedBytes = data.length;
|
|
248
|
+
const zipFile = await new Promise((resolve, reject) => {
|
|
249
|
+
(0, yauzl_1.fromRandomAccessReader)(reader, range.total, { lazyEntries: true, autoClose: false }, (err, file) => (err ? reject(err) : resolve(file)));
|
|
250
|
+
});
|
|
251
|
+
return { kind: 'zip', zipFile, reader };
|
|
252
|
+
}
|
|
253
|
+
/** Read the first matching entry of an opened remote zip, then close it. */
|
|
254
|
+
function readRemoteZipEntry(zipFile, matches) {
|
|
255
|
+
return new Promise((resolve, reject) => {
|
|
256
|
+
let settled = false;
|
|
257
|
+
const finish = (error, result = null) => {
|
|
258
|
+
if (settled)
|
|
259
|
+
return;
|
|
260
|
+
settled = true;
|
|
261
|
+
zipFile.close();
|
|
262
|
+
error ? reject(error) : resolve(result);
|
|
263
|
+
};
|
|
264
|
+
zipFile.on('error', (error) => finish(error));
|
|
265
|
+
zipFile.on('end', () => finish(null, null));
|
|
266
|
+
zipFile.on('entry', (entry) => {
|
|
267
|
+
if (!matches(entry.fileName)) {
|
|
268
|
+
zipFile.readEntry();
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
(0, zip_entries_1.readEntry)(entry, zipFile).then((data) => finish(null, data), (error) => finish(error));
|
|
272
|
+
});
|
|
273
|
+
zipFile.readEntry();
|
|
274
|
+
});
|
|
275
|
+
}
|
package/lib/versions.js
CHANGED
|
@@ -19,6 +19,7 @@ const hbcTransform_1 = require("./utils/hbcTransform");
|
|
|
19
19
|
const hermes_base_1 = require("./utils/hermes-base");
|
|
20
20
|
const i18n_1 = require("./utils/i18n");
|
|
21
21
|
const options_1 = require("./utils/options");
|
|
22
|
+
const zip_range_1 = require("./utils/zip-range");
|
|
22
23
|
function normalizeDeps(input) {
|
|
23
24
|
if (!input) {
|
|
24
25
|
return undefined;
|
|
@@ -335,6 +336,17 @@ async function describePpkBundle(ppkPath, base) {
|
|
|
335
336
|
if (hbcVersion != null)
|
|
336
337
|
meta.bytecodeVersion = hbcVersion;
|
|
337
338
|
await (0, hermes_base_1.cachePut)(bundle).catch(() => { });
|
|
339
|
+
// where the bundle's compressed bytes live inside the ppk, so the next
|
|
340
|
+
// build can fetch just them with one HTTP Range request
|
|
341
|
+
const location = await (0, zip_range_1.locateZipEntry)(ppkPath, (name) => hermes_base_1.BUNDLE_ENTRY_NAMES.includes(name)).catch(() => null);
|
|
342
|
+
if (location &&
|
|
343
|
+
location.compressedSize > 0 &&
|
|
344
|
+
(location.compressionMethod === zip_range_1.ZIP_STORED ||
|
|
345
|
+
location.compressionMethod === zip_range_1.ZIP_DEFLATED)) {
|
|
346
|
+
meta.bundleOffset = location.dataOffset;
|
|
347
|
+
meta.bundleCompressedSize = location.compressedSize;
|
|
348
|
+
meta.bundleCompression = location.compressionMethod;
|
|
349
|
+
}
|
|
338
350
|
}
|
|
339
351
|
}
|
|
340
352
|
catch {
|
package/package.json
CHANGED
package/src/locales/en.ts
CHANGED
|
@@ -218,6 +218,10 @@ This can reduce the risk of inconsistent dependencies and supply chain attacks.
|
|
|
218
218
|
'Hermes base: none ({{- reason}}); compiling without -base-bytecode',
|
|
219
219
|
hermesBaseUsing: 'Hermes base: {{- source}} (HBC v{{version}})',
|
|
220
220
|
hermesBaseDownloading: 'Hermes base: downloading {{- url}}',
|
|
221
|
+
hermesBaseRangeFetched:
|
|
222
|
+
'Hermes base: fetched only the bundle via HTTP Range ({{fetchedKb}} KB of {{totalKb}} KB)',
|
|
223
|
+
hermesBaseRangeFallback:
|
|
224
|
+
'Hermes base: partial download unavailable ({{- reason}}); downloading the whole package',
|
|
221
225
|
hermesBaseCompileFailed:
|
|
222
226
|
'Hermes base compile failed ({{- reason}}); retrying without -base-bytecode',
|
|
223
227
|
hermesBaseCompileFailedLog:
|
package/src/locales/zh.ts
CHANGED
|
@@ -201,6 +201,10 @@ export default {
|
|
|
201
201
|
hermesBaseNone: 'Hermes base:未使用({{- reason}}),按普通方式编译',
|
|
202
202
|
hermesBaseUsing: 'Hermes base:{{- source}}(HBC v{{version}})',
|
|
203
203
|
hermesBaseDownloading: 'Hermes base:下载 {{- url}}',
|
|
204
|
+
hermesBaseRangeFetched:
|
|
205
|
+
'Hermes base:已通过 HTTP Range 仅下载 bundle({{fetchedKb}} KB / 整包 {{totalKb}} KB)',
|
|
206
|
+
hermesBaseRangeFallback:
|
|
207
|
+
'Hermes base:无法按需下载({{- reason}}),改为下载整包',
|
|
204
208
|
hermesBaseCompileFailed:
|
|
205
209
|
'Hermes base 编译失败({{- reason}}),改为不带 -base-bytecode 重编',
|
|
206
210
|
hermesBaseCompileFailedLog: 'Hermes base:完整编译错误已写入 {{- file}}',
|
package/src/utils/hermes-base.ts
CHANGED
|
@@ -18,6 +18,14 @@ import { tempDir } from './constants';
|
|
|
18
18
|
import { getHbcVersion } from './hbcTransform';
|
|
19
19
|
import { t } from './i18n';
|
|
20
20
|
import { enumZipEntries, readEntry } from './zip-entries';
|
|
21
|
+
import {
|
|
22
|
+
fetchZipEntryData,
|
|
23
|
+
openRemoteZip,
|
|
24
|
+
RangeUnsupportedError,
|
|
25
|
+
readRemoteZipEntry,
|
|
26
|
+
ZIP_DEFLATED,
|
|
27
|
+
ZIP_STORED,
|
|
28
|
+
} from './zip-range';
|
|
21
29
|
|
|
22
30
|
export type HermesBaseOption = 'auto' | 'none' | string;
|
|
23
31
|
|
|
@@ -181,6 +189,22 @@ export const BUNDLE_ENTRY_NAMES = [
|
|
|
181
189
|
const APK_BUNDLE = /^assets\/index\.android\.bundle$/;
|
|
182
190
|
const IPA_BUNDLE = /^payload\/[^/]+\.app\/main\.jsbundle$/i;
|
|
183
191
|
|
|
192
|
+
export type BaseArtifactType = 'ppk' | 'apk' | 'ipa' | 'app';
|
|
193
|
+
|
|
194
|
+
/** Which zip entry holds the JS/HBC bundle in each kind of artifact. */
|
|
195
|
+
export function bundleEntryMatcher(
|
|
196
|
+
artifactType: BaseArtifactType,
|
|
197
|
+
): (name: string) => boolean {
|
|
198
|
+
switch (artifactType) {
|
|
199
|
+
case 'apk':
|
|
200
|
+
return (name) => APK_BUNDLE.test(name);
|
|
201
|
+
case 'ipa':
|
|
202
|
+
return (name) => IPA_BUNDLE.test(name.toLowerCase());
|
|
203
|
+
default:
|
|
204
|
+
return (name) => BUNDLE_ENTRY_NAMES.includes(name);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
184
208
|
/**
|
|
185
209
|
* Extract the JS/HBC bundle from a local artifact: a raw bundle file, a ppk,
|
|
186
210
|
* or a native package (apk / ipa / harmony app). Returns null when not found.
|
|
@@ -198,17 +222,10 @@ export async function extractBundleFromArchive(
|
|
|
198
222
|
) {
|
|
199
223
|
return fs.readFile(filePath);
|
|
200
224
|
}
|
|
201
|
-
if (ext === '.ppk') {
|
|
202
|
-
return readFirstZipEntry(
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
}
|
|
206
|
-
if (ext === '.apk') {
|
|
207
|
-
return readFirstZipEntry(filePath, (name) => APK_BUNDLE.test(name));
|
|
208
|
-
}
|
|
209
|
-
if (ext === '.ipa') {
|
|
210
|
-
return readFirstZipEntry(filePath, (name) =>
|
|
211
|
-
IPA_BUNDLE.test(name.toLowerCase()),
|
|
225
|
+
if (ext === '.ppk' || ext === '.apk' || ext === '.ipa') {
|
|
226
|
+
return readFirstZipEntry(
|
|
227
|
+
filePath,
|
|
228
|
+
bundleEntryMatcher(ext.slice(1) as BaseArtifactType),
|
|
212
229
|
);
|
|
213
230
|
}
|
|
214
231
|
if (ext === '.app') {
|
|
@@ -399,10 +416,139 @@ export async function downloadToFile(
|
|
|
399
416
|
export interface HermesBaseServerRecord {
|
|
400
417
|
versionId?: number | null;
|
|
401
418
|
hash: string;
|
|
402
|
-
artifactType?:
|
|
419
|
+
artifactType?: BaseArtifactType;
|
|
403
420
|
bundleHash?: string | null;
|
|
404
421
|
bytecodeVersion?: number | null;
|
|
405
422
|
url: string;
|
|
423
|
+
/**
|
|
424
|
+
* Location of the bundle's compressed bytes inside the ppk, reported by the
|
|
425
|
+
* publishing CLI; lets the base be fetched with a single HTTP Range request.
|
|
426
|
+
*/
|
|
427
|
+
bundleOffset?: number | null;
|
|
428
|
+
bundleCompressedSize?: number | null;
|
|
429
|
+
/** zip compression method: 0 stored, 8 deflate */
|
|
430
|
+
bundleCompression?: number | null;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
interface FetchedBaseBundle {
|
|
434
|
+
bundle: Buffer;
|
|
435
|
+
/** how the bytes were obtained, for the log line */
|
|
436
|
+
transport: 'range-entry' | 'range-zip' | 'full';
|
|
437
|
+
fetchedBytes?: number;
|
|
438
|
+
totalBytes?: number;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function hasBundleLocation(record: HermesBaseServerRecord): boolean {
|
|
442
|
+
return (
|
|
443
|
+
record.bundleOffset != null &&
|
|
444
|
+
record.bundleCompressedSize != null &&
|
|
445
|
+
record.bundleCompression != null &&
|
|
446
|
+
(record.bundleCompression === ZIP_STORED ||
|
|
447
|
+
record.bundleCompression === ZIP_DEFLATED)
|
|
448
|
+
);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
async function saveResponse(
|
|
452
|
+
response: Response,
|
|
453
|
+
destination: string,
|
|
454
|
+
): Promise<void> {
|
|
455
|
+
if (!response.body) throw new Error('empty response body');
|
|
456
|
+
await fs.ensureDir(path.dirname(destination));
|
|
457
|
+
const { Readable } = await import('stream');
|
|
458
|
+
await pipeline(
|
|
459
|
+
Readable.fromWeb(response.body as any),
|
|
460
|
+
fs.createWriteStream(destination),
|
|
461
|
+
);
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* Obtain the base bundle with as little traffic as possible, in order:
|
|
466
|
+
* 1. one Range request for the bundle's compressed bytes when the server
|
|
467
|
+
* knows their location (ppk published by a CLI that reported it);
|
|
468
|
+
* 2. the archive's central directory over Range, then just the bundle
|
|
469
|
+
* entry (any zip: ppk, apk, ipa — harmony .app nests a second zip and
|
|
470
|
+
* is skipped);
|
|
471
|
+
* 3. the whole archive, as before.
|
|
472
|
+
* A server that ignores Range (HTTP 200) streams the full archive into
|
|
473
|
+
* `archive` without a second request. Range results are verified against
|
|
474
|
+
* `record.bundleHash` here; a mismatch (e.g. re-packaged object) falls
|
|
475
|
+
* through to the next transport instead of failing the resolution.
|
|
476
|
+
*/
|
|
477
|
+
export async function fetchBaseBundle(
|
|
478
|
+
record: HermesBaseServerRecord,
|
|
479
|
+
artifactType: BaseArtifactType,
|
|
480
|
+
archive: string,
|
|
481
|
+
log: (message: string) => void = () => {},
|
|
482
|
+
): Promise<FetchedBaseBundle | null> {
|
|
483
|
+
const matches = bundleEntryMatcher(artifactType);
|
|
484
|
+
const verified = (bundle: Buffer | null): Buffer | null => {
|
|
485
|
+
if (!bundle) throw new Error('bundle entry not found');
|
|
486
|
+
if (record.bundleHash && sha256Hex(bundle) !== record.bundleHash) {
|
|
487
|
+
throw new Error('bundleHash mismatch');
|
|
488
|
+
}
|
|
489
|
+
return bundle;
|
|
490
|
+
};
|
|
491
|
+
const fromFullResponse = async (
|
|
492
|
+
response: Response,
|
|
493
|
+
): Promise<FetchedBaseBundle | null> => {
|
|
494
|
+
await saveResponse(response, archive);
|
|
495
|
+
const bundle = await extractBundleFromArchive(archive);
|
|
496
|
+
return bundle ? { bundle, transport: 'full' } : null;
|
|
497
|
+
};
|
|
498
|
+
const skip = (reason: string) =>
|
|
499
|
+
log(t('hermesBaseRangeFallback', { reason }));
|
|
500
|
+
|
|
501
|
+
if (artifactType === 'ppk' && hasBundleLocation(record)) {
|
|
502
|
+
try {
|
|
503
|
+
const { data, fetchedBytes, totalBytes } = await fetchZipEntryData(
|
|
504
|
+
record.url,
|
|
505
|
+
{
|
|
506
|
+
dataOffset: record.bundleOffset as number,
|
|
507
|
+
compressedSize: record.bundleCompressedSize as number,
|
|
508
|
+
compressionMethod: record.bundleCompression as number,
|
|
509
|
+
},
|
|
510
|
+
);
|
|
511
|
+
return {
|
|
512
|
+
bundle: verified(data) as Buffer,
|
|
513
|
+
transport: 'range-entry',
|
|
514
|
+
fetchedBytes,
|
|
515
|
+
totalBytes,
|
|
516
|
+
};
|
|
517
|
+
} catch (error: any) {
|
|
518
|
+
if (error instanceof RangeUnsupportedError) {
|
|
519
|
+
skip('server ignores Range');
|
|
520
|
+
return fromFullResponse(error.response);
|
|
521
|
+
}
|
|
522
|
+
skip(`entry range: ${error?.message ?? error}`);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
if (artifactType !== 'app') {
|
|
527
|
+
try {
|
|
528
|
+
const remote = await openRemoteZip(record.url);
|
|
529
|
+
if (remote.kind === 'full') {
|
|
530
|
+
skip('server ignores Range');
|
|
531
|
+
return fromFullResponse(remote.response);
|
|
532
|
+
}
|
|
533
|
+
const bundle = await readRemoteZipEntry(remote.zipFile, matches);
|
|
534
|
+
return {
|
|
535
|
+
bundle: verified(bundle) as Buffer,
|
|
536
|
+
transport: 'range-zip',
|
|
537
|
+
fetchedBytes: remote.reader.fetchedBytes,
|
|
538
|
+
totalBytes: remote.reader.totalSize,
|
|
539
|
+
};
|
|
540
|
+
} catch (error: any) {
|
|
541
|
+
if (error instanceof RangeUnsupportedError) {
|
|
542
|
+
skip('server ignores Range');
|
|
543
|
+
return fromFullResponse(error.response);
|
|
544
|
+
}
|
|
545
|
+
skip(`zip range: ${error?.message ?? error}`);
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
await downloadToFile(record.url, archive);
|
|
550
|
+
const bundle = await extractBundleFromArchive(archive);
|
|
551
|
+
return bundle ? { bundle, transport: 'full' } : null;
|
|
406
552
|
}
|
|
407
553
|
|
|
408
554
|
export interface ResolveHermesBaseParams {
|
|
@@ -525,10 +671,13 @@ export async function resolveHermesBase(
|
|
|
525
671
|
for (let attempt = 1; attempt <= 2; attempt++) {
|
|
526
672
|
const dir = tmpDir();
|
|
527
673
|
await fs.ensureDir(dir);
|
|
528
|
-
const artifactType = [
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
674
|
+
const artifactType: BaseArtifactType = [
|
|
675
|
+
'ppk',
|
|
676
|
+
'apk',
|
|
677
|
+
'ipa',
|
|
678
|
+
'app',
|
|
679
|
+
].includes(record.artifactType ?? '')
|
|
680
|
+
? (record.artifactType as BaseArtifactType)
|
|
532
681
|
: 'ppk';
|
|
533
682
|
const archive = path.join(
|
|
534
683
|
dir,
|
|
@@ -536,10 +685,18 @@ export async function resolveHermesBase(
|
|
|
536
685
|
);
|
|
537
686
|
try {
|
|
538
687
|
log(t('hermesBaseDownloading', { url: record.url }));
|
|
539
|
-
await
|
|
540
|
-
|
|
541
|
-
if (!bundle)
|
|
688
|
+
const fetched = await fetchBaseBundle(record, artifactType, archive, log);
|
|
689
|
+
if (!fetched)
|
|
542
690
|
throw new Error('bundle entry not found in downloaded package');
|
|
691
|
+
const { bundle } = fetched;
|
|
692
|
+
if (fetched.transport !== 'full') {
|
|
693
|
+
log(
|
|
694
|
+
t('hermesBaseRangeFetched', {
|
|
695
|
+
fetchedKb: Math.ceil((fetched.fetchedBytes ?? 0) / 1024),
|
|
696
|
+
totalKb: Math.ceil((fetched.totalBytes ?? 0) / 1024),
|
|
697
|
+
}),
|
|
698
|
+
);
|
|
699
|
+
}
|
|
543
700
|
const actualHash = sha256Hex(bundle);
|
|
544
701
|
if (record.bundleHash && actualHash !== record.bundleHash) {
|
|
545
702
|
throw new Error(
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
// Byte-range access to zip archives.
|
|
2
|
+
//
|
|
3
|
+
// Two halves of the same trick: at publish time `locateZipEntry` records where
|
|
4
|
+
// the bundle's compressed bytes sit inside the ppk (so the server can hand
|
|
5
|
+
// that location to the next build), and at build time `fetchZipEntryData` /
|
|
6
|
+
// `openRemoteZip` read just the bundle of a remote archive through HTTP Range
|
|
7
|
+
// requests instead of downloading the whole ppk / apk / ipa. Every helper
|
|
8
|
+
// throws on anything unexpected; callers fall back to a full download.
|
|
9
|
+
import fs from 'fs-extra';
|
|
10
|
+
import { PassThrough, Readable } from 'stream';
|
|
11
|
+
import {
|
|
12
|
+
type Entry,
|
|
13
|
+
fromRandomAccessReader,
|
|
14
|
+
open as openZipFile,
|
|
15
|
+
RandomAccessReader,
|
|
16
|
+
type ZipFile,
|
|
17
|
+
} from 'yauzl';
|
|
18
|
+
import { inflateRawSync } from 'zlib';
|
|
19
|
+
import { readEntry } from './zip-entries';
|
|
20
|
+
|
|
21
|
+
export const ZIP_STORED = 0;
|
|
22
|
+
export const ZIP_DEFLATED = 8;
|
|
23
|
+
|
|
24
|
+
const LOCAL_HEADER_SIGNATURE = 0x04034b50;
|
|
25
|
+
const LOCAL_HEADER_SIZE = 30;
|
|
26
|
+
/** covers the EOCD (≤ 22 + 65535 bytes) and, for small archives, everything */
|
|
27
|
+
const TAIL_BYTES = 64 * 1024;
|
|
28
|
+
/** minimum span fetched for header reads, so header + directory share a request */
|
|
29
|
+
const CHUNK_BYTES = 64 * 1024;
|
|
30
|
+
|
|
31
|
+
export interface ZipEntryLocation {
|
|
32
|
+
fileName: string;
|
|
33
|
+
/** absolute offset of the compressed data, past the local file header */
|
|
34
|
+
dataOffset: number;
|
|
35
|
+
compressedSize: number;
|
|
36
|
+
uncompressedSize: number;
|
|
37
|
+
/** 0 = stored, 8 = deflate; anything else cannot be inflated here */
|
|
38
|
+
compressionMethod: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Data location of the first entry matching `matches` in a local zip. */
|
|
42
|
+
export async function locateZipEntry(
|
|
43
|
+
zipPath: string,
|
|
44
|
+
matches: (name: string) => boolean,
|
|
45
|
+
): Promise<ZipEntryLocation | null> {
|
|
46
|
+
const entry = await findEntry(zipPath, matches);
|
|
47
|
+
if (!entry) return null;
|
|
48
|
+
const header = Buffer.alloc(LOCAL_HEADER_SIZE);
|
|
49
|
+
const fd = await fs.open(zipPath, 'r');
|
|
50
|
+
try {
|
|
51
|
+
const { bytesRead } = await fs.read(
|
|
52
|
+
fd,
|
|
53
|
+
header,
|
|
54
|
+
0,
|
|
55
|
+
LOCAL_HEADER_SIZE,
|
|
56
|
+
entry.relativeOffsetOfLocalHeader,
|
|
57
|
+
);
|
|
58
|
+
if (bytesRead !== LOCAL_HEADER_SIZE) {
|
|
59
|
+
throw new Error('truncated local file header');
|
|
60
|
+
}
|
|
61
|
+
} finally {
|
|
62
|
+
await fs.close(fd);
|
|
63
|
+
}
|
|
64
|
+
if (header.readUInt32LE(0) !== LOCAL_HEADER_SIGNATURE) {
|
|
65
|
+
throw new Error('invalid local file header signature');
|
|
66
|
+
}
|
|
67
|
+
const fileNameLength = header.readUInt16LE(26);
|
|
68
|
+
const extraFieldLength = header.readUInt16LE(28);
|
|
69
|
+
return {
|
|
70
|
+
fileName: entry.fileName,
|
|
71
|
+
dataOffset:
|
|
72
|
+
entry.relativeOffsetOfLocalHeader +
|
|
73
|
+
LOCAL_HEADER_SIZE +
|
|
74
|
+
fileNameLength +
|
|
75
|
+
extraFieldLength,
|
|
76
|
+
compressedSize: entry.compressedSize,
|
|
77
|
+
uncompressedSize: entry.uncompressedSize,
|
|
78
|
+
compressionMethod: entry.compressionMethod,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function findEntry(
|
|
83
|
+
zipPath: string,
|
|
84
|
+
matches: (name: string) => boolean,
|
|
85
|
+
): Promise<Entry | null> {
|
|
86
|
+
return new Promise((resolve, reject) => {
|
|
87
|
+
openZipFile(zipPath, { lazyEntries: true }, (err, zipFile) => {
|
|
88
|
+
if (err) return reject(err);
|
|
89
|
+
let found: Entry | null = null;
|
|
90
|
+
zipFile.on('error', reject);
|
|
91
|
+
zipFile.on('end', () => resolve(found));
|
|
92
|
+
zipFile.on('entry', (entry: Entry) => {
|
|
93
|
+
if (!found && matches(entry.fileName)) {
|
|
94
|
+
found = entry;
|
|
95
|
+
zipFile.close();
|
|
96
|
+
resolve(found);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
zipFile.readEntry();
|
|
100
|
+
});
|
|
101
|
+
zipFile.readEntry();
|
|
102
|
+
});
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// ---------------------------------------------------------------------------
|
|
107
|
+
// HTTP Range
|
|
108
|
+
// ---------------------------------------------------------------------------
|
|
109
|
+
|
|
110
|
+
/** The server answered a Range request with the whole body (HTTP 200). */
|
|
111
|
+
export class RangeUnsupportedError extends Error {
|
|
112
|
+
constructor(readonly response: Response) {
|
|
113
|
+
super(`HTTP ${response.status} without Content-Range`);
|
|
114
|
+
this.name = 'RangeUnsupportedError';
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
interface ContentRange {
|
|
119
|
+
start: number;
|
|
120
|
+
end: number;
|
|
121
|
+
total: number;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function parseContentRange(header: string | null): ContentRange | null {
|
|
125
|
+
const match = /^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(header?.trim() ?? '');
|
|
126
|
+
if (!match) return null;
|
|
127
|
+
const [start, end, total] = match.slice(1).map(Number);
|
|
128
|
+
if (end < start || end >= total) return null;
|
|
129
|
+
return { start, end, total };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** One Range request; `end` is exclusive. Resolves with a 206 response. */
|
|
133
|
+
async function fetchRange(
|
|
134
|
+
url: string,
|
|
135
|
+
start: number,
|
|
136
|
+
end: number,
|
|
137
|
+
): Promise<Response & { range: ContentRange }> {
|
|
138
|
+
const response = await fetch(url, {
|
|
139
|
+
headers: {
|
|
140
|
+
Range: `bytes=${start}-${end - 1}`,
|
|
141
|
+
'Accept-Encoding': 'identity',
|
|
142
|
+
},
|
|
143
|
+
});
|
|
144
|
+
if (response.status === 200) throw new RangeUnsupportedError(response);
|
|
145
|
+
if (response.status !== 206 || !response.body) {
|
|
146
|
+
await response.body?.cancel().catch(() => {});
|
|
147
|
+
throw new Error(`HTTP ${response.status} for bytes=${start}-${end - 1}`);
|
|
148
|
+
}
|
|
149
|
+
const range = parseContentRange(response.headers.get('content-range'));
|
|
150
|
+
if (!range || range.start !== start || range.end !== end - 1) {
|
|
151
|
+
await response.body.cancel().catch(() => {});
|
|
152
|
+
throw new Error(
|
|
153
|
+
`unexpected Content-Range ${response.headers.get('content-range')}`,
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
return Object.assign(response, { range });
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function fetchRangeBuffer(
|
|
160
|
+
url: string,
|
|
161
|
+
start: number,
|
|
162
|
+
end: number,
|
|
163
|
+
): Promise<{ data: Buffer; total: number }> {
|
|
164
|
+
const response = await fetchRange(url, start, end);
|
|
165
|
+
const data = Buffer.from(await response.arrayBuffer());
|
|
166
|
+
if (data.length !== end - start) {
|
|
167
|
+
throw new Error(
|
|
168
|
+
`range returned ${data.length} bytes, expected ${end - start}`,
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
return { data, total: response.range.total };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Fetch one entry whose compressed bytes are already located (the ppk's own
|
|
176
|
+
* publish-time report) and decompress it. Returns the raw entry content.
|
|
177
|
+
*/
|
|
178
|
+
export async function fetchZipEntryData(
|
|
179
|
+
url: string,
|
|
180
|
+
location: Pick<
|
|
181
|
+
ZipEntryLocation,
|
|
182
|
+
'dataOffset' | 'compressedSize' | 'compressionMethod'
|
|
183
|
+
>,
|
|
184
|
+
): Promise<{ data: Buffer; fetchedBytes: number; totalBytes: number }> {
|
|
185
|
+
const { dataOffset, compressedSize, compressionMethod } = location;
|
|
186
|
+
if (compressionMethod !== ZIP_STORED && compressionMethod !== ZIP_DEFLATED) {
|
|
187
|
+
throw new Error(`unsupported compression method ${compressionMethod}`);
|
|
188
|
+
}
|
|
189
|
+
if (
|
|
190
|
+
!Number.isInteger(dataOffset) ||
|
|
191
|
+
!Number.isInteger(compressedSize) ||
|
|
192
|
+
dataOffset < 0 ||
|
|
193
|
+
compressedSize <= 0
|
|
194
|
+
) {
|
|
195
|
+
throw new Error('invalid bundle location');
|
|
196
|
+
}
|
|
197
|
+
const { data, total } = await fetchRangeBuffer(
|
|
198
|
+
url,
|
|
199
|
+
dataOffset,
|
|
200
|
+
dataOffset + compressedSize,
|
|
201
|
+
);
|
|
202
|
+
return {
|
|
203
|
+
data: compressionMethod === ZIP_DEFLATED ? inflateRawSync(data) : data,
|
|
204
|
+
fetchedBytes: compressedSize,
|
|
205
|
+
totalBytes: total,
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* yauzl reader over HTTP Range. Header reads (EOCD, central directory, local
|
|
211
|
+
* file headers) are widened to CHUNK_BYTES and cached so a small archive costs
|
|
212
|
+
* one request; entry data streams straight from its own request.
|
|
213
|
+
*/
|
|
214
|
+
export class HttpRangeReader extends RandomAccessReader {
|
|
215
|
+
private readonly chunks: { start: number; data: Buffer }[] = [];
|
|
216
|
+
requests = 0;
|
|
217
|
+
fetchedBytes = 0;
|
|
218
|
+
|
|
219
|
+
constructor(
|
|
220
|
+
private readonly url: string,
|
|
221
|
+
readonly totalSize: number,
|
|
222
|
+
tail?: { start: number; data: Buffer },
|
|
223
|
+
) {
|
|
224
|
+
super();
|
|
225
|
+
if (tail) this.chunks.push(tail);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
private cached(start: number, end: number): Buffer | null {
|
|
229
|
+
for (const chunk of this.chunks) {
|
|
230
|
+
if (start >= chunk.start && end <= chunk.start + chunk.data.length) {
|
|
231
|
+
return chunk.data.subarray(start - chunk.start, end - chunk.start);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
return null;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
_readStreamForRange(start: number, end: number): Readable {
|
|
238
|
+
const hit = this.cached(start, end);
|
|
239
|
+
if (hit) return Readable.from([hit]);
|
|
240
|
+
const out = new PassThrough();
|
|
241
|
+
this.requests++;
|
|
242
|
+
fetchRange(this.url, start, end)
|
|
243
|
+
.then((response) => {
|
|
244
|
+
this.fetchedBytes += end - start;
|
|
245
|
+
const body = Readable.fromWeb(response.body as any);
|
|
246
|
+
body.on('error', (error) => out.destroy(error));
|
|
247
|
+
body.pipe(out);
|
|
248
|
+
})
|
|
249
|
+
.catch((error) => out.destroy(error));
|
|
250
|
+
return out;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
read(
|
|
254
|
+
buffer: Buffer,
|
|
255
|
+
offset: number,
|
|
256
|
+
length: number,
|
|
257
|
+
position: number,
|
|
258
|
+
callback: (err: Error | null, bytesRead?: number) => void,
|
|
259
|
+
): void {
|
|
260
|
+
const hit = this.cached(position, position + length);
|
|
261
|
+
if (hit) {
|
|
262
|
+
hit.copy(buffer, offset);
|
|
263
|
+
setImmediate(() => callback(null, length));
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
const end = Math.min(
|
|
267
|
+
this.totalSize,
|
|
268
|
+
Math.max(position + length, position + CHUNK_BYTES),
|
|
269
|
+
);
|
|
270
|
+
this.requests++;
|
|
271
|
+
fetchRangeBuffer(this.url, position, end).then(
|
|
272
|
+
({ data }) => {
|
|
273
|
+
this.fetchedBytes += data.length;
|
|
274
|
+
this.chunks.push({ start: position, data });
|
|
275
|
+
data.copy(buffer, offset, 0, length);
|
|
276
|
+
callback(null, length);
|
|
277
|
+
},
|
|
278
|
+
(error) => callback(error),
|
|
279
|
+
);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export type RemoteZip =
|
|
284
|
+
| { kind: 'zip'; zipFile: ZipFile; reader: HttpRangeReader }
|
|
285
|
+
/** the server ignored Range: the whole archive is streaming in `response` */
|
|
286
|
+
| { kind: 'full'; response: Response };
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Open a remote zip by fetching its tail (EOCD + central directory for
|
|
290
|
+
* typical archives) and letting yauzl read the rest on demand.
|
|
291
|
+
*/
|
|
292
|
+
export async function openRemoteZip(url: string): Promise<RemoteZip> {
|
|
293
|
+
const response = await fetch(url, {
|
|
294
|
+
headers: { Range: `bytes=-${TAIL_BYTES}`, 'Accept-Encoding': 'identity' },
|
|
295
|
+
});
|
|
296
|
+
if (!response.ok || !response.body) {
|
|
297
|
+
await response.body?.cancel().catch(() => {});
|
|
298
|
+
throw new Error(`HTTP ${response.status}`);
|
|
299
|
+
}
|
|
300
|
+
if (response.status !== 206) return { kind: 'full', response };
|
|
301
|
+
const range = parseContentRange(response.headers.get('content-range'));
|
|
302
|
+
if (!range) {
|
|
303
|
+
await response.body.cancel().catch(() => {});
|
|
304
|
+
throw new Error(
|
|
305
|
+
`unexpected Content-Range ${response.headers.get('content-range')}`,
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
const data = Buffer.from(await response.arrayBuffer());
|
|
309
|
+
if (data.length !== range.end - range.start + 1) {
|
|
310
|
+
throw new Error(
|
|
311
|
+
`tail returned ${data.length} bytes, expected ${range.end - range.start + 1}`,
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
const reader = new HttpRangeReader(url, range.total, {
|
|
315
|
+
start: range.start,
|
|
316
|
+
data,
|
|
317
|
+
});
|
|
318
|
+
reader.requests = 1;
|
|
319
|
+
reader.fetchedBytes = data.length;
|
|
320
|
+
const zipFile = await new Promise<ZipFile>((resolve, reject) => {
|
|
321
|
+
fromRandomAccessReader(
|
|
322
|
+
reader,
|
|
323
|
+
range.total,
|
|
324
|
+
{ lazyEntries: true, autoClose: false },
|
|
325
|
+
(err, file) => (err ? reject(err) : resolve(file)),
|
|
326
|
+
);
|
|
327
|
+
});
|
|
328
|
+
return { kind: 'zip', zipFile, reader };
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** Read the first matching entry of an opened remote zip, then close it. */
|
|
332
|
+
export function readRemoteZipEntry(
|
|
333
|
+
zipFile: ZipFile,
|
|
334
|
+
matches: (name: string) => boolean,
|
|
335
|
+
): Promise<Buffer | null> {
|
|
336
|
+
return new Promise((resolve, reject) => {
|
|
337
|
+
let settled = false;
|
|
338
|
+
const finish = (error: Error | null, result: Buffer | null = null) => {
|
|
339
|
+
if (settled) return;
|
|
340
|
+
settled = true;
|
|
341
|
+
zipFile.close();
|
|
342
|
+
error ? reject(error) : resolve(result);
|
|
343
|
+
};
|
|
344
|
+
zipFile.on('error', (error) => finish(error));
|
|
345
|
+
zipFile.on('end', () => finish(null, null));
|
|
346
|
+
zipFile.on('entry', (entry: Entry) => {
|
|
347
|
+
if (!matches(entry.fileName)) {
|
|
348
|
+
zipFile.readEntry();
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
readEntry(entry, zipFile).then(
|
|
352
|
+
(data) => finish(null, data),
|
|
353
|
+
(error) => finish(error),
|
|
354
|
+
);
|
|
355
|
+
});
|
|
356
|
+
zipFile.readEntry();
|
|
357
|
+
});
|
|
358
|
+
}
|
package/src/versions.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { depVersions } from './utils/dep-versions';
|
|
|
10
10
|
import { getCommitInfo } from './utils/git';
|
|
11
11
|
import { getHbcVersion } from './utils/hbcTransform';
|
|
12
12
|
import {
|
|
13
|
+
BUNDLE_ENTRY_NAMES,
|
|
13
14
|
cachePut,
|
|
14
15
|
extractBundleFromArchive,
|
|
15
16
|
type HermesBaseMeta,
|
|
@@ -17,6 +18,7 @@ import {
|
|
|
17
18
|
} from './utils/hermes-base';
|
|
18
19
|
import { t } from './utils/i18n';
|
|
19
20
|
import { getBooleanOption, getStringListOption } from './utils/options';
|
|
21
|
+
import { locateZipEntry, ZIP_DEFLATED, ZIP_STORED } from './utils/zip-range';
|
|
20
22
|
|
|
21
23
|
interface VersionCommandOptions {
|
|
22
24
|
[key: string]: unknown;
|
|
@@ -480,6 +482,21 @@ async function describePpkBundle(
|
|
|
480
482
|
const hbcVersion = getHbcVersion(bundle) ?? base?.bytecodeVersion;
|
|
481
483
|
if (hbcVersion != null) meta.bytecodeVersion = hbcVersion;
|
|
482
484
|
await cachePut(bundle).catch(() => {});
|
|
485
|
+
// where the bundle's compressed bytes live inside the ppk, so the next
|
|
486
|
+
// build can fetch just them with one HTTP Range request
|
|
487
|
+
const location = await locateZipEntry(ppkPath, (name) =>
|
|
488
|
+
BUNDLE_ENTRY_NAMES.includes(name),
|
|
489
|
+
).catch(() => null);
|
|
490
|
+
if (
|
|
491
|
+
location &&
|
|
492
|
+
location.compressedSize > 0 &&
|
|
493
|
+
(location.compressionMethod === ZIP_STORED ||
|
|
494
|
+
location.compressionMethod === ZIP_DEFLATED)
|
|
495
|
+
) {
|
|
496
|
+
meta.bundleOffset = location.dataOffset;
|
|
497
|
+
meta.bundleCompressedSize = location.compressedSize;
|
|
498
|
+
meta.bundleCompression = location.compressionMethod;
|
|
499
|
+
}
|
|
483
500
|
}
|
|
484
501
|
} catch {
|
|
485
502
|
// best effort: metadata never blocks a publish
|