vitest-native 0.15.0 → 0.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ // The hot runtime's diagnostics go to stderr directly. Vitest drops console output made
2
+ // while it starts a file, which is when the per-file reset runs, so a console.log there
3
+ // never printed (#775). One path for every worker-side hot diagnostic keeps them visible
4
+ // wherever in a file's life they are written.
5
+ export function hotDiagnostic(message) {
6
+ process.stderr.write(`[vitest-native] ${message}\n`);
7
+ }
@@ -13,6 +13,7 @@ import {
13
13
  transformRN,
14
14
  isFlow,
15
15
  cjsExportNames,
16
+ cjsReexports,
16
17
  needsTransform,
17
18
  } from "./transform.mjs";
18
19
  import { boundarySourceFor } from "./boundary.mjs";
@@ -430,6 +431,15 @@ function resolveAfter(resolved, context) {
430
431
  if (versionable(resolved.url)) {
431
432
  const gen = generationOf();
432
433
  if (gen > 0 && !resolved.url.includes("vnhot=")) {
434
+ // A require() from compiled code this loader served as source: served as Node's
435
+ // CommonJS loader serves a require, behind no generation facade (#847).
436
+ if (requiredFromServedSource(context.parentURL)) {
437
+ return {
438
+ ...resolved,
439
+ url: `${resolved.url}?vnhot=${gen}${NODE_SERVED}`,
440
+ shortCircuit: true,
441
+ };
442
+ }
433
443
  const url = `${resolved.url}?vnhot=${gen}`;
434
444
  pinFacade(url, context.parentURL);
435
445
  return { ...resolved, url, shortCircuit: true };
@@ -574,7 +584,7 @@ export function requireFacade(url, file, compiled) {
574
584
  // A `#!` line is valid only as a source's first characters; carried inside the
575
585
  // facade it would be a syntax error. The carried code is never run.
576
586
  const code = compiled.startsWith("#!") ? compiled.replace(/^#!.*/, "") : compiled;
577
- const names = cjsExportNames(code);
587
+ const names = [...new Set([...cjsExportNames(code), ...compiledReexports(file, code)])];
578
588
  // An `.mjs` file is an ES module wherever it is loaded, so the CommonJS loader cannot
579
589
  // own it: requiring it is Node's require(esm), which on Node 20.19 and 22.13 fails
580
590
  // for a module this loader is still loading ("Cannot require() ES Module ... in a
@@ -583,6 +593,7 @@ export function requireFacade(url, file, compiled) {
583
593
  // loader cannot see it (hooks.mjs), and both routes give one instance
584
594
  // (tests-native/ecosystem-mjs.test.ts).
585
595
  if (file.endsWith(".mjs")) {
596
+ compiledSourceModules.add(url.replace(STAMP, ""));
586
597
  return {
587
598
  format: "commonjs",
588
599
  source: names.length > 0 ? `${code}\n0 && (module.exports = { ${names.join(", ")} });` : code,
@@ -603,6 +614,88 @@ export function requireFacade(url, file, compiled) {
603
614
  };
604
615
  }
605
616
 
617
+ /**
618
+ * The code this loader compiles `file` to, or null for a file Node runs as published (or
619
+ * React Native's own, which has its own facade). The decisions loadModule makes, for a
620
+ * file reached by `require` rather than loaded here.
621
+ */
622
+ function compiledCodeOf(file) {
623
+ const norm = file.replace(/\\/g, "/");
624
+ if (ownership.reactNativePathFor(file) !== null) return null;
625
+ if (!isExtra(norm)) {
626
+ return NODE_MODULES_TS.test(norm) ? transformRN(file, undefined, PROJECT_ROOT, PLATFORM) : null;
627
+ }
628
+ const stub = boundarySourceFor(norm, PLATFORM, REACT_NATIVE_VERSION);
629
+ if (stub != null) return stub;
630
+ if (!TRANSFORMABLE.test(norm)) return null;
631
+ const held = heldTransform(file, PROJECT_ROOT, PLATFORM);
632
+ if (held !== undefined) return held;
633
+ const src = fs.readFileSync(file, "utf8");
634
+ return needsTransform(file, src) ? transformRN(file, src, PROJECT_ROOT, PLATFORM) : null;
635
+ }
636
+
637
+ /**
638
+ * The names a CommonJS module re-exports from files this loader compiles.
639
+ *
640
+ * Node builds an imported CommonJS module's named exports with cjs-module-lexer, and for
641
+ * a re-export (`module.exports = { ...require("./avatar") }`, `__exportStar(require(…))`)
642
+ * it reads the re-exported file from disk to lex it there. That read passes no loader
643
+ * hook, so for a file the engine compiles Node lexes the published source instead: JSX in
644
+ * a `.js` file (an esbuild build left untransformed), which the lexer cannot read, so the
645
+ * names were dropped. An esbuild-built library meets this through its ES build: the
646
+ * index's `export * from "./avatar"` compiles to Babel's `Object.keys(_avatar).forEach`
647
+ * re-export, and avatar.js is JSX. The namespace held only `default`, and Vitest takes a
648
+ * namespace with `__esModule` as it is, so `import * as Avatar` gave `Avatar.Root ===
649
+ * undefined`. Here each re-exported file is followed (cjsReexports), and the names of
650
+ * one this loader compiles are read from its compiled code, through its own re-exports
651
+ * too. For the compiled modules this loader serves (requireFacade); a module Node loads
652
+ * as published is loaded through the CommonJS loader first, and its names are read from
653
+ * the loaded module.
654
+ */
655
+ function compiledReexports(file, code, seen = new Set([file])) {
656
+ const names = new Set();
657
+ for (const specifier of cjsReexports(code)) {
658
+ // Unresolvable: Node fails the require itself, with its own error.
659
+ const target = resolvedOrNull(file, specifier);
660
+ if (target === null || seen.has(target) || !path.isAbsolute(target)) continue;
661
+ seen.add(target);
662
+ // Failing to compile: the require compiles it, and reports its own error.
663
+ const compiled = compiledCodeOrFailure(target);
664
+ if (compiled === COMPILE_FAILED) continue;
665
+ if (compiled !== null) for (const name of cjsExportNames(compiled)) names.add(name);
666
+ const source = compiled ?? readOrNull(target);
667
+ if (source !== null)
668
+ for (const name of compiledReexports(target, source, seen)) names.add(name);
669
+ }
670
+ return [...names];
671
+ }
672
+
673
+ const COMPILE_FAILED = Symbol("compile failed");
674
+
675
+ function compiledCodeOrFailure(file) {
676
+ try {
677
+ return compiledCodeOf(file);
678
+ } catch {
679
+ return COMPILE_FAILED;
680
+ }
681
+ }
682
+
683
+ function resolvedOrNull(from, specifier) {
684
+ try {
685
+ return createRequire(from).resolve(specifier);
686
+ } catch {
687
+ return null;
688
+ }
689
+ }
690
+
691
+ function readOrNull(file) {
692
+ try {
693
+ return fs.readFileSync(file, "utf8");
694
+ } catch {
695
+ return null;
696
+ }
697
+ }
698
+
606
699
  /**
607
700
  * A file Node loads as published. True ESM among them is recorded in the ownership ledger
608
701
  * (ownership-ledger.mjs), through the engine's dispatcher channel, before Node evaluates
@@ -699,6 +792,20 @@ const pinnedFacades = new Set();
699
792
  // externalized modules (pinFacade), or null to release nothing.
700
793
  let runnerImportSite = null;
701
794
 
795
+ // Unstamped URLs of compiled modules this loader hands Node as CommonJS source (an `.mjs`
796
+ // file, see requireFacade). Node gives such source a `require` that resolves through
797
+ // this loader, with import conditions, so its require()s arrive here looking like
798
+ // imports. A generation facade is an ES module, and a require() must get the module's
799
+ // `module.exports`: on Node 22 an ES facade reached this way failed to link
800
+ // (ERR_VM_MODULE_LINK_FAILURE, "is from a module not been linked", #847), and a facade
801
+ // imported from outside the runner is pinned for the run (pinFacade). Served as
802
+ // `&vnnode`, the request is the module Node's CommonJS loader owns, the instance the
803
+ // file's own import of it reaches, and dropped per file by the hot reset.
804
+ const compiledSourceModules = new Set();
805
+ function requiredFromServedSource(parentURL) {
806
+ return typeof parentURL === "string" && compiledSourceModules.has(parentURL.replace(STAMP, ""));
807
+ }
808
+
702
809
  /**
703
810
  * Vitest's module evaluator, the module whose `import(file)` loads a test file's
704
811
  * externalized modules (`runExternalModule`): resolved from the installed Vitest's own
@@ -5,6 +5,7 @@ import { createRequire } from "node:module";
5
5
  import { pathToFileURL } from "node:url";
6
6
  import { VitestNativeError } from "../errors.mjs";
7
7
  import { METRO_ASSET_EXTS } from "./assets.mjs";
8
+ import { readInput } from "./bounded-process.mjs";
8
9
 
9
10
  const BARE_SOURCE_EXTS = ["js", "jsx", "json", "ts", "tsx"];
10
11
 
@@ -185,7 +186,7 @@ async function loadProject(input) {
185
186
  }
186
187
 
187
188
  try {
188
- const input = JSON.parse(fs.readFileSync(0, "utf8"));
189
+ const input = readInput();
189
190
  const started = performance.now();
190
191
  const profile = await loadProject(input);
191
192
  respond({
@@ -6,6 +6,7 @@
6
6
  // the Vite main process must never retain Metro module identities.
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { runBoundedProcess } from "./bounded-process.mjs";
9
+ import { cacheRootFor } from "./transform.mjs";
9
10
  import { VitestNativeError, VitestNativeTypeError } from "../errors.mjs";
10
11
 
11
12
  const INITIAL_HEAP_MB = 128;
@@ -88,6 +89,7 @@ export async function loadMetroProfile(
88
89
  retryHeapMb: RETRY_HEAP_MB,
89
90
  timeoutMs: TIMEOUT_MS,
90
91
  label: "Metro profile loader",
92
+ inputDir: cacheRootFor(projectRoot),
91
93
  },
92
94
  );
93
95
  if (!result.ok) {
@@ -1,9 +1,10 @@
1
1
  // Short-lived entrypoint for a cold React Native registry build.
2
2
  //
3
- // One JSON options object in on stdin, one JSON result out. No logging: the output is a
3
+ // One JSON options object in (a file named by the first argument), one JSON result out. No logging: the output is a
4
4
  // protocol, and a failure is returned for the parent to report once.
5
5
  import fs from "node:fs";
6
6
  import { Worker } from "node:worker_threads";
7
+ import { readInput } from "./bounded-process.mjs";
7
8
  import { buildLibraryRegistry, buildRegistry } from "./registry.mjs";
8
9
 
9
10
  // A watchdog thread ends this process if its parent dies or it runs longer than the
@@ -28,7 +29,7 @@ function respond(value) {
28
29
  }
29
30
 
30
31
  try {
31
- const { testDelayMs, ...options } = JSON.parse(fs.readFileSync(0, "utf8"));
32
+ const { testDelayMs, ...options } = readInput();
32
33
  if (testDelayMs > 0) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, testDelayMs);
33
34
  const started = performance.now();
34
35
  const registryFile = buildRegistry({
@@ -8,6 +8,7 @@ import {
8
8
  registryLocation,
9
9
  } from "./registry.mjs";
10
10
  import { runBoundedProcess } from "./bounded-process.mjs";
11
+ import { cacheRootFor } from "./transform.mjs";
11
12
 
12
13
  const INITIAL_HEAP_MB = 96;
13
14
  const RETRY_HEAP_MB = 256;
@@ -36,6 +37,7 @@ export async function compileRegistryInChild(
36
37
  priority,
37
38
  unref,
38
39
  label: "compiler",
40
+ inputDir: options?.projectRoot ? cacheRootFor(options.projectRoot) : undefined,
39
41
  });
40
42
  if (result.ok && typeof result.registryFile !== "string") {
41
43
  return {
@@ -39,7 +39,7 @@ import {
39
39
  TRANSFORM_CACHE_VERSION,
40
40
  } from "./transform.mjs";
41
41
 
42
- import { boundarySourceFor, BOUNDARY_SOURCES } from "./boundary.mjs";
42
+ import { boundarySourceFor, BOUNDARY_SOURCES, PACKAGE_STUBS } from "./boundary.mjs";
43
43
  import { resolveTransformPreset } from "./babel-preset.mjs";
44
44
  import { assetRegistryPathFor, nativeAssetModuleSource } from "./assets.mjs";
45
45
  import {
@@ -311,6 +311,11 @@ export function registryKeyInputs({
311
311
  );
312
312
  boundaries.update("\0");
313
313
  }
314
+ for (const [dir, stubs] of Object.entries(PACKAGE_STUBS)) {
315
+ for (const suffix of Object.keys(stubs).sort()) {
316
+ boundaries.update(`${dir}/${suffix}\0${stubs[suffix]}\0`);
317
+ }
318
+ }
314
319
  return [
315
320
  `f${REGISTRY_FORMAT_VERSION}`,
316
321
  // The registry stores TRANSFORMED module source, so a change in what the
@@ -11,6 +11,7 @@ import { fileURLToPath } from "node:url";
11
11
  import { VitestNativeError } from "../errors.mjs";
12
12
  import { isRuntimeResidentFile, isTestRuntimeResidentFile } from "./ownership.mjs";
13
13
  import { createStateManifest } from "./state-manifest.mjs";
14
+ import { hotDiagnostic } from "./hot-diagnostic.mjs";
14
15
 
15
16
  // Keys owned by Vitest, Vite, coverage or this plugin: never deleted or put back by the
16
17
  // globals diff. Vitest names its own in both cases, and replaces some per task:
@@ -18,11 +19,6 @@ import { createStateManifest } from "./state-manifest.mjs";
18
19
  // is defined anew for every file. Matched case-sensitively as `__vitest_native_` once,
19
20
  // which missed it, so every later file got the first file's worker state back (#690).
20
21
  const HARNESS_GLOBALS = /^(?:__vitest|__VITEST|__VITE|__coverage__)/;
21
- // Node's bundled undici installs these non-configurable symbols lazily. Their
22
- // lifecycle belongs to the host runtime, not to the test file that happens to
23
- // trigger initialization, and attempting to delete them poisons every later
24
- // file. Keep the allowlist narrow and description-based across Node releases.
25
- const NODE_LAZY_GLOBAL_SYMBOLS = /^undici\.(?:globalDispatcher|globalOrigin)(?:\.|$)/;
26
22
  // Vitest updates these scheduler-owned values between tasks.
27
23
  const ENV_PRESERVED = new Set(["VITEST_POOL_ID", "VITEST_WORKER_ID"]);
28
24
  const RESET_FILE = fileURLToPath(import.meta.url).replaceAll("\\", "/");
@@ -58,7 +54,7 @@ export function isResidentImportListener(stack, projectRoot) {
58
54
  return sawExternalFrame;
59
55
  }
60
56
 
61
- function captureDescriptors(target) {
57
+ export function captureDescriptors(target) {
62
58
  return new Map(
63
59
  Reflect.ownKeys(target).map((key) => [key, Object.getOwnPropertyDescriptor(target, key)]),
64
60
  );
@@ -76,22 +72,39 @@ function sameDescriptor(left, right) {
76
72
  );
77
73
  }
78
74
 
79
- function restoreDescriptors(target, baseline, skip = () => false) {
75
+ // A non-configurable property can't be deleted or redefined, so no reset can give the
76
+ // next file the worker's baseline for it, and per-file isolation has nothing to put
77
+ // back. Such a property is worker state, as Node's own process-wide registries are
78
+ // (undici's global dispatcher, or a library's `Symbol.for` registry defined once per
79
+ // process, #773): it joins the baseline, and later files restore and verify against
80
+ // it. Failing the restore instead failed every later file in the worker.
81
+ export function restoreDescriptors(target, baseline, { skip = () => false, onResident } = {}) {
82
+ const keepResident = (key) => {
83
+ const current = Object.getOwnPropertyDescriptor(target, key);
84
+ baseline.set(key, current);
85
+ onResident?.(key, current);
86
+ };
80
87
  for (const key of Reflect.ownKeys(target)) {
81
88
  if (skip(key) || baseline.has(key)) continue;
82
- if (!Reflect.deleteProperty(target, key)) {
89
+ if (Reflect.deleteProperty(target, key)) continue;
90
+ if (Object.getOwnPropertyDescriptor(target, key)?.configurable !== false) {
83
91
  throw stateFailure(`could not delete ${String(key)}`);
84
92
  }
93
+ keepResident(key);
85
94
  }
86
95
  for (const [key, descriptor] of baseline) {
87
96
  if (skip(key)) continue;
88
- if (!sameDescriptor(Object.getOwnPropertyDescriptor(target, key), descriptor)) {
89
- Object.defineProperty(target, key, descriptor);
97
+ const current = Object.getOwnPropertyDescriptor(target, key);
98
+ if (sameDescriptor(current, descriptor)) continue;
99
+ if (Reflect.defineProperty(target, key, descriptor)) continue;
100
+ if (current?.configurable !== false) {
101
+ throw stateFailure(`could not restore ${String(key)}`);
90
102
  }
103
+ keepResident(key);
91
104
  }
92
105
  }
93
106
 
94
- function verifyDescriptors(target, baseline, skip = () => false) {
107
+ export function verifyDescriptors(target, baseline, skip = () => false) {
95
108
  for (const key of Reflect.ownKeys(target)) {
96
109
  if (!skip(key) && !baseline.has(key)) throw stateFailure(`unexpected ${String(key)}`);
97
110
  }
@@ -335,25 +348,37 @@ export function installHotReset({ projectRoot, diagnostics, preserveGlobals = []
335
348
  },
336
349
  });
337
350
 
351
+ // Each worker-resident property is recorded once, with the file that was running
352
+ // when it appeared: the property's name usually names its library, and the file is
353
+ // where to look when it does not.
354
+ let previousFile = null;
355
+ const residentNotice = (where) => (key) => {
356
+ if (!diagnostics) return;
357
+ const by = previousFile ? `; it appeared while ${previousFile} ran` : "";
358
+ hotDiagnostic(
359
+ `hot reset: kept ${where}${String(key)} for the worker's life: ` +
360
+ `it is non-configurable, so no reset can remove or replace it${by}`,
361
+ );
362
+ };
363
+
338
364
  manifest.register({
339
365
  id: "global.descriptors",
340
366
  capture: () => captureDescriptors(globalThis),
341
367
  restore: (baseline) => {
342
368
  const deleted = [];
343
369
  const skip = (key) =>
344
- globallyPreserved.has(key) ||
345
- (typeof key === "string" && HARNESS_GLOBALS.test(key)) ||
346
- (typeof key === "symbol" &&
347
- !baseline.has(key) &&
348
- NODE_LAZY_GLOBAL_SYMBOLS.test(key.description ?? ""));
370
+ globallyPreserved.has(key) || (typeof key === "string" && HARNESS_GLOBALS.test(key));
349
371
  if (diagnostics) {
350
372
  for (const key of Reflect.ownKeys(globalThis)) {
351
- if (!skip(key) && !baseline.has(key)) deleted.push(String(key));
373
+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, key);
374
+ if (!skip(key) && !baseline.has(key) && descriptor.configurable) {
375
+ deleted.push(String(key));
376
+ }
352
377
  }
353
378
  }
354
- restoreDescriptors(globalThis, baseline, skip);
379
+ restoreDescriptors(globalThis, baseline, { skip, onResident: residentNotice("globalThis.") });
355
380
  if (diagnostics && deleted.length) {
356
- console.log(`[vitest-native] hot reset: deleted test-phase globals: ${deleted.join(", ")}`);
381
+ hotDiagnostic(`hot reset: deleted test-phase globals: ${deleted.join(", ")}`);
357
382
  }
358
383
  },
359
384
  verify: (baseline) =>
@@ -361,18 +386,15 @@ export function installHotReset({ projectRoot, diagnostics, preserveGlobals = []
361
386
  globalThis,
362
387
  baseline,
363
388
  (key) =>
364
- globallyPreserved.has(key) ||
365
- (typeof key === "string" && HARNESS_GLOBALS.test(key)) ||
366
- (typeof key === "symbol" &&
367
- !baseline.has(key) &&
368
- NODE_LAZY_GLOBAL_SYMBOLS.test(key.description ?? "")),
389
+ globallyPreserved.has(key) || (typeof key === "string" && HARNESS_GLOBALS.test(key)),
369
390
  ),
370
391
  });
371
392
 
372
393
  manifest.register({
373
394
  id: "console.descriptors",
374
395
  capture: () => captureDescriptors(console),
375
- restore: (baseline) => restoreDescriptors(console, baseline),
396
+ restore: (baseline) =>
397
+ restoreDescriptors(console, baseline, { onResident: residentNotice("console.") }),
376
398
  verify: (baseline) => verifyDescriptors(console, baseline),
377
399
  });
378
400
 
@@ -394,7 +416,9 @@ export function installHotReset({ projectRoot, diagnostics, preserveGlobals = []
394
416
  capture: () => captureDescriptors(globalThis.expo ?? {}),
395
417
  restore: (baseline) => {
396
418
  globalThis.expo?.[Symbol.for("vitest-native.expo.reset")]?.();
397
- if (globalThis.expo) restoreDescriptors(globalThis.expo, baseline);
419
+ if (globalThis.expo) {
420
+ restoreDescriptors(globalThis.expo, baseline, { onResident: residentNotice("expo.") });
421
+ }
398
422
  },
399
423
  verify: (baseline) => {
400
424
  if (globalThis.expo) {
@@ -427,6 +451,7 @@ export function installHotReset({ projectRoot, diagnostics, preserveGlobals = []
427
451
 
428
452
  return {
429
453
  hotReset: (file = null) => {
454
+ previousFile = startingFile;
430
455
  startingFile = file;
431
456
  manifest.beginFile();
432
457
  },
@@ -20,9 +20,14 @@ import {
20
20
  requireProjectContext,
21
21
  } from "../context.mjs";
22
22
  import { importPresetModule, presetModulePaths } from "../preset-modules.mjs";
23
+ import { presetFactoryContext } from "../preset-react.mjs";
23
24
  import { installNitroProxy } from "./nitro.mjs";
24
25
  import { createExpoNativeModuleResolver } from "./expo-native-modules.mjs";
25
- import { beginTestFile, installLibraryJest } from "./library-jest.mjs";
26
+ import { beginTestFile, installLibraryJest, libraryJestFor } from "./library-jest.mjs";
27
+ import {
28
+ GESTURE_HANDLER_SETUP,
29
+ registerGestureHandlerButtons,
30
+ } from "./gesture-handler-buttons.mjs";
26
31
  import { cacheRootFor } from "./transform.mjs";
27
32
  import { installKnownNativeModules } from "./native-modules.mjs";
28
33
  import { OWNERSHIP_META_KEY, installOwnershipLedger } from "./ownership-ledger.mjs";
@@ -355,6 +360,11 @@ for (const request of runContext.librarySetupFiles ?? []) {
355
360
  if (file === null) continue;
356
361
  delete load.cache[file];
357
362
  load(request);
363
+ // What the package's own setup leaves real and a test cannot press: Gesture Handler
364
+ // 3's button host (gesture-handler-buttons.mjs), registered as if from its jestSetup.js.
365
+ if (request === GESTURE_HANDLER_SETUP) {
366
+ registerGestureHandlerButtons(libraryJestFor(vi, file));
367
+ }
358
368
  }
359
369
  // Through Vitest, so a TypeScript preset module loads. Its export lists already
360
370
  // reached the ESM loader from the plugin; a module the plugin did not read would be
@@ -397,7 +407,10 @@ for (const { pkg, mod, presetName } of presetDefs) {
397
407
  enumerable: true,
398
408
  get() {
399
409
  if (!builtPresetMocks.has(pkg)) {
400
- builtPresetMocks.set(pkg, mod.factory());
410
+ builtPresetMocks.set(
411
+ pkg,
412
+ mod.factory(presetFactoryContext(pkg, projectRoot, { check: true })),
413
+ );
401
414
  if (diagnostics) {
402
415
  console.log(`[vitest-native] (native) built preset mock: ${pkg} (${presetName})`);
403
416
  }
@@ -6,6 +6,7 @@
6
6
  // restored and verified before the next file. A failure names the responsible entry
7
7
  // instead of being swallowed and turning into an order-dependent later assertion.
8
8
  import { VitestNativeError, VitestNativeTypeError } from "../errors.mjs";
9
+ import { hotDiagnostic } from "./hot-diagnostic.mjs";
9
10
 
10
11
  const NOT_CAPTURED = Symbol("vitest-native.state.not-captured");
11
12
 
@@ -67,9 +68,7 @@ export function createStateManifest({ diagnostics = false, mutation = null } = {
67
68
  for (const record of records) capture(record);
68
69
  initialized = true;
69
70
  if (diagnostics) {
70
- console.log(
71
- `[vitest-native] state manifest: ${records.map(({ entry }) => entry.id).join(", ")}`,
72
- );
71
+ hotDiagnostic(`state manifest: ${records.map(({ entry }) => entry.id).join(", ")}`);
73
72
  }
74
73
  }
75
74
 
@@ -334,6 +334,117 @@ export function transformCacheDir(projectRoot) {
334
334
  return contexts.get(canonicalRoot(projectRoot))?.cacheDir ?? null;
335
335
  }
336
336
 
337
+ /** The specifier of `require("x")`, or null. */
338
+ function requiredSpecifier(node) {
339
+ return node?.type === "CallExpression" &&
340
+ node.callee.type === "Identifier" &&
341
+ node.callee.name === "require" &&
342
+ node.arguments.length === 1 &&
343
+ node.arguments[0].type === "StringLiteral"
344
+ ? node.arguments[0].value
345
+ : null;
346
+ }
347
+
348
+ // Helpers that copy every export of a required module: TypeScript's (`__exportStar`,
349
+ // `__export`) and esbuild's (`__reExport`).
350
+ const REEXPORT_HELPERS = new Set(["__exportStar", "__export", "__reExport"]);
351
+
352
+ /**
353
+ * The specifiers a CommonJS module re-exports whole, read from its AST: the forms
354
+ * cjs-module-lexer follows as re-exports.
355
+ *
356
+ * - `module.exports = require("x")`;
357
+ * - a spread in an object assigned to `module.exports`, as in esbuild's
358
+ * `0 && (module.exports = { ...require("x") })` hint;
359
+ * - TypeScript's `__exportStar(require("x"), exports)` and esbuild's
360
+ * `__reExport(target, require("x"), module.exports)`;
361
+ * - Babel's `var _x = require("x"); Object.keys(_x).forEach(…)`.
362
+ *
363
+ * Node reads a re-exported file from disk to find its names, past the module loader's
364
+ * hooks, so the names of a file the engine compiles are lost there (compiledReexports
365
+ * in loader.mjs). Returns [] for code that does not parse.
366
+ */
367
+ export function cjsReexports(code) {
368
+ if (!/\brequire\s*\(/.test(code)) return [];
369
+ const ctx = anyContext();
370
+ if (!ctx) return [];
371
+ if (!ctx.babel) ctx.babel = ctx.req("@babel/core");
372
+ let ast;
373
+ try {
374
+ ast = ctx.babel.parseSync(code, { babelrc: false, configFile: false, sourceType: "script" });
375
+ } catch {
376
+ return [];
377
+ }
378
+ const found = new Set();
379
+ const required = new Map(); // `var _x = require("x")`: _x → "x"
380
+ const isModuleExports = (node) =>
381
+ node?.type === "MemberExpression" &&
382
+ !node.computed &&
383
+ node.object.type === "Identifier" &&
384
+ node.object.name === "module" &&
385
+ node.property.type === "Identifier" &&
386
+ node.property.name === "exports";
387
+ const visitExpression = (node) => {
388
+ if (!node) return;
389
+ if (node.type === "LogicalExpression" || node.type === "SequenceExpression") {
390
+ for (const part of node.type === "LogicalExpression"
391
+ ? [node.left, node.right]
392
+ : node.expressions)
393
+ visitExpression(part);
394
+ return;
395
+ }
396
+ if (node.type === "AssignmentExpression" && isModuleExports(node.left)) {
397
+ const direct = requiredSpecifier(node.right);
398
+ if (direct) found.add(direct);
399
+ if (node.right.type === "ObjectExpression") {
400
+ for (const property of node.right.properties) {
401
+ const spread =
402
+ property.type === "SpreadElement" ? requiredSpecifier(property.argument) : null;
403
+ if (spread) found.add(spread);
404
+ }
405
+ }
406
+ return;
407
+ }
408
+ if (node.type !== "CallExpression") return;
409
+ if (node.callee.type === "Identifier" && REEXPORT_HELPERS.has(node.callee.name)) {
410
+ for (const argument of node.arguments) {
411
+ const specifier = requiredSpecifier(argument) ?? required.get(argument.name);
412
+ if (specifier) found.add(specifier);
413
+ }
414
+ return;
415
+ }
416
+ // Object.keys(_x).forEach(…)
417
+ const callee = node.callee;
418
+ if (
419
+ callee.type === "MemberExpression" &&
420
+ callee.property.type === "Identifier" &&
421
+ callee.property.name === "forEach" &&
422
+ callee.object.type === "CallExpression" &&
423
+ callee.object.callee.type === "MemberExpression" &&
424
+ callee.object.callee.object.type === "Identifier" &&
425
+ callee.object.callee.object.name === "Object" &&
426
+ callee.object.callee.property.name === "keys" &&
427
+ callee.object.arguments[0]?.type === "Identifier"
428
+ ) {
429
+ const specifier = required.get(callee.object.arguments[0].name);
430
+ if (specifier) found.add(specifier);
431
+ }
432
+ };
433
+ for (const statement of ast.program.body) {
434
+ if (statement.type === "VariableDeclaration") {
435
+ for (const declaration of statement.declarations) {
436
+ const specifier = requiredSpecifier(declaration.init);
437
+ if (specifier && declaration.id.type === "Identifier") {
438
+ required.set(declaration.id.name, specifier);
439
+ }
440
+ }
441
+ } else if (statement.type === "ExpressionStatement") {
442
+ visitExpression(statement.expression);
443
+ }
444
+ }
445
+ return [...found];
446
+ }
447
+
337
448
  /** Returns true if the source contains RN Flow syntax that must be transformed. */
338
449
  /** A valid identifier, so a name can appear in the shorthand export hint. */
339
450
  const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
@@ -388,7 +499,17 @@ export function cjsExportNames(code) {
388
499
  };
389
500
  for (const statement of ast.program.body) {
390
501
  if (statement.type !== "ExpressionStatement") continue;
391
- const expression = statement.expression;
502
+ let expression = statement.expression;
503
+ // esbuild's dead hint for Node, `0 && (module.exports = { a, b })`, is the one place
504
+ // its CommonJS output names its exports: they are otherwise getters set up through
505
+ // `__export(target, { a: () => a })` and `module.exports = __toCommonJS(target)`.
506
+ if (
507
+ expression.type === "LogicalExpression" &&
508
+ expression.operator === "&&" &&
509
+ expression.right.type === "AssignmentExpression"
510
+ ) {
511
+ expression = expression.right;
512
+ }
392
513
  if (expression.type !== "AssignmentExpression" || expression.operator !== "=") continue;
393
514
  const target = expression.left;
394
515
  // `module.exports = { … }` / `exports = { … }` — take the literal's own keys.
@@ -30,6 +30,7 @@ import { residentProblems } from "./resident-health.mjs";
30
30
  import { enableV8CompileCache } from "./compile-cache.mjs";
31
31
  import { installOwnershipLedger } from "./ownership-ledger.mjs";
32
32
  import { VitestNativeError } from "../errors.mjs";
33
+ import { hotDiagnostic } from "./hot-diagnostic.mjs";
33
34
  import { activeRegistry, markBootContext, requireProjectContext } from "../context.mjs";
34
35
 
35
36
  if (isMainThread || !parentPort) {
@@ -50,7 +51,7 @@ const sourceExts = context.sourceExts ?? ["js", "jsx", "json", "ts", "tsx"];
50
51
  if (diagnostics) {
51
52
  // One line per worker boot: under a hot pool, N files sharing a worker print
52
53
  // this once, not N times — the "RN loads once" proof.
53
- console.log(`[vitest-native] hot worker boot (pid ${process.pid}, tid ${threadId})`);
54
+ hotDiagnostic(`hot worker boot (pid ${process.pid}, tid ${threadId})`);
54
55
  }
55
56
 
56
57
  // --- One-time worker init: load RN into the resident Node require cache ---
@@ -155,9 +156,7 @@ globalThis.__vitest_native_hot_reset = (file) => {
155
156
  const dropped = resetModules();
156
157
  hotReset(file);
157
158
  if (diagnostics) {
158
- console.log(
159
- `[vitest-native] hot reset: dropped ${dropped} modules, released ${released} module generations`,
160
- );
159
+ hotDiagnostic(`hot reset: dropped ${dropped} modules, released ${released} module generations`);
161
160
  }
162
161
  };
163
162
  globalThis.__vitest_native_hot_bless = bless;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Types for preset-react.mjs. Self-contained, since it ships beside the built files;
3
+ * callers pass the result to a preset module's factory (PresetFactoryContext).
4
+ */
5
+ export function presetFactoryContext(
6
+ pkg: string,
7
+ root: string,
8
+ options?: { check?: boolean },
9
+ ): { React: any };
10
+ export function rendererRequire(root: string): NodeJS.Require;
11
+ export function assertOneReact(root: string, user?: string): void;