vitest-native 0.14.0-rc.8 → 0.14.0

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 (99) hide show
  1. package/README.md +91 -72
  2. package/dist/cli.d.mts +1 -3
  3. package/dist/cli.mjs +215 -76
  4. package/dist/context.d.mts +45 -0
  5. package/dist/context.mjs +243 -0
  6. package/dist/errors.d.mts +3 -0
  7. package/dist/helpers.cjs +53 -4
  8. package/dist/helpers.d.cts +1 -3
  9. package/dist/helpers.d.mts +1 -3
  10. package/dist/helpers.mjs +2 -3
  11. package/dist/host-5o48Ujzs.mjs +939 -0
  12. package/dist/{index-BSyUeoga.d.mts → index-DqU4YO3D.d.mts} +32 -53
  13. package/dist/index.d.mts +1 -3
  14. package/dist/index.mjs +464 -596
  15. package/dist/jest-compat/error-equality.mjs +127 -0
  16. package/dist/jest-compat/jest-object.mjs +149 -4
  17. package/dist/jest-compat/node-registry.mjs +233 -58
  18. package/dist/jest-compat/setup.mjs +34 -4
  19. package/dist/jest-compat.cjs +227 -52
  20. package/dist/jest-compat.d.cts +5 -6
  21. package/dist/jest-compat.d.mts +5 -6
  22. package/dist/jest-compat.mjs +204 -52
  23. package/dist/matchers.cjs +1 -2
  24. package/dist/matchers.d.cts +0 -2
  25. package/dist/matchers.d.mts +0 -2
  26. package/dist/matchers.mjs +1 -2
  27. package/dist/{memory-FYbP0_gg.mjs → memory-Couw0Esx.mjs} +31 -6
  28. package/dist/native/assets.d.mts +2 -0
  29. package/dist/native/assets.mjs +34 -0
  30. package/dist/native/babel-toolchain.mjs +190 -0
  31. package/dist/native/babel-worker.mjs +47 -0
  32. package/dist/native/boundary.mjs +23 -8
  33. package/dist/native/compile-cache.mjs +21 -9
  34. package/dist/native/coverage-v8.mjs +287 -0
  35. package/dist/native/esm-interop.mjs +216 -0
  36. package/dist/native/expo-native-modules.mjs +7 -1
  37. package/dist/native/globals.mjs +104 -6
  38. package/dist/native/hooks.mjs +271 -60
  39. package/dist/native/loader.mjs +409 -20
  40. package/dist/native/match.d.mts +24 -2
  41. package/dist/native/match.mjs +117 -12
  42. package/dist/native/metro-profile-compiler.mjs +2 -31
  43. package/dist/native/module-reset.mjs +37 -5
  44. package/dist/native/native-modules.d.mts +2 -3
  45. package/dist/native/native-modules.mjs +22 -21
  46. package/dist/native/ownership.d.mts +10 -0
  47. package/dist/native/ownership.mjs +96 -9
  48. package/dist/native/registry-compiler.mjs +6 -0
  49. package/dist/native/registry.mjs +138 -119
  50. package/dist/native/resident-health.mjs +133 -0
  51. package/dist/native/resolve.d.mts +6 -0
  52. package/dist/native/resolve.mjs +100 -9
  53. package/dist/native/rntl-hooks.mjs +157 -6
  54. package/dist/native/rntl-text-host.mjs +64 -0
  55. package/dist/native/runner.mjs +106 -1
  56. package/dist/native/setup.mjs +105 -77
  57. package/dist/native/state-manifest.mjs +14 -8
  58. package/dist/native/transform.d.mts +2 -0
  59. package/dist/native/transform.mjs +476 -59
  60. package/dist/native/worker.mjs +151 -46
  61. package/dist/{pool-DjpOjOf3.mjs → pool-CFSpNfyw.mjs} +37 -11
  62. package/dist/{preset-map-BlBriTA0.mjs → preset-map-CogjYmSw.mjs} +4 -19
  63. package/dist/preset-modules.mjs +2 -11
  64. package/dist/{presets--zrEWQC2.mjs → presets-CXDyg51l.mjs} +65 -82
  65. package/dist/presets.d.mts +1 -1
  66. package/dist/presets.mjs +1 -1
  67. package/dist/report-error.d.mts +20 -0
  68. package/dist/report-error.mjs +145 -0
  69. package/dist/rntl-support.d.mts +12 -0
  70. package/dist/rntl-support.mjs +189 -0
  71. package/dist/{rolldown-runtime-BhDjJH2R.mjs → rolldown-runtime-D70C1uOS.mjs} +1 -2
  72. package/dist/serializer.cjs +1 -2
  73. package/dist/serializer.d.cts +1 -3
  74. package/dist/serializer.d.mts +1 -3
  75. package/dist/serializer.mjs +1 -2
  76. package/dist/setup.mjs +95 -156
  77. package/dist/{worker-vitest-BGPo0ek6.mjs → worker-vitest-CILPFeRX.mjs} +2 -3
  78. package/docs/migrating-from-jest.md +76 -12
  79. package/docs/migrating-from-vitest-react-native.md +1 -1
  80. package/docs/release-readiness.md +6 -5
  81. package/docs/versioning.md +1 -1
  82. package/package.json +121 -103
  83. package/CHANGELOG.md +0 -2475
  84. package/dist/cli.cjs +0 -1924
  85. package/dist/cli.d.cts +0 -3
  86. package/dist/ecosystem-D6e1OVOg.mjs +0 -1019
  87. package/dist/ecosystem-MFwkbnaC.cjs +0 -1099
  88. package/dist/errors-B3lJK46O.cjs +0 -75
  89. package/dist/errors-CxoBUfVJ.mjs +0 -64
  90. package/dist/index-bZ7AHqLc.d.cts +0 -482
  91. package/dist/memory-6EPHrJA1.cjs +0 -144
  92. package/dist/pool-B4yesGhI.cjs +0 -121
  93. package/dist/preset-map-jSFsNy1Q.cjs +0 -241
  94. package/dist/preset-modules-BoLkaeEN.cjs +0 -53
  95. package/dist/preset-modules-CG8-G82P.mjs +0 -36
  96. package/dist/presets-9f83H0WW.cjs +0 -3939
  97. package/dist/rolldown-runtime-C0BPl7ul.cjs +0 -43
  98. package/dist/worker-vitest-BfiQB8ND.cjs +0 -62
  99. package/docs/hot-default-design.md +0 -216
