react-native-update-cli 2.22.7 → 2.22.8

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.
Files changed (59) hide show
  1. package/README.md +1 -1
  2. package/README.zh-CN.md +1 -1
  3. package/cli.json +5 -0
  4. package/lib/api.d.ts +7 -0
  5. package/lib/api.js +106 -38
  6. package/lib/app.js +3 -2
  7. package/lib/bin.js +16 -2
  8. package/lib/bundle-runner.d.ts +11 -4
  9. package/lib/bundle-runner.js +176 -90
  10. package/lib/bundle.d.ts +1 -0
  11. package/lib/bundle.js +2 -0
  12. package/lib/diff.d.ts +9 -0
  13. package/lib/diff.js +162 -120
  14. package/lib/locales/en.d.ts +1 -0
  15. package/lib/locales/en.js +1 -0
  16. package/lib/locales/zh.d.ts +1 -0
  17. package/lib/locales/zh.js +1 -0
  18. package/lib/package.d.ts +7 -3
  19. package/lib/package.js +22 -12
  20. package/lib/types.d.ts +2 -0
  21. package/lib/utils/dep-versions.d.ts +7 -0
  22. package/lib/utils/dep-versions.js +66 -31
  23. package/lib/utils/hbcTransform.d.ts +21 -0
  24. package/lib/utils/hbcTransform.js +146 -5
  25. package/lib/utils/hermes-base.d.ts +21 -4
  26. package/lib/utils/hermes-base.js +146 -37
  27. package/lib/utils/http-helper.d.ts +6 -1
  28. package/lib/utils/http-helper.js +23 -11
  29. package/lib/utils/index.d.ts +30 -1
  30. package/lib/utils/index.js +98 -24
  31. package/lib/utils/latest-version/index.d.ts +11 -8
  32. package/lib/utils/latest-version/index.js +63 -18
  33. package/lib/utils/zip-entries.js +20 -15
  34. package/lib/utils/zip-options.d.ts +2 -0
  35. package/lib/utils/zip-options.js +9 -4
  36. package/lib/utils/zip-range.d.ts +47 -15
  37. package/lib/utils/zip-range.js +192 -83
  38. package/lib/versions.js +19 -9
  39. package/package.json +11 -11
  40. package/src/api.ts +126 -46
  41. package/src/app.ts +3 -2
  42. package/src/bin.ts +17 -2
  43. package/src/bundle-runner.ts +225 -113
  44. package/src/bundle.ts +3 -0
  45. package/src/diff.ts +210 -153
  46. package/src/locales/en.ts +2 -0
  47. package/src/locales/zh.ts +2 -0
  48. package/src/package.ts +26 -13
  49. package/src/types.ts +2 -0
  50. package/src/utils/dep-versions.ts +76 -33
  51. package/src/utils/hbcTransform.ts +194 -5
  52. package/src/utils/hermes-base.ts +156 -45
  53. package/src/utils/http-helper.ts +24 -13
  54. package/src/utils/index.ts +136 -26
  55. package/src/utils/latest-version/index.ts +82 -29
  56. package/src/utils/zip-entries.ts +18 -16
  57. package/src/utils/zip-options.ts +8 -3
  58. package/src/utils/zip-range.ts +244 -88
  59. package/src/versions.ts +17 -7
@@ -19,11 +19,14 @@ const isPackageJson = (obj) => {
19
19
  obj.devDependencies !== undefined ||
20
20
  obj.peerDependencies !== undefined);
21
21
  };
