react-native-update-cli 2.22.7 → 2.22.9

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 (65) 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/native-package.d.ts +5 -1
  19. package/lib/native-package.js +145 -84
  20. package/lib/package.d.ts +7 -3
  21. package/lib/package.js +22 -12
  22. package/lib/types.d.ts +2 -0
  23. package/lib/utils/dep-versions.d.ts +7 -0
  24. package/lib/utils/dep-versions.js +66 -31
  25. package/lib/utils/hbcTransform.d.ts +21 -0
  26. package/lib/utils/hbcTransform.js +146 -5
  27. package/lib/utils/hermes-base.d.ts +21 -4
  28. package/lib/utils/hermes-base.js +146 -37
  29. package/lib/utils/http-helper.d.ts +6 -1
  30. package/lib/utils/http-helper.js +23 -11
  31. package/lib/utils/index.d.ts +30 -1
  32. package/lib/utils/index.js +98 -24
  33. package/lib/utils/latest-version/index.d.ts +11 -8
  34. package/lib/utils/latest-version/index.js +91 -25
  35. package/lib/utils/zip-entries.js +20 -15
  36. package/lib/utils/zip-options.d.ts +2 -0
  37. package/lib/utils/zip-options.js +9 -4
  38. package/lib/utils/zip-range.d.ts +47 -15
  39. package/lib/utils/zip-range.js +192 -83
  40. package/lib/utils/zip-raw-writer.d.ts +47 -0
  41. package/lib/utils/zip-raw-writer.js +204 -0
  42. package/lib/versions.js +19 -9
  43. package/package.json +10 -12
  44. package/src/api.ts +126 -46
  45. package/src/app.ts +3 -2
  46. package/src/bin.ts +17 -2
  47. package/src/bundle-runner.ts +225 -113
  48. package/src/bundle.ts +3 -0
  49. package/src/diff.ts +210 -153
  50. package/src/locales/en.ts +2 -0
  51. package/src/locales/zh.ts +2 -0
  52. package/src/native-package.ts +186 -96
  53. package/src/package.ts +26 -13
  54. package/src/types.ts +2 -0
  55. package/src/utils/dep-versions.ts +76 -33
  56. package/src/utils/hbcTransform.ts +194 -5
  57. package/src/utils/hermes-base.ts +156 -45
  58. package/src/utils/http-helper.ts +24 -13
  59. package/src/utils/index.ts +136 -26
  60. package/src/utils/latest-version/index.ts +109 -33
  61. package/src/utils/zip-entries.ts +18 -16
  62. package/src/utils/zip-options.ts +8 -3
  63. package/src/utils/zip-range.ts +244 -88
  64. package/src/utils/zip-raw-writer.ts +247 -0
  65. package/src/versions.ts +17 -7
@@ -1,18 +1,34 @@
1
1
  import chalk from 'chalk';
2
- import { satisfies } from 'compare-versions';
2
+ import { compare, satisfies } from 'compare-versions';
3
3
  import { createHash } from 'crypto';
4
4
  import path from 'path';
5
5
  import type { Root as ProtobufRoot } from 'protobufjs';
6
6
  import { read } from 'read';
7
7
  import { open as openZipFile, type Entry as YauzlEntry } from 'yauzl';
8
8
  import pkg from '../../package.json';
9
- import latestVersion from '../utils/latest-version';
10
- import AppInfoParser from './app-info-parser';
9
+ import type AppInfoParserType from './app-info-parser';
11
10
  import { checkPlugins } from './check-plugin';
12
11
  import { IS_CRESC } from './constants';
13
- import { depVersions } from './dep-versions';
12
+ import { getDepVersions } from './dep-versions';
14
13
  import { t } from './i18n';
15
14
 
