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,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