react-native-update-cli 2.22.6 → 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 +35 -2
  9. package/lib/bundle-runner.js +313 -128
  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 +31 -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 +31 -7
  26. package/lib/utils/hermes-base.js +284 -76
  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 +84 -13
  37. package/lib/utils/zip-range.js +363 -63
  38. package/lib/versions.js +30 -23
  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 +419 -171
  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 +42 -14
  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 +311 -81
  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 +436 -67
  59. package/src/versions.ts +34 -26
@@ -1,4 +1,4 @@
1
- import { spawnSync } from 'child_process';
1
+ import { spawn } from 'child_process';
2
2
  import { satisfies } from 'compare-versions';
3
3
  import * as fs from 'fs-extra';
4
4
  import os from 'os';
@@ -40,6 +40,8 @@ export interface RunBundleCommandOptions {
40
40
  forceHermes?: boolean;
41
41
  /** Hermes -base-bytecode settings; omitted → compile without a base */
42
42
  hermesBase?: HermesBaseRequest;
43
+ /** pass --reset-cache to Metro (default true); false reuses its transform cache */
44
+ resetCache?: boolean;
43
45
  cli: BundleCliOptions;
44
46
  isSentry: boolean;
45
47
  }
@@ -58,6 +60,18 @@ export interface HermesCompileResult {
58
60
  verified?: boolean;
59
61
  }
60
62
 