package/dist/cli.mjs CHANGED
@@ -1,28 +1,15 @@
1
1
  #!/usr/bin/env node
2
- import { f as validatePeerDependency, i as createNativeOwnershipPolicy, n as detectEngine, r as resolveTransformPreset, s as formatNativeOwnershipManifest, t as detectEcosystemPackages, u as PEER_REQUIREMENTS } from "./ecosystem-D6e1OVOg.mjs";
3
- import { i as autoDetectedPresetApplies, n as DEFAULT_ASSET_EXTS, o as presetShadowing, r as PRESET_MODULES, s as testsItself, t as AUTO_DETECT_PRESETS } from "./preset-map-BlBriTA0.mjs";
4
- import { n as formatHotMemoryPlan, t as createHotMemoryPlan } from "./memory-FYbP0_gg.mjs";
2
+ import { c as detectEcosystemPackages, d as fsModuleCacheOnByDefault, g as unsupportedExpoSdkMessage, h as installedExpoVersion, i as ownVitestPackage, l as detectEngine, o as usesVitePlus, p as PEER_REQUIREMENTS, r as installedViteVersion, v as validatePeerDependency } from "./host-5o48Ujzs.mjs";
3
+ import { i as autoDetectedPresetApplies, n as DEFAULT_ASSET_EXTS, o as presetShadowing, r as PRESET_MODULES, s as testsItself, t as AUTO_DETECT_PRESETS } from "./preset-map-CogjYmSw.mjs";
4
+ import { n as formatHotMemoryPlan, t as createHotMemoryPlan } from "./memory-Couw0Esx.mjs";
5
5
  import { createRequire } from "node:module";
6
- import fs from "node:fs";
6
+ import { fileURLToPath } from "node:url";
7
7
  import path from "node:path";
8
- //#region src/native/state-manifest.mjs
9
- const HOT_STATE_MANIFEST_ENTRIES = Object.freeze([
10
- "vitest-runtime",
11
- "native-boundary-mocks",
12
- "native-module-mocks",
13
- "react-native.dimensions",
14
- "react-native.appearance",
15
- "react-native.event-listeners",
16
- "process.env",
17
- "process.listeners",
18
- "global.descriptors",
19
- "console.descriptors",
20
- "react-native.error-utils",
21
- "expo.runtime",
22
- "jest-compat.node-mocks"
23
- ]);
24
- //#endregion
25
- //#region src/cli/manifest.ts
8
+ import fs from "node:fs";
9
+ import { createNativeOwnershipPolicy, formatNativeOwnershipManifest } from "./native/ownership.mjs";
10
+ import { resolveTransformPreset } from "./native/babel-preset.mjs";
11
+ import { HOT_STATE_MANIFEST_ENTRIES } from "./native/state-manifest.mjs";
12
+ // src/cli/manifest.ts
26
13
  /**
27
14
  * Installed-package facts for the CLI, read from disk.
28
15
  *
@@ -72,8 +59,7 @@ function activePresets(root, disabled = [], engine = "native") {
72
59
  }
73
60
  return [...active];
74
61
  }
75
- //#endregion
76
- //#region src/cli/babel-config.ts
62
+ // src/cli/babel-config.ts
77
63
  /**
78
64
  * The project's Babel configuration, as `migrate` and `doctor` need to see it.
79
65
  *
@@ -297,7 +283,8 @@ function classifyBabelPlugins(report, root, active) {
297
283
  }
298
284
  /** The installed major version of `vite`, or null. */
299
285
  function viteMajor(root) {
300
- return installedMajor(root, "vite");
286
+ const major = Number(installedViteVersion(root)?.replace(/^[^0-9]*/, "").split(".")[0]);
287
+ return Number.isFinite(major) ? major : installedMajor(root, "vite");
301
288
  }
302
289
  /** Whether `name` is installed where the project resolves it. */
303
290
  function installed(root, name) {
@@ -331,8 +318,7 @@ function serializableOptions(entry) {
331
318
  };
332
319
  return entry.options === void 0 || plain(entry.options);
333
320
  }
