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
@@ -13,6 +13,7 @@ import { createHash } from 'crypto';
13
13
  import fs from 'fs-extra';
14
14
  import os from 'os';
15
15
  import path from 'path';
16
+ import { PassThrough, Readable } from 'stream';
16
17
  import { pipeline } from 'stream/promises';
17
18
  import { tempDir } from './constants';
18
19
  import { getHbcVersion } from './hbcTransform';
@@ -29,6 +30,27 @@ import {
29
30
 
30
31
  export type HermesBaseOption = 'auto' | 'none' | string;
31
32
 
33
+ /**
34
+ * The base cannot be obtained whatever the transport or how often it is
35
+ * retried (wrong content on the server, no bundle in the package, ...).
36
+ */
37
+ export class PermanentBaseError extends Error {}
38
+ /** The fetched bundle's sha256 differs from what the server recorded. */
39
+ export class BundleHashMismatchError extends PermanentBaseError {
40
+ constructor(actual: string, expected: string) {
41
+ super(
42
+ `bundleHash mismatch (${actual.slice(0, 12)} != ${expected.slice(0, 12)})`,
43
+ );
44
+ }
45
+ }
46
+
47
+ /** time allowed for a response to start (headers) */
48
+ const FETCH_HEADERS_TIMEOUT_MS = 30_000;
49
+ /** a download that receives nothing for this long is abandoned */
50
+ const STREAM_IDLE_TIMEOUT_MS = 60_000;
51
+ /** cachePut leftovers (`<hash>.<pid>.tmp`) older than this are evicted */
52
+ const STALE_CACHE_TMP_MS = 60 * 60 * 1000;
53
+
32
54
  export interface HermesBaseSelection {
33
55
  /** path of the bundle (HBC) handed to hermesc as -base-bytecode */
34
56
  path: string;
@@ -151,6 +173,27 @@ export function sha256Hex(data: Buffer): string {
151
173
  return createHash('sha256').update(data).digest('hex');
152
174
  }
153
175
 
176
+ /** sha256 of a file, streamed (a cached base can be tens of MB) */
177
+ export async function sha256File(file: string): Promise<string> {
178
+ const hash = createHash('sha256');
179
+ for await (const chunk of fs.createReadStream(file)) hash.update(chunk);
180
+ return hash.digest('hex');
181
+ }
182
+
183
+ /** HBC version from the first bytes of a file, without reading the rest */
184
+ export async function readFileHbcVersion(file: string): Promise<number | null> {
185
+ const header = Buffer.alloc(128);
186
+ const fd = await fs.open(file, 'r');
187
+ try {
188
+ const { bytesRead } = await fs.read(fd, header, 0, 128, 0);
189
+ return getHbcVersion(header.subarray(0, bytesRead));
190
+ } catch {
191
+ return null;
192
+ } finally {
193
+ await fs.close(fd);
194
+ }
195
+ }
196
+
154
197
  const PROBE_CACHE_FILE = 'hbc-versions.json';
155
198
  const PROBE_CACHE_ENTRIES = 16;
156
199
 
@@ -348,8 +391,7 @@ export async function cacheLookup(bundleHash: string): Promise<string | null> {
348
391
  if (!/^[0-9a-f]{64}$/.test(bundleHash)) return null;
349
392
  const file = path.join(cacheDir(), bundleHash);
350
393
  if (!(await fs.pathExists(file))) return null;
351
- const data = await fs.readFile(file);
352
- if (sha256Hex(data) !== bundleHash) {
394
+ if ((await sha256File(file).catch(() => '')) !== bundleHash) {
353
395
  // corrupt entry: never trust cache content
354
396
  await fs.remove(file).catch(() => {});
355
397
  return null;
@@ -389,11 +431,19 @@ export async function enforceCacheLimits(
389
431
  if (!(await fs.pathExists(dir))) return;
390
432
  const { maxBytes, maxFiles } = cacheLimits(maxMb);
391
433
  const entries: { name: string; size: number; mtime: number }[] = [];
434
+ const staleTmpCutoff = Date.now() - STALE_CACHE_TMP_MS;
392
435
  for (const name of await fs.readdir(dir)) {
393
- if (!/^[0-9a-f]{64}$/.test(name)) continue;
436
+ const isTmp = isCacheTmpName(name);
437
+ if (!isTmp && !/^[0-9a-f]{64}$/.test(name)) continue;
394
438
  const stat = await fs.stat(path.join(dir, name)).catch(() => null);
395
- if (stat?.isFile())
396
- entries.push({ name, size: stat.size, mtime: stat.mtimeMs });
439
+ if (!stat?.isFile()) continue;
440
+ if (isTmp) {
441
+ // an interrupted cachePut; nothing will ever rename it into place
442
+ if (stat.mtimeMs < staleTmpCutoff)
443
+ await fs.remove(path.join(dir, name)).catch(() => {});
444
+ continue;
445
+ }
446
+ entries.push({ name, size: stat.size, mtime: stat.mtimeMs });
397
447
  }
398
448
  entries.sort((a, b) => b.mtime - a.mtime); // newest first
399
449
  let total = 0;
@@ -407,12 +457,23 @@ export async function enforceCacheLimits(
407
457
  }
408
458
  }
409
459
 
460
+ /** `<sha256>.<pid>.tmp`, the staging name cachePut writes before renaming */
461
+ function isCacheTmpName(name: string): boolean {
462
+ return /^[0-9a-f]{64}\.\d+\.tmp$/.test(name);
463
+ }
464
+
465
+ /** Remove every cached bundle (and staging leftovers); returns the bundle count. */
410
466
  export async function cleanCache(): Promise<number> {
411
467
  const dir = cacheDir();
412
468
  if (!(await fs.pathExists(dir))) return 0;
413
- const names = (await fs.readdir(dir)).filter((n) => /^[0-9a-f]{64}$/.test(n));
414
- for (const name of names) await fs.remove(path.join(dir, name));
415
- return names.length;
469
+ let bundles = 0;
470
+ for (const name of await fs.readdir(dir)) {
471
+ const isBundle = /^[0-9a-f]{64}$/.test(name);
472
+ if (!isBundle && !isCacheTmpName(name)) continue;
473
+ await fs.remove(path.join(dir, name));
474
+ if (isBundle) bundles += 1;
475
+ }
476
+ return bundles;
416
477
  }
417
478
 
418
479
  export async function cacheStats(): Promise<{
@@ -458,16 +519,21 @@ export async function downloadToFile(
458
519
  url: string,
459
520
  destination: string,
460
521
  ): Promise<void> {
461
- const response = await fetch(url);
522
+ const controller = new AbortController();
523
+ const headersTimer = setTimeout(
524
+ () => controller.abort(new Error('timeout waiting for response')),
525
+ FETCH_HEADERS_TIMEOUT_MS,
526
+ );
527
+ let response: Response;
528
+ try {
529
+ response = await fetch(url, { signal: controller.signal });
530
+ } finally {
531
+ clearTimeout(headersTimer);
532
+ }
462
533
  if (!response.ok || !response.body) {
463
534
  throw new Error(`download failed: HTTP ${response.status} ${url}`);
464
535
  }
465
- await fs.ensureDir(path.dirname(destination));
466
- const { Readable } = await import('stream');
467
- await pipeline(
468
- Readable.fromWeb(response.body as any),
469
- fs.createWriteStream(destination),
470
- );
536
+ await saveResponse(response, destination, controller);
471
537
  }
472
538
 
473
539
  // ---------------------------------------------------------------------------
@@ -511,17 +577,40 @@ function hasBundleLocation(record: HermesBaseServerRecord): boolean {
511
577
  );
512
578
  }
513
579
 
580
+ /**
581
+ * Stream a response body to disk, giving up when no bytes arrive for
582
+ * STREAM_IDLE_TIMEOUT_MS. `controller` is the one the request was made with
583
+ * (aborting it also tears down the socket); a foreign response gets its own.
584
+ */
514
585
  async function saveResponse(
515
586
  response: Response,
516
587
  destination: string,
588
+ controller = new AbortController(),
517
589
  ): Promise<void> {
518
590
  if (!response.body) throw new Error('empty response body');
519
591
  await fs.ensureDir(path.dirname(destination));
520
- const { Readable } = await import('stream');
521
- await pipeline(
522
- Readable.fromWeb(response.body as any),
523
- fs.createWriteStream(destination),
524
- );
592
+ const abort = () =>
593
+ controller.abort(
594
+ new Error(`download stalled for ${STREAM_IDLE_TIMEOUT_MS / 1000}s`),
595
+ );
596
+ let idle = setTimeout(abort, STREAM_IDLE_TIMEOUT_MS);
597
+ const watchdog = new PassThrough({
598
+ transform(chunk, _encoding, callback) {
599
+ clearTimeout(idle);
600
+ idle = setTimeout(abort, STREAM_IDLE_TIMEOUT_MS);
601
+ callback(null, chunk);
602
+ },
603
+ });
604
+ try {
605
+ await pipeline(
606
+ Readable.fromWeb(response.body as any),
607
+ watchdog,
608
+ fs.createWriteStream(destination),
609
+ { signal: controller.signal },
610
+ );
611
+ } finally {
612
+ clearTimeout(idle);
613
+ }
525
614
  }
526
615
 
527
616
  /**
@@ -534,35 +623,37 @@ async function saveResponse(
534
623
  * is skipped);
535
624
  * 3. the whole archive, as before.
536
625
  * A server that ignores Range (HTTP 200) streams the full archive into
537
- * `archive` without a second request. Range results are verified against
538
- * `record.bundleHash` here; a mismatch (e.g. re-packaged object) falls
539
- * through to the next transport instead of failing the resolution.
626
+ * `archive` without a second request. Every result is verified against
627
+ * `record.bundleHash`. A mismatch of the located bytes (1) may only mean the
628
+ * recorded location is stale, so the directory transport (2) still runs; a
629
+ * mismatch of the entry itself (2, 3) is final — the same bytes would come
630
+ * back however they are fetched — and raises BundleHashMismatchError.
540
631
  */
541
632
  export async function fetchBaseBundle(
542
633
  record: HermesBaseServerRecord,
543
634
  artifactType: BaseArtifactType,
544
635
  archive: string,
545
636
  log: (message: string) => void = () => {},
546
- ): Promise<FetchedBaseBundle | null> {
637
+ ): Promise<FetchedBaseBundle> {
547
638
  const matches = bundleEntryMatcher(artifactType);
548
639
  const verified = (
549
640
  bundle: Buffer | null,
550
641
  ): { bundle: Buffer; bundleHash: string } => {
551
- if (!bundle) throw new Error('bundle entry not found');
642
+ if (!bundle) throw new PermanentBaseError('bundle entry not found');
552
643
  const bundleHash = sha256Hex(bundle);
553
644
  if (record.bundleHash && bundleHash !== record.bundleHash) {
554
- throw new Error('bundleHash mismatch');
645
+ throw new BundleHashMismatchError(bundleHash, record.bundleHash);
555
646
  }
556
647
  return { bundle, bundleHash };
557
648
  };
558
649
  const fromFullResponse = async (
559
650
  response: Response,
560
- ): Promise<FetchedBaseBundle | null> => {
651
+ ): Promise<FetchedBaseBundle> => {
561
652
  await saveResponse(response, archive);
562
- const bundle = await extractBundleFromArchive(archive);
563
- return bundle
564
- ? { bundle, bundleHash: sha256Hex(bundle), transport: 'full' }
565
- : null;
653
+ return {
654
+ ...verified(await extractBundleFromArchive(archive)),
655
+ transport: 'full',
656
+ };
566
657
  };
567
658
  const skip = (reason: string) =>
568
659
  log(t('hermesBaseRangeFallback', { reason }));
@@ -617,15 +708,17 @@ export async function fetchBaseBundle(
617
708
  skip('server ignores Range');
618
709
  return fromFullResponse(error.response);
619
710
  }
711
+ // the real entry was read and is not the recorded one: final
712
+ if (error instanceof PermanentBaseError) throw error;
620
713
  skip(`zip range: ${error?.message ?? error}`);
621
714
  }
622
715
  }
623
716
 
624
717
  await downloadToFile(record.url, archive);
625
- const bundle = await extractBundleFromArchive(archive);
626
- return bundle
627
- ? { bundle, bundleHash: sha256Hex(bundle), transport: 'full' }
628
- : null;
718
+ return {
719
+ ...verified(await extractBundleFromArchive(archive)),
720
+ transport: 'full',
721
+ };
629
722
  }
630
723
 
631
724
  export interface ResolveHermesBaseParams {
@@ -694,7 +787,9 @@ export async function resolveHermesBase(
694
787
  }
695
788
  let record: HermesBaseServerRecord | null = null;
696
789
  try {
697
- record = await params.fetchBase(params.appId, bytecodeVersion);
790
+ record = await retryOnce(() =>
791
+ params.fetchBase(params.appId as string, bytecodeVersion),
792
+ );
698
793
  } catch (error: any) {
699
794
  log(
700
795
  t('hermesBaseNone', {
@@ -727,6 +822,19 @@ export async function resolveHermesBase(
727
822
  // 1. cache by bundleHash
728
823
  if (record.bundleHash) {
729
824
  const hit = await cacheLookup(record.bundleHash);
825
+ if (hit && record.bytecodeVersion == null) {
826
+ // the server does not know the HBC version (legacy version, native
827
+ // package): the download path checks it, the cache path must too
828
+ const version = await readFileHbcVersion(hit);
829
+ if (version !== bytecodeVersion) {
830
+ log(
831
+ t('hermesBaseNone', {
832
+ reason: `cached base is HBC ${version ?? 'n/a'}, need ${bytecodeVersion}`,
833
+ }),
834
+ );
835
+ return null;
836
+ }
837
+ }
730
838
  if (hit) {
731
839
  log(
732
840
  t('hermesBaseUsing', {
@@ -744,7 +852,7 @@ export async function resolveHermesBase(
744
852
  };
745
853
  }
746
854
  }
747
- // 2. download, extract, verify, cache — up to two attempts
855
+ // 2. download, extract, verify, cache — transport errors get a second try
748
856
  for (let attempt = 1; attempt <= 2; attempt++) {
749
857
  const dir = tmpDir();
750
858
  await fs.ensureDir(dir);
@@ -763,8 +871,6 @@ export async function resolveHermesBase(
763
871
  try {
764
872
  log(t('hermesBaseDownloading', { url: record.url }));
765
873
  const fetched = await fetchBaseBundle(record, artifactType, archive, log);
766
- if (!fetched)
767
- throw new Error('bundle entry not found in downloaded package');
768
874
  const { bundle, bundleHash: actualHash } = fetched;
769
875
  if (fetched.transport !== 'full') {
770
876
  log(
@@ -774,11 +880,6 @@ export async function resolveHermesBase(
774
880
  }),
775
881
  );
776
882
  }
777
- if (record.bundleHash && actualHash !== record.bundleHash) {
778
- throw new Error(
779
- `bundleHash mismatch (${actualHash.slice(0, 12)} != ${record.bundleHash.slice(0, 12)})`,
780
- );
781
- }
782
883
  const version = getHbcVersion(bundle);
783
884
  if (version !== bytecodeVersion) {
784
885
  log(
@@ -807,7 +908,7 @@ export async function resolveHermesBase(
807
908
  source,
808
909
  };
809
910
  } catch (error: any) {
810
- if (attempt === 2) {
911
+ if (attempt === 2 || error instanceof PermanentBaseError) {
811
912
  log(
812
913
  t('hermesBaseNone', {
813
914
  reason: `download/verify failed: ${error?.message ?? error}`,
@@ -822,6 +923,16 @@ export async function resolveHermesBase(
822
923
  return null;
823
924
  }
824
925
 
926
+ /** one retry after a short pause, for transient network failures */
927
+ async function retryOnce<T>(action: () => Promise<T>): Promise<T> {
928
+ try {
929
+ return await action();
930
+ } catch {
931
+ await new Promise((resolve) => setTimeout(resolve, 500));
932
+ return action();
933
+ }
934
+ }
935
+
825
936
  export function hermescArgsWithBase(
826
937
  baseArgs: string[],
827
938
  basePath: string | null,
@@ -122,20 +122,31 @@ export const testUrls = async (
122
122
  });
123
123
  };
124
124
 
125
- export const getBaseUrl = (async () => {
125
+ let baseUrlPromise: Promise<string> | undefined;
126
+
127
+ async function resolveBaseUrl(): Promise<string> {
126
128
  const testEndpoint = process.env.PUSHY_REGISTRY || process.env.RNU_API;
127
129
  if (testEndpoint) {
128
130
  return testEndpoint;
129
131
  }
130
- return testUrls(defaultEndpoints.map((url) => `${url}/status`)).then(
131
- (ret) => {
132
- let baseUrl = defaultEndpoints[0];
133
- if (ret) {
134
- // remove /status
135
- baseUrl = ret.replace('/status', '');
136
- }
137
- // console.log('baseUrl', baseUrl);
138
- return baseUrl;
139
- },
140
- );
141
- })();
132
+ const ret = await testUrls(defaultEndpoints.map((url) => `${url}/status`));
133
+ let baseUrl = defaultEndpoints[0];
134
+ if (ret) {
135
+ // remove /status
136
+ baseUrl = ret.replace('/status', '');
137
+ }
138
+ // console.log('baseUrl', baseUrl);
139
+ return baseUrl;
140
+ }
141
+
142
+ /**
143
+ * The API base url: the env override, or the first default endpoint that
144
+ * answers a HEAD ping. Resolved lazily on the first API call (offline commands
145
+ * such as `hdiff`/`help` never ping) and memoized for the process lifetime.
146
+ */
147
+ export const getBaseUrl = (): Promise<string> => {
148
+ if (!baseUrlPromise) {
149
+ baseUrlPromise = resolveBaseUrl();
150
+ }
151
+ return baseUrlPromise;
152
+ };
@@ -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 };