vitest-native 0.15.0-rc.3 → 0.15.0-rc.5

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.
package/README.md CHANGED
@@ -105,7 +105,7 @@ through the jest-compat layer. See [migrating from Jest](https://vitest-native.d
105
105
  | | Supported |
106
106
  |---|---|
107
107
  | Node.js | 22.22.3+ on Node 22, 24.12+ on Node 24, or 26+ |
108
- | Vitest | 5.x |
108
+ | Vitest | 5.x (5.1.0 or later recommended) |
109
109
  | Vite | ^8.0.5 |
110
110
  | React | 19 or later |
111
111
  | React Native | 0.86–0.88 |
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { A as PEER_REQUIREMENTS, C as SUPPORTED_NODE, E as unsupportedNodeMessage, F as unsupportedExpoSdkMessage, I as unsupportedReactNativeMessage, M as belowRecommendedMessage, N as installedExpoVersion, O as validatePeerDependency, P as isBelowSupportedReactNative, T as satisfiesNodeRange, _ as normalizeBabelName, c as detectEcosystemPackages, g as isKnownPlugin, h as classifyBabelPlugins, i as ownVitestPackage, l as babelParser, m as projectBabelTrigger, o as usesVitePlus, p as missingBabelCoreNotice, r as installedViteVersion, u as isPlainJavaScript, v as installedManifest, y as detectEngine } from "./host-C02lnLzW.mjs";
2
+ import { A as PEER_REQUIREMENTS, C as SUPPORTED_NODE, E as unsupportedNodeMessage, F as unsupportedExpoSdkMessage, I as unsupportedReactNativeMessage, M as belowRecommendedMessage, N as installedExpoVersion, O as validatePeerDependency, P as isBelowSupportedReactNative, T as satisfiesNodeRange, _ as isKnownPlugin, c as detectEcosystemPackages, d as detectEngine, g as classifyBabelPlugins, h as projectBabelTrigger, i as ownVitestPackage, l as babelParser, m as missingBabelCoreNotice, o as usesVitePlus, r as installedViteVersion, u as isPlainJavaScript, v as normalizeBabelName, y as installedManifest } from "./host-TAGjG56H.mjs";
3
3
  import { a as PRESET_MODULES, f as presetShadowing, i as LIBRARY_SETUP_FILES, m as testsItself, r as DEFAULT_ASSET_EXTS, s as autoDetectedPresetApplies, t as AUTO_DETECT_PRESETS } from "./preset-map-DdAexIwz.mjs";
4
4
  import { n as ignorePattern, t as findNodeModuleMocks } from "./root-mocks-DP95ncxD.mjs";
5
5
  import { n as formatHotMemoryPlan, t as createHotMemoryPlan } from "./memory-Couw0Esx.mjs";
@@ -11,8 +11,8 @@ import os from "node:os";
11
11
  import { VitestNativeError } from "./errors.mjs";
12
12
  import { docsUrl } from "./docs-url.mjs";
13
13
  import { createNativeOwnershipPolicy, formatNativeOwnershipManifest } from "./native/ownership.mjs";
14
- import { resolveTransformPreset } from "./native/babel-preset.mjs";
15
14
  import { relativeToRoot, rootSpellings } from "./native/root-spelling.mjs";
15
+ import { resolveTransformPreset } from "./native/babel-preset.mjs";
16
16
  import { HOT_STATE_MANIFEST_ENTRIES } from "./native/state-manifest.mjs";
17
17
  import { isDeepStrictEqual } from "node:util";
18
18
  import { spawn, spawnSync } from "node:child_process";
@@ -277,6 +277,16 @@ function serializableOptions(entry) {
277
277
  };
278
278
  return entry.options === void 0 || plain(entry.options);
279
279
  }
280
+ // src/regexp.ts
281
+ /**
282
+ * `text` as a RegExp source that matches exactly that text. Every value interpolated into
283
+ * a RegExp goes through an escape helper (lint rule vitest-native/escaped-regexp): a
284
+ * path, package name or identifier can hold `.`, `+`, `(` or `$`, which otherwise match
285
+ * more, or less, than themselves.
286
+ */
287
+ function escapeRegExp(text) {
288
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
289
+ }
280
290
  // src/cli/doctor.ts