334
- //#endregion
335
- //#region src/cli/doctor.ts
321
+ // src/cli/doctor.ts
336
322
  /**
337
323
  * `vitest-native doctor` — diagnose the project's environment: peer versions,
338
324
  * engine resolution (and why), detected presets, RNTL/Node compatibility, and
@@ -346,20 +332,57 @@ function packageVersion(root, name) {
346
332
  }
347
333
  }
348
334
  /**
349
- * The supported Node floor, as [major, minor], read from this package's own
350
- * `engines.node`. Single source: the manifest is what a package manager enforces
351
- * at install time, so a diagnostic must not carry its own copy of the number.
335
+ * The supported Node versions, as this package's own `engines.node` states them.
336
+ * Single source: the manifest is what a package manager enforces at install time, so a
337
+ * diagnostic must not carry its own copy of the range.
352
338
  */
353
- function nodeFloor() {
354
- const fallback = [20, 19];
339
+ function nodeRange() {
340
+ const fallback = ">=22.13.0 <23 || >=24.3.0";
341
+ for (let dir = path.dirname(fileURLToPath(import.meta.url));; dir = path.dirname(dir)) {
342
+ const manifest = readManifest(path.join(dir, "package.json"));
343
+ if (manifest?.name === "vitest-native") return manifest.engines?.node?.trim() || fallback;
344
+ if (path.dirname(dir) === dir) return fallback;
345
+ }
346
+ }
347
+ /** A package.json, or null where there is none or it does not parse. */
348
+ function readManifest(file) {
355
349
  try {
356
- const manifest = JSON.parse(fs.readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
357
- const match = /(\d+)\.(\d+)/.exec(manifest.engines?.node ?? "");
358
- return match ? [Number(match[1]), Number(match[2])] : fallback;
350
+ return JSON.parse(fs.readFileSync(file, "utf8"));
359
351
  } catch {
360
- return fallback;
352
+ return null;
361
353
  }
362
354
  }
355
+ const versionParts = (version) => {
356
+ const [major = 0, minor = 0, patch = 0] = version.replace(/^v/, "").split(/[.-]/).map((part) => Number.parseInt(part, 10) || 0);
357
+ return [
358
+ major,
359
+ minor,
360
+ patch
361
+ ];
362
+ };
363
+ const compareVersions = (a, b) => {
364
+ const [x, y] = [versionParts(a), versionParts(b)];
365
+ return x[0] - y[0] || x[1] - y[1] || x[2] - y[2];
366
+ };
367
+ /**
368
+ * Whether `version` is in `range`: `||`-separated sets of space-separated comparators
369
+ * (`>=`, `>`, `<=`, `<`, `=`), the forms `engines.node` uses. A version missing parts
370
+ * reads them as 0 (`<23` is `<23.0.0`).
371
+ */
372
+ function satisfiesNodeRange(version, range) {
373
+ return range.split("||").some((set) => set.trim().split(/\s+/).filter(Boolean).every((comparator) => {
374
+ const match = /^(>=|<=|>|<|=)?\s*v?(\d[\w.-]*)$/.exec(comparator);
375
+ if (!match) return false;
376
+ const order = compareVersions(version, match[2]);
377
+ switch (match[1] ?? "=") {
378
+ case ">=": return order >= 0;
379
+ case ">": return order > 0;
380
+ case "<=": return order <= 0;
381
+ case "<": return order < 0;
382
+ default: return order === 0;
383
+ }
384
+ }));
385
+ }
363
386
  /**
364
387
  * In Vitest's own precedence order: a `vitest.config.*` wins, and `vite.config.*`
365
388
  * is used when there is none.
@@ -392,6 +415,67 @@ function findConfigFile(root) {
392
415
  function withoutComments(source) {
393
416
  return source.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/(^|[^:])\/\/[^\n]*/g, "$1");
394
417
  }