63
+ /** Outcome of picking a base: what to compile with, plus the log lines. */
64
+ export interface HermesBaseSelectionResult {
65
+ base: HermesBaseSelection | null;
66
+ bytecodeVersion: number | null;
67
+ /** messages to print when the compile phase starts (kept out of Metro's output) */
68
+ logs: string[];
69
+ /** the hermesc the selection was made with (the compile reuses it) */
70
+ hermesCommand?: string;
71
+ /** hermesc could not be resolved; the compile phase will report it */
72
+ commandUnavailable?: boolean;
73
+ }
74
+
61
75
  interface GradleConfig {
62
76
  crunchPngs?: boolean;
63
77
  enableHermes?: boolean;
@@ -197,6 +211,7 @@ export async function runReactNativeBundleCommand({
197
211
  config,
198
212
  forceHermes,
199
213
  hermesBase,
214
+ resetCache = true,
200
215
  cli,
201
216
  isSentry,
202
217
  }: RunBundleCommandOptions): Promise<HermesCompileResult | null> {
@@ -302,7 +317,8 @@ export async function runReactNativeBundleCommand({
302
317
  );
303
318
 
304
319
  if (platform !== 'harmony') {
305
- reactNativeBundleArgs.push('--platform', platform, '--reset-cache');
320
+ reactNativeBundleArgs.push('--platform', platform);
321
+ if (resetCache) reactNativeBundleArgs.push('--reset-cache');
306
322
  }
307
323
 
308
324
  if (cli.taro) {
@@ -319,11 +335,25 @@ export async function runReactNativeBundleCommand({
319
335
  reactNativeBundleArgs.push('--config', config);
320
336
  }
321
337
 
338
+ // Decide about Hermes before Metro runs so the base lookup (server query,
339
+ // Range download, cache) overlaps the bundling instead of following it.
340
+ const hermesEnabled = await detectHermesEnabled(
341
+ platform,
342
+ forceHermes,
343
+ gradleConfig,
344
+ );
345
+
322
346
  const jsRuntime = getJavaScriptRuntime();
323
347
  const reactNativeBundleProcess = spawnJavaScript(reactNativeBundleArgs);
324
348
  console.log(
325
349
  `Running bundle command: ${jsRuntime} ${reactNativeBundleArgs.join(' ')}`,
326
350
  );
351
+ // Metro is running; the synchronous head of the selection (hermesc lookup,
352
+ // HBC version probe) now overlaps it instead of delaying its start.
353
+ const pendingBase =
354
+ hermesEnabled && hermesBase
355
+ ? startHermesBaseSelection(hermesBase)
356
+ : undefined;
327
357
 
328
358
  let hermesResult: HermesCompileResult | null = null;
329
359
  await new Promise<void>((resolve, reject) => {
@@ -344,51 +374,15 @@ export async function runReactNativeBundleCommand({
344
374
  }
345
375
 
346
376
  try {
347
- let hermesEnabled: boolean | undefined = false;
348
-
349
- if (forceHermes) {
350
- hermesEnabled = true;
351
- console.log(t('forceHermes'));
352
- } else if (platform === 'android') {
353
- const gradleProperties = await new Promise<{
354
- hermesEnabled?: boolean;
355
- }>((resolve) => {
356
- properties.parse(
357
- './android/gradle.properties',
358
- { path: true },
359
- (
360
- error: Error | null,
361
- props: { hermesEnabled?: boolean } = {},
362
- ) => {
363
- if (error) {
364
- console.error(error);
365
- resolve({});
366
- return;
367
- }
368
- resolve(props);
369
- },
370
- );
371
- });
372
- hermesEnabled = gradleProperties.hermesEnabled;
373
-
374
- if (typeof hermesEnabled !== 'boolean') {
375
- hermesEnabled = gradleConfig.enableHermes;
376
- }
377
- } else if (
378
- platform === 'ios' &&
379
- fs.existsSync('ios/Pods/hermes-engine')
380
- ) {
381
- hermesEnabled = true;
382
- }
383
-
384
377
  if (hermesEnabled) {
385
- hermesResult = await compileHermesByteCode(
378
+ hermesResult = await compileHermesByteCode({
386
379
  bundleName,
387
380
  outputFolder,
388
381
  sourcemapOutput,
389
- !isSentry,
390
- hermesBase,
391
- );
382
+ shouldCleanSourcemap: !isSentry,
383
+ baseRequest: hermesBase,
384
+ pendingBase,
385
+ });
392
386
  }
393
387
 
394
388
  if (platform === 'harmony') {
@@ -416,6 +410,43 @@ export async function runReactNativeBundleCommand({
416
410
  return hermesResult;
417
411
  }
418
412
 
413
+ async function detectHermesEnabled(
414
+ platform: string,
415
+ forceHermes: boolean | undefined,
416
+ gradleConfig: GradleConfig,
417
+ ): Promise<boolean> {
418
+ if (forceHermes) {
419
+ console.log(t('forceHermes'));
420
+ return true;
421
+ }
422
+ if (platform === 'android') {
423
+ const gradleProperties = await new Promise<{ hermesEnabled?: boolean }>(
424
+ (resolve) => {
425
+ properties.parse(
426
+ './android/gradle.properties',
427
+ { path: true },
428
+ (error: Error | null, props: { hermesEnabled?: boolean } = {}) => {
429
+ if (error) {
430
+ console.error(error);
431
+ resolve({});
432
+ return;
433
+ }
434
+ resolve(props);
435
+ },
436
+ );
437
+ },
438
+ );
439
+ if (typeof gradleProperties.hermesEnabled === 'boolean') {
440
+ return gradleProperties.hermesEnabled;
441
+ }
442
+ return Boolean(gradleConfig.enableHermes);
443
+ }
444
+ if (platform === 'ios' && fs.existsSync('ios/Pods/hermes-engine')) {
445
+ return true;
446
+ }
447
+ return false;
448
+ }
449
+
419
450
  function getHermesOSBin() {
420
451
  if (os.platform() === 'win32') return 'win64-bin';
421
452
  if (os.platform() === 'darwin') return 'osx-bin';
@@ -583,59 +614,251 @@ export function summarizeHermescStderr(stderr: string): string {
583
614
  return (notWarnings.length > 0 ? notWarnings : kept).slice(-3).join(' ');
584
615
  }
585
616
 
586
- export function buildHermescArgs(bundlePath: string): string[] {
617
+ /** hermesc arguments writing `bundlePath` from `input` (in place by default) */
618
+ export function buildHermescArgs(
619
+ bundlePath: string,
620
+ input: string = bundlePath,
621
+ ): string[] {
587
622
  return [
588
623
  '-emit-binary',
589
624
  '-out',
590
625
  bundlePath,
591
- bundlePath,
626
+ input,
592
627
  '-O',
593
628
  '-output-source-map',
594
629
  ];
595
630
  }
596
631
 
597
- async function compileHermesByteCode(
598
- bundleName: string,
599
- outputFolder: string,
632
+ interface ProcessOutcome {
633
+ status: number | null;
634
+ signal: NodeJS.Signals | null;
635
+ stderr: string;
636
+ error?: Error;
637
+ }
638
+
639
+ /** captured stderr is bounded to this much head and this much tail */
640
+ const STDERR_KEEP_BYTES = 512 * 1024;
641
+
642
+ /** spawn without blocking the event loop, so two hermesc runs can overlap */
643
+ function runProcess(
644
+ command: string,
645
+ args: string[],
646
+ captureStderr: boolean,
647
+ ): Promise<ProcessOutcome> {
648
+ return new Promise((resolve) => {
649
+ const child = spawn(command, args, {
650
+ stdio: ['ignore', 'ignore', captureStderr ? 'pipe' : 'ignore'],
651
+ });
652
+ // hermesc echoes whole (minified) source lines per diagnostic: keep the
653
+ // head and the tail, never an unbounded transcript
654
+ const head: Buffer[] = [];
655
+ const tail: Buffer[] = [];
656
+ let headBytes = 0;
657
+ let tailBytes = 0;
658
+ let dropped = false;
659
+ child.stderr?.on('data', (chunk: Buffer) => {
660
+ if (headBytes < STDERR_KEEP_BYTES) {
661
+ head.push(chunk);
662
+ headBytes += chunk.length;
663
+ return;
664
+ }
665
+ tail.push(chunk);
666
+ tailBytes += chunk.length;
667
+ while (tail.length > 1 && tailBytes > STDERR_KEEP_BYTES) {
668
+ tailBytes -= (tail.shift() as Buffer).length;
669
+ dropped = true;
670
+ }
671
+ });
672
+ let settled = false;
673
+ const finish = (outcome: ProcessOutcome) => {
674
+ if (settled) return;
675
+ settled = true;
676
+ resolve(outcome);
677
+ };
678
+ child.once('error', (error) =>
679
+ finish({ status: null, signal: null, stderr: '', error }),
680
+ );
681
+ child.once('close', (status, signal) =>
682
+ finish({
683
+ status,
684
+ signal,
685
+ stderr:
686
+ Buffer.concat(head).toString() +
687
+ (dropped ? '\n[... output truncated ...]\n' : '') +
688
+ Buffer.concat(tail).toString(),
689
+ }),
690
+ );
691
+ });
692
+ }
693
+
694
+ export interface CompileHermesOptions {
695
+ bundleName: string;
696
+ outputFolder: string;
697
+ sourcemapOutput: string;
698
+ shouldCleanSourcemap: boolean;
699
+ baseRequest?: HermesBaseRequest;
700
+ /** base selection started alongside Metro (see startHermesBaseSelection) */
701
+ pendingBase?: Promise<HermesBaseSelectionResult>;
702
+ /** defaults to the hermesc the selection used, else the project's */
703
+ hermesCommand?: string;
704
+ }
705
+
706
+ /** how long the compile phase waits for a base that is still being fetched */
707
+ const HERMES_BASE_WAIT_MS = 60_000;
708
+
709
+ /**
710
+ * The selection runs while Metro bundles; when Metro is done first, wait a
711
+ * bounded time for it — a stalled download must never hold up the compile.
712
+ */
713
+ async function awaitPendingBase(
714
+ pending: Promise<HermesBaseSelectionResult>,
715
+ ): Promise<HermesBaseSelectionResult> {
716
+ const waitMs =
717
+ Number(process.env.PUSHY_HERMES_BASE_WAIT_MS) || HERMES_BASE_WAIT_MS;
718
+ let timer: NodeJS.Timeout | undefined;
719
+ const gaveUp = new Promise<HermesBaseSelectionResult>((resolve) => {
720
+ timer = setTimeout(
721
+ () =>
722
+ resolve({
723
+ base: null,
724
+ bytecodeVersion: null,
725
+ logs: [
726
+ t('hermesBaseNone', {
727
+ reason: `base not ready after ${Math.round(waitMs / 1000)}s`,
728
+ }),
729
+ ],
730
+ }),
731
+ waitMs,
732
+ );
733
+ });
734
+ try {
735
+ return await Promise.race([pending, gaveUp]);
736
+ } finally {
737
+ clearTimeout(timer);
738
+ }
739
+ }
740
+
741
+ /** plain compile of `input` into `out`; throws when hermesc fails */
742
+ async function compilePlain(
743
+ hermesCommand: string,
744
+ out: string,
745
+ input: string = out,
746
+ ): Promise<void> {
747
+ const args = buildHermescArgs(out, input);
748
+ console.log(
749
+ t('runningHermesc', { command: hermesCommand, args: args.join(' ') }),
750
+ );
751
+ assertSuccessfulSyncProcess(
752
+ await runProcess(hermesCommand, args, false),
753
+ hermesCommand,
754
+ );
755
+ }
756
+
757
+ /**
758
+ * Merge the packager map with the hermes map into `sourcemapOutput` (which is
759
+ * normally the hermes map's own path). Resolves false when React Native's
760
+ * composer cannot be found; throws when it fails.
761
+ */
762
+ async function composeSourceMaps(
763
+ packagerMap: string,
764
+ hermesMap: string,
600
765
  sourcemapOutput: string,
601
- shouldCleanSourcemap: boolean,
602
- baseRequest?: HermesBaseRequest,
603
- ): Promise<HermesCompileResult> {
766
+ ): Promise<boolean> {
767
+ let composerPath: string;
768
+ try {
769
+ // resolve through the project so hoisted node_modules (monorepos) work
770
+ composerPath = require.resolve(
771
+ 'react-native/scripts/compose-source-maps.js',
772
+ { paths: [process.cwd()] },
773
+ );
774
+ } catch {
775
+ console.warn(t('composeSourceMapsNotFound'));
776
+ return false;
777
+ }
778
+ console.log(t('composingSourceMap'));
779
+ assertSuccessfulSyncProcess(
780
+ await runProcess(
781
+ getJavaScriptRuntime(),
782
+ [composerPath, packagerMap, hermesMap, '-o', sourcemapOutput],
783
+ false,
784
+ ),
785
+ composerPath,
786
+ );
787
+ return true;
788
+ }
789
+
790
+ export async function compileHermesByteCode({
791
+ bundleName,
792
+ outputFolder,
793
+ sourcemapOutput,
794
+ shouldCleanSourcemap,
795
+ baseRequest,
796
+ pendingBase,
797
+ hermesCommand = resolveHermesCommand(),
798
+ }: CompileHermesOptions): Promise<HermesCompileResult> {
604
799
  console.log(t('hermesEnabledCompiling'));
605
- const hermesCommand = resolveHermesCommand();
606
800
 
607
801
  const bundlePath = path.join(outputFolder, bundleName);
608
- const plainArgs = buildHermescArgs(bundlePath);
802
+ const hermesMap = `${bundlePath}.map`;
803
+ const packagerMap = path.join(outputFolder, `${bundleName}.txt.map`);
609
804
  if (sourcemapOutput) {
610
- fs.copyFileSync(
611
- sourcemapOutput,
612
- path.join(outputFolder, `${bundleName}.txt.map`),
613
- );
805
+ // hermesc is about to write its own map at `<bundle>.map`, which is where
806
+ // the packager map normally sits: move it aside (copy only when elsewhere)
807
+ if (path.resolve(sourcemapOutput) === path.resolve(hermesMap)) {
808
+ fs.renameSync(sourcemapOutput, packagerMap);
809
+ } else {
810
+ fs.copyFileSync(sourcemapOutput, packagerMap);
811
+ }
614
812
  } else {
615
- console.log(t('hermesSourcemapKept', { file: `${bundlePath}.map` }));
813
+ console.log(t('hermesSourcemapKept', { file: hermesMap }));
616
814
  }
617
815
 
618
- const result: HermesCompileResult = { bytecodeVersion: null, base: null };
619
- const base = await selectHermesBase(hermesCommand, baseRequest, result);
620
-
621
- // hermesc reads its input in full before writing, so compiling in place is
622
- // safe; keep the JS bundle aside while a base compile may still fail or be
623
- // rejected by the equivalence check.
624
- const jsBackup = base ? `${bundlePath}.js.bak` : '';
625
- if (base) fs.copyFileSync(bundlePath, jsBackup);
626
- let usedBase = false;
627
- if (base) {
628
- const args = hermescArgsWithBase(plainArgs, base.path);
629
- console.log(
630
- t('runningHermesc', { command: hermesCommand, args: args.join(' ') }),
816
+ let selection = pendingBase ? await awaitPendingBase(pendingBase) : null;
817
+ const command =
818
+ hermesCommand ?? selection?.hermesCommand ?? resolveHermesCommand();
819
+ if (!selection || selection.commandUnavailable) {
820
+ selection = await selectHermesBase(command, baseRequest);
821
+ }
822
+ for (const line of selection.logs) console.log(line);
823
+ const result: HermesCompileResult = {
824
+ bytecodeVersion: selection.bytecodeVersion,
825
+ base: null,
826
+ };
827
+ const base = selection.base;
828
+ // the packager + hermes maps merged into sourcemapOutput
829
+ let composed = false;
830
+
831
+ if (!base) {
832
+ await compilePlain(command, bundlePath);
833
+ } else {
834
+ // The JS bundle moves into a work dir and both hermesc runs read it there
835
+ // (no copies); the base compile writes the real output, and with
836
+ // verification on the plain compile the check needs runs concurrently
837
+ // into `plain/` — it simply becomes the result when the base is rejected,
838
+ // so a rejected base never costs a third compile.
839
+ const workDir = path.join(outputFolder, '.hermes-base');
840
+ const jsSource = path.join(workDir, bundleName);
841
+ const plainPath = path.join(workDir, 'plain', bundleName);
842
+ const wantPlain = Boolean(baseRequest?.verify);
843
+ fs.ensureDirSync(path.dirname(plainPath));
844
+ fs.renameSync(bundlePath, jsSource);
845
+ const args = hermescArgsWithBase(
846
+ buildHermescArgs(bundlePath, jsSource),
847
+ base.path,
631
848
  );
632
- const attempt = spawnSync(hermesCommand, args, {
633
- stdio: ['ignore', 'ignore', 'pipe'],
634
- });
635
- if (attempt.status === 0) {
636
- usedBase = true;
637
- } else {
638
- const fullStderr = attempt.stderr ? String(attempt.stderr) : '';
849
+ console.log(t('runningHermesc', { command, args: args.join(' ') }));
850
+ const [attempt, plain] = await Promise.all([
851
+ // -w: warnings only bloat the captured stderr, errors still print
852
+ runProcess(command, [...args, '-w'], true),
853
+ wantPlain
854
+ ? runProcess(command, buildHermescArgs(plainPath, jsSource), false)
855
+ : Promise.resolve<ProcessOutcome | null>(null),
856
+ ]);
857
+ let usedBase = attempt.status === 0 && !attempt.error;
858
+ if (!usedBase) {
859
+ const fullStderr = attempt.error
860
+ ? String(attempt.error.message ?? attempt.error)
861
+ : attempt.stderr;
639
862
  const reason = summarizeHermescStderr(fullStderr);
640
863
  console.warn(
641
864
  t('hermesBaseCompileFailed', {
@@ -643,141 +866,166 @@ async function compileHermesByteCode(
643
866
  }),
644
867
  );
645
868
  if (fullStderr.trim()) {
646
- // the summary drops warning noise; keep everything for bug reports
647
- const logPath = path.join(outputFolder, 'hermes-base-error.log');
869
+ // the summary drops noise; keep everything for bug reports — next to
870
+ // the intermediate dir, never inside it (its content is packed)
871
+ const logPath = hermesBaseErrorLogPath(outputFolder);
648
872
  try {
649
873
  fs.writeFileSync(logPath, fullStderr);
650
874
  console.warn(t('hermesBaseCompileFailedLog', { file: logPath }));
651
875
  } catch {}
652
876
  }
653
- fs.copyFileSync(jsBackup, bundlePath);
654
877
  }
655
- }
656
- if (usedBase && baseRequest?.verify) {
657
- // plain compile next to it, compare disassembly, keep whichever is right
658
- const plainOut = `${bundlePath}.plain.hbc`;
659
- const plain = spawnSync(
660
- hermesCommand,
661
- // same flags as the real compile (only the base differs), otherwise
662
- // debug-info settings would make the two dumps legitimately differ
663
- ['-emit-binary', '-out', plainOut, jsBackup, '-O', '-output-source-map'],
664
- { stdio: 'ignore' },
665
- );
666
- let ok = plain.status === 0;
667
- if (ok) {
668
- try {
669
- ok = await verifyHermesBaseEquivalence(
670
- hermesCommand,
671
- bundlePath,
672
- plainOut,
878
+ const plainOk = plain !== null && plain.status === 0 && !plain.error;
879
+ // compose the base output's map while the disassembly compare runs; it is
880
+ // redone from the plain map in the rare case the base is rejected
881
+ const speculativeCompose =
882
+ usedBase && sourcemapOutput
883
+ ? composeSourceMaps(packagerMap, hermesMap, sourcemapOutput)
884
+ : null;
885
+ if (usedBase && wantPlain) {
886
+ if (!plainOk) {
887
+ // the check could not run; that is not a verification failure
888
+ console.warn(
889
+ t('hermesBasePlainCompileFailed', {
890
+ reason:
891
+ (plain?.error && String(plain.error.message ?? plain.error)) ||
892
+ `exit ${plain?.status}`,
893
+ }),
673
894
  );
674
- } catch {
675
- ok = false;
895
+ } else {
896
+ let ok: boolean;
897
+ try {
898
+ ok = await verifyHermesBaseEquivalence(
899
+ command,
900
+ bundlePath,
901
+ plainPath,
902
+ );
903
+ } catch {
904
+ ok = false;
905
+ }
906
+ result.verified = ok;
907
+ if (ok) {
908
+ console.log(t('hermesBaseVerified'));
909
+ } else {
910
+ console.warn(t('hermesBaseVerifyFailed'));
911
+ usedBase = false;
912
+ }
676
913
  }
677
914
  }
678
- fs.removeSync(plainOut);
679
- fs.removeSync(`${plainOut}.map`);
680
- result.verified = ok;
681
- if (ok) {
682
- console.log(t('hermesBaseVerified'));
683
- } else {
684
- console.warn(t('hermesBaseVerifyFailed'));
685
- fs.copyFileSync(jsBackup, bundlePath);
686
- usedBase = false;
915
+ if (speculativeCompose) {
916
+ const done = await speculativeCompose.catch((error) => {
917
+ if (usedBase) throw error;
918
+ return false;
919
+ });
920
+ composed = usedBase && done;
687
921
  }
922
+ if (!usedBase) {
923
+ if (plainOk) {
924
+ fs.moveSync(plainPath, bundlePath, { overwrite: true });
925
+ if (fs.existsSync(`${plainPath}.map`)) {
926
+ fs.moveSync(`${plainPath}.map`, hermesMap, { overwrite: true });
927
+ }
928
+ } else {
929
+ await compilePlain(command, bundlePath, jsSource);
930
+ }
931
+ }
932
+ fs.removeSync(workDir);
933
+ result.base = usedBase ? base : null;
688
934
  }
689
- if (jsBackup) fs.removeSync(jsBackup);
690
- if (!usedBase) {
691
- console.log(
692
- t('runningHermesc', {
693
- command: hermesCommand,
694
- args: plainArgs.join(' '),
695
- }),
696
- );
697
- assertSuccessfulSyncProcess(
698
- spawnSync(hermesCommand, plainArgs, {
699
- stdio: 'ignore',
700
- }),
701
- hermesCommand,
702
- );
703
- result.base = null;
704
- } else {
705
- result.base = base;
935
+ if (sourcemapOutput && !composed) {
936
+ await composeSourceMaps(packagerMap, hermesMap, sourcemapOutput);
706
937
  }
707
- if (sourcemapOutput) {
708
- let composerPath: string;
938
+ if (shouldCleanSourcemap) {
939
+ fs.removeSync(packagerMap);
940
+ }
941
+ return result;
942
+ }
943
+
944
+ /** where a failed base attempt's full hermesc output goes (never packed) */
945
+ export function hermesBaseErrorLogPath(outputFolder: string): string {
946
+ return path.join(
947
+ path.dirname(path.resolve(outputFolder)),
948
+ 'hermes-base-error.log',
949
+ );
950
+ }
951
+
952
+ /**
953
+ * Begin resolving the base right away (before Metro); the compile phase awaits
954
+ * the result. Never rejects: any failure is reported there instead.
955
+ */
956
+ export function startHermesBaseSelection(
957
+ request: HermesBaseRequest,
958
+ ): Promise<HermesBaseSelectionResult> {
959
+ return (async () => {
960
+ let hermesCommand: string;
709
961
  try {
710
- // resolve through the project so hoisted node_modules (monorepos) work
711
- composerPath = require.resolve(
712
- 'react-native/scripts/compose-source-maps.js',
713
- { paths: [process.cwd()] },
714
- );
962
+ hermesCommand = resolveHermesCommand();
715
963
  } catch {
716
- console.warn(t('composeSourceMapsNotFound'));
717
- return result;
964
+ return {
965
+ base: null,
966
+ bytecodeVersion: null,
967
+ logs: [],
968
+ commandUnavailable: true,
969
+ };
718
970
  }
719
- console.log(t('composingSourceMap'));
720
- assertSuccessfulSyncProcess(
721
- spawnJavaScriptSync(
722
- [
723
- composerPath,
724
- path.join(outputFolder, `${bundleName}.txt.map`),
725
- path.join(outputFolder, `${bundleName}.map`),
726
- '-o',
727
- sourcemapOutput,
971
+ try {
972
+ return await selectHermesBase(hermesCommand, request);
973
+ } catch (error: any) {
974
+ return {
975
+ base: null,
976
+ bytecodeVersion: null,
977
+ logs: [
978
+ t('hermesBaseNone', { reason: error?.message ?? String(error) }),
728
979
  ],
729
- {
730
- stdio: 'ignore',
731
- },
732
- ),
733
- composerPath,
734
- );
735
- }
736
- if (shouldCleanSourcemap) {
737
- fs.removeSync(path.join(outputFolder, `${bundleName}.txt.map`));
738
- }
739
- return result;
980
+ hermesCommand,
981
+ };
982
+ }
983
+ })();
740
984
  }
741
985
 
742
986
  async function selectHermesBase(
743
987
  hermesCommand: string,
744
988
  request: HermesBaseRequest | undefined,
745
- result: HermesCompileResult,
746
- ): Promise<HermesBaseSelection | null> {
989
+ ): Promise<HermesBaseSelectionResult> {
990
+ const logs: string[] = [];
991
+ const none = (bytecodeVersion: number | null = null) => ({
992
+ base: null,
993
+ bytecodeVersion,
994
+ logs,
995
+ hermesCommand,
996
+ });
747
997
  if (!request || request.option === 'none') {
748
998
  if (request) {
749
- console.log(t('hermesBaseNone', { reason: 'disabled by option' }));
999
+ logs.push(t('hermesBaseNone', { reason: 'disabled by option' }));
750
1000
  }
751
- return null;
1001
+ return none();
752
1002
  }
753
1003
  const gate = classifyHermesCommand(hermesCommand);
754
1004
  if (!gate.allowed) {
755
- console.log(
1005
+ logs.push(
756
1006
  t('hermesBaseNone', { reason: gate.reason ?? 'hermesc not eligible' }),
757
1007
  );
758
- return null;
1008
+ return none();
759
1009
  }
760
1010
  const bytecodeVersion = probeHbcVersion(hermesCommand);
761
- result.bytecodeVersion = bytecodeVersion;
762
1011
  if (bytecodeVersion === null) {
763
- console.log(t('hermesBaseNone', { reason: 'could not probe HBC version' }));
764
- return null;
1012
+ logs.push(t('hermesBaseNone', { reason: 'could not probe HBC version' }));
1013
+ return none();
765
1014
  }
766
1015
  try {
767
- return await resolveHermesBase({
1016
+ const base = await resolveHermesBase({
768
1017
  option: request.option,
769
1018
  hermesCommand,
770
1019
  bytecodeVersion,
771
1020
  appId: request.appId,
772
1021
  cacheMaxMb: request.cacheMaxMb,
773
1022
  fetchBase: getHermesBase,
774
- log: (message) => console.log(message),
1023
+ log: (message) => logs.push(message),
775
1024
  });
1025
+ return { base, bytecodeVersion, logs, hermesCommand };
776
1026
  } catch (error: any) {
777
- console.log(
778
- t('hermesBaseNone', { reason: error?.message ?? String(error) }),
779
- );
780
- return null;
1027
+ logs.push(t('hermesBaseNone', { reason: error?.message ?? String(error) }));
1028
+ return none(bytecodeVersion);
781
1029
  }
782
1030
  }
783
1031