281
291
  /**
282
292
  * `vitest-native doctor` — diagnose the project's environment: peer versions,
@@ -362,12 +372,97 @@ function extendsSharedConfig(source) {
362
372
  const bindings = [...clause.matchAll(/([A-Za-z_$][\w$]*)/g)].map((m) => m[1]);
363
373
  for (const binding of bindings) {
364
374
  if (binding === "defineConfig" || binding === "default") continue;
365
- if (new RegExp(`export\\s+default\\s+${binding}\\s*;?\\s*$`, "m").test(code)) return true;
366
- if (new RegExp(`\\bmergeConfig\\s*\\(\\s*${binding}\\b`).test(code)) return true;
375
+ if (new RegExp(`export\\s+default\\s+${escapeRegExp(binding)}\\s*;?\\s*$`, "m").test(code)) return true;
376
+ if (new RegExp(`\\bmergeConfig\\s*\\(\\s*${escapeRegExp(binding)}(?![\\w$])`).test(code)) return true;
367
377
  }
368
378
  }
369
379
  return false;
370
380
  }
381
+ /** Source extensions a shared config module can have, in the order a relative import tries them. */
382
+ const CONFIG_MODULE_EXTENSIONS = [
383
+ ".ts",
384
+ ".mts",
385
+ ".cts",
386
+ ".js",
387
+ ".mjs",
388
+ ".cjs"
389
+ ];
390
+ /** How many relative imports deep the config is followed (config → shared → its base). */
391
+ const SHARED_CONFIG_DEPTH = 3;
392
+ const RELATIVE_SPECIFIER = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|\bimport\s+)["'](\.{1,2}\/[^"']+)["']/g;
393
+ /** The relative modules `code` imports (static, dynamic, side-effect, require). */
394
+ function relativeSpecifiers(code) {
395
+ return [...new Set([...code.matchAll(RELATIVE_SPECIFIER)].map((m) => m[1]))];
396
+ }
397
+ /** A relative import as a file, as Vite resolves it: as written, by extension, as a directory index. */
398
+ function resolveConfigModule(fromFile, specifier) {
399
+ const base = path.resolve(path.dirname(fromFile), specifier);
400
+ const stem = /\.[cm]?js$/.test(base) ? base.replace(/\.([cm]?)js$/, "") : null;
401
+ return [
402
+ base,
403
+ ...CONFIG_MODULE_EXTENSIONS.map((ext) => base + ext),
404
+ ...stem ? [
405
+ ".ts",
406
+ ".mts",
407
+ ".cts"
408
+ ].map((ext) => stem + ext) : [],
409
+ ...CONFIG_MODULE_EXTENSIONS.map((ext) => path.join(base, `index${ext}`))
410
+ ].find((file) => fs.statSync(file, { throwIfNoEntry: false })?.isFile()) ?? null;
411
+ }
412
+ /**
413
+ * Whether a config that does not import vitest-native itself builds on a module that does:
414
+ * a monorepo package's config merging a shared `../../vitest.shared.ts`, say. The config's
415
+ * relative imports are followed up to SHARED_CONFIG_DEPTH deep, each module once. A
416
+ * relative import that cannot be resolved or read, or the depth running out, leaves it
417
+ * unconfirmed rather than "does not import".
418
+ */
419
+ function sharedConfigUse(configFile) {
420
+ const shown = (file) => path.relative(path.dirname(configFile), file).split(path.sep).join("/");
421
+ const seen = /* @__PURE__ */ new Set([path.resolve(configFile)]);
422
+ let unconfirmed = null;
423
+ const note = (reason) => unconfirmed ??= reason;
424
+ let level = [path.resolve(configFile)];
425
+ for (let depth = 1; level.length > 0; depth++) {
426
+ const next = [];
427
+ for (const file of level) {
428
+ let source;
429
+ try {
430
+ source = fs.readFileSync(file, "utf8");
431
+ } catch (error) {
432
+ note(`${shown(file)} could not be read (${error.code ?? "error"})`);
433
+ continue;
434
+ }
435
+ const code = withoutComments$1(source);
436
+ if (file !== path.resolve(configFile)) {
437
+ const usage = analyzeConfigUsage(source);
438
+ if (usage.imports && usage.invokes) return {
439
+ via: shown(file),
440
+ unconfirmed: null
441
+ };
442
+ if (usage.imports) note(`${shown(file)} imports vitest-native but does not call reactNative() there`);
443
+ }
444
+ for (const specifier of relativeSpecifiers(code)) {
445
+ const target = resolveConfigModule(file, specifier);
446
+ if (!target) {
447
+ note(`'${specifier}' (imported by ${shown(file)}) could not be resolved`);
448
+ continue;
449
+ }
450
+ if (!CONFIG_MODULE_EXTENSIONS.includes(path.extname(target)) || seen.has(target)) continue;
451
+ if (depth > SHARED_CONFIG_DEPTH) {
452
+ note(`it builds on modules more than ${SHARED_CONFIG_DEPTH} imports deep`);
453
+ continue;
454
+ }
455
+ seen.add(target);
456
+ next.push(target);
457
+ }
458
+ }
459
+ level = next;
460
+ }
461
+ return {
462
+ via: null,
463
+ unconfirmed
464
+ };
465
+ }
371
466
  /**
372
467
  * Whether a config genuinely uses the plugin.
373
468
  *
@@ -399,12 +494,12 @@ function analyzeConfigUsage(source) {
399
494
  };
400
495
  return {
401
496
  imports: true,
402
- invokes: new RegExp(`\\b${binding}\\s*\\(`).test(code)
497
+ invokes: new RegExp(`(?<![\\w$])${escapeRegExp(binding)}\\s*\\(`).test(code)
403
498
  };
404
499
  }
405
500
  if (namespaced) return {
406
501
  imports: true,
407
- invokes: new RegExp(`\\b${namespaced[1]}\\.\\w+\\s*\\(`).test(code)
502
+ invokes: new RegExp(`(?<![\\w$])${escapeRegExp(namespaced[1])}\\.\\w+\\s*\\(`).test(code)
408
503
  };
409
504
  if (/from\s*["']vitest-native["']|require\(\s*["']vitest-native["']\s*\)/.test(code)) return {
410
505
  imports: true,
@@ -588,6 +683,10 @@ function runDoctor(root, nodeVersion = process.versions.node) {
588
683
  else {
589
684
  const content = fs.readFileSync(path.join(configRoot, configFile), "utf8");
590
685
  const usage = analyzeConfigUsage(content);
686
+ let shared = {
687
+ via: null,
688
+ unconfirmed: null
689
+ };
591
690
  const code = withoutComments$1(content);
592
691
  if (/@rolldown\/plugin-babel|vite-plugin-babel/.test(code)) {
593
692
  const listed = new Set([...code.matchAll(/["'`]([^"'`\s]+)["'`]/g)].map((m) => normalizeBabelName(m[1])));
@@ -602,7 +701,9 @@ function runDoctor(root, nodeVersion = process.versions.node) {
602
701
  if (model === "resolution") lines.push(" · 'resolution' turns on experimental.nodeMocks: a vi.mock also reaches the modules Node loads, and a mock Node cannot have synchronously fails as MOCK_NOT_SEEN_BY_NODE.");
603
702
  }
604
703
  } else if (usage.imports) warn(`${configFile} imports vitest-native but never calls reactNative() — the plugin is not in \`plugins: [...]\`, so React Native imports will not resolve.`);
704
+ else if ((shared = sharedConfigUse(path.join(configRoot, configFile))).via) pass(`${configFile} uses vitest-native through ${shared.via}.`);
605
705
  else if (extendsSharedConfig(content)) lines.push(` · ${configFile} builds on a shared config, so this cannot tell from here whether the plugin is wired up. Check the config it extends.`);
706
+ else if (shared.unconfirmed) lines.push(` · couldn't confirm that ${configFile} uses vitest-native: it does not import it itself, and ${shared.unconfirmed}. Check that reactNative() is in its plugins.`);
606
707
  else warn(`${configFile} exists but does not import vitest-native` + (content.includes("vitest-native") ? " (it is only mentioned in a comment)" : "") + " — add `reactNative()` to `plugins: [...]`, or run `vitest-native init`.");
607
708
  }
608
709
  lines.push("", ok ? "✓ No blocking problems found." : "✗ Blocking problems found (see ✗ above).");
@@ -2003,7 +2104,12 @@ function analyzeJestConfig(root) {
2003
2104
  const setupFiles = ["jestCompatSetup"];
2004
2105
  const aliasEntries = [];
2005
2106
  const aliasKeys = /* @__PURE__ */ new Set();