418
+ const settingOf = (value) => value === void 0 ? null : value === "false" ? "off" : "set";
419
+ /**
420
+ * How a config sets Vitest's `fsModuleCache`, read as text, in each spelling: inside
421
+ * `experimental: { ... }` (Vitest 4.0.11 and later) and anywhere else (the top-level
422
+ * option, Vitest 5). `off` for a literal `false`, `set` for any other value, null when
423
+ * that spelling is absent.
424
+ */
425
+ function fsModuleCacheSetting(source) {
426
+ const code = withoutComments(source);
427
+ const nested = /\bexperimental\s*:\s*\{[^{}]*?\bfsModuleCache\s*:\s*([^,}\s]*)/.exec(code);
428
+ const rest = nested ? code.replace(nested[0], " ") : code;
429
+ const top = /\bfsModuleCache\s*:\s*([^,}\s]*)/.exec(rest);
430
+ return {
431
+ experimental: settingOf(nested?.[1]),
432
+ topLevel: settingOf(top?.[1])
433
+ };
434
+ }
435
+ /** Whether `version` is at or above `[major, minor, patch]`. */
436
+ function versionAtLeast(version, floor) {
437
+ const parts = version.replace(/^[^0-9]*/, "").split(/[.-]/).slice(0, 3).map(Number);
438
+ for (let i = 0; i < 3; i++) {
439
+ const part = parts[i] ?? 0;
440
+ if (part !== floor[i]) return part > floor[i];
441
+ }
442
+ return true;
443
+ }
444
+ /** The first Vitest with `experimental.fsModuleCache`. */
445
+ const EXPERIMENTAL_FS_MODULE_CACHE_FROM = [
446
+ 4,
447
+ 0,
448
+ 11
449
+ ];
450
+ const TROUBLESHOOTING_STALE_IMPORT = "https://danfry1.github.io/vitest-native/guide/troubleshooting#cannot-find-module-keeps-failing-after-the-missing-file-exists";
451
+ /**
452
+ * The transform-cache note for a Vitest the plugin does not turn the cache on for.
453
+ * Empty where it does (fsModuleCacheOnByDefault, which the plugin reads too), and where
454
+ * the config turns the cache off on purpose.
455
+ */
456
+ function transformCacheAdvice(vitestVersion, configSource) {
457
+ const major = Number(vitestVersion?.replace(/^[^0-9]*/, "").split(".")[0]);
458
+ if (!vitestVersion || !(major >= 4) || fsModuleCacheOnByDefault(major)) return [];
459
+ const setting = configSource === null ? {
460
+ experimental: null,
461
+ topLevel: null
462
+ } : fsModuleCacheSetting(configSource);
463
+ if (setting.experimental === "off") return [];
464
+ const hasOption = versionAtLeast(vitestVersion, EXPERIMENTAL_FS_MODULE_CACHE_FROM);
465
+ const caveat = `A Vitest bug can keep a "Cannot find module" failure cached after the file exists (reproduced on Vitest 5.0.5, unverified on 4); ${TROUBLESHOOTING_STALE_IMPORT} lists when it happens and how to recover.`;
466
+ if (setting.experimental === "set" && hasOption) return [`Vitest ${vitestVersion}: the config sets \`experimental.fsModuleCache\`; while it is on, transformed modules are kept on disk between runs. ${caveat}`];
467
+ const lines = [`Vitest ${vitestVersion} re-transforms every imported module on each run, about half a second per thousand imported modules on one benchmark. Vitest 5 keeps transformed modules on disk between runs, and vitest-native turns that on.`];
468
+ if (setting.topLevel !== null) lines.push("The config sets `test.fsModuleCache`, the Vitest 5 spelling, which has no effect on Vitest 4.");
469
+ lines.push(hasOption ? `To keep them on disk on Vitest 4, set \`test.experimental.fsModuleCache: true\`. ${caveat}` : `Vitest 4.0.11 adds \`test.experimental.fsModuleCache\` to keep them on disk.`);
470
+ return lines;
471
+ }
472
+ /**
473
+ * The Vitest that runs here, as the peer check reports it: the project's own, or under
474
+ * Vite+ the copy this package loads.
475
+ */
476
+ function runningVitestVersion(from) {
477
+ return packageVersion(from, "vitest") ?? (usesVitePlus(from) ? ownVitestPackage()?.version ?? null : null);
478
+ }
395
479
  /**
396
480
  * Whether a config is built on one imported from elsewhere — a shared preset in a
397
481
  * workspace, typically. Such a file legitimately never mentions vitest-native, and
@@ -503,19 +587,18 @@ function runDoctor(root, nodeVersion = process.versions.node) {
503
587
  const rootFor = (name) => resolvesHere(name) || configRoot === root ? root : configRoot;
504
588
  lines.push(`vitest-native doctor — ${root}`);
505
589
  lines.push("", "Runtime");
506
- const nodeMajorMinor = nodeVersion.split(".").slice(0, 2).map(Number);
507
- const [floorMajor, floorMinor] = nodeFloor();
508
- const floorText = `${floorMajor}.${floorMinor}`;
509
- if (nodeMajorMinor[0] > floorMajor || nodeMajorMinor[0] === floorMajor && nodeMajorMinor[1] >= floorMinor) pass(`Node ${nodeVersion} (floor: ${floorText})`);
510
- else fail(`Node ${nodeVersion} — vitest-native requires Node >= ${floorText}.`);
590
+ const range = nodeRange();
591
+ if (satisfiesNodeRange(nodeVersion, range)) pass(`Node ${nodeVersion} (supported: ${range})`);
592
+ else fail(`Node ${nodeVersion} — vitest-native supports Node ${range}.`);
511
593
  lines.push("", "Peer dependencies");
512
594
  for (const { name, minimum, maximumMajor, minimumByMajor, optional } of PEER_REQUIREMENTS) {
513
595
  if (optional) continue;
514
596
  const from = rootFor(name);
515
- const error = validatePeerDependency(name, minimum, from, maximumMajor, minimumByMajor);
597
+ const running = name === "vite" ? installedViteVersion(from) : name === "vitest" ? runningVitestVersion(from) : null;
598
+ const error = validatePeerDependency(name, minimum, from, maximumMajor, minimumByMajor, running);
516
599
  if (error) fail(error);
517
600
  else {
518
- pass(`${name} ${packageVersion(from, name)}`);
601
+ pass(`${name} ${running ?? packageVersion(from, name)}`);
519
602
  if (from !== root) lines.push(` (resolved from ${from}, not from here)`);
520
603
  }
521
604
  }
@@ -555,7 +638,7 @@ function runDoctor(root, nodeVersion = process.versions.node) {
555
638
  const rntlReq = PEER_REQUIREMENTS.find((r) => r.name === "@testing-library/react-native");
556
639
  const rntlError = rntlReq && validatePeerDependency(rntlReq.name, rntlReq.minimum, root, rntlReq.maximumMajor, rntlReq.minimumByMajor);
557
640
  if (rntlError) warn(rntlError);
558
- else if (rntlMajor >= 14 && (nodeMajorMinor[0] < 22 || nodeMajorMinor[0] === 22 && nodeMajorMinor[1] < 13)) fail(`@testing-library/react-native ${rntl} requires Node >= 22.13, but this is Node ${nodeVersion}. Upgrade Node or pin @testing-library/react-native@13.`);
641
+ else if (rntlMajor >= 14 && !satisfiesNodeRange(nodeVersion, ">=22.13.0")) fail(`@testing-library/react-native ${rntl} requires Node >= 22.13, but this is Node ${nodeVersion}. Upgrade Node or pin @testing-library/react-native@13.`);
559
642
  else if (rntlMajor >= 14 && !packageVersion(rootFor("test-renderer"), "test-renderer")) fail(`@testing-library/react-native ${rntl} requires the 'test-renderer' package, which is not installed. Every render() will fail with "Cannot find module 'test-renderer'". Install it:\n\n npm install -D test-renderer\n`);
560
643
  else pass(`@testing-library/react-native ${rntl}${rntlMajor >= 14 ? " (14 is async: await render/fireEvent)" : ""}`);
561
644
  }
@@ -571,8 +654,12 @@ function runDoctor(root, nodeVersion = process.versions.node) {
571
654
  }
572
655
  if (detected.length) for (const d of detected) pass(d);
573
656
  else if (!installedAny) lines.push(" (none — no preset-covered packages installed)");
574
- const expo = packageVersion(rootFor("expo"), "expo");
575
- if (expo) {
657
+ const expo = installedExpoVersion(root) ?? (configRoot === root ? null : installedExpoVersion(configRoot));
658
+ const unsupported = expo && unsupportedExpoSdkMessage(expo);
659
+ if (unsupported) {
660
+ lines.push("", "Expo");
661
+ warn(unsupported);
662
+ } else if (expo) {
576
663
  lines.push("", "Expo");
577
664
  pass((decision.engine === "native" ? `expo ${expo} detected. Under the native engine Expo modules run their real JavaScript on native-module mocks, as under jest-expo (unless the config sets \`engine: 'mock'\` or \`presets: { expo: true }\`, where the expo preset shadows ${PRESET_MODULES.expo.join(", ")}). ` : `expo ${expo} detected. Under the mock engine the expo preset shadows ${PRESET_MODULES.expo.join(", ")}; other Expo modules load their real JavaScript. `) + `Coming from jest-expo, run \`vitest-native migrate\`. See https://danfry1.github.io/vitest-native/guide/expo`);
578
665
  }
@@ -590,28 +677,44 @@ function runDoctor(root, nodeVersion = process.versions.node) {
590
677
  }
591
678
  lines.push("", "Config");
592
679
  const configFile = findConfigFile(configRoot);
680
+ let configSource = null;
593
681
  if (!configFile) warn("no vitest.config.* found — run `vitest-native init` to create one.");
594
682
  else {
595
683
  const content = fs.readFileSync(path.join(configRoot, configFile), "utf8");
684
+ configSource = content;
596
685
  const usage = analyzeConfigUsage(content);
597
686
  if (usage.imports && usage.invokes) pass(`${configFile} uses vitest-native.`);
598
687
  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.`);
599
688
  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.`);
600
689
  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`.");
601
690
  }
691
+ const advice = transformCacheAdvice(runningVitestVersion(rootFor("vitest")), configSource);
692
+ if (advice.length) {
693
+ lines.push("", "Transform cache");
694
+ for (const line of advice) lines.push(` · ${line}`);
695
+ }
602
696
  lines.push("", ok ? "✓ No blocking problems found." : "✗ Blocking problems found (see ✗ above).");
603
697
  return {
604
698
  lines,
605
699
  ok
606
700
  };
607
701
  }
608
- //#endregion
609
- //#region src/cli/init.ts
702
+ // src/cli/init.ts
610
703
  /**
611
704
  * `vitest-native init` — write a ready-to-run Vitest config. Two shapes:
612
705
  * the zero-config default, and the jest-compat variant (the exact block the
613
706
  * migration guide documents, so docs and CLI can never drift apart by shape).
614
707
  */
