react-native-update-cli 2.22.4 → 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.
@@ -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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-update-cli",
3
- "version": "2.22.4",
3
+ "version": "2.22.6",
4
4
  "description": "command line tool for react-native-update (remote updates for react native)",
5
5
  "main": "lib/exports.js",
6
6
  "types": "lib/exports.d.ts",
@@ -552,6 +552,37 @@ async function checkGradleConfig(): Promise<GradleConfig> {
552
552
  * simply stays in the intermediate directory (never packed into the ppk) so
553
553
  * `address at` stack frames can still be symbolicated later.
554
554
  */
555
+ /**
556
+ * hermesc echoes every diagnostic as three lines (header, the offending source
557
+ * line, a caret line). Minified bundles put a whole module on one line, so a
558
+ * single warning can be 100k+ characters and blindly keeping the tail of stderr
559
+ * buries the actual error under warning noise. Keep the diagnostic headers,
560
+ * prefer errors over warnings, and cap the length of whatever survives.
561
+ */
562
+ export function summarizeHermescStderr(stderr: string): string {
563
+ const raw = String(stderr ?? '').split(/\r?\n/);
564
+ const kept: string[] = [];
565
+ for (let i = 0; i < raw.length; i++) {
566
+ const line = raw[i].trim();
567
+ if (!line) continue;
568
+ if (/^\^~*$/.test(line)) continue; // caret line
569
+ // the line before a caret is the echoed source, never the message
570
+ const next = raw[i + 1]?.trim();
571
+ if (next && /^\^~*$/.test(next)) continue;
572
+ kept.push(line.length > 300 ? `${line.slice(0, 300)}…` : line);
573
+ }
574
+ if (kept.length === 0) return '';
575
+ const isError = (line: string) =>
576
+ /(?::\s*|^)(?:fatal error|error)\b/i.test(line) ||
577
+ /^(?:Assertion|Stack dump|PLEASE submit a bug report)/i.test(line);
578
+ const errors = kept.filter(isError);
579
+ if (errors.length > 0) return errors.slice(-3).join(' ');
580
+ const notWarnings = kept.filter(
581
+ (line) => !/:\s*(?:warning|note):/i.test(line),
582
+ );
583
+ return (notWarnings.length > 0 ? notWarnings : kept).slice(-3).join(' ');
584
+ }
585
+
555
586
  export function buildHermescArgs(bundlePath: string): string[] {
556
587
  return [
557
588
  '-emit-binary',
@@ -604,14 +635,21 @@ async function compileHermesByteCode(
604
635
  if (attempt.status === 0) {
605
636
  usedBase = true;
606
637
  } else {
607
- const stderr = attempt.stderr
608
- ? String(attempt.stderr).trim().split('\n').slice(-3).join(' ')
609
- : '';
638
+ const fullStderr = attempt.stderr ? String(attempt.stderr) : '';
639
+ const reason = summarizeHermescStderr(fullStderr);
610
640
  console.warn(
611
641
  t('hermesBaseCompileFailed', {
612
- reason: stderr || `exit ${attempt.status}`,
642
+ reason: reason || `exit ${attempt.status}`,
613
643
  }),
614
644
  );
645
+ if (fullStderr.trim()) {
646
+ // the summary drops warning noise; keep everything for bug reports
647
+ const logPath = path.join(outputFolder, 'hermes-base-error.log');
648
+ try {
649
+ fs.writeFileSync(logPath, fullStderr);
650
+ console.warn(t('hermesBaseCompileFailedLog', { file: logPath }));
651
+ } catch {}
652
+ }
615
653
  fs.copyFileSync(jsBackup, bundlePath);
616
654
  }
617
655
  }
package/src/locales/en.ts CHANGED
@@ -218,8 +218,14 @@ 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',
227
+ hermesBaseCompileFailedLog:
228
+ 'Hermes base: full compiler output written to {{- file}}',
223
229
  hermesBaseVerified:
224
230
  'Hermes base: bytecode verified equivalent to a plain compile',
225
231
  hermesBaseVerifyFailed:
package/src/locales/zh.ts CHANGED
@@ -201,8 +201,13 @@ 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 重编',
210
+ hermesBaseCompileFailedLog: 'Hermes base:完整编译错误已写入 {{- file}}',
206
211
  hermesBaseVerified: 'Hermes base:字节码与普通编译等价,校验通过',
207
212
  hermesBaseVerifyFailed:
208
213
  'Hermes base:字节码与普通编译不等价,放弃 base 重新编译',
@@ -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(filePath, (name) =>
203
- BUNDLE_ENTRY_NAMES.includes(name),
204
- );
205
- }
206
- if (ext === '.apk') {
207
- return readFirstZipEntry(filePath, (name) => APK_BUNDLE.test(name));
208
- }
209
- if (ext === '.ipa') {
210
- return readFirstZipEntry(filePath, (name) =>
211
- IPA_BUNDLE.test(name.toLowerCase()),
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?: 'ppk' | 'apk' | 'ipa' | 'app';
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 = ['ppk', 'apk', 'ipa', 'app'].includes(
529
- record.artifactType ?? '',
530
- )
531
- ? record.artifactType
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 downloadToFile(record.url, archive);
540
- const bundle = await extractBundleFromArchive(archive);
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(