2006
- const regexAliases = [];
2107
+ const aliasArray = [];
2108
+ let regexAlias = false;
2109
+ const addRegexAlias = (entry) => {
2110
+ aliasArray.push(entry);
2111
+ regexAlias = true;
2112
+ };
2007
2113
  const transformPkgs = [];
2008
2114
  const extraImports = [];
2009
2115
  const extraPlugins = [];
@@ -2025,6 +2131,7 @@ function analyzeJestConfig(root) {
2025
2131
  if (aliasKeys.has(key)) return false;
2026
2132
  aliasKeys.add(key);
2027
2133
  aliasEntries.push(`${JSON.stringify(key)}: ${value}`);
2134
+ aliasArray.push(`{ find: ${JSON.stringify(key)}, replacement: ${value} }`);
2028
2135
  return true;
2029
2136
  };
2030
2137
  const projectSource = (file) => {
@@ -2106,7 +2213,7 @@ function analyzeJestConfig(root) {
2106
2213
  }
2107
2214
  } else if (plainPrefix) {
2108
2215
  const find = `${regexLiteral(plainPrefix.key).slice(0, -2)}\\/(${plainPrefix.rest})$/`;
2109
- regexAliases.push(`{ find: ${find}, replacement: ${absolutePath(plainPrefix.dir)} + "/$1" }`);
2216
+ addRegexAlias(`{ find: ${find}, replacement: ${absolutePath(plainPrefix.dir)} + "/$1" }`);
2110
2217
  automatic.push(`moduleNameMapper '${pattern}' → resolve.alias { find: ${find} } (absolute path).`);
2111
2218
  } else if (/^\^?@\/|\^~\/|\^src\//.test(pattern)) {
2112
2219
  const aliasKey = pattern.replace(/[\^$]/g, "").replace(/\((\.\*|\.\+)\)\$?$/, "").replace(/\/$/, "");
@@ -2120,7 +2227,7 @@ function analyzeJestConfig(root) {
2120
2227
  if (packageOfPath(target) === splitSpecifier(literal).pkg && packageServes(root, literal)) dropped.push(`moduleNameMapper '${pattern}' → '${target}' — '${literal}' is served by its package's exports, which Vite and Node resolve (Jest's CommonJS resolver could not); dropped.`);
2121
2228
  else {
2122
2229
  const replacement = target.startsWith("<rootDir>") ? absolutePath(target.replace(/^<rootDir>\/?/, "./")) : target.startsWith(".") ? absolutePath(target) : JSON.stringify(target);
2123
- regexAliases.push(`{ find: ${regexLiteral(literal)}, replacement: ${replacement} }`);
2230
+ addRegexAlias(`{ find: ${regexLiteral(literal)}, replacement: ${replacement} }`);
2124
2231
  automatic.push(`moduleNameMapper '${pattern}' → resolve.alias { find: ${regexLiteral(literal)} } (anchored: a string find would also catch '${literal}/…').`);
2125
2232
  }
2126
2233
  } else attention.push(`moduleNameMapper '${pattern}' → '${String(target)}' — map manually to resolve.alias (regex mappers need rewriting).`);
@@ -2368,10 +2475,7 @@ function analyzeJestConfig(root) {
2368
2475
  if (transformPkgs.length) pluginOptions.unshift(`transform: [${transformPkgs.map((p) => JSON.stringify(p)).join(", ")}]`);
2369
2476
  const transformLine = pluginOptions.length ? `reactNative({ ${pluginOptions.join(", ")} })` : `reactNative()`;
2370
2477
  if (excludeGlobs.length) testEntries.push(`exclude: [...configDefaults.exclude, ${excludeGlobs.map((g) => JSON.stringify(g)).join(", ")}]`);
2371
- const aliasSource = regexAliases.length ? `[\n ...Object.entries(jestCompatAliases()).map(([find, replacement]) => ({ find, replacement })),\n` + aliasEntries.map((e) => {
2372
- const at = e.indexOf(": ");
2373
- return ` { find: ${e.slice(0, at)}, replacement: ${e.slice(at + 2)} },\n`;
2374
- }).join("") + regexAliases.map((e) => ` ${e},\n`).join("") + ` ]` : `{ ${["...jestCompatAliases()", ...aliasEntries].join(", ")} }`;
2478
+ const aliasSource = regexAlias ? `[\n ...Object.entries(jestCompatAliases()).map(([find, replacement]) => ({ find, replacement })),\n` + aliasArray.map((e) => ` ${e},\n`).join("") + ` ]` : `{ ${["...jestCompatAliases()", ...aliasEntries].join(", ")} }`;
2375
2479
  const vitePlus = usesVitePlus(root);
2376
2480
  return {
2377
2481
  source,
@@ -5164,9 +5268,9 @@ function main(argv, log = console.log) {
5164
5268
  json: parsed.json,
5165
5269
  timeoutMs: parsed.timeoutMs,
5166
5270
  showOutput: parsed.showOutput,
5167
- runs: parsed.runs ?? 2,
5168
- shuffle: parsed.shuffle ?? true,
5169
- seed: parsed.seed ?? 0
5271
+ runs: parsed.runs,
5272
+ shuffle: parsed.shuffle,
5273
+ seed: parsed.seed
5170
5274
  });
5171
5275
  return runCompare({
5172
5276
  ...parsed,
@@ -1,4 +1,4 @@
1
- import { f as presetShadowing, l as libraryMockUsable, t as AUTO_DETECT_PRESETS } from "./preset-map-DdAexIwz.mjs";
1
+ import { t as AUTO_DETECT_PRESETS } from "./preset-map-DdAexIwz.mjs";
2
2
  import { createRequire } from "node:module";
3
3
  import path from "node:path";
4
4
  import fs from "node:fs";
@@ -6,9 +6,9 @@ import { VitestNativeError, VitestNativeTypeError } from "./errors.mjs";
6
6
  import { mainFieldFile } from "./native/shared-resolver.mjs";
7
7
  import crypto, { createHash } from "node:crypto";
8
8
  import { AsyncLocalStorage } from "node:async_hooks";
9
- import { resolveTransformPreset } from "./native/babel-preset.mjs";
10
9
  import { projectBabelCaller } from "./native/babel-caller.mjs";
11
10
  import { relativeToRoot, rootSpellingOf } from "./native/root-spelling.mjs";
11
+ import { resolveTransformPreset } from "./native/babel-preset.mjs";
12
12
  import { containsPath, dependencyDirOf } from "./native/match.mjs";
13
13
  // src/peer-requirements.ts
14
14
  const PEER_REQUIREMENTS = [
@@ -525,75 +525,6 @@ async function readProjectSource(id) {
525
525
  function isProjectSourceOnDisk(id) {
526
526
  return fs.statSync(id, { throwIfNoEntry: false })?.isFile() ?? false;
527
527
  }
528
- /**
529
- * The native engine's dependencies that do NOT resolve from the project root.
530
- *
531
- * react-native itself is part of the check: the Babel toolchain alone chose
532
- * native mode in a project with the preset installed but no react-native — an
533
- * incomplete install, a babel-only workspace — which then failed later at RN
534
- * resolution with nothing pointing at the cause. Resolution, not declaration:
535
- * every check walks node_modules upward from the root — so a hoisted workspace
536
- * install or Expo's transitive react-native counts, and a project does not need
537
- * react-native in its own manifest.
538
- */
539
- function missingNativeDeps(projectRoot) {
540
- const req = createRequire(path.join(projectRoot, "package.json"));
541
- const missing = [];
542
- if (!reactNativeInstalledNear(projectRoot)) missing.push("react-native");
543
- if (resolveTransformPreset(projectRoot) === null) missing.push("@react-native/babel-preset");
544
- try {
545
- req.resolve("@babel/core");
546
- } catch {
547
- missing.push("@babel/core");
548
- }
549
- return missing;
550
- }
551
- /** Does node_modules/react-native exist in projectRoot or any ancestor? */
552
- function reactNativeInstalledNear(projectRoot) {
553
- let dir = path.resolve(projectRoot);
554
- for (;;) {
555
- if (fs.existsSync(path.join(dir, "node_modules", "react-native", "package.json"))) return true;
556
- const parent = path.dirname(dir);
557
- if (parent === dir) return false;
558
- dir = parent;
559
- }
560
- }
561
- /** Resolve the concrete engine for a run. Pure; never throws. */
562
- function detectEngine(requested, projectRoot, opts) {
563
- const missing = missingNativeDeps(projectRoot);
564
- const nativeAvailable = missing.length === 0;
565
- if (requested === "native") return {
566
- engine: "native",
567
- nativeAvailable,
568
- missing,
569
- notice: null
570
- };
571
- if (requested === "mock") return {
572
- engine: "mock",
573
- nativeAvailable,
574
- missing,
575
- notice: null
576
- };
577
- const prefersNative = opts?.autoPrefersNative ?? true;
578
- if (prefersNative && nativeAvailable) return {
579
- engine: "native",
580
- nativeAvailable,
581
- missing,
582
- notice: null
583
- };
584
- if (prefersNative) return {
585
- engine: "mock",
586
- nativeAvailable: false,
587
- missing,
588
- notice: `[vitest-native] ${missing.join(", ")} not found — using the mock engine. Install what's missing to run real React Native, or set engine:'mock' to silence this.`
589
- };
590
- return {
591
- engine: "mock",
592
- nativeAvailable,
593
- missing,
594
- notice: null
595
- };
596
- }
597
528
  // src/installed-manifest.ts
598
529
  /**
599
530
  * A package's manifest as the package manager wrote it (see cli/manifest.ts for why
@@ -613,10 +544,6 @@ function installedManifest(root, pkg) {
613
544
  }
614
545
  // src/babel-plugins.ts
615
546
  /**
616
- * Babel plugin classification shared by the engine (projectBabel) and the CLI (doctor,
617
- * migrate): what a project's Babel plugins do under vitest-native.
618
- */
619
- /**
620
547
  * @babel/core's `standardizeName` (lib/config/files/plugins.js), rule for rule except that a name
621
548
  * starting with `.` is taken as a relative path: `foo` →
622
549
  * `babel-plugin-foo`, `@babel/foo` → `@babel/plugin-foo` (`@babel/plugin-foo` unchanged),
@@ -631,20 +558,16 @@ function normalizeBabelName(name, kind = "plugin") {
631
558
  return name.replace(prefix, `babel-${kind}-`).replace(babelOrg, `$1${kind}-`).replace(otherOrg, `$1babel-${kind}-`).replace(/^(@(?!babel$)[^/]+)$/, `$1/babel-${kind}`).replace(/^module:/, "");
632
559
  }
633
560
  /**
634
- * Whether the generated config runs Reanimated as its own mock: the native engine (as
635
- * `engine: 'auto'` resolves it) with Reanimated 4.7+ and Worklets 0.9+ (libraryMockUsable).
636
- * That mock runs Reanimated's real hooks, which need the worklets Babel plugin; only the
637
- * preset's own module (the mock engine, or an older Reanimated) makes the plugin unneeded.
561
+ * Whether real Reanimated or Worklets code can run in a test, so the worklets Babel plugin
562
+ * matters: whenever either is installed. A preset standing in for the library does not
563
+ * change that: Reanimated 4.7+ runs as its own mock, whose hooks are the real ones, and with
564
+ * an older Reanimated (or the mock engine) a mock that loads the library itself
565
+ * (`jest.requireActual('react-native-reanimated')`) hands the real hooks to the components
566
+ * it renders. Those components are compiled where they live, not where the mock is, so no
567
+ * file can be told apart; the plugin is kept for every file it applies to, as under Jest.
638
568
  */
639
- function reanimatedRunsItsOwnMock(root, active) {
640
- return active.includes("reanimated") && detectEngine("auto", root).engine === "native" && libraryMockUsable(root);
641
- }
642
- /** Why a worklet plugin is not needed — only when the preset replacing its library is active. */
643
- function workletReason(pkg, active, root) {
644
- const preset = presetShadowing(pkg);
645
- if (preset && active.includes(preset)) return `transforms worklets for ${pkg}; the active ${preset} preset (auto-detected from ${Object.entries(AUTO_DETECT_PRESETS).filter(([, name]) => name === preset).map(([detect]) => detect).join(", ")}) replaces ${pkg} with a mock, so no worklet runs.`;
646
- if (!installedManifest(root, pkg)) return `transforms worklets for ${pkg}, which is not installed.`;
647
- return null;
569
+ function realWorkletsCanRun(root) {
570
+ return installedManifest(root, "react-native-reanimated") !== null || installedManifest(root, "react-native-worklets") !== null;
648
571
  }
649
572
  /** Whether `name` is one of the plugins this module knows by name. */
650
573
  const isKnownPlugin = (name) => KNOWN_PLUGINS.some((known) => known.names.includes(name));
@@ -679,21 +602,16 @@ const unknownReason = (e) => `${e.written} ran on every file under babel-jest an
679
602
  function classifyBabelPlugins(report, root, active) {
680
603
  return report.plugins.map((entry) => {
681
604
  const worklets = /^(react-native-worklets|react-native-reanimated)\/plugin$/.exec(entry.name);
682
- if (worklets && reanimatedRunsItsOwnMock(root, active)) return {
683
- ...entry,
684
- verdict: "required",
685
- reason: `${entry.written} gives Reanimated's hooks their dependencies. Under the native engine, Reanimated runs as its own mock, whose useAnimatedStyle throws without it ("used without a dependency array or Babel plugin").`
686
- };
687
605
  if (worklets) {
688
- const reason = workletReason(worklets[1], active, root);
689
- return reason ? {
606
+ if (!realWorkletsCanRun(root)) return {
690
607
  ...entry,
691
608
  verdict: "unneeded",
692
- reason
693
- } : {
609
+ reason: `${entry.written} transforms worklets for ${worklets[1]}, which is not installed.`
610
+ };
611
+ return {
694
612
  ...entry,
695
- verdict: "unknown",
696
- reason: unknownReason(entry)
613
+ verdict: "required",
614
+ reason: `${entry.written} gives Reanimated's hooks their dependencies. Real Reanimated runs in tests (as its own mock from 4.7, or through a mock that loads jest.requireActual('react-native-reanimated')), and its useAnimatedStyle throws without it ("used without a dependency array or Babel plugin").`
697
615
  };
698
616
  }
699
617
  const known = KNOWN_PLUGINS.find((k) => k.names.includes(entry.name));
@@ -948,7 +866,7 @@ function classifyProjectBabelEntry(entry, root, active) {
948
866
  if (opts.jsxImportSource !== void 0) return needed(`${name}'s \`jsxImportSource\``, JSX);
949
867
  const changes = optionKeys(options).find((key) => !allowed.has(key));
950
868
  if (changes) return needed(`${name}'s \`${changes}\` option`, null);
951
- if (name === "babel-preset-expo" && opts.worklets !== false && opts.reanimated !== false && reanimatedRunsItsOwnMock(root, active)) return needed("babel-preset-expo's worklets plugin", WORKLET);
869
+ if (name === "babel-preset-expo" && opts.worklets !== false && opts.reanimated !== false && realWorkletsCanRun(root)) return needed("babel-preset-expo's worklets plugin", WORKLET);
952
870
  return COVERED;
953
871
  }
954
872
  if (STRIPPED.has(name)) return STRIP;
@@ -1235,7 +1153,16 @@ function createProjectBabel(root, mode, options, announce = () => {}) {
1235
1153
  for (const reason of fresh) announced.add(reason);
1236
1154
  announce(fresh);
1237
1155
  };
1238
- const projectRootOf = (id) => isProjectSourceFile(id) ? rootSpellingOf(root, path.normalize(id)) : null;
1156
+ const rootSpellingById = /* @__PURE__ */ new Map();
1157
+ const projectRootOf = (id) => {
1158
+ if (!isProjectSourceFile(id)) return null;
1159
+ let spelling = rootSpellingById.get(id);
1160
+ if (spelling === void 0) {
1161
+ spelling = rootSpellingOf(root, path.normalize(id));
1162
+ rootSpellingById.set(id, spelling);
1163
+ }
1164
+ return spelling;
1165
+ };
1239
1166
  const versionOf = (item) => {
1240
1167
  const file = item.file?.resolved;
1241
1168
  if (!file) return "inline";
@@ -1362,6 +1289,75 @@ function envFilesHash(root, configured) {
1362
1289
  for (const file of [...new Set(files)].sort()) if (fs.existsSync(file)) hash.update(file).update(fs.readFileSync(file));
1363
1290
  return hash.digest("hex");
1364
1291
  }
1292
+ /**
1293
+ * The native engine's dependencies that do NOT resolve from the project root.
1294
+ *
1295
+ * react-native itself is part of the check: the Babel toolchain alone chose
1296
+ * native mode in a project with the preset installed but no react-native — an
1297
+ * incomplete install, a babel-only workspace — which then failed later at RN
1298
+ * resolution with nothing pointing at the cause. Resolution, not declaration:
1299
+ * every check walks node_modules upward from the root — so a hoisted workspace
1300
+ * install or Expo's transitive react-native counts, and a project does not need
1301
+ * react-native in its own manifest.
1302
+ */
1303
+ function missingNativeDeps(projectRoot) {
1304
+ const req = createRequire(path.join(projectRoot, "package.json"));
1305
+ const missing = [];
1306
+ if (!reactNativeInstalledNear(projectRoot)) missing.push("react-native");
1307
+ if (resolveTransformPreset(projectRoot) === null) missing.push("@react-native/babel-preset");
1308
+ try {
1309
+ req.resolve("@babel/core");
1310
+ } catch {
1311
+ missing.push("@babel/core");
1312
+ }
1313
+ return missing;
1314
+ }
1315
+ /** Does node_modules/react-native exist in projectRoot or any ancestor? */
1316
+ function reactNativeInstalledNear(projectRoot) {
1317
+ let dir = path.resolve(projectRoot);
1318
+ for (;;) {
1319
+ if (fs.existsSync(path.join(dir, "node_modules", "react-native", "package.json"))) return true;
1320
+ const parent = path.dirname(dir);
1321
+ if (parent === dir) return false;
1322
+ dir = parent;
1323
+ }
1324
+ }
1325
+ /** Resolve the concrete engine for a run. Pure; never throws. */
1326
+ function detectEngine(requested, projectRoot, opts) {
1327
+ const missing = missingNativeDeps(projectRoot);
1328
+ const nativeAvailable = missing.length === 0;
1329
+ if (requested === "native") return {
1330
+ engine: "native",
1331
+ nativeAvailable,
1332
+ missing,
1333
+ notice: null
1334
+ };
1335
+ if (requested === "mock") return {
1336
+ engine: "mock",
1337
+ nativeAvailable,
1338
+ missing,
1339
+ notice: null
1340
+ };
1341
+ const prefersNative = opts?.autoPrefersNative ?? true;
1342
+ if (prefersNative && nativeAvailable) return {
1343
+ engine: "native",
1344
+ nativeAvailable,
1345
+ missing,
1346
+ notice: null
1347
+ };
1348
+ if (prefersNative) return {
1349
+ engine: "mock",
1350
+ nativeAvailable: false,
1351
+ missing,
1352
+ notice: `[vitest-native] ${missing.join(", ")} not found — using the mock engine. Install what's missing to run real React Native, or set engine:'mock' to silence this.`
1353
+ };
1354
+ return {
1355
+ engine: "mock",
1356
+ nativeAvailable,
1357
+ missing,
1358
+ notice: null
1359
+ };
1360
+ }
1365
1361
  // src/native/plain-javascript.ts
1366
1362
  /**
1367
1363
  * Whether a file is standard JavaScript, read with the project's own Babel parser and no
@@ -2041,4 +2037,4 @@ function assertHotWorkerLoadsRunningVitest(running, workerEntry) {
2041
2037
  version: running.version
2042
2038
  }, loadedRoot, "the hot runtime's worker", " Or set `hotRuntime: false`: per-file isolation loads Vitest through Vitest's own resolver, which reaches the running copy.");
2043
2039
  }
2044
- export { PEER_REQUIREMENTS as A, SUPPORTED_NODE as C, validateOptions as D, unsupportedNodeMessage as E, unsupportedExpoSdkMessage as F, unsupportedReactNativeMessage as I, belowRecommendedMessage as M, installedExpoVersion as N, validatePeerDependency as O, isBelowSupportedReactNative as P, shouldDefaultFsModuleCache as S, satisfiesNodeRange as T, normalizeBabelName as _, runningVite as a, readProjectSource as b, detectEcosystemPackages as c, createProjectBabel as d, isProjectSourceFile as f, isKnownPlugin as g, classifyBabelPlugins as h, ownVitestPackage as i, SUPPORTED_EXPO_SDKS as j, warnUnknownOptions as k, babelParser as l, projectBabelTrigger as m, assertHotWorkerLoadsRunningVitest as n, usesVitePlus as o, missingBabelCoreNotice as p, installedViteVersion as r, aliasReachedPaths as s, assertHostResolvesRunningVitest as t, isPlainJavaScript as u, installedManifest as v, assertSupportedNode as w, fsModuleCacheKey as x, detectEngine as y };
2040
+ export { PEER_REQUIREMENTS as A, SUPPORTED_NODE as C, validateOptions as D, unsupportedNodeMessage as E, unsupportedExpoSdkMessage as F, unsupportedReactNativeMessage as I, belowRecommendedMessage as M, installedExpoVersion as N, validatePeerDependency as O, isBelowSupportedReactNative as P, shouldDefaultFsModuleCache as S, satisfiesNodeRange as T, isKnownPlugin as _, runningVite as a, readProjectSource as b, detectEcosystemPackages as c, detectEngine as d, createProjectBabel as f, classifyBabelPlugins as g, projectBabelTrigger as h, ownVitestPackage as i, SUPPORTED_EXPO_SDKS as j, warnUnknownOptions as k, babelParser as l, missingBabelCoreNotice as m, assertHotWorkerLoadsRunningVitest as n, usesVitePlus as o, isProjectSourceFile as p, installedViteVersion as r, aliasReachedPaths as s, assertHostResolvesRunningVitest as t, isPlainJavaScript as u, normalizeBabelName as v, assertSupportedNode as w, fsModuleCacheKey as x, installedManifest as y };
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { C as VitestNativeOptions, S as ReactNativeMock, t as index_d_exports, x as Preset } from "./index-BpZ0E2eJ.mjs";
2
- import { Plugin } from "vite";
3
2
  import "./context.mjs";
3
+ import { Plugin } from "vite";
4
4
  /**
5
5
  * Preset names switched off by the object form of the `presets` option.
6
6
  *
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { A as PEER_REQUIREMENTS, D as validateOptions, F as unsupportedExpoSdkMessage, I as unsupportedReactNativeMessage, M as belowRecommendedMessage, N as installedExpoVersion, O as validatePeerDependency, P as isBelowSupportedReactNative, S as shouldDefaultFsModuleCache, a as runningVite, b as readProjectSource, c as detectEcosystemPackages, d as createProjectBabel, f as isProjectSourceFile, j as SUPPORTED_EXPO_SDKS, k as warnUnknownOptions, n as assertHotWorkerLoadsRunningVitest, p as missingBabelCoreNotice, s as aliasReachedPaths, t as assertHostResolvesRunningVitest, v as installedManifest, w as assertSupportedNode, x as fsModuleCacheKey, y as detectEngine } from "./host-C02lnLzW.mjs";
2
- import { N as BUILT_IN_PRESET, t as presets_exports } from "./presets-D_-kRSYm.mjs";
3
- import { a as PRESET_MODULES, d as presetForInstalled, i as LIBRARY_SETUP_FILES, r as DEFAULT_ASSET_EXTS, s as autoDetectedPresetApplies, t as AUTO_DETECT_PRESETS, u as libraryRegistryEntries } from "./preset-map-DdAexIwz.mjs";
1
+ import { A as PEER_REQUIREMENTS, D as validateOptions, F as unsupportedExpoSdkMessage, I as unsupportedReactNativeMessage, M as belowRecommendedMessage, N as installedExpoVersion, O as validatePeerDependency, P as isBelowSupportedReactNative, S as shouldDefaultFsModuleCache, a as runningVite, b as readProjectSource, c as detectEcosystemPackages, d as detectEngine, f as createProjectBabel, j as SUPPORTED_EXPO_SDKS, k as warnUnknownOptions, m as missingBabelCoreNotice, n as assertHotWorkerLoadsRunningVitest, p as isProjectSourceFile, s as aliasReachedPaths, t as assertHostResolvesRunningVitest, w as assertSupportedNode, x as fsModuleCacheKey, y as installedManifest } from "./host-TAGjG56H.mjs";
2
+ import { A as KEYBOARD_CONTROLLER_MOCK, F as BUILT_IN_PRESET, O as SAFE_AREA_MOCK, t as presets_exports } from "./presets-DLH7uRGA.mjs";
3
+ import { a as PRESET_MODULES, c as libraryMockDir, d as presetForInstalled, i as LIBRARY_SETUP_FILES, r as DEFAULT_ASSET_EXTS, s as autoDetectedPresetApplies, t as AUTO_DETECT_PRESETS, u as libraryRegistryEntries } from "./preset-map-DdAexIwz.mjs";
4
4
  import { t as workerVitestMismatch } from "./worker-vitest-CILPFeRX.mjs";
5
5
  import { createRequire } from "node:module";
6
6
  import { extensionsFor, firstExact, platformSubpathFile } from "./native/resolve.mjs";
@@ -12,6 +12,7 @@ import flowRemoveTypes from "flow-remove-types";
12
12
  import { VitestNativeError, VitestNativeTypeError } from "./errors.mjs";
13
13
  import { docsUrl } from "./docs-url.mjs";
14
14
  import { presetFromModule } from "./preset-modules.mjs";
15
+ import { CONTEXT_ENV, ensureProjectContext, projectContext, writeProjectContext } from "./context.mjs";
15
16
  import { serializableAliases } from "./jest-compat/aliases.mjs";
16
17
  import { tsconfigPathAliases } from "./native/tsconfig-paths.mjs";
17
18
  import { aliasList, checkResolverInputs, conditionsIn, createSharedResolver, identityKey, nodeDefaultConditions, nodeOptionsList, ownershipShadowFile, resolverInputsHash, serializeResolutionAliases } from "./native/shared-resolver.mjs";
@@ -21,7 +22,6 @@ import { AsyncLocalStorage } from "node:async_hooks";
21
22
  import { transformWithOxc } from "vite";
22
23
  import { containsPath, dependencyDirOf, isPackageEntryFile, memoizePackageDirOf, packageDirOf } from "./native/match.mjs";
23
24
  import { OWNERSHIP_META_KEY, OWNERSHIP_ROUTES, viteMarkerFor } from "./native/ownership-ledger.mjs";
24
- import { CONTEXT_ENV, ensureProjectContext, projectContext, writeProjectContext } from "./context.mjs";
25
25
  import { cacheRootFor } from "./native/transform.mjs";
26
26
  import { HangWatch, debugging, hangTimeoutFor } from "./hang-watch.mjs";
27
27
  import inspector from "node:inspector";
@@ -42,6 +42,53 @@ function getPlatformExtensions(platform) {
42
42
  function getConfiguredPlatformExtensions(platform, sourceExts) {
43
43
  return extensionsFor(platform, sourceExts);
44
44
  }
45
+ // src/fresh-runtime-presets.ts
46
+ /**
47
+ * The presets whose module, as served, uses React through vitest-native's own dist (a
48
+ * module-scope `import React`). The hot runtime keeps that dist resident, so under
49
+ * `hotRuntime.freshRuntime`, where React is evaluated again for each file, these modules
50
+ * keep the first file's React, and later files fail with "Invalid hook call" or read a
51
+ * default (#719). While one is active, freshRuntime declines and React stays resident.
52
+ *
53
+ * reanimated corrects even the library's own mock with React-using helpers, and
54
+ * bottomSheet serves the names the library's mock lacks from its built-in module, so
55
+ * both count whichever module they serve.
56
+ *
57
+ * Temporary: removed when the preset factories take React from the file's own require.
58
+ */
59
+ const HOLD_REACT = /* @__PURE__ */ new Set([
60
+ "bottomSheet",
61
+ "expo",
62
+ "flashList",
63
+ "gestureHandler",
64
+ "keyboardController",
65
+ "mmkv",
66
+ "navigation",
67
+ "reanimated",
68
+ "safeAreaContext",
69
+ "screens",
70
+ "svg",
71
+ "unistyles",
72
+ "vectorIcons",
73
+ "webview"
74
+ ]);
75
+ /** Presets that serve the library's own Jest mock, which does not use the preset's React, when it is installed. */
76
+ const NOT_WITH_OWN_MOCK = {
77
+ safeAreaContext: SAFE_AREA_MOCK,
78
+ keyboardController: KEYBOARD_CONTROLLER_MOCK
79
+ };
80
+ /** The active presets, by name, whose served module holds React per worker. */
81
+ function presetsHoldingReact(presetNames, projectRoot) {
82
+ return presetNames.filter((name) => {
83
+ if (!HOLD_REACT.has(name)) return false;
84
+ const mock = NOT_WITH_OWN_MOCK[name];
85
+ return mock === void 0 || libraryMockDir(mock, projectRoot) === null;
86
+ });
87
+ }
88
+ /** The one line printed when freshRuntime declines. */
89
+ function freshRuntimeDeclinedNotice(names) {
90
+ return `[vitest-native] hotRuntime.freshRuntime declined: ${names.join(", ")} ${names.length === 1 ? "holds" : "hold"} React per worker (#719). React stays resident, as without freshRuntime.`;
91
+ }
45
92
  // src/native/apply.ts
46
93
  /**
47
94
  * Vite/Vitest config fragment for the native engine.
@@ -590,6 +637,7 @@ async function startRegistryFor(options) {
590
637
  }
591
638
  /** Recommended-floor warnings already printed in this process. */
592
639
  const warnedRecommended = /* @__PURE__ */ new Set();
640
+ const freshRuntimeNotices = /* @__PURE__ */ new Set();
593
641
  /** Vitest instances whose close already settles the background registry builds. */
594
642
  const registrySettlers = /* @__PURE__ */ new WeakSet();
595
643
  /** Load declarative Metro data without retaining Metro/Expo in Vite's process. */
@@ -1756,6 +1804,17 @@ function reactNative(options) {
1756
1804
  const selection = selectPresets(options?.presets, resolvedRoot);
1757
1805
  const nativePresetNames = selection.listed ? selection.listed.map((p) => p.name) : autoDetectPresetNames(resolvedRoot, diagnostics).filter((n) => !disabledNative.has(n) && autoDetectedPresetApplies(n, "native", options?.presets));
1758
1806
  if (nativePresetNames.length > 0) fields.presetNames = nativePresetNames;
1807
+ if (fields.hotFreshRuntime === true) {
1808
+ const holding = presetsHoldingReact(nativePresetNames, resolvedRoot);
1809
+ if (holding.length > 0) {
1810
+ delete fields.hotFreshRuntime;
1811
+ const notice = freshRuntimeDeclinedNotice(holding);
1812
+ if (!freshRuntimeNotices.has(notice)) {
1813
+ freshRuntimeNotices.add(notice);
1814
+ console.warn(notice);
1815
+ }
1816
+ }
1817
+ }
1759
1818
  if (options?.experimental?.nodeMocks === true || ownershipModel === "resolution") fields.nodeMocks = true;
1760
1819
  let ownJestSupport = [];
1761
1820
  if (!selection.listed) {
@@ -381,7 +381,15 @@ function jestMockTransform(options = {}) {
381
381
  const module = rootMockModules.get(id);
382
382
  if (!module) return null;
383
383
  const owner = projectsByRoot.get(module.root) ?? project;
384
- return rootMocksSource(module, (spec) => owner.coveredBy(spec));
384
+ const code = rootMocksSource(module, (spec) => owner.coveredBy(spec));
385
+ return {
386
+ code,
387
+ map: new magic_string.MagicString(code).generateMap({
388
+ hires: true,
389
+ includeContent: true,
390
+ source: id
391
+ })
392
+ };
385
393
  },
386
394
  transform(code, id) {
387
395
  if (id.includes("/node_modules/")) return null;