22
+ const resolveRegistryUrl = (pkgName, options) => {
23
+ const i = pkgName.indexOf('/');
24
+ const pkgScope = i !== -1 ? pkgName.slice(0, i) : '';
25
+ return options?.registryUrl ?? (0, registry_url_1.default)(pkgScope);
26
+ };
22
27
  const downloadMetadata = (pkgName, options) => {
23
28
  return new Promise((resolve, reject) => {
24
- const i = pkgName.indexOf('/');
25
- const pkgScope = i !== -1 ? pkgName.slice(0, i) : '';
26
- const registryUrl = options?.registryUrl ?? (0, registry_url_1.default)(pkgScope);
29
+ const registryUrl = resolveRegistryUrl(pkgName, options);
27
30
  const pkgUrl = new url_1.URL(encodeURIComponent(pkgName).replace(/^%40/, '@'), registryUrl);
28
31
  let requestOptions = {
29
32
  headers: {
@@ -60,6 +63,7 @@ const downloadMetadata = (pkgName, options) => {
60
63
  lastUpdateDate: Date.now(),
61
64
  versions: Object.keys(pkgMetadata.versions),
62
65
  distTags: pkgMetadata['dist-tags'],
66
+ registryUrl,
63
67
  });
64
68
  return;
65
69
  }
@@ -89,10 +93,22 @@ const downloadMetadata = (pkgName, options) => {
89
93
  request.on('close', () => {
90
94
  request.removeAllListeners();
91
95
  });
96
+ if (options?.unref) {
97
+ // A background check must never delay the process exit: drop the
98
+ // socket's ref (also for a pooled keep-alive socket, which the agent
99
+ // ref's again right before handing it out).
100
+ request.once('socket', (socket) => {
101
+ socket.unref?.();
102
+ });
103
+ }
92
104
  });
93
105
  };
94
106
  const getCacheDir = (name = '@badisi/latest-version') => {
95
107
  const homeDir = (0, os_1.homedir)();
108
+ if (process.env.XDG_CACHE_HOME) {
109
+ // an explicit override wins on every platform (also lets tests isolate)
110
+ return (0, path_1.join)(process.env.XDG_CACHE_HOME, name);
111
+ }
96
112
  switch (process.platform) {
97
113
  case 'darwin':
98
114
  return (0, path_1.join)(homeDir, 'Library', 'Caches', name);
@@ -103,32 +119,61 @@ const getCacheDir = (name = '@badisi/latest-version') => {
103
119
  }
104
120
  };
105
121
  const saveMetadataToCache = (pkg) => {
106
- const filePath = (0, path_1.join)(getCacheDir(), `${pkg.name}.json`);
107
- if (!(0, fs_1.existsSync)((0, path_1.dirname)(filePath))) {
108
- (0, fs_1.mkdirSync)((0, path_1.dirname)(filePath), { recursive: true });
122
+ try {
123
+ const filePath = (0, path_1.join)(getCacheDir(), `${pkg.name}.json`);
124
+ if (!(0, fs_1.existsSync)((0, path_1.dirname)(filePath))) {
125
+ (0, fs_1.mkdirSync)((0, path_1.dirname)(filePath), { recursive: true });
126
+ }
127
+ (0, fs_1.writeFileSync)(filePath, JSON.stringify(pkg));
128
+ }
129
+ catch {
130
+ // a read-only or missing cache dir must not turn into an error
109
131
  }
110
- (0, fs_1.writeFileSync)(filePath, JSON.stringify(pkg));
111
132
  };
133
+ /**
134
+ * The cached metadata of a package (from the same registry), and whether it is
135
+ * still younger than `cacheMaxAge`. A stale entry is returned as well so it can
136
+ * serve as a fallback when the registry is unreachable.
137
+ */
112
138
  const getMetadataFromCache = (pkgName, options) => {
113
139
  const maxAge = options?.cacheMaxAge ?? exports.ONE_DAY;
114
- if (maxAge !== 0) {
140
+ try {
115
141
  const pkgCacheFilePath = (0, path_1.join)(getCacheDir(), `${pkgName}.json`);
116
- if ((0, fs_1.existsSync)(pkgCacheFilePath)) {
117
- const pkg = JSON.parse((0, fs_1.readFileSync)(pkgCacheFilePath).toString());
118
- if (Date.now() - pkg.lastUpdateDate < maxAge) {
119
- return pkg;
120
- }
142
+ if (!(0, fs_1.existsSync)(pkgCacheFilePath)) {
143
+ return undefined;
144
+ }
145
+ const metadata = JSON.parse((0, fs_1.readFileSync)(pkgCacheFilePath).toString());
146
+ if (!metadata ||
147
+ typeof metadata.lastUpdateDate !== 'number' ||
148
+ !metadata.distTags ||
149
+ metadata.registryUrl !== resolveRegistryUrl(pkgName, options)) {
150
+ return undefined;
121
151
  }
152
+ const age = Date.now() - metadata.lastUpdateDate;
153
+ return { metadata, fresh: maxAge !== 0 && age >= 0 && age < maxAge };
154
+ }
155
+ catch {
156
+ return undefined; // unreadable / corrupt cache is the same as no cache
122
157
  }
123
- return undefined; // invalidates cache
124
158
  };
125
159
  const getRegistryVersions = async (pkgName, tagOrRange, options) => {
126
160
  let pkgMetadata;
127
161
  if (pkgName.length && options?.useCache) {
128
- pkgMetadata = getMetadataFromCache(pkgName, options);
129
- if (!pkgMetadata) {
130
- pkgMetadata = await downloadMetadata(pkgName, options);
131
- saveMetadataToCache(pkgMetadata);
162
+ const cached = getMetadataFromCache(pkgName, options);
163
+ if (cached?.fresh) {
164
+ pkgMetadata = cached.metadata;
165
+ }
166
+ else {
167
+ try {
168
+ pkgMetadata = await downloadMetadata(pkgName, options);
169
+ saveMetadataToCache(pkgMetadata);
170
+ }
171
+ catch (err) {
172
+ if (!cached) {
173
+ throw err;
174
+ }
175
+ pkgMetadata = cached.metadata; // stale beats nothing
176
+ }
132
177
  }
133
178
  }
134
179
  else if (pkgName.length) {
@@ -45,7 +45,6 @@ const os_1 = __importDefault(require("os"));
45
45
  const path_1 = __importDefault(require("path"));
46
46
  const promises_1 = require("stream/promises");
47
47
  const yauzl_1 = require("yauzl");
48
- const i18n_1 = require("./i18n");
49
48
  function readEntry(entry, zipFile) {
50
49
  const buffers = [];
51
50
  return new Promise((resolve, reject) => {
@@ -60,7 +59,8 @@ function readEntry(entry, zipFile) {
60
59
  buffers.push(chunk);
61
60
  });
62
61
  stream.on('end', () => {
63
- resolve(Buffer.concat(buffers));
62
+ // a single chunk (a cached Range read) is handed back as-is, not copied
63
+ resolve(buffers.length === 1 ? buffers[0] : Buffer.concat(buffers));
64
64
  });
65
65
  stream.on('error', (err) => {
66
66
  reject(err);
@@ -168,19 +168,23 @@ async function enumZipEntries(zipFn, callback, nestedPath = '') {
168
168
  entry.fileName.toLowerCase().endsWith('.hap')) {
169
169
  const tempDir = await fs.mkdtemp(path_1.default.join(os_1.default.tmpdir(), 'nested_zip_'));
170
170
  const tempZipPath = path_1.default.join(tempDir, 'temp.zip');
171
- await new Promise((res, rej) => {
172
- zipfile.openReadStream(entry, async (err, readStream) => {
173
- if (err)
174
- return rej(err);
175
- const writeStream = fs.createWriteStream(tempZipPath);
176
- readStream.on('error', rej);
177
- readStream.pipe(writeStream);
178
- writeStream.on('finish', () => res(void 0));
179
- writeStream.on('error', rej);
171
+ try {
172
+ await new Promise((res, rej) => {
173
+ zipfile.openReadStream(entry, async (err, readStream) => {
174
+ if (err)
175
+ return rej(err);
176
+ const writeStream = fs.createWriteStream(tempZipPath);
177
+ readStream.on('error', rej);
178
+ readStream.pipe(writeStream);
179
+ writeStream.on('finish', () => res(void 0));
180
+ writeStream.on('error', rej);
181
+ });
180
182
  });
181
- });
182
- await enumZipEntries(tempZipPath, callback, `${fullPath}/`);
183
- await fs.remove(tempDir);
183
+ await enumZipEntries(tempZipPath, callback, `${fullPath}/`);
184
+ }
185
+ finally {
186
+ await fs.remove(tempDir);
187
+ }
184
188
  }
185
189
  const result = callback(entry, zipfile, fullPath);
186
190
  if (result && typeof result.then === 'function') {
@@ -188,7 +192,8 @@ async function enumZipEntries(zipFn, callback, nestedPath = '') {
188
192
  }
189
193
  }
190
194
  catch (error) {
191
- console.error((0, i18n_1.t)('processingError', { error }));
195
+ // the rejection carries the error; logging it here too would make
196
+ // callers report it twice
192
197
  zipfile.close();
193
198
  reject(error);
194
199
  return;
@@ -4,6 +4,8 @@ export type ZipEntryOptions = {
4
4
  };
5
5
  export declare const ZIP_ENTRY_SNIFF_BYTES = 64;
6
6
  export declare const MANIFEST_COMPRESSION_THRESHOLD_BYTES = 256;
7
+ export declare const PAYLOAD_COMPRESSION_LEVEL = 6;
8
+ export declare const MANIFEST_COMPRESSION_LEVEL = 9;
7
9
  export declare function zipOptionsForPatchEntry(): ZipEntryOptions;
8
10
  export declare function zipOptionsForManifestEntry(byteLength?: number): ZipEntryOptions;
9
11
  export declare function zipOptionsForPayloadEntry(fileName: string, prefix?: Buffer): ZipEntryOptions;
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.MANIFEST_COMPRESSION_THRESHOLD_BYTES = exports.ZIP_ENTRY_SNIFF_BYTES = void 0;
39
+ exports.MANIFEST_COMPRESSION_LEVEL = exports.PAYLOAD_COMPRESSION_LEVEL = exports.MANIFEST_COMPRESSION_THRESHOLD_BYTES = exports.ZIP_ENTRY_SNIFF_BYTES = void 0;
40
40
  exports.zipOptionsForPatchEntry = zipOptionsForPatchEntry;
41
41
  exports.zipOptionsForManifestEntry = zipOptionsForManifestEntry;
42
42
  exports.zipOptionsForPayloadEntry = zipOptionsForPayloadEntry;
@@ -45,6 +45,11 @@ const fs = __importStar(require("fs"));
45
45
  const path_1 = __importDefault(require("path"));
46
46
  exports.ZIP_ENTRY_SNIFF_BYTES = 64;
47
47
  exports.MANIFEST_COMPRESSION_THRESHOLD_BYTES = 256;
48
+ // Deflate level for the bundle/asset payload. Level 9 measured ~4x the CPU
49
+ // of level 6 on Hermes bytecode for ~0.6% smaller output, so 6 is the sweet
50
+ // spot; the manifest is tiny, so it can afford 9.
51
+ exports.PAYLOAD_COMPRESSION_LEVEL = 6;
52
+ exports.MANIFEST_COMPRESSION_LEVEL = 9;
48
53
  const alreadyCompressedExtensions = new Set([
49
54
  '.7z',
50
55
  '.aab',
@@ -155,7 +160,7 @@ function zipOptionsForPatchEntry() {
155
160
  }
156
161
  function zipOptionsForManifestEntry(byteLength = 0) {
157
162
  if (byteLength >= exports.MANIFEST_COMPRESSION_THRESHOLD_BYTES) {
158
- return { compressionLevel: 9 };
163
+ return { compressionLevel: exports.MANIFEST_COMPRESSION_LEVEL };
159
164
  }
160
165
  return { compress: false };
161
166
  }
@@ -163,7 +168,7 @@ function zipOptionsForPayloadEntry(fileName, prefix) {
163
168
  if (prefix && prefix.length > 0) {
164
169
  if (hasHermesBytecodeMagic(prefix)) {
165
170
  // Hermes bytecode is binary, but still benefits significantly from zip deflate.
166
- return { compress: true, compressionLevel: 9 };
171
+ return { compress: true, compressionLevel: exports.PAYLOAD_COMPRESSION_LEVEL };
167
172
  }
168
173
  if (hasAlreadyCompressedMagic(prefix)) {
169
174
  return { compress: false };
@@ -173,7 +178,7 @@ function zipOptionsForPayloadEntry(fileName, prefix) {
173
178
  if (alreadyCompressedExtensions.has(extension)) {
174
179
  return { compress: false };
175
180
  }
176
- return { compress: true, compressionLevel: 9 };
181
+ return { compress: true, compressionLevel: exports.PAYLOAD_COMPRESSION_LEVEL };
177
182
  }
178
183
  function zipOptionsForPayloadFile(filePath, entryName = filePath) {
179
184
  return zipOptionsForPayloadEntry(entryName, readFilePrefix(filePath));
@@ -28,6 +28,15 @@ export declare function readZipEntryWithLocation(zipPath: string, matches: (name
28
28
  * fetched by a single Range request (unknown, empty or exotic compression).
29
29
  */
30
30
  export declare function bundleLocationFields(location: ZipEntryLocation | null | undefined): Record<string, number>;
31
+ /** Deadlines for the Range requests; every field has a default. */
32
+ export interface RangeOptions {
33
+ /** reads of at most CHUNK_BYTES (tail, headers, directory pages), default 20 s */
34
+ headerTimeoutMs?: number;
35
+ /** base deadline for larger reads (entry data, a prefetched directory), default 30 s */
36
+ dataTimeoutMs?: number;
37
+ /** added to `dataTimeoutMs` per MB requested, default 1 s */
38
+ dataTimeoutPerMbMs?: number;
39
+ }
31
40
  /** The server answered a Range request with the whole body (HTTP 200). */
32
41
  export declare class RangeUnsupportedError extends Error {
33
42
  readonly response: Response;
@@ -39,34 +48,49 @@ interface ContentRange {
39
48
  total: number;
40
49
  }
41
50
  export declare function parseContentRange(header: string | null): ContentRange | null;
51
+ /**
52
+ * The validator to send as `If-Range` on later requests for the same object,
53
+ * so a replaced archive answers 200 (handled like a server without Range)
54
+ * instead of mixing bytes of two versions. Weak ETags are not allowed there.
55
+ */
56
+ export declare function rangeValidator(headers: Headers): string | undefined;
42
57
  /**
43
58
  * Fetch one entry whose compressed bytes are already located (the ppk's own
44
59
  * publish-time report) and decompress it. Returns the raw entry content.
45
60
  */
46
- export declare function fetchZipEntryData(url: string, location: Pick<ZipEntryLocation, 'dataOffset' | 'compressedSize' | 'compressionMethod'>): Promise<{
61
+ export declare function fetchZipEntryData(url: string, location: Pick<ZipEntryLocation, 'dataOffset' | 'compressedSize' | 'compressionMethod'>, options?: RangeOptions): Promise<{
47
62
  data: Buffer;
48
63
  fetchedBytes: number;
49
64
  totalBytes: number;
50
65
  }>;
66
+ export interface HttpRangeReaderOptions extends RangeOptions {
67
+ /** validator of the archive (see `rangeValidator`), sent as If-Range */
68
+ ifRange?: string;
69
+ }
70
+ interface Chunk {
71
+ start: number;
72
+ data: Buffer;
73
+ }
51
74
  /**
52
75
  * yauzl reader over HTTP Range. Header reads (EOCD, central directory, local
53
- * file headers) are widened to CHUNK_BYTES and cached — adjacent or
54
- * overlapping chunks are merged so a read never re-fetches bytes it already
55
- * has — and entry data reuses whatever prefix the cache holds (typically the
56
- * bytes following the local file header) before requesting the rest.
76
+ * file headers) are widened to CHUNK_BYTES and cached. Chunks are kept as
77
+ * fetched — only overlapping ones are merged, touching ones are read across —
78
+ * so an entry's bytes are held once, and a read reuses whatever prefix the
79
+ * cache holds (typically the bytes following the local file header) before
80
+ * requesting the rest. Every request after the first carries If-Range and
81
+ * must report the same archive size.
57
82
  */
58
83
  export declare class HttpRangeReader extends RandomAccessReader {
59
84
  private readonly url;
60
85
  readonly totalSize: number;
86
+ private readonly options;
87
+ /** sorted by `start`, never overlapping */
61
88
  private chunks;
62
89
  /** span a header read inside it should widen to (see `hintEntry`) */
63
90
  private hint;
64
91
  requests: number;
65
92
  fetchedBytes: number;
66
- constructor(url: string, totalSize: number, tail?: {
67
- start: number;
68
- data: Buffer;
69
- });
93
+ constructor(url: string, totalSize: number, tail?: Chunk, options?: HttpRangeReaderOptions);
70
94
  /**
71
95
  * The next entry to be read: yauzl first reads its local file header, and
72
96
  * widening that read to the entry's data makes the data stream a cache hit
@@ -74,13 +98,21 @@ export declare class HttpRangeReader extends RandomAccessReader {
74
98
  * may understate the local header's extra field, hence the slack.
75
99
  */
76
100
  hintEntry(entry: Entry): void;
77
- /** Cache `data` at `start`, merging with any chunk it touches. */
101
+ /** Cache `data` at `start`, merging with any chunk it overlaps. */
78
102
  addChunk(start: number, data: Buffer): void;
79
- /** cached bytes starting exactly at `start`, up to `end` (may be shorter) */
80
- private cachedPrefix;
81
- private cached;
82
- /** start of the cached chunk holding byte `end - 1`, when there is one */
103
+ /** Fetch `[start, end)` into the cache in one request. */
104
+ prefetch(start: number, end: number): Promise<void>;
105
+ private requestOptions;
106
+ private fetchBuffer;
107
+ /**
108
+ * Contiguous cached pieces starting exactly at `start`, up to `end`: views
109
+ * into one chunk or into a run of touching chunks, possibly ending short.
110
+ */
111
+ private cachedPieces;
112
+ /** start of the cached run (touching chunks) holding byte `end - 1` */
83
113
  private cachedSuffixStart;
114
+ /** start of the first cached chunk at or after `position` */
115
+ private nextCachedStart;
84
116
  _readStreamForRange(start: number, end: number): Readable;
85
117
  read(buffer: Buffer, offset: number, length: number, position: number, callback: (err: Error | null, bytesRead?: number) => void): void;
86
118
  }
@@ -102,7 +134,7 @@ export type RemoteZip = {
102
134
  * Open a remote zip by fetching its tail (EOCD + central directory for
103
135
  * typical archives) and letting yauzl read the rest on demand.
104
136
  */
105
- export declare function openRemoteZip(url: string): Promise<RemoteZip>;
137
+ export declare function openRemoteZip(url: string, options?: RangeOptions): Promise<RemoteZip>;
106
138
  /**
107
139
  * Read the first matching entry of an opened remote zip, then close it. With
108
140
  * `reader` given, the entry's header and data are fetched in one request.