15
+ // app-info-parser (and its zip/plist/protobuf stack) is only needed by the
16
+ // package commands; load it on first use instead of on every CLI start.
17
+ function createAppInfoParser(fn: string): AppInfoParserType {
18
+ const { default: AppInfoParser } =
19
+ require('./app-info-parser') as typeof import('./app-info-parser');
20
+ return new AppInfoParser(fn);
21
+ }
22
+
23
+ /**
24
+ * tty-table (~25 ms to load) only when a table is rendered. Bun's require of
25
+ * a CJS module can hand back a namespace object, so unwrap `default`.
26
+ */
27
+ export function loadTtyTable(): typeof import('tty-table') {
28
+ const mod = require('tty-table');
29
+ return (mod.default ?? mod) as typeof import('tty-table');
30
+ }
31
+
16
32
  type ApkMetaEntry = {
17
33
  name?: string;
18
34
  value?: string | number | Array<string | number>;
@@ -160,7 +176,7 @@ export const ApkBundleFileName = /^assets\/index\.android\.bundle$/;
160
176
  const ApkUpdateJsonName = /^res\/raw\/update\.json$/;
161
177
 
162
178
  export async function getApkInfo(fn: string) {
163
- const appInfoParser = new AppInfoParser(fn);
179
+ const appInfoParser = createAppInfoParser(fn);
164
180
  // read both entries in a single scan over the archive
165
181
  const entries = await appInfoParser.parser.getEntries([
166
182
  ApkBundleFileName,
@@ -208,7 +224,7 @@ export async function getApkInfo(fn: string) {
208
224
  }
209
225
 
210
226
  export async function getAppInfo(fn: string) {
211
- const appInfoParser = new AppInfoParser(fn);
227
+ const appInfoParser = createAppInfoParser(fn);
212
228
  // single scan (and single nested .hap extraction) for all three entries
213
229
  const [bundleFile, updateJsonFile, metaJsonFile] =
214
230
  await appInfoParser.parser.getEntriesFromHarmonyApp([
@@ -259,7 +275,7 @@ const IpaBuildTimeFrameworkName =
259
275
  /^payload\/[^/]+\.app\/frameworks\/react_native_update\.framework\/pushy_build_time\.txt$/;
260
276
 
261
277
  export async function getIpaInfo(fn: string) {
262
- const appInfoParser = new AppInfoParser(fn);
278
+ const appInfoParser = createAppInfoParser(fn);
263
279
  // read all four entries in a single scan over the archive
264
280
  const entries = await appInfoParser.parser.getEntries([
265
281
  IpaBundleFileName,
@@ -490,34 +506,101 @@ async function resolveResource(
490
506
  return null;
491
507
  }
492
508
 
493
- async function getLatestVersion(pkgNames: string[]) {
494
- return latestVersion(pkgNames, {
495
- // useCache: true,
509
+ const VERSION_CHECK_PACKAGES = [
510
+ 'react-native-update-cli',
511
+ 'react-native-update',
512
+ ];
513
+
514
+ /**
515
+ * Latest registry versions of the CLI and the client library, in that order
516
+ * (`undefined` where unknown). Never rejects.
517
+ *
518
+ * `background: true` answers from a 1-day cache when possible and otherwise
519
+ * refreshes it with an unref'd request, so the process is free to exit before
520
+ * the registry answers; `background: false` always asks the registry and
521
+ * waits (refreshing the cache on the way).
522
+ */
523
+ async function getLatestVersions(
524
+ background: boolean,
525
+ ): Promise<Array<string | undefined>> {
526
+ // the registry client pulls in global-dirs/registry-auth-token/semver: only
527
+ // pay for them when actually checking
528
+ const { default: latestVersion } =
529
+ require('./latest-version') as typeof import('./latest-version');
530
+ return latestVersion(VERSION_CHECK_PACKAGES, {
531
+ useCache: true,
532
+ ...(background ? { unref: true } : { cacheMaxAge: 0 }),
496
533
  requestOptions: {
497
534
  timeout: 2000,
498
535
  },
499
536
  })
500
537
  .then((pkgs) => pkgs.map((pkg) => pkg.latest))
501
- .catch(() => []);
538
+ .catch(() => VERSION_CHECK_PACKAGES.map(() => undefined));
502
539
  }
503
540
 
504
- export async function printVersionCommand() {
505
- let [latestRnuCliVersion, latestRnuVersion] = await getLatestVersion([
506
- 'react-native-update-cli',
507
- 'react-native-update',
508
- ]);
509
- latestRnuCliVersion = latestRnuCliVersion
510
- ? ` ${t('latestVersionTag', {
511
- version: chalk.green(latestRnuCliVersion),
512
- })}`
541
+ function isNewer(latest: string | undefined, current: string | undefined) {
542
+ if (!latest || !current) {
543
+ return false;
544
+ }
545
+ try {
546
+ return compare(latest, current, '>');
547
+ } catch {
548
+ return false;
549
+ }
550
+ }
551
+
552
+ function latestTag(version: string | undefined) {
553
+ return version
554
+ ? ` ${t('latestVersionTag', { version: chalk.green(version) })}`
513
555
  : '';
514
- console.log(`react-native-update-cli: ${pkg.version}${latestRnuCliVersion}`);
515
- const rnuVersion = depVersions['react-native-update'];
556
+ }
557
+
558
+ export interface VersionCheck {
559
+ /** settles once the registry check has finished (or failed); never rejects */
560
+ done: Promise<void>;
561
+ /** wait for the check, but never longer than `graceMs` */
562
+ settle: (graceMs: number) => Promise<void>;
563
+ /**
564
+ * Print the "newer version available" hints if the check has completed by
565
+ * now; a no-op while it is still pending, when nothing is newer, and after
566
+ * the first call. Safe to call from a process 'exit' handler.
567
+ */
568
+ printHints: () => void;
569
+ }
570
+
571
+ /**
572
+ * Print the installed CLI / react-native-update versions (and refuse or warn
573
+ * about unsupported client versions) immediately, without touching the
574
+ * network.
575
+ *
576
+ * With `wait: true` (the `-v`/`version` command) the registry is queried
577
+ * first and the latest versions are printed inline. Otherwise the registry
578
+ * check runs in the background and the returned `printHints` shows what is
579
+ * newer once the command is done — the command itself is never delayed by it.
580
+ */
581
+ export async function printVersionCommand({
582
+ wait = true,
583
+ }: {
584
+ wait?: boolean;
585
+ } = {}): Promise<VersionCheck> {
586
+ const rnuVersion = getDepVersions()['react-native-update'];
587
+
588
+ let latest: Array<string | undefined> | undefined;
589
+ const check = getLatestVersions(!wait).then((versions) => {
590
+ latest = versions;
591
+ });
592
+ if (wait) {
593
+ await check;
594
+ }
595
+ const [latestCliVersion, latestRnuVersion] = latest ?? [];
596
+
597
+ console.log(
598
+ `react-native-update-cli: ${pkg.version}${latestTag(latestCliVersion)}`,
599
+ );
516
600
  if (rnuVersion) {
517
- latestRnuVersion = latestRnuVersion
518
- ? ` ${t('latestVersionTag', { version: chalk.green(latestRnuVersion) })}`
519
- : '';
520
- console.log(`react-native-update: ${rnuVersion}${latestRnuVersion}`);
601
+ console.log(
602
+ `react-native-update: ${rnuVersion}${latestTag(latestRnuVersion)}`,
603
+ );
521
604
  if (IS_CRESC) {
522
605
  if (satisfies(rnuVersion, '<10.27.0')) {
523
606
  console.error(
@@ -545,6 +628,33 @@ export async function printVersionCommand() {
545
628
  } else {
546
629
  console.log(t('rnuVersionNotFound'));
547
630
  }
631
+
632
+ let hinted = wait; // inline tags already shown
633
+ const printHints = () => {
634
+ if (hinted || !latest) {
635
+ return;
636
+ }
637
+ hinted = true;
638
+ const [cliLatest, rnuLatest] = latest;
639
+ if (isNewer(cliLatest, pkg.version)) {
640
+ console.log(
641
+ `react-native-update-cli: ${pkg.version}${latestTag(cliLatest)}`,
642
+ );
643
+ }
644
+ if (rnuVersion && isNewer(rnuLatest, rnuVersion)) {
645
+ console.log(`react-native-update: ${rnuVersion}${latestTag(rnuLatest)}`);
646
+ }
647
+ };
648
+
649
+ const settle = (graceMs: number) => {
650
+ let timer: NodeJS.Timeout | undefined;
651
+ const grace = new Promise<void>((resolve) => {
652
+ timer = setTimeout(resolve, graceMs);
653
+ });
654
+ return Promise.race([check, grace]).then(() => clearTimeout(timer));
655
+ };
656
+
657
+ return { done: check, settle, printHints };
548
658
  }
549
659
 
550
660
  export { checkPlugins };
@@ -1,3 +1,4 @@
1
+ import { compare, compareVersions, satisfies } from 'compare-versions';
1
2
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
2
3
  import { npm, yarn } from 'global-dirs';
3
4
  import type {
@@ -10,8 +11,6 @@ import { homedir } from 'os';
10
11
  import { dirname, join, parse, resolve as pathResolve } from 'path';
11
12
  import registryAuthToken from 'registry-auth-token';
12
13
  import getRegistryUrl from 'registry-auth-token/registry-url';
13
- import gt from 'semver/functions/gt';
14
- import maxSatisfying from 'semver/ranges/max-satisfying';
15
14
  import { URL } from 'url';
16
15
 
17
16
  interface RegistryVersions {
@@ -82,10 +81,10 @@ interface LatestVersionOptions {
82
81
  * Awaiting the api to return might take time, depending on the network, and might impact your package loading performance.
83
82
  * You can use the cache mechanism to improve load performance and reduce unnecessary network requests.
84
83
  * If `useCache` is not supplied, the api will always check for updates and wait for every requests to return before returning itself.
85
- * If `useCache` is used, the api will always returned immediately, with either (for each provided packages):
86
- * 1) a latest/next version available if a cache was found
87
- * 2) no latest/next version available if no cache was found - in such case updates will be fetched in the background and a cache will
88
- * be created for each provided packages and made available for the next call to the api.
84
+ * If `useCache` is used (for each provided package):
85
+ * 1) a fresh cache (younger than `cacheMaxAge`, from the same registry) answers without any network request
86
+ * 2) otherwise the registry is queried and the cache refreshed; when that query fails, a stale cache (if any) is used instead.
87
+ * Combine with `unref` so a slow refresh never keeps the process alive.
89
88
  * @default false
90
89
  */
91
90
  readonly useCache?: boolean;
@@ -93,14 +92,18 @@ interface LatestVersionOptions {
93
92
  /**
94
93
  * How long the cache for the provided packages should be used before being refreshed (in milliseconds).
95
94
  * If `useCache` is not supplied, this option has no effect.
96
- * If `0` is used, this will force the cache to refresh immediately:
97
- * 1) The api will returned immediately (without any latest nor next version available for the provided packages)
98
- * 2) New updates will be fetched in the background
99
- * 3) The cache for each provided packages will be refreshed and made available for the next call to the api
95
+ * If `0` is used, the cache is always refreshed (a stale cache still serves as a fallback when the refresh fails).
100
96
  * @default ONE_DAY
101
97
  */
102
98
  readonly cacheMaxAge?: number;
103
99
 
100
+ /**
101
+ * Do not let the registry request keep the process alive: its socket is `unref`'d, so the process may exit before the
102
+ * request completes (the returned promise then simply never settles). Use for opportunistic background checks.
103
+ * @default false
104
+ */
105
+ readonly unref?: boolean;
106
+
104
107
  /**
105
108
  * A JavaScript package registry url that implements the CommonJS Package Registry specification.
106
109
  * @default "Looks at any registry urls in the .npmrc file or fallback to the default npm registry instead"
@@ -190,6 +193,8 @@ interface PackageMetadata {
190
193
  lastUpdateDate: number;
191
194
  versions: string[];
192
195
  distTags: Record<string, string>;
196
+ /** registry the metadata came from; a cache from another registry is not reused */
197
+ registryUrl?: string;
193
198
  }
194
199
 
195
200
  export const ONE_DAY = 1000 * 60 * 60 * 24; // eslint-disable-line @typescript-eslint/naming-convention
@@ -202,14 +207,21 @@ const isPackageJson = (obj: any): obj is PackageJson => {
202
207
  );
203
208
  };
204
209
 
210
+ const resolveRegistryUrl = (
211
+ pkgName: string,
212
+ options?: LatestVersionOptions,
213
+ ): string => {
214
+ const i = pkgName.indexOf('/');
215
+ const pkgScope = i !== -1 ? pkgName.slice(0, i) : '';
216
+ return options?.registryUrl ?? getRegistryUrl(pkgScope);
217
+ };
218
+
205
219
  const downloadMetadata = (
206
220
  pkgName: string,
207
221
  options?: LatestVersionOptions,
208
222
  ): Promise<PackageMetadata> => {
209
223
  return new Promise((resolve, reject) => {
210
- const i = pkgName.indexOf('/');
211
- const pkgScope = i !== -1 ? pkgName.slice(0, i) : '';
212
- const registryUrl = options?.registryUrl ?? getRegistryUrl(pkgScope);
224
+ const registryUrl = resolveRegistryUrl(pkgName, options);
213
225
  const pkgUrl = new URL(
214
226
  encodeURIComponent(pkgName).replace(/^%40/, '@'),
215
227
  registryUrl,
@@ -252,6 +264,7 @@ const downloadMetadata = (
252
264
  lastUpdateDate: Date.now(),
253
265
  versions: Object.keys(pkgMetadata.versions as string[]),
254
266
  distTags: pkgMetadata['dist-tags'],
267
+ registryUrl,
255
268
  });
256
269
  return;
257
270
  } catch (err) {
@@ -279,11 +292,23 @@ const downloadMetadata = (
279
292
  request.on('close', () => {
280
293
  request.removeAllListeners();
281
294
  });
295
+ if (options?.unref) {
296
+ // A background check must never delay the process exit: drop the
297
+ // socket's ref (also for a pooled keep-alive socket, which the agent
298
+ // ref's again right before handing it out).
299
+ request.once('socket', (socket: { unref?: () => void }) => {
300
+ socket.unref?.();
301
+ });
302
+ }
282
303
  });
283
304
  };
284
305
 
285
306
  const getCacheDir = (name = '@badisi/latest-version'): string => {
286
307
  const homeDir = homedir();
308
+ if (process.env.XDG_CACHE_HOME) {
309
+ // an explicit override wins on every platform (also lets tests isolate)
310
+ return join(process.env.XDG_CACHE_HOME, name);
311
+ }
287
312
  switch (process.platform) {
288
313
  case 'darwin':
289
314
  return join(homeDir, 'Library', 'Caches', name);
@@ -299,30 +324,48 @@ const getCacheDir = (name = '@badisi/latest-version'): string => {
299
324
  };
300
325
 
301
326
  const saveMetadataToCache = (pkg: PackageMetadata): void => {
302
- const filePath = join(getCacheDir(), `${pkg.name}.json`);
303
- if (!existsSync(dirname(filePath))) {
304
- mkdirSync(dirname(filePath), { recursive: true });
327
+ try {
328
+ const filePath = join(getCacheDir(), `${pkg.name}.json`);
329
+ if (!existsSync(dirname(filePath))) {
330
+ mkdirSync(dirname(filePath), { recursive: true });
331
+ }
332
+ writeFileSync(filePath, JSON.stringify(pkg));
333
+ } catch {
334
+ // a read-only or missing cache dir must not turn into an error
305
335
  }
306
- writeFileSync(filePath, JSON.stringify(pkg));
307
336
  };
308
337
 
338
+ /**
339
+ * The cached metadata of a package (from the same registry), and whether it is
340
+ * still younger than `cacheMaxAge`. A stale entry is returned as well so it can
341
+ * serve as a fallback when the registry is unreachable.
342
+ */
309
343
  const getMetadataFromCache = (
310
344
  pkgName: string,
311
345
  options?: LatestVersionOptions,
312
- ): PackageMetadata | undefined => {
346
+ ): { metadata: PackageMetadata; fresh: boolean } | undefined => {
313
347
  const maxAge = options?.cacheMaxAge ?? ONE_DAY;
314
- if (maxAge !== 0) {
348
+ try {
315
349
  const pkgCacheFilePath = join(getCacheDir(), `${pkgName}.json`);
316
- if (existsSync(pkgCacheFilePath)) {
317
- const pkg = JSON.parse(
318
- readFileSync(pkgCacheFilePath).toString(),
319
- ) as PackageMetadata;
320
- if (Date.now() - pkg.lastUpdateDate < maxAge) {
321
- return pkg;
322
- }
350
+ if (!existsSync(pkgCacheFilePath)) {
351
+ return undefined;
323
352
  }
353
+ const metadata = JSON.parse(
354
+ readFileSync(pkgCacheFilePath).toString(),
355
+ ) as PackageMetadata;
356
+ if (
357
+ !metadata ||
358
+ typeof metadata.lastUpdateDate !== 'number' ||
359
+ !metadata.distTags ||
360
+ metadata.registryUrl !== resolveRegistryUrl(pkgName, options)
361
+ ) {
362
+ return undefined;
363
+ }
364
+ const age = Date.now() - metadata.lastUpdateDate;
365
+ return { metadata, fresh: maxAge !== 0 && age >= 0 && age < maxAge };
366
+ } catch {
367
+ return undefined; // unreadable / corrupt cache is the same as no cache
324
368
  }
325
- return undefined; // invalidates cache
326
369
  };
327
370
 
328
371
  const getRegistryVersions = async (
@@ -332,10 +375,19 @@ const getRegistryVersions = async (
332
375
  ): Promise<RegistryVersions> => {
333
376
  let pkgMetadata: PackageMetadata | undefined;
334
377
  if (pkgName.length && options?.useCache) {
335
- pkgMetadata = getMetadataFromCache(pkgName, options);
336
- if (!pkgMetadata) {
337
- pkgMetadata = await downloadMetadata(pkgName, options);
338
- saveMetadataToCache(pkgMetadata);
378
+ const cached = getMetadataFromCache(pkgName, options);
379
+ if (cached?.fresh) {
380
+ pkgMetadata = cached.metadata;
381
+ } else {
382
+ try {
383
+ pkgMetadata = await downloadMetadata(pkgName, options);
384
+ saveMetadataToCache(pkgMetadata);
385
+ } catch (err) {
386
+ if (!cached) {
387
+ throw err;
388
+ }
389
+ pkgMetadata = cached.metadata; // stale beats nothing
390
+ }
339
391
  }
340
392
  } else if (pkgName.length) {
341
393
  pkgMetadata = await downloadMetadata(pkgName, options);
@@ -348,12 +400,36 @@ const getRegistryVersions = async (
348
400
  if (tagOrRange && pkgMetadata?.distTags[tagOrRange]) {
349
401
  versions.wanted = pkgMetadata.distTags[tagOrRange];
350
402
  } else if (tagOrRange && pkgMetadata?.versions.length) {
351
- versions.wanted =
352
- maxSatisfying(pkgMetadata.versions, tagOrRange) ?? undefined;
403
+ versions.wanted = maxSatisfying(pkgMetadata.versions, tagOrRange);
353
404
  }
354
405
  return versions;
355
406
  };
356
407
 
408
+ /** the highest of `versions` within `range` (npm range syntax), if any */
409
+ const maxSatisfying = (
410
+ versions: string[],
411
+ range: string,
412
+ ): string | undefined => {
413
+ const matching = versions.filter((version) => {
414
+ try {
415
+ return satisfies(version, range);
416
+ } catch {
417
+ return false;
418
+ }
419
+ });
420
+ if (!matching.length) return undefined;
421
+ return matching.sort(compareVersions)[matching.length - 1];
422
+ };
423
+
424
+ /** `a > b` for two versions; invalid input counts as "not newer" */
425
+ const gt = (a: string, b: string): boolean => {
426
+ try {
427
+ return compare(a, b, '>');
428
+ } catch {
429
+ return false;
430
+ }
431
+ };
432
+
357
433
  const getInstalledVersion = (
358
434
  pkgName: string,
359
435
  location: keyof InstalledVersions = 'local',
@@ -7,7 +7,6 @@ import {
7
7
  open as openZipFile,
8
8
  type ZipFile as YauzlZipFile,
9
9
  } from 'yauzl';
10
- import { t } from './i18n';
11
10
 
12
11
  export function readEntry(
13
12
  entry: Entry,
@@ -26,7 +25,8 @@ export function readEntry(
26
25
  buffers.push(chunk);
27
26
  });
28
27
  stream.on('end', () => {
29
- resolve(Buffer.concat(buffers));
28
+ // a single chunk (a cached Range read) is handed back as-is, not copied
29
+ resolve(buffers.length === 1 ? buffers[0] : Buffer.concat(buffers));
30
30
  });
31
31
  stream.on('error', (err) => {
32
32
  reject(err);
@@ -169,21 +169,22 @@ export async function enumZipEntries(
169
169
  path.join(os.tmpdir(), 'nested_zip_'),
170
170
  );
171
171
  const tempZipPath = path.join(tempDir, 'temp.zip');
172
-
173
- await new Promise((res, rej) => {
174
- zipfile.openReadStream(entry, async (err, readStream) => {
175
- if (err) 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);
172
+ try {
173
+ await new Promise((res, rej) => {
174
+ zipfile.openReadStream(entry, async (err, readStream) => {
175
+ if (err) 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
+ });
181
182
  });
182
- });
183
-
184
- await enumZipEntries(tempZipPath, callback, `${fullPath}/`);
185
183
 
186
- await fs.remove(tempDir);
184
+ await enumZipEntries(tempZipPath, callback, `${fullPath}/`);
185
+ } finally {
186
+ await fs.remove(tempDir);
187
+ }
187
188
  }
188
189
 
189
190
  const result = callback(entry, zipfile, fullPath);
@@ -191,7 +192,8 @@ export async function enumZipEntries(
191
192
  await result;
192
193
  }
193
194
  } catch (error) {
194
- console.error(t('processingError', { error }));
195
+ // the rejection carries the error; logging it here too would make
196
+ // callers report it twice
195
197
  zipfile.close();
196
198
  reject(error);
197
199
  return;
@@ -8,6 +8,11 @@ export type ZipEntryOptions = {
8
8
 
9
9
  export const ZIP_ENTRY_SNIFF_BYTES = 64;
10
10
  export const MANIFEST_COMPRESSION_THRESHOLD_BYTES = 256;
11
+ // Deflate level for the bundle/asset payload. Level 9 measured ~4x the CPU
12
+ // of level 6 on Hermes bytecode for ~0.6% smaller output, so 6 is the sweet
13
+ // spot; the manifest is tiny, so it can afford 9.
14
+ export const PAYLOAD_COMPRESSION_LEVEL = 6;
15
+ export const MANIFEST_COMPRESSION_LEVEL = 9;
11
16
 
12
17
  const alreadyCompressedExtensions = new Set([
13
18
  '.7z',
@@ -139,7 +144,7 @@ export function zipOptionsForPatchEntry(): ZipEntryOptions {
139
144
 
140
145
  export function zipOptionsForManifestEntry(byteLength = 0): ZipEntryOptions {
141
146
  if (byteLength >= MANIFEST_COMPRESSION_THRESHOLD_BYTES) {
142
- return { compressionLevel: 9 };
147
+ return { compressionLevel: MANIFEST_COMPRESSION_LEVEL };
143
148
  }
144
149
  return { compress: false };
145
150
  }
@@ -151,7 +156,7 @@ export function zipOptionsForPayloadEntry(
151
156
  if (prefix && prefix.length > 0) {
152
157
  if (hasHermesBytecodeMagic(prefix)) {
153
158
  // Hermes bytecode is binary, but still benefits significantly from zip deflate.
154
- return { compress: true, compressionLevel: 9 };
159
+ return { compress: true, compressionLevel: PAYLOAD_COMPRESSION_LEVEL };
155
160
  }
156
161
  if (hasAlreadyCompressedMagic(prefix)) {
157
162
  return { compress: false };
@@ -162,7 +167,7 @@ export function zipOptionsForPayloadEntry(
162
167
  if (alreadyCompressedExtensions.has(extension)) {
163
168
  return { compress: false };
164
169
  }
165
- return { compress: true, compressionLevel: 9 };
170
+ return { compress: true, compressionLevel: PAYLOAD_COMPRESSION_LEVEL };
166
171
  }
167
172
 
168
173
  export function zipOptionsForPayloadFile(