708
+ /**
709
+ * Printed after `init` and `migrate`: the hot runtime is off by default, so a user
710
+ * reading only the CLI output would not otherwise learn it exists or what it costs.
711
+ */
712
+ const HOT_RUNTIME_NOTE = [
713
+ "Hot runtime: off by default. `hotRuntime: 'auto'` reuses workers across test files instead of",
714
+ "starting a fresh one per file. Whether that is faster depends on the suite, so measure it on yours.",
715
+ "It has known differences from per-file isolation:",
716
+ " https://danfry1.github.io/vitest-native/guide/troubleshooting#a-test-passes-on-its-own-but-fails-when-run-with-other-files"
717
+ ];
615
718
  const PLAIN_CONFIG = `import { defineConfig } from 'vitest/config'
616
719
  import { reactNative } from 'vitest-native'
617
720
 
@@ -645,11 +748,23 @@ export default defineConfig({
645
748
  },
646
749
  })
647
750
  `;
648
- function renderInitConfig(jestCompat) {
649
- return jestCompat ? JEST_COMPAT_CONFIG : PLAIN_CONFIG;
751
+ /**
752
+ * The config source. Under Vite+ the config is `vite.config.ts` with `defineConfig`
753
+ * from 'vite-plus' (viteplus.dev/guide/test): the project does not install `vitest`
754
+ * itself, so a config importing 'vitest/config' fails to load under pnpm.
755
+ */
756
+ function renderInitConfig(jestCompat, vitePlus = false) {
757
+ const source = jestCompat ? JEST_COMPAT_CONFIG : PLAIN_CONFIG;
758
+ return vitePlus ? source.replace("import { defineConfig } from 'vitest/config'", "import { defineConfig } from 'vite-plus'") : source;
650
759
  }
651
- function existingConfig(root) {
760
+ function existingConfig(root, vitePlus) {
652
761
  for (const name of [
762
+ ...vitePlus ? [
763
+ "vite.config.ts",
764
+ "vite.config.mts",
765
+ "vite.config.js",
766
+ "vite.config.mjs"
767
+ ] : [],
653
768
  "vitest.config.ts",
654
769
  "vitest.config.mts",
655
770
  "vitest.config.js",
@@ -661,18 +776,36 @@ function existingConfig(root) {
661
776
  }
662
777
  function runInit(root, opts = {}) {
663
778
  const lines = [];
664
- const existing = existingConfig(root);
779
+ const vitePlus = usesVitePlus(root);
780
+ const existing = existingConfig(root, vitePlus);
781
+ if (existing && vitePlus && existing.startsWith("vite.config")) return {
782
+ lines: [
783
+ `✗ ${existing} already exists. Vite+ keeps tests in the same config, so add`,
784
+ ` vitest-native to it rather than replacing it:`,
785
+ ``,
786
+ ` import { reactNative } from 'vitest-native'`,
787
+ ``,
788
+ ` export default defineConfig({`,
789
+ ` plugins: [reactNative()],`,
790
+ ` test: { environment: 'node' },`,
791
+ ` })`,
792
+ ``,
793
+ ` Then run: vp test`
794
+ ],
795
+ ok: false
796
+ };
665
797
  if (existing && !opts.force) return {
666
798
  lines: [`✗ ${existing} already exists — not overwriting. Re-run with --force to replace it,`, ` or run \`vitest-native migrate\` to analyze an existing Jest setup first.`],
667
799
  ok: false
668
800
  };
669
- const file = fs.existsSync(path.join(root, "tsconfig.json")) ? "vitest.config.mts" : "vitest.config.mjs";
801
+ const file = vitePlus ? "vite.config.ts" : fs.existsSync(path.join(root, "tsconfig.json")) ? "vitest.config.mts" : "vitest.config.mjs";
670
802
  const target = path.join(root, file);
671
- fs.writeFileSync(target, renderInitConfig(opts.jestCompat ?? false));
803
+ fs.writeFileSync(target, renderInitConfig(opts.jestCompat ?? false, vitePlus));
672
804
  lines.push(`✓ wrote ${file}${opts.jestCompat ? " (jest-compat variant)" : ""}`);
673
805
  if (existing && opts.force) lines.push(` (replaced ${existing === file ? "it" : existing})`);
674
- lines.push("", "Next steps:", ` 1. add a script: "test": "vitest"`, ` 2. run: npx vitest`, ` 3. check the environment: npx vitest-native doctor`);
806
+ lines.push("", "Next steps:", vitePlus ? ` 1. add a script: "test": "vp test"` : ` 1. add a script: "test": "vitest"`, vitePlus ? ` 2. run: vp test` : ` 2. run: npx vitest`, ` 3. check the environment: npx vitest-native doctor`);
675
807
  if (opts.jestCompat) lines.push(` 4. migrating a Jest suite? \`vitest-native migrate\` maps your jest.config onto this file.`);
808
+ lines.push("", ...HOT_RUNTIME_NOTE);
676
809
  return {
677
810
  lines,
678
811
  ok: true,
@@ -749,8 +882,7 @@ function tryExpand(source, literalDot) {
749
882
  throw error;
750
883
  }
751
884
  }
752
- //#endregion
753
- //#region src/cli/allowlist.ts
885
+ // src/cli/allowlist.ts
754
886
  /**
755
887
  * Reading Jest's `transformIgnorePatterns` allowlist,
756
888
  * `node_modules/(?!(a|b|@scope/c)/)`. Real ones nest — React Native's own preset
@@ -847,8 +979,7 @@ function allows(entry, pkg) {
847
979
  if (entry.kind === "scope") return pkg.startsWith(`${entry.name}/`);
848
980
  return pkg.startsWith(entry.name);
849
981
  }
850
- //#endregion
851
- //#region src/cli/jest-discovery.ts
982
+ // src/cli/jest-discovery.ts
852
983
  /**
853
984
  * Which files Jest treats as tests, said to Vitest.
854
985
  *
@@ -1211,8 +1342,7 @@ function booleanFlag(value) {
1211
1342
  if (value === true || value === "true") return true;
1212
1343
  if (value === "false") return false;
1213
1344
  }
1214
- //#endregion
1215
- //#region src/cli/untranspiled.ts
1345
+ // src/cli/untranspiled.ts
1216
1346
  /**
1217
1347
  * Evidence that a package needs `transform`: a `.js` file under one of its entry
1218
1348
  * points that is not standard JavaScript (JSX or Flow), which neither Node nor Vite
@@ -1320,8 +1450,7 @@ function untranspiledFile(root, pkg) {
1320
1450
  }
1321
1451
  return null;
1322
1452
  }
1323
- //#endregion
1324
- //#region src/cli/migrate.ts
1453
+ // src/cli/migrate.ts
1325
1454
  /**
1326
1455
  * `vitest-native migrate` — analyze a project's Jest configuration and report,
1327
1456
  * key by key, what maps automatically, what the presets already cover (delete
@@ -1631,7 +1760,7 @@ function analyzeJestConfig(root) {
1631
1760
  "c"
1632
1761
  ].includes(name)) continue;
1633
1762
  if (name === "forceExit") dropped.push("scripts.test --forceExit — `vitest run` exits by itself: if something keeps the process alive after the run it waits test.teardownTimeout, warns, and exits.");
1634
- else if (name === "ci") dropped.push(`scripts.test --ci — Vitest already refuses to write new snapshots when it detects CI.`);
1763
+ else if (name === "ci") dropped.push("scripts.test --ci — Vitest writes no new snapshots when it detects CI, as Jest's --ci defaults to; set CI=true to get that elsewhere.");
1635
1764
  else if ((name === "silent" || name === "passWithNoTests") && booleanFlag(value) !== void 0) {
1636
1765
  const on = booleanFlag(value);
1637
1766
  testEntries.push(`${name}: ${on}`);
@@ -1647,7 +1776,7 @@ function analyzeJestConfig(root) {
1647
1776
  const env = take("testEnvironment");
1648
1777
  if (env && env !== "node") attention.push(`testEnvironment: '${env}' — vitest-native suites run under 'node'; review.`);
1649
1778
  else handled.add("testEnvironment");
1650
- if (take("fakeTimers") !== void 0) attention.push(`fakeTimers — configure per-suite with vi.useFakeTimers() (the jest-compat shim covers jest.useFakeTimers()).`);
1779
+ if (take("fakeTimers") !== void 0) attention.push(`fakeTimers — not carried over: call jest.useFakeTimers(options) in a beforeEach, which the jest-compat shim translates, or set Vitest's test.fakeTimers. Not at a setup file's top level: RNTL's import drops options set there.`);
1651
1780
  const discoveryOptions = {};
1652
1781
  for (const key of [
1653
1782
  "testMatch",
@@ -1752,14 +1881,14 @@ function analyzeJestConfig(root) {
1752
1881
  const at = e.indexOf(": ");
1753
1882
  return ` { find: ${e.slice(0, at)}, replacement: ${e.slice(at + 2)} },\n`;
1754
1883
  }).join("") + regexAliases.map((e) => ` ${e},\n`).join("") + ` ]` : `{ ${["...jestCompatAliases()", ...aliasEntries].join(", ")} }`;
1884
+ const vitePlus = usesVitePlus(root);
1755
1885
  return {
1756
1886
  source,
1757
1887
  automatic,
1758
1888
  attention,
1759
1889
  presetCovered,
1760
1890
  dropped,
1761
- suggestedConfig: `import { ${excludeGlobs.length ? "configDefaults, " : ""}defineConfig } from 'vitest/config'
1762
- import { reactNative } from 'vitest-native'
1891
+ suggestedConfig: `${vitePlus ? `import { defineConfig } from 'vite-plus'\n${excludeGlobs.length ? "import { configDefaults } from 'vite-plus/test/config'\n" : ""}` : `import { ${excludeGlobs.length ? "configDefaults, " : ""}defineConfig } from 'vitest/config'\n`}import { reactNative } from 'vitest-native'
1763
1892
  import { jestCompatAliases, jestCompatSetup, jestMockTransform } from 'vitest-native/jest-compat'
1764
1893
  ${needsUrlImport ? "import { fileURLToPath } from 'node:url'\n" : ""}${extraImports.map((i) => `${i}\n`).join("")}
1765
1894
  export default defineConfig({
@@ -1778,6 +1907,7 @@ export default defineConfig({
1778
1907
  },
1779
1908
  })
1780
1909
  `,
1910
+ vitePlus,
1781
1911
  ok: source !== null
1782
1912
  };
1783
1913
  }
@@ -1819,7 +1949,16 @@ function classifyAllowlist(root, entries, active, autoInlined, out) {
1819
1949
  if (groups.detected.length) out.automatic.push(`transformIgnorePatterns allows ${list(groups.detected)} — detected by the engine (React Native ecosystem), which compiles what Node cannot run; nothing to do.`);
1820
1950
  if (groups.absent.length) out.automatic.push(`transformIgnorePatterns allows ${list(groups.absent)} — not installed; nothing to do.`);
1821
1951
  }
1822
- function renderMigrationReport(report) {
1952
+ /** The commands to run once the suggested config is saved. */
1953
+ function migrationNextStep(report) {
1954
+ return report.vitePlus ? "npx vitest-native doctor && vp test" : "npx vitest-native doctor && npx vitest";
1955
+ }
1956
+ /**
1957
+ * The report `migrate` prints. With `write: true` (`migrate --write`) the config is about to
1958
+ * be saved, so the closing line does not ask for a re-run with --write; the CLI prints the
1959
+ * next step after the file is written.
1960
+ */
1961
+ function renderMigrationReport(report, { write = false } = {}) {
1823
1962
  const lines = [];
1824
1963
  if (!report.source) {
1825
1964
  lines.push("✗ no Jest configuration found (package.json#jest or jest.config.{js,cjs,json}).", " Starting fresh? Run `vitest-native init` instead.");
@@ -1836,13 +1975,13 @@ function renderMigrationReport(report) {
1836
1975
  section("Covered by presets — delete", report.presetCovered);
1837
1976
  section("Needs your attention", report.attention);
1838
1977
  section("Dropped (no equivalent needed)", report.dropped);
1839
- lines.push("Suggested vitest.config:", "");
1978
+ lines.push(report.vitePlus ? "Suggested vite.config:" : "Suggested vitest.config:", "");
1840
1979
  lines.push(...report.suggestedConfig.split("\n").map((l) => ` ${l}`));
1841
- lines.push("Re-run with --write to save this config, then: npx vitest-native doctor && npx vitest");
1980
+ if (!write) lines.push(`Re-run with --write to save this config, then: ${migrationNextStep(report)}`, "");
1981
+ lines.push(...HOT_RUNTIME_NOTE);
1842
1982
  return lines;
1843
1983
  }
1844
- //#endregion
1845
- //#region src/cli/index.ts
1984
+ // src/cli/index.ts
1846
1985
  /**
1847
1986
  * vitest-native CLI: `init` (write a ready config), `doctor` (diagnose the
1848
1987
  * environment), `migrate` (analyze a Jest config and report the mapping).
@@ -1895,8 +2034,9 @@ function main(argv, log = console.log) {
1895
2034
  }
1896
2035
  case "migrate": {
1897
2036
  const report = analyzeJestConfig(root);
1898
- for (const line of renderMigrationReport(report)) log(line);
1899
- if (report.ok && has("--write")) {
2037
+ const write = has("--write");
2038
+ for (const line of renderMigrationReport(report, { write })) log(line);
2039
+ if (report.ok && write) {
1900
2040
  const init = runInit(root, { force: has("--force") });
1901
2041
  if (!init.ok) {
1902
2042
  for (const line of init.lines) log(line);
@@ -1904,7 +2044,7 @@ function main(argv, log = console.log) {
1904
2044
  }
1905
2045
  const target = path.join(root, init.wrote);
1906
2046
  fs.writeFileSync(target, report.suggestedConfig);
1907
- log(`✓ wrote ${init.wrote} from the analysis above.`);
2047
+ log(`✓ wrote ${init.wrote} from the analysis above. Next: ${migrationNextStep(report)}`);
1908
2048
  }
1909
2049
  return report.ok ? 0 : 1;
1910
2050
  }
@@ -1916,5 +2056,4 @@ function main(argv, log = console.log) {
1916
2056
  }
1917
2057
  const entry = process.argv[1] ? path.basename(process.argv[1]) : "";
1918
2058
  if (entry === "cli.mjs" || entry === "cli.cjs" || entry === "vitest-native") process.exit(main(process.argv.slice(2)));
1919
- //#endregion
1920
2059
  export { main };
@@ -0,0 +1,45 @@
1
+ export declare const CONTEXT_ENV: "VITEST_NATIVE_CONTEXT";
2
+ export declare const CONTEXT_VERSION: number;
3
+ /** Hand-set diagnostic switches that stay environment variables. */
4
+ export declare const ESCAPE_HATCHES: readonly string[];
5
+
6
+ export interface ProjectContextFields {
7
+ platform: "ios" | "android";
8
+ diagnostics: boolean;
9
+ projectRoot: string;
10
+ reactNativeVersion?: string;
11
+ transform?: string[];
12
+ sourceExts?: string[];
13
+ assetExts?: string[];
14
+ hotPreserveGlobals?: string[];
15
+ hotEsmGeneration?: boolean;
16
+ /** Coverage is on: Node-compiled project source carries an inline source map. */
17
+ sourceMaps?: boolean;
18
+ hotReleaseGenerations?: boolean;
19
+ registry?: string;
20
+ ownership?: Record<string, unknown>;
21
+ projectDirs?: string[];
22
+ requireAliases?: [string, string][];
23
+ requireAliasesSkipped?: string[];
24
+ presetNames?: string[];
25
+ presetConfig?: Record<string, Record<string, unknown>>;
26
+ presetExports?: Record<string, string[] | null>;
27
+ presetModules?: string[];
28
+ presetDisabled?: string[];
29
+ mocks?: unknown;
30
+ knownNativeModules?: string[];
31
+ nativeModuleSpecs?: Record<string, string[]>;
32
+ nativeModules?: "permissive";
33
+ /** The supported Expo SDKs, `[minimum, maximum]` (checkLoadedExpoSdk). */
34
+ expoSdks?: [number, number];
35
+ }
36
+
37
+ export declare function writeProjectContext(
38
+ fields: ProjectContextFields,
39
+ cacheRoot: string,
40
+ ): string;
41
+ export declare function ensureProjectContext(ref: string, fields: ProjectContextFields): string;
42
+ export declare function projectContext(ref?: string): Readonly<ProjectContextFields> | null;
43
+ export declare function requireProjectContext(ref?: string): Readonly<ProjectContextFields>;
44
+ export declare function markBootContext(ref?: string): void;
45
+ export declare function assertBootContext(ref?: string): void;