vitest-native 0.13.0 → 0.14.0-rc.2

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 (77) hide show
  1. package/CHANGELOG.md +339 -0
  2. package/README.md +138 -48
  3. package/dist/cli.cjs +70 -5
  4. package/dist/cli.d.cts +2 -3
  5. package/dist/cli.d.mts +2 -3
  6. package/dist/cli.mjs +70 -5
  7. package/dist/{ecosystem-Duw40-mO.mjs → ecosystem-DFbU_MPe.mjs} +389 -18
  8. package/dist/{ecosystem-CEIF_-jq.cjs → ecosystem-DI1AhK_k.cjs} +408 -25
  9. package/dist/errors.d.mts +12 -0
  10. package/dist/helpers.cjs +6 -3
  11. package/dist/helpers.d.cts +8 -9
  12. package/dist/helpers.d.mts +8 -9
  13. package/dist/helpers.mjs +6 -3
  14. package/dist/{index-CPGq6p95.d.cts → index-BxzW2D7K.d.cts} +33 -9
  15. package/dist/{index-CmETArCM.d.mts → index-CEbwa4QU.d.mts} +33 -9
  16. package/dist/index.d.mts +4 -4
  17. package/dist/index.mjs +537 -118
  18. package/dist/jest-compat/aliases.d.mts +5 -0
  19. package/dist/jest-compat/aliases.mjs +65 -0
  20. package/dist/jest-compat/caller.mjs +53 -0
  21. package/dist/jest-compat/setup.mjs +72 -36
  22. package/dist/jest-compat.cjs +1 -3
  23. package/dist/jest-compat.d.cts +4 -5
  24. package/dist/jest-compat.d.mts +4 -5
  25. package/dist/jest-compat.mjs +1 -1
  26. package/dist/matchers.d.cts +9 -9
  27. package/dist/matchers.d.mts +9 -9
  28. package/dist/memory-6EPHrJA1.cjs +144 -0
  29. package/dist/memory-FYbP0_gg.mjs +126 -0
  30. package/dist/native/boundary.mjs +13 -2
  31. package/dist/native/bounded-process.mjs +165 -0
  32. package/dist/native/export-condition-recovery-preload.mjs +5 -0
  33. package/dist/native/export-condition-recovery.mjs +195 -0
  34. package/dist/native/globals.mjs +133 -5
  35. package/dist/native/hooks.mjs +131 -71
  36. package/dist/native/loader.mjs +41 -28
  37. package/dist/native/match.d.mts +3 -0
  38. package/dist/native/match.mjs +38 -2
  39. package/dist/native/metro-profile-compiler.mjs +234 -0
  40. package/dist/native/metro-profile.mjs +115 -0
  41. package/dist/native/module-reset.mjs +111 -6
  42. package/dist/native/ownership.d.mts +105 -0
  43. package/dist/native/ownership.mjs +474 -0
  44. package/dist/native/registry-compiler.mjs +43 -0
  45. package/dist/native/registry-process.mjs +124 -0
  46. package/dist/native/registry.mjs +139 -32
  47. package/dist/native/reset.mjs +305 -135
  48. package/dist/native/resolve.d.mts +20 -3
  49. package/dist/native/resolve.mjs +32 -12
  50. package/dist/native/rntl-hooks.mjs +76 -0
  51. package/dist/native/setup.mjs +81 -32
  52. package/dist/native/state-manifest.d.mts +22 -0
  53. package/dist/native/state-manifest.mjs +136 -0
  54. package/dist/native/transform.mjs +29 -8
  55. package/dist/native/worker.mjs +52 -4
  56. package/dist/pool-B4yesGhI.cjs +121 -0
  57. package/dist/pool-DjpOjOf3.mjs +119 -0
  58. package/dist/{presets-CoNf4ByH.cjs → presets-BYHmi7-W.cjs} +117 -18
  59. package/dist/{presets-DGProTaA.mjs → presets-DC-eM5IA.mjs} +117 -18
  60. package/dist/presets.d.mts +1 -1
  61. package/dist/presets.mjs +1 -1
  62. package/dist/rntl-matchers.d.ts +58 -12
  63. package/dist/serializer.cjs +4 -2
  64. package/dist/serializer.d.cts +3 -4
  65. package/dist/serializer.d.mts +3 -4
  66. package/dist/serializer.mjs +4 -2
  67. package/dist/setup.mjs +61 -50
  68. package/dist/worker-vitest-BGPo0ek6.mjs +49 -0
  69. package/dist/worker-vitest-BfiQB8ND.cjs +62 -0
  70. package/docs/hot-default-design.md +175 -88
  71. package/docs/migrating-from-jest.md +12 -5
  72. package/docs/migrating-from-vitest-react-native.md +4 -4
  73. package/docs/release-readiness.md +39 -13
  74. package/docs/versioning.md +19 -18
  75. package/package.json +42 -31
  76. package/dist/pool-BU-1ecIF.cjs +0 -122
  77. package/dist/pool-Bcxn9a3I.mjs +0 -118
package/dist/index.mjs CHANGED
@@ -1,11 +1,13 @@
1
1
  import { t as VitestNativeError } from "./errors-CxoBUfVJ.mjs";
2
- import { a as packageDirOf, c as validateOptions, i as containsPath, l as validatePeerDependency, n as detectEngine, o as packagePatterns, r as REACT_NATIVE_PATH, s as PEER_REQUIREMENTS, t as detectEcosystemPackages, u as warnUnknownOptions } from "./ecosystem-Duw40-mO.mjs";
2
+ import { a as findNativeOwnershipConflict, c as packageDirOf, d as validatePeerDependency, f as warnUnknownOptions, i as findNativeInlineConflicts, l as PEER_REQUIREMENTS, n as detectEngine, o as formatNativeOwnershipManifest, r as createNativeOwnershipPolicy, s as containsPath, t as detectEcosystemPackages, u as validateOptions } from "./ecosystem-DFbU_MPe.mjs";
3
3
  import { t as AUTO_DETECT_PRESETS } from "./preset-map-DuX0ocdn.mjs";
4
- import { t as presets_exports } from "./presets-DGProTaA.mjs";
4
+ import { t as workerVitestMismatch } from "./worker-vitest-BGPo0ek6.mjs";
5
+ import { t as presets_exports } from "./presets-DC-eM5IA.mjs";
5
6
  import { createRequire } from "node:module";
6
7
  import fs from "node:fs";
7
8
  import path from "node:path";
8
9
  import { fileURLToPath, pathToFileURL } from "node:url";
10
+ import os from "node:os";
9
11
  import flowRemoveTypes from "flow-remove-types";
10
12
  //#region src/native/resolve.mjs
11
13
  /**
@@ -40,12 +42,31 @@ const METRO_SOURCE_EXTS = [
40
42
  * ships. The order is asserted against real metro-resolver by
41
43
  * tests/metro-resolver-oracle.test.ts, not just against these literals.
42
44
  */
43
- function extensionsFor(platform) {
45
+ function extensionsFor(platform, sourceExts = METRO_SOURCE_EXTS) {
44
46
  const suffix = platform === "android" ? "android" : "ios";
45
47
  const exts = [];
46
- for (const e of METRO_SOURCE_EXTS) exts.push(`.${suffix}.${e}`, `.native.${e}`, `.${e}`);
48
+ for (const e of sourceExts) exts.push(`.${suffix}.${e}`, `.native.${e}`, `.${e}`);
47
49
  return exts;
48
50
  }
51
+ /**
52
+ * Whether `file` exists under exactly this name.
53
+ *
54
+ * macOS and Windows disks are case-insensitive by default, so `fs.existsSync("App.json")`
55
+ * is true when only `app.json` exists. Resolving `./App` in extension order (Metro's: js,
56
+ * jsx, json, ts, tsx) then picks the React Native template's `app.json` over its `App.tsx`,
57
+ * and the template's own test renders `{ name, displayName }`. Metro resolves from a
58
+ * case-sensitive file map, as does Linux, which is why neither Metro nor CI saw it. The
59
+ * directory listing has the real names. Checked for the file's own name: the case the
60
+ * template hits, and one `readdir` per hit, which the resolution caches absorb.
61
+ */
62
+ function existsExact(file) {
63
+ if (!fs.existsSync(file)) return false;
64
+ try {
65
+ return fs.readdirSync(path.dirname(file)).includes(path.basename(file));
66
+ } catch {
67
+ return true;
68
+ }
69
+ }
49
70
  //#endregion
50
71
  //#region src/resolve.ts
51
72
  /**
@@ -60,23 +81,62 @@ const PLATFORM_EXTENSIONS_ANDROID = extensionsFor("android");
60
81
  function getPlatformExtensions(platform) {
61
82
  return platform === "ios" ? PLATFORM_EXTENSIONS_IOS : PLATFORM_EXTENSIONS_ANDROID;
62
83
  }
84
+ /** Build the shared Vite/Node candidate order for a resolved Metro profile. */
85
+ function getConfiguredPlatformExtensions(platform, sourceExts) {
86
+ return extensionsFor(platform, sourceExts);
87
+ }
63
88
  //#endregion
64
- //#region src/native/apply.ts
89
+ //#region src/jest-compat/aliases.mjs
65
90
  /**
66
- * Files outside any installed package that Vitest may be running as an ENTRY rather
67
- * than importing as a module: the two naming conventions test runners use.
91
+ * The string-to-string entries of a Vite `resolve.alias`, in either of its shapes, with
92
+ * relative replacements made absolute against `root`. Regex `find`s and custom
93
+ * resolvers cannot cross into the test worker, so they are listed as `skipped` for the
94
+ * error that explains a miss.
68
95
  *
69
- * Neither is exhaustive — a project can point `test.include` anywhere — but a file
70
- * that matches one of these is a test by convention and never library source, which
71
- * is what makes it safe to keep out of Node's graph unconditionally.
96
+ * @param {unknown} alias `resolve.alias`: an object, or an array of `{ find, replacement }`
97
+ * @param {string} root project root, for relative replacements
98
+ * @returns {{ entries: [string, string][], skipped: string[] }}
72
99
  */
73
- const OUTSIDE_NODE_MODULES = String.raw`^(?!.*[\\/]node_modules[\\/])`;
74
- const TEST_ENTRY_PATTERNS = [new RegExp(String.raw`${OUTSIDE_NODE_MODULES}.*\.(?:test|spec)\.[cm]?[jt]sx?$`), new RegExp(String.raw`${OUTSIDE_NODE_MODULES}.*[\\/]__tests__[\\/].*\.[cm]?[jt]sx?$`)];
75
- function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [], hot, jsxTransform = { esbuild: { jsx: "automatic" } }, userPool, inlinePkgs = [], projectRoot = process.cwd(), userInlinesEverything = false) {
76
- const extraExternal = transformPkgs.flatMap((p) => packagePatterns(p, projectRoot));
77
- const ecosystemExternal = inlinePkgs.flatMap((p) => packagePatterns(p, projectRoot));
78
- const nodeTransformed = [.../* @__PURE__ */ new Set([...transformPkgs, ...inlinePkgs])];
100
+ function serializableAliases(alias, root) {
101
+ const entries = [];
102
+ const skipped = [];
103
+ const list = Array.isArray(alias) ? alias : alias && typeof alias === "object" ? Object.entries(alias).map(([find, replacement]) => ({
104
+ find,
105
+ replacement
106
+ })) : [];
107
+ for (const item of list) {
108
+ const find = item?.find;
109
+ const replacement = item?.replacement;
110
+ if (typeof find !== "string" || typeof replacement !== "string" || item.customResolver) {
111
+ skipped.push(String(find));
112
+ continue;
113
+ }
114
+ entries.push([find, replacement.startsWith(".") ? path.resolve(root, replacement) : replacement]);
115
+ }
116
+ return {
117
+ entries,
118
+ skipped
119
+ };
120
+ }
121
+ //#endregion
122
+ //#region src/native/apply.ts
123
+ function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [], hot, jsxTransform = { esbuild: { jsx: "automatic" } }, userPool, inlinePkgs = [], projectRoot = process.cwd(), userInlinesEverything = false, projectDirs = [], ownershipPolicy) {
124
+ const ownership = ownershipPolicy ?? createNativeOwnershipPolicy({
125
+ projectRoot,
126
+ explicitTransforms: transformPkgs,
127
+ ecosystemPackages: inlinePkgs,
128
+ projectDirs,
129
+ serverDepsInlineAll: userInlinesEverything
130
+ });
131
+ const nodeTransformed = ownership.nodeTransformPackages;
79
132
  const fullEnv = { ...env };
133
+ const ownershipManifest = ownership.manifest();
134
+ fullEnv.VITEST_NATIVE_OWNERSHIP = JSON.stringify(ownershipManifest);
135
+ if (fullEnv.VITEST_NATIVE_DIAGNOSTICS === "true") for (const line of formatNativeOwnershipManifest(ownershipManifest)) {
136
+ const report = `[vitest-native] ownership: ${line}`;
137
+ if (line.startsWith("WARNING:")) console.warn(report);
138
+ else console.log(report);
139
+ }
80
140
  if (nodeTransformed.length > 0) fullEnv.VITEST_NATIVE_TRANSFORM = JSON.stringify(nodeTransformed);
81
141
  return {
82
142
  ...jsxTransform,
@@ -111,15 +171,12 @@ function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [],
111
171
  ...hot ? {
112
172
  pool: hot.pool,
113
173
  isolate: false,
114
- runner: hot.runnerPath
174
+ runner: hot.runnerPath,
175
+ ...hot.maxWorkers == null ? {} : { maxWorkers: hot.maxWorkers }
115
176
  } : { pool: userPool ?? "threads" },
116
177
  server: { deps: {
117
- ...userInlinesEverything ? {} : { inline: TEST_ENTRY_PATTERNS },
118
- external: [
119
- REACT_NATIVE_PATH,
120
- ...extraExternal,
121
- ...ecosystemExternal
122
- ]
178
+ ...userInlinesEverything ? {} : { inline: ownership.testEntryPatterns },
179
+ external: ownership.externalPatterns
123
180
  } }
124
181
  }
125
182
  };
@@ -149,6 +206,22 @@ const DEFAULT_ASSET_EXTS = [
149
206
  "woff",
150
207
  "woff2"
151
208
  ];
209
+ function uniqueExtensions(values) {
210
+ const seen = /* @__PURE__ */ new Set();
211
+ const result = [];
212
+ for (const value of values) {
213
+ const extension = value.replace(/^\./, "").toLowerCase();
214
+ if (extension && !seen.has(extension)) {
215
+ seen.add(extension);
216
+ result.push(extension);
217
+ }
218
+ }
219
+ return result;
220
+ }
221
+ function assetExtensionsFor(sourceExts, metroAssets, user) {
222
+ const sources = new Set(sourceExts.map((extension) => extension.toLowerCase()));
223
+ return uniqueExtensions([...uniqueExtensions(metroAssets).filter((extension) => !sources.has(extension)), ...user]);
224
+ }
152
225
  /** Strip Vite's /@fs/ prefix to get a real filesystem path. */
153
226
  function stripFsPrefix(id) {
154
227
  return id.startsWith("/@fs/") ? id.slice(4) : id;
@@ -258,6 +331,45 @@ function resolvePackageVersion(packageName, projectRoot) {
258
331
  }
259
332
  }
260
333
  /**
334
+ * Whether to resolve tsconfig `paths` the way Expo's Metro does. Expo CLI enables
335
+ * tsconfig path aliases by default (`experiments.tsconfigPaths`, docs.expo.dev/guides/
336
+ * typescript), and the SDK 57 template imports its own components through `@/…`, so
337
+ * without this a new Expo project's first component test fails to resolve. Bare React
338
+ * Native's Metro does not, so neither does this. Vite 8 resolves tsconfig paths itself
339
+ * when `resolve.tsconfigPaths` is on; Vite 6 and 7 have no such option.
340
+ *
341
+ * Returns "enable" (Vite 8), "unsupported" (an older Vite with `paths` to resolve, worth
342
+ * a warning), or null (not an Expo project, no tsconfig, opted out, or the user set
343
+ * `resolve.tsconfigPaths` themselves).
344
+ */
345
+ function expoTsconfigPaths(projectRoot, userTsconfigPaths, viteMajor) {
346
+ if (userTsconfigPaths !== void 0) return null;
347
+ const read = (file) => {
348
+ try {
349
+ return fs.readFileSync(path.join(projectRoot, file), "utf8");
350
+ } catch {
351
+ return null;
352
+ }
353
+ };
354
+ let manifest = {};
355
+ try {
356
+ manifest = JSON.parse(read("package.json") ?? "{}");
357
+ } catch {
358
+ return null;
359
+ }
360
+ if (!("expo" in {
361
+ ...manifest.dependencies,
362
+ ...manifest.devDependencies
363
+ })) return null;
364
+ const tsconfig = read("tsconfig.json");
365
+ if (tsconfig === null) return null;
366
+ try {
367
+ if (JSON.parse(read("app.json") ?? "{}").expo?.experiments?.tsconfigPaths === false) return null;
368
+ } catch {}
369
+ if (viteMajor >= 8) return "enable";
370
+ return /"paths"\s*:/.test(tsconfig) ? "unsupported" : null;
371
+ }
372
+ /**
261
373
  * One line, once per process, stating which engine this run actually uses.
262
374
  * Tests pass either way; a team that believes it's exercising real React Native
263
375
  * while running the mock (or vice versa) must be able to see it in every log.
@@ -267,13 +379,14 @@ function resolvePackageVersion(packageName, projectRoot) {
267
379
  * Written to stderr: this is the plugin's only unconditional output, and stdout
268
380
  * must stay parseable for pipelines like `vitest --reporter=json > results.json`.
269
381
  */
270
- function printEngineBanner(engine, platform, projectRoot) {
382
+ function printEngineBanner(engine, platform, projectRoot, hotRuntime = false) {
271
383
  const g = globalThis;
272
384
  if (g.__vitest_native_banner_printed) return;
273
385
  g.__vitest_native_banner_printed = true;
274
386
  if (engine === "native") {
275
387
  const rn = resolvePackageVersion("react-native", projectRoot);
276
- console.error(`[vitest-native] engine: native — real react-native${rn ? `@${rn}` : ""} (platform ${platform})`);
388
+ const runtime = hotRuntime ? ", hot runtime" : "";
389
+ console.error(`[vitest-native] engine: native — real react-native${rn ? `@${rn}` : ""} (platform ${platform}${runtime})`);
277
390
  } else console.error(`[vitest-native] engine: mock — React Native reimplementation, cross-checked against real RN (platform ${platform})`);
278
391
  }
279
392
  function getJsxTransformConfig(projectRoot) {
@@ -297,15 +410,37 @@ function getJsxTransformConfig(projectRoot) {
297
410
  * real module in the native suite, across every React Native version in CI.
298
411
  */
299
412
  function parseReactNativeExports(indexSource) {
413
+ return parseReactNativeMembers(indexSource).map((member) => member.name);
414
+ }
415
+ /**
416
+ * The members of React Native's index that announce their own deprecation.
417
+ *
418
+ * React Native marks a deprecated or extracted export by calling `warnOnce` inside
419
+ * its getter, so reading the member is what prints the notice. The facade must not
420
+ * read these while it initialises, or every file that imports `Pressable` prints
421
+ * notices for `SafeAreaView`, `Clipboard` and the rest; it exposes them as getters
422
+ * instead, and the notice appears only where a test really uses one.
423
+ */
424
+ function parseDeprecatedReactNativeExports(indexSource) {
425
+ return parseReactNativeMembers(indexSource).filter((member) => member.deprecated).map((member) => member.name);
426
+ }
427
+ function parseReactNativeMembers(indexSource) {
300
428
  const start = indexSource.indexOf("module.exports = {");
301
429
  if (start === -1) return [];
302
- const body = indexSource.slice(start);
303
- const names = /* @__PURE__ */ new Set();
304
- for (const match of body.matchAll(/^ {2}(?:get\s+)?([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*[(:,]/gm)) {
430
+ const end = indexSource.slice(start).search(/^\}/m);
431
+ const body = end === -1 ? indexSource.slice(start) : indexSource.slice(start, start + end);
432
+ const matches = [...body.matchAll(/^ {2}(?:get\s+)?([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*[(:,]/gm)];
433
+ const members = /* @__PURE__ */ new Map();
434
+ matches.forEach((match, i) => {
305
435
  const name = match[1];
306
- if (name !== "default" && name !== "__esModule" && name !== "get") names.add(name);
307
- }
308
- return [...names];
436
+ if (name === "default" || name === "__esModule" || name === "get") return;
437
+ const text = body.slice(match.index, matches[i + 1]?.index ?? body.length);
438
+ members.set(name, (members.get(name) ?? false) || /\bwarnOnce\s*\(/.test(text));
439
+ });
440
+ return [...members].map(([name, deprecated]) => ({
441
+ name,
442
+ deprecated
443
+ }));
309
444
  }
310
445
  /**
311
446
  * Build (or reuse) the precompiled React Native registry for a project.
@@ -319,27 +454,21 @@ function parseReactNativeExports(indexSource) {
319
454
  async function buildRegistryFor(options) {
320
455
  try {
321
456
  const dir = path.dirname(fileURLToPath(import.meta.url));
322
- return (await import(pathToFileURL(path.resolve(dir, "native/registry.mjs")).href)).buildRegistry(options);
457
+ return (await import(pathToFileURL(path.resolve(dir, "native/registry-process.mjs")).href)).buildRegistryFor(options);
323
458
  } catch (error) {
324
- if (options.diagnostics) console.warn(`[vitest-native] could not precompile the React Native registry (${error?.message}); using per-file module loading.`);
459
+ try {
460
+ const dir = path.dirname(fileURLToPath(import.meta.url));
461
+ (await import(pathToFileURL(path.resolve(dir, "native/registry.mjs")).href))._warnRegistryUnavailable(error?.message ?? error);
462
+ } catch {
463
+ console.warn(`[vitest-native] (native) could not precompile the React Native registry (${error?.message ?? error}); using slower per-file module loading.`);
464
+ }
325
465
  return null;
326
466
  }
327
467
  }
328
- /**
329
- * Compile one inlined ecosystem file with the project's React Native Babel preset.
330
- *
331
- * The transformer ships as runtime `.mjs` (Node's loader hooks use it too), so it is
332
- * loaded through a computed path rather than a static import, and synchronously —
333
- * Vite's transform hook may be sync and the module is already resident by the time
334
- * any file reaches this point.
335
- */
336
- let ecosystemTransformer = null;
337
- function transformEcosystem(file, code, projectRoot, platform) {
338
- if (!ecosystemTransformer) {
339
- const dir = path.dirname(fileURLToPath(import.meta.url));
340
- ecosystemTransformer = createRequire(import.meta.url)(path.resolve(dir, "native/transform.mjs")).transformRN;
341
- }
342
- return ecosystemTransformer(file, code, projectRoot, platform);
468
+ /** Load declarative Metro data without retaining Metro/Expo in Vite's process. */
469
+ async function loadProjectMetroProfile(options) {
470
+ const dir = path.dirname(fileURLToPath(import.meta.url));
471
+ return (await import(pathToFileURL(path.resolve(dir, "native/metro-profile.mjs")).href)).loadMetroProfile(options);
343
472
  }
344
473
  /**
345
474
  * Vite 6/7 and Vite 8 expose mutually exclusive JSX config types:
@@ -369,11 +498,14 @@ function autoDetectPresetNames(projectRoot, diagnostics) {
369
498
  }
370
499
  return [...names];
371
500
  }
372
- async function resolveOptions(options = {}, projectRoot) {
501
+ /**
502
+ * `resolution` is the extension profile the plugin already settled on — Metro's when
503
+ * metroConfig is on, the built-in one otherwise — so it is computed in one place.
504
+ */
505
+ async function resolveOptions(options = {}, projectRoot, resolution) {
373
506
  const platform = options.platform ?? "ios";
374
507
  const diagnostics = options.diagnostics ?? false;
375
508
  const engine = options.engine === "native" ? "native" : "mock";
376
- const userExts = (options.assetExts ?? []).map((e) => e.replace(/^\./, ""));
377
509
  let presets;
378
510
  if (Array.isArray(options.presets)) presets = options.presets;
379
511
  else {
@@ -385,10 +517,10 @@ async function resolveOptions(options = {}, projectRoot) {
385
517
  platform,
386
518
  engine,
387
519
  diagnostics,
388
- extensions: getPlatformExtensions(platform),
520
+ extensions: resolution.extensions,
389
521
  presets,
390
522
  mocks: options.mocks ?? {},
391
- assetExts: [...DEFAULT_ASSET_EXTS, ...userExts]
523
+ assetExts: resolution.assetExts
392
524
  };
393
525
  }
394
526
  /**
@@ -610,8 +742,9 @@ const FORMAT_ONLY_FIELDS = [
610
742
  * cannot parse at all. Aligning upward would turn a wrong-value bug into a crash for
611
743
  * any package the engine does not also transform.
612
744
  *
613
- * Packages the engine inlines and transforms are left alone: Vite is meant to own
614
- * their source, and rewriting them to `main` would undo the reason they are inlined.
745
+ * Packages the engine itself virtualizes are left alone. Node-owned ecosystem
746
+ * packages are intentionally not exempt: if Vite also reaches one, aligning a
747
+ * format-only field to Node's file prevents a silent second instance.
615
748
  *
616
749
  * @returns the absolute file to use, or null to leave resolution alone
617
750
  */
@@ -646,11 +779,139 @@ function disabledPresetNames(presets) {
646
779
  if (!presets || Array.isArray(presets) || typeof presets !== "object") return /* @__PURE__ */ new Set();
647
780
  return new Set(Object.entries(presets).filter(([, enabled]) => enabled === false).map(([name]) => name));
648
781
  }
782
+ /**
783
+ * Config-time reasons that make automatic hot selection unsafe. Suites migrated from
784
+ * Jest (jestMockTransform(), the jest-compat setup) are not among them: the jest-compat
785
+ * surface has its own cross-file isolation gate under hot (tests-native/hot-jest-compat)
786
+ * and the hot runtime resets before user setup files run (tests-native/hot-user-setup).
787
+ */
788
+ function hotAutoConfigDeclineReason(userPool, userIsolate) {
789
+ if (userIsolate !== void 0) return `test.isolate is explicitly ${String(userIsolate)}`;
790
+ if (userPool != null) return `${typeof userPool === "string" ? `'${userPool}'` : "a custom pool"} is explicitly configured`;
791
+ return null;
792
+ }
793
+ /**
794
+ * Why the resolved Vitest config overrides a hot runtime chosen at config time, or
795
+ * null. Vitest 4 applies CLI flags after plugins' config hooks, so `--maxWorkers=1`,
796
+ * `--no-file-parallelism`, `--pool` and `--isolate`/`--no-isolate` arrive only in the
797
+ * resolved config. `--no-isolate` sets the same `isolate: false` the hot runtime uses,
798
+ * so it is read from the CLI options themselves.
799
+ */
800
+ function hotOverrideReason(resolved, cli, hotPool, singleWorkerAccepted = false) {
801
+ if (cli.isolate !== void 0) return `--${cli.isolate ? "" : "no-"}isolate was passed`;
802
+ const poolName = (pool) => typeof pool === "string" ? pool : pool !== null && typeof pool === "object" ? pool.name : void 0;
803
+ if (!(resolved.pool === hotPool || poolName(hotPool) !== void 0 && poolName(resolved.pool) === poolName(hotPool))) return `the pool '${typeof resolved.pool === "string" ? resolved.pool : "custom"}' was set`;
804
+ if (singleWorkerAccepted) return null;
805
+ if (resolved.fileParallelism === false) return "file parallelism is off";
806
+ if (typeof resolved.maxWorkers === "number" && resolved.maxWorkers < 2) return `maxWorkers is ${resolved.maxWorkers}`;
807
+ return null;
808
+ }
809
+ /**
810
+ * The root Vitest gives a project: `test.root` over Vite's `root` (Vitest 4 and 5's
811
+ * resolveConfig). `vitest --root` arrives as `test.root`. Per-project state is keyed
812
+ * by it, since that is the root configureVitest sees.
813
+ */
814
+ function vitestRootOf(config) {
815
+ const testRoot = config.test?.root;
816
+ const root = typeof testRoot === "string" && testRoot ? testRoot : config.root;
817
+ return path.resolve(typeof root === "string" && root ? root : process.cwd());
818
+ }
819
+ /**
820
+ * Pin each inline project's `root` to the root it would inherit anyway, so Vitest 5
821
+ * resolves it through the config file with this plugin instead of sharing the
822
+ * declaring config's Vite server. A server-sharing project gets its `test` options
823
+ * from the user's raw config, captured before any plugin's config hook runs, so it
824
+ * would miss everything this plugin contributes to `test` — setup files, dependency
825
+ * ownership, env, the hot pool. Vitest shares a server only when an entry sets no
826
+ * Vite-level option; `root` is one, and pinning it to the inherited value changes
827
+ * nothing else. Unlike `sharedViteServer: false`, which Vitest reads from the
828
+ * top-level config alone, this works in a nested config too. Vitest 4 resolves every
829
+ * inline project through the config file already. Returns how many were pinned.
830
+ */
831
+ function pinInlineProjectRoots(test, declaringRoot) {
832
+ const projects = test?.projects;
833
+ if (!Array.isArray(projects)) return 0;
834
+ let pinned = 0;
835
+ for (const entry of projects) {
836
+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) continue;
837
+ const project = entry;
838
+ if (project.root !== void 0) continue;
839
+ project.root = declaringRoot;
840
+ pinned++;
841
+ }
842
+ return pinned;
843
+ }
844
+ function hasSetupFile(setupFiles, file) {
845
+ const real = (f) => {
846
+ try {
847
+ return fs.realpathSync(f);
848
+ } catch {
849
+ return path.resolve(f);
850
+ }
851
+ };
852
+ const wanted = real(file);
853
+ return Array.isArray(setupFiles) && setupFiles.some((f) => typeof f === "string" && real(f) === wanted);
854
+ }
855
+ /**
856
+ * Why this project's worker count cannot coexist with another project's, or null.
857
+ * Vitest schedules projects that share a `sequence.groupOrder` (0 unless set) as one
858
+ * group, and throws when they resolve to different `maxWorkers` ("Projects … have
859
+ * different 'maxWorkers' but same 'sequence.groupOrder'", groupSpecs in Vitest 4 and
860
+ * 5). The hot runtime's memory plan caps workers (at most four), while a project
861
+ * beside it gets Vitest's default of one fewer than the CPUs, so a native project next
862
+ * to a mock or non-React-Native project failed on any machine with more than five
863
+ * cores. Mirrors Vitest's resolveMaxWorkers and its grouping, including the exemption
864
+ * for a single-worker isolated project in the default group.
865
+ */
866
+ function sharedGroupConflict(self, others, root, cpus) {
867
+ const order = (p) => Number(p.config.sequence?.groupOrder ?? 0);
868
+ const workers = (p) => p.config.maxWorkers || root.maxWorkers || vitestMaxWorkers(void 0, root.watch === true, cpus);
869
+ const ownGroup = (p) => p.config.isolate === true && order(p) === 0 && p.config.maxWorkers === 1;
870
+ for (const other of others) {
871
+ if (other === self || ownGroup(other) || order(other) !== order(self)) continue;
872
+ if (workers(other) !== workers(self)) return `the project '${String(other.name ?? other.config.name ?? "another project")}' is in the same sequence.groupOrder (${order(self)}) with ${workers(other)} workers to this project's ${workers(self)}, which Vitest rejects (a distinct test.sequence.groupOrder runs them as separate groups)`;
873
+ }
874
+ return null;
875
+ }
876
+ function isVmPool(pool) {
877
+ return pool === "vmThreads" || pool === "vmForks";
878
+ }
879
+ function vmPoolUnsupported(pool) {
880
+ return new VitestNativeError("UNSUPPORTED_POOL", `engine:'native' cannot run on the '${pool}' pool. React Native is loaded through Node's module hooks, which a VM pool's context does not use — React Native fails to resolve its platform files there. Use 'threads' (the default) or 'forks', or switch to engine:'mock', which needs no hooks.`);
881
+ }
882
+ function hotRuntimeOverridden(reason) {
883
+ return new VitestNativeError("HOT_RUNTIME_OVERRIDDEN", `hotRuntime was requested, but ${reason}, which the hot runtime cannot honour. Remove that setting, or use hotRuntime:'auto' to fall back to it automatically or hotRuntime:false.`);
884
+ }
885
+ /**
886
+ * The worker count Vitest would have used had the hot runtime not capped it: the
887
+ * user's own value (a count or a percentage of the CPUs), else Vitest's default.
888
+ * Mirrors Vitest 4/5's resolveMaxWorkers and getWorkersCountByPercentage.
889
+ */
890
+ function vitestMaxWorkers(userValue, watch, cpus = os.availableParallelism?.() ?? os.cpus().length) {
891
+ if (typeof userValue === "number" && userValue > 0) return userValue;
892
+ if (typeof userValue === "string") {
893
+ const percent = /^(\d+)%$/.exec(userValue.trim());
894
+ if (percent) return Math.max(1, Math.min(cpus, Math.round(Number(percent[1]) / 100 * cpus)));
895
+ const count = Number.parseInt(userValue, 10);
896
+ if (count > 0) return count;
897
+ }
898
+ return watch ? Math.max(Math.floor(cpus / 2), 1) : Math.max(cpus - 1, 1);
899
+ }
900
+ /** Why hot cannot run here because its worker would load a different Vitest, or null. */
901
+ function workerVitestMismatchReason(workerEntry, projectRoot) {
902
+ const mismatch = workerVitestMismatch(workerEntry, projectRoot);
903
+ return mismatch ? `its worker would load vitest@${mismatch.worker.version} while this run uses vitest@${mismatch.project.version}` : null;
904
+ }
649
905
  function reactNative(options) {
650
906
  let jestMockTransformPresent = true;
907
+ const hotSelections = /* @__PURE__ */ new Map();
908
+ const nativeRoots = /* @__PURE__ */ new Set();
909
+ const contributedSetup = /* @__PURE__ */ new Map();
651
910
  let warnedMissingJestMockTransform = false;
911
+ let warnedTsconfigPaths = false;
652
912
  const warnIfJestMockUnhoisted = (code, id) => {
653
913
  if (jestMockTransformPresent || warnedMissingJestMockTransform) return;
914
+ if (/[\\/]node_modules[\\/]/.test(id) || containsPath(ownPackageDir, id)) return;
654
915
  if (!HAS_JEST_MOCK_CALL.test(code)) return;
655
916
  warnedMissingJestMockTransform = true;
656
917
  console.warn(`[vitest-native] ${id} calls jest.mock(), but jestMockTransform() is not in your plugins. Vitest only hoists mocks written on the vi/vitest identifier, so this call runs after the imports it should intercept and the mock will not apply.\nAdd it AFTER reactNative():\n\n import { jestMockTransform } from 'vitest-native/jest-compat'\n plugins: [reactNative(), jestMockTransform()]`);
@@ -666,11 +927,42 @@ function reactNative(options) {
666
927
  let assetPattern;
667
928
  let realRnPackageJson;
668
929
  let rnFacadeExports = null;
930
+ let rnFacadeDeprecated = /* @__PURE__ */ new Set();
669
931
  let rnFacadeRoot = "";
670
- let ecosystemPattern = null;
932
+ let nativeOwnership = null;
933
+ const assertInlineOwnership = (inline) => {
934
+ if (engine !== "native" || !nativeOwnership) return;
935
+ const conflicts = findNativeInlineConflicts(nativeOwnership, inline);
936
+ if (conflicts.length === 0) return;
937
+ const selection = conflicts.includes("*") ? "server.deps.inline:true" : `server.deps.inline overlaps Node-owned package${conflicts.length === 1 ? "" : "s"}: ${conflicts.join(", ")}`;
938
+ throw new VitestNativeError("INLINE_BREAKS_OWNERSHIP", `engine:'native' cannot run because ${selection}. Vitest gives inlining precedence over the engine's Node-ownership rules, so the same React Native package can load once through Vite and again through Node with separate module state. Remove the overlapping inline rule; use reactNative({ transform: [...] }) for Metro-source packages that need compiling.`);
939
+ };
671
940
  let alignRoot = "";
672
- let ecosystemRoot = "";
673
941
  const alignedCache = /* @__PURE__ */ new Map();
942
+ const resolveExtensionless = (source, importer) => {
943
+ if (importer && path.isAbsolute(importer) && source.startsWith(".") && !path.extname(source)) {
944
+ const cacheKey = `${importer}\0${source}`;
945
+ const cached = resolveCache.get(cacheKey);
946
+ if (cached !== void 0) return cached;
947
+ const importerDir = path.dirname(importer);
948
+ const absolute = path.resolve(importerDir, source);
949
+ for (const ext of extensions) {
950
+ const candidate = absolute + ext;
951
+ if (existsExact(candidate)) {
952
+ resolveCache.set(cacheKey, candidate);
953
+ return candidate;
954
+ }
955
+ }
956
+ for (const ext of extensions) {
957
+ const candidate = path.join(absolute, `index${ext}`);
958
+ if (existsExact(candidate)) {
959
+ resolveCache.set(cacheKey, candidate);
960
+ return candidate;
961
+ }
962
+ }
963
+ resolveCache.set(cacheKey, void 0);
964
+ }
965
+ };
674
966
  const alignedResolution = (source, importer) => {
675
967
  if (engine !== "native") return void 0;
676
968
  const from = importer && path.isAbsolute(importer) && !importer.startsWith("\0") ? importer : path.join(alignRoot || process.cwd(), "package.json");
@@ -708,23 +1000,35 @@ function reactNative(options) {
708
1000
  const resolveCache = /* @__PURE__ */ new Map();
709
1001
  const virtualCodeCache = /* @__PURE__ */ new Map();
710
1002
  const thisDir = path.dirname(fileURLToPath(import.meta.url));
1003
+ const ownPackageDir = path.resolve(thisDir, "..");
711
1004
  let setupFilePath = path.resolve(thisDir, "setup.mjs");
712
1005
  if (!fs.existsSync(setupFilePath)) {
713
1006
  const srcPath = path.resolve(thisDir, "setup.ts");
714
1007
  if (fs.existsSync(srcPath)) setupFilePath = srcPath;
715
1008
  }
716
1009
  const nativeSetupPath = path.resolve(thisDir, "native/setup.mjs");
1010
+ const EXPORT_RECOVERY_ARGV = ["--import", pathToFileURL(path.resolve(thisDir, "native/export-condition-recovery-preload.mjs")).href];
717
1011
  const nativeWorkerPath = path.resolve(thisDir, "native/worker.mjs");
718
1012
  const nativeRunnerPath = path.resolve(thisDir, "native/runner.mjs");
719
1013
  const platform = options?.platform ?? "ios";
720
1014
  const diagnostics = options?.diagnostics ?? false;
721
1015
  const requestedEngine = options?.engine ?? "auto";
722
1016
  const { include: transformPkgs, exclude: neverTransform } = normalizeTransformOption(options?.transform);
723
- const hotRuntimeOpt = options?.hotRuntime ?? false;
724
- const hotRuntime = hotRuntimeOpt !== false;
1017
+ const hotRuntimeExplicit = options?.hotRuntime !== void 0;
1018
+ const hotRuntimeOpt = options?.hotRuntime ?? "auto";
1019
+ const hotRuntimeRequested = hotRuntimeOpt !== false;
1020
+ const hotRuntimeAuto = hotRuntimeOpt === "auto";
725
1021
  const hotRecycle = typeof hotRuntimeOpt === "object" ? hotRuntimeOpt : {};
726
1022
  let engine = requestedEngine === "native" ? "native" : "mock";
727
- const extensions = getPlatformExtensions(platform);
1023
+ let sourceExts = [
1024
+ "js",
1025
+ "jsx",
1026
+ "json",
1027
+ "ts",
1028
+ "tsx"
1029
+ ];
1030
+ let extensions = getPlatformExtensions(platform);
1031
+ let assetExtList = assetExtensionsFor(sourceExts, DEFAULT_ASSET_EXTS, options?.assetExts ?? []);
728
1032
  const resolvePresetId = (source) => {
729
1033
  if (presetModules.has(source)) return `\0virtual:preset:${source}`;
730
1034
  if (!assetPattern) return void 0;
@@ -732,29 +1036,57 @@ function reactNative(options) {
732
1036
  const pkg = packageNameOf(source);
733
1037
  if (pkg !== source && presetModules.has(pkg)) return `\0virtual:preset:${source}`;
734
1038
  };
735
- return {
1039
+ const pluginDefinition = {
736
1040
  name: "vitest-native",
737
1041
  enforce: "pre",
738
1042
  async config(userConfig, _env) {
739
1043
  const resolvedRoot = userConfig.root ? path.resolve(userConfig.root) : process.cwd();
740
1044
  alignRoot = resolvedRoot;
1045
+ const metroOption = options?.metroConfig;
1046
+ if (metroOption === true || typeof metroOption === "object") {
1047
+ const metroSettings = typeof metroOption === "object" ? metroOption : {};
1048
+ let metro;
1049
+ try {
1050
+ metro = await loadProjectMetroProfile({
1051
+ projectRoot: resolvedRoot,
1052
+ platform,
1053
+ configFile: metroSettings.configFile
1054
+ });
1055
+ } catch (error) {
1056
+ const code = error?.code;
1057
+ if (code !== void 0 && code !== "METRO_CONFIG_LOAD_FAILED") throw error;
1058
+ throw new VitestNativeError("METRO_CONFIG_LOAD_FAILED", `${String(error?.message ?? error).replace(/^\[vitest-native\] /, "")}\nFix the Metro config, pass metroConfig:{ configFile:'...' } when it lives outside the project root, or use metroConfig:false to explicitly keep vitest-native's built-in React Native defaults.`, { cause: error });
1059
+ }
1060
+ if (metro.profile.customResolver) console.warn("[vitest-native] The Metro config installs resolver.resolveRequest, which is code and does not run under Vitest. Its source and asset extensions apply; a module it redirects resolves as Vite and Node resolve it. Where a redirect matters to tests, reproduce it with resolve.alias.");
1061
+ sourceExts = [...metro.profile.sourceExts];
1062
+ extensions = getConfiguredPlatformExtensions(platform, sourceExts);
1063
+ assetExtList = assetExtensionsFor(sourceExts, metro.profile.assetExts, options?.assetExts ?? []);
1064
+ if (diagnostics) {
1065
+ const childRss = metro.evidence.rss ? `, child RSS ${Math.ceil(metro.evidence.rss / 1024 / 1024)} MiB` : "";
1066
+ console.log(`[vitest-native] Metro profile: ${metro.profile.provenance}${metro.profile.configPath ? ` (${metro.profile.configPath})` : ""}; sourceExts=${sourceExts.join(",")}; assetExts=${assetExtList.join(",")}; loaded in ${metro.evidence.durationMs ?? "?"}ms${childRss}.`);
1067
+ console.log(`[vitest-native] Metro resolverMainFields=${metro.profile.resolverMainFields.join(",")} and conditions=${metro.profile.conditionNames.join(",")} are observational; module ownership keeps the package-format policy authoritative.`);
1068
+ }
1069
+ }
741
1070
  const jsxTransform = getJsxTransformConfig(resolvedRoot);
742
1071
  const decision = detectEngine(requestedEngine, resolvedRoot);
743
1072
  engine = decision.engine;
744
1073
  if (engine === "native" && !decision.nativeAvailable) throw new VitestNativeError("ENGINE_REQUIRES_BABEL", `engine:'native' requires react-native, '@react-native/babel-preset', and '@babel/core' to resolve from ${resolvedRoot} — missing: ${decision.missing.join(", ")}. React Native projects ship all three by default. Install what's missing (react-native as a dependency, the toolchain as devDependencies), or set engine:'mock' to run without a React Native install.`);
745
1074
  if (decision.notice) console.warn(decision.notice);
746
- printEngineBanner(engine, platform, resolvedRoot);
1075
+ if (engine !== "native") printEngineBanner(engine, platform, resolvedRoot);
747
1076
  const env = {
748
1077
  VITEST_NATIVE_PLATFORM: platform,
749
1078
  VITEST_NATIVE_DIAGNOSTICS: String(diagnostics),
750
1079
  VITEST_NATIVE_PROJECT_ROOT: resolvedRoot
751
1080
  };
1081
+ const requireAliases = serializableAliases(userConfig.resolve?.alias, resolvedRoot);
1082
+ if (requireAliases.entries.length > 0) env.VITEST_NATIVE_REQUIRE_ALIASES = JSON.stringify(requireAliases.entries);
1083
+ if (requireAliases.skipped.length > 0) env.VITEST_NATIVE_REQUIRE_ALIASES_SKIPPED = JSON.stringify(requireAliases.skipped);
752
1084
  const reactNativeVersion = resolvePackageVersion("react-native", resolvedRoot);
753
1085
  if (reactNativeVersion) env.VITEST_NATIVE_RN_VERSION = reactNativeVersion;
754
- const assetExtList = [...DEFAULT_ASSET_EXTS, ...(options?.assetExts ?? []).map((e) => e.replace(/^\./, ""))];
755
1086
  env.VITEST_NATIVE_ASSET_EXTS = JSON.stringify(assetExtList);
756
- if (hotRuntime && hotRecycle.preserveGlobals?.length) env.VITEST_NATIVE_HOT_PRESERVE_GLOBALS = JSON.stringify(hotRecycle.preserveGlobals);
757
- if (hotRuntime && hotRecycle.esmGeneration === false) env.VITEST_NATIVE_HOT_ESM_GEN = "0";
1087
+ if (metroOption === true || typeof metroOption === "object") env.VITEST_NATIVE_SOURCE_EXTS = JSON.stringify(sourceExts);
1088
+ if (hotRuntimeRequested && hotRecycle.preserveGlobals?.length) env.VITEST_NATIVE_HOT_PRESERVE_GLOBALS = JSON.stringify(hotRecycle.preserveGlobals);
1089
+ if (hotRuntimeRequested && hotRecycle.esmGeneration === false) env.VITEST_NATIVE_HOT_ESM_GEN = "0";
758
1090
  if (engine === "native") {
759
1091
  if (options?.mocks && Object.keys(options.mocks).length > 0) throw new VitestNativeError("MOCKS_REQUIRE_MOCK_ENGINE", "The \"mocks\" option is only supported by engine:'mock'. The native engine runs the real react-native module and cannot safely merge arbitrary exports into it. Use vi.mock() in a setup file, mockNativeModule() for native modules, or set engine:'mock'.");
760
1092
  const disabledNative = disabledPresetNames(options?.presets);
@@ -766,45 +1098,91 @@ function reactNative(options) {
766
1098
  if (Object.keys(presetConfig).length > 0) env.VITEST_NATIVE_PRESET_CONFIG = JSON.stringify(presetConfig);
767
1099
  }
768
1100
  const includeRoots = testIncludeRoots(userConfig.test?.include, resolvedRoot);
769
- const ecosystem = detectEcosystemPackages([resolvedRoot, ...includeRoots], transformPkgs, includeRoots, neverTransform);
1101
+ const userInline = userConfig.test?.server?.deps?.inline;
1102
+ const userInlinesEverything = userInline === true;
1103
+ const ecosystem = detectEcosystemPackages([resolvedRoot, ...includeRoots], transformPkgs, includeRoots, neverTransform, nativePresetNames);
770
1104
  const linkedDetectedDirs = ecosystem.map((name) => packageDirOf(name, resolvedRoot)).filter((dir) => dir !== null && !/[\\/]node_modules[\\/]/.test(dir));
771
1105
  const projectDirs = [...new Set([resolvedRoot, ...includeRoots].map((dir) => nearestPackageDir(dir)).filter((dir) => dir !== null))].filter((dir) => !linkedDetectedDirs.some((detected) => containsPath(dir, detected)));
772
1106
  if (projectDirs.length > 0) env.VITEST_NATIVE_PROJECT_DIRS = JSON.stringify(projectDirs);
773
- if (ecosystem.length > 0) {
774
- ecosystemRoot = resolvedRoot;
775
- ecosystemPattern = new RegExp(`[\\\\/]node_modules[\\\\/](?:${ecosystem.map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})[\\\\/]`);
776
- if (diagnostics) console.log(`[vitest-native] inlining React Native packages: ${ecosystem.join(", ")}`);
1107
+ nativeOwnership = createNativeOwnershipPolicy({
1108
+ projectRoot: resolvedRoot,
1109
+ explicitTransforms: transformPkgs,
1110
+ ecosystemPackages: ecosystem,
1111
+ runtimeTransformAugmentations: nativePresetNames.length > 0 ? ["preset-pass-through-modules"] : [],
1112
+ projectDirs,
1113
+ serverDepsInlineAll: userInlinesEverything
1114
+ });
1115
+ assertInlineOwnership(userInline);
1116
+ const userTest = userConfig.test;
1117
+ const userPool = userTest?.pool;
1118
+ if (isVmPool(userPool)) throw vmPoolUnsupported(userPool);
1119
+ nativeRoots.add(vitestRootOf(userConfig));
1120
+ let hotMemory;
1121
+ if (hotRuntimeRequested) {
1122
+ const { createHotMemoryPlan, formatHotMemoryPlan, resolveRequestedWorkers } = await import("./memory-FYbP0_gg.mjs").then((n) => n.r);
1123
+ const requestedWorkers = resolveRequestedWorkers(userTest?.maxWorkers, { fileParallelism: userTest?.fileParallelism });
1124
+ const plan = createHotMemoryPlan({ requestedWorkers });
1125
+ const allowUnboundedMemory = hotRecycle.allowUnboundedMemory === true;
1126
+ const configConflict = hotAutoConfigDeclineReason(userPool, userTest?.isolate);
1127
+ if (!hotRuntimeAuto && configConflict !== null) throw hotRuntimeOverridden(configConflict);
1128
+ const autoDeclineReason = hotRuntimeAuto ? configConflict ?? workerVitestMismatchReason(nativeWorkerPath, resolvedRoot) ?? (plan.maxWorkers < 2 ? `the ${plan.source} memory/scheduler plan selects only one unrecyclable worker` : null) : null;
1129
+ if (autoDeclineReason !== null) {
1130
+ if (hotRuntimeExplicit || diagnostics) console.warn(`[vitest-native] hotRuntime:'auto' kept default isolation: ${autoDeclineReason}.`);
1131
+ } else if (!allowUnboundedMemory && plan.maxWorkers < 2) throw new VitestNativeError("HOT_MEMORY_UNBOUNDED", `hotRuntime cannot enforce its memory budget with one worker because Vitest batches every file into one unrecyclable task. The effective ${plan.source} memory ceiling admits ${plan.admittedWorkers} worker, or this config explicitly selects one. Use hotRuntime:false, provide enough memory for at least two workers, or explicitly accept unbounded growth with hotRuntime:{ allowUnboundedMemory:true }.`);
1132
+ if (autoDeclineReason === null && (hotRuntimeExplicit || diagnostics) && !allowUnboundedMemory && userTest?.maxWorkers != null && plan.maxWorkers < requestedWorkers) console.warn(`[vitest-native] hotRuntime capped maxWorkers from ${requestedWorkers} to ${plan.maxWorkers} for the ${plan.source} memory budget. Set diagnostics:true to see the full envelope.`);
1133
+ if (autoDeclineReason === null && diagnostics) {
1134
+ for (const line of formatHotMemoryPlan(plan)) console.log(`[vitest-native] memory: ${line}`);
1135
+ if (allowUnboundedMemory) console.warn("[vitest-native] memory: allowUnboundedMemory:true disables the automatic worker cap and process-RSS enforcement.");
1136
+ }
1137
+ if (autoDeclineReason === null) {
1138
+ env.VITEST_NATIVE_MEMORY_PLAN = JSON.stringify({
1139
+ ...plan,
1140
+ enforced: !allowUnboundedMemory
1141
+ });
1142
+ hotMemory = {
1143
+ plan,
1144
+ memoryLimit: hotRecycle.memoryLimit ?? plan.workerHeapLimit,
1145
+ allowUnboundedMemory
1146
+ };
1147
+ }
777
1148
  }
778
1149
  const registryFile = await buildRegistryFor({
779
1150
  projectRoot: resolvedRoot,
780
1151
  platform,
781
1152
  reactNativeVersion: reactNativeVersion ?? "0.0.0",
782
1153
  assetExts: assetExtList,
1154
+ sourceExts,
783
1155
  diagnostics
784
1156
  });
785
1157
  if (registryFile) env.VITEST_NATIVE_RN_REGISTRY = registryFile;
786
1158
  let hot;
787
- if (hotRuntime) {
788
- const { nativePool, defaultHotMemoryLimit } = await import("./pool-Bcxn9a3I.mjs");
789
- const memoryLimit = hotRecycle.memoryLimit ?? (hotRecycle.recycleAfterFiles == null ? defaultHotMemoryLimit() : void 0);
1159
+ if (hotMemory) {
1160
+ const { nativePool } = await import("./pool-DjpOjOf3.mjs");
790
1161
  hot = {
791
1162
  pool: nativePool({
792
1163
  workerEntry: nativeWorkerPath,
793
1164
  projectRoot: resolvedRoot,
794
1165
  recycleAfterFiles: hotRecycle.recycleAfterFiles,
795
- memoryLimit,
1166
+ memoryLimit: hotMemory.memoryLimit,
1167
+ memoryPlan: hotMemory.plan,
1168
+ allowUnboundedMemory: hotMemory.allowUnboundedMemory,
796
1169
  diagnostics
797
1170
  }),
798
- runnerPath: nativeRunnerPath
1171
+ runnerPath: nativeRunnerPath,
1172
+ maxWorkers: hotMemory.allowUnboundedMemory ? void 0 : hotMemory.plan.maxWorkers
799
1173
  };
800
1174
  }
801
- const userPool = userConfig.test?.pool;
802
- const userInlinesEverything = userConfig.test?.server?.deps?.inline === true;
803
- if (userPool === "vmThreads" || userPool === "vmForks") throw new VitestNativeError("UNSUPPORTED_POOL", `engine:'native' cannot run on the '${userPool}' pool. React Native is loaded through Node's module hooks, which a VM pool's context does not use — React Native fails to resolve its platform files there. Use 'threads' (the default) or 'forks', or switch to engine:'mock', which needs no hooks.`);
804
- if (hot && userPool) console.warn(`[vitest-native] 'hotRuntime' supplies its own pool, overriding the configured pool '${typeof userPool === "string" ? userPool : "(custom)"}'.`);
805
- return asCompatibleViteConfig(nativeEngineConfig(nativeSetupPath, env, extensions, transformPkgs, hot, jsxTransform, userPool, ecosystem, resolvedRoot, userInlinesEverything));
1175
+ printEngineBanner(engine, platform, resolvedRoot, hot !== void 0);
1176
+ if (hot) hotSelections.set(vitestRootOf(userConfig), {
1177
+ pool: hot.pool,
1178
+ userPool,
1179
+ userMaxWorkers: userTest?.maxWorkers,
1180
+ singleWorkerAccepted: hotMemory?.allowUnboundedMemory === true
1181
+ });
1182
+ else hotSelections.delete(vitestRootOf(userConfig));
1183
+ return asCompatibleViteConfig(nativeEngineConfig(nativeSetupPath, env, extensions, transformPkgs, hot, jsxTransform, userPool, ecosystem, resolvedRoot, userInlinesEverything, projectDirs, nativeOwnership));
806
1184
  }
807
- if (hotRuntime) console.warn(`[vitest-native] 'hotRuntime' only applies to engine:'native' (resolved engine: '${engine}'); ignoring.`);
1185
+ if (hotRuntimeRequested && hotRuntimeExplicit) console.warn(`[vitest-native] 'hotRuntime' only applies to engine:'native' (resolved engine: '${engine}'); ignoring.`);
808
1186
  if (options?.mocks && Object.keys(options.mocks).length > 0) env.VITEST_NATIVE_MOCKS = JSON.stringify(options.mocks);
809
1187
  if (Array.isArray(options?.presets)) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(options.presets.map((p) => p.name));
810
1188
  else {
@@ -846,6 +1224,8 @@ function reactNative(options) {
846
1224
  },
847
1225
  async configResolved(config) {
848
1226
  jestMockTransformPresent = (config.plugins ?? []).some((plugin) => plugin?.name === "vitest-native:jest-mock-hoist");
1227
+ const finalInline = config.test?.server?.deps?.inline;
1228
+ assertInlineOwnership(finalInline);
849
1229
  const duplicateReact = findDuplicateReact((specifier, from) => {
850
1230
  try {
851
1231
  return createRequire(path.join(from, "package.json")).resolve(specifier);
@@ -870,7 +1250,10 @@ function reactNative(options) {
870
1250
  const error = validatePeerDependency(name, minimum, config.root, maximumMajor, minimumByMajor);
871
1251
  if (error && !error.includes("not found")) console.warn(`[vitest-native] ${error}`);
872
1252
  }
873
- resolved = await resolveOptions(options, config.root);
1253
+ resolved = await resolveOptions(options, config.root, {
1254
+ extensions,
1255
+ assetExts: assetExtList
1256
+ });
874
1257
  try {
875
1258
  realRnPackageJson = createRequire(path.join(config.root, "package.json")).resolve("react-native/package.json");
876
1259
  } catch {}
@@ -883,8 +1266,10 @@ function reactNative(options) {
883
1266
  rnFacadeRoot = config.root;
884
1267
  try {
885
1268
  const indexPath = createRequire(path.join(config.root, "package.json")).resolve("react-native");
886
- const names = parseReactNativeExports(fs.readFileSync(indexPath, "utf8"));
1269
+ const indexSource = fs.readFileSync(indexPath, "utf8");
1270
+ const names = parseReactNativeExports(indexSource);
887
1271
  rnFacadeExports = names.length > 0 ? names : null;
1272
+ rnFacadeDeprecated = new Set(parseDeprecatedReactNativeExports(indexSource));
888
1273
  } catch {
889
1274
  rnFacadeExports = null;
890
1275
  }
@@ -897,7 +1282,7 @@ function reactNative(options) {
897
1282
  if (source === "react-native" && rnFacadeExports !== null) return "\0virtual:rn-facade";
898
1283
  const presetHit = resolvePresetId(source);
899
1284
  if (presetHit) return presetHit;
900
- return alignedResolution(source, importer);
1285
+ return resolveExtensionless(source, importer) ?? alignedResolution(source, importer);
901
1286
  }
902
1287
  if (source === "react-native") return "\0virtual:react-native";
903
1288
  if (source.startsWith("react-native/")) {
@@ -906,28 +1291,8 @@ function reactNative(options) {
906
1291
  }
907
1292
  const presetId = resolvePresetId(source);
908
1293
  if (presetId) return presetId;
909
- if (importer && importer.includes("node_modules") && source.startsWith(".") && !path.extname(source)) {
910
- const cacheKey = `${importer}\0${source}`;
911
- const cached = resolveCache.get(cacheKey);
912
- if (cached !== void 0) return cached;
913
- const importerDir = path.dirname(importer);
914
- const absolute = path.resolve(importerDir, source);
915
- for (const ext of extensions) {
916
- const candidate = absolute + ext;
917
- if (fs.existsSync(candidate)) {
918
- resolveCache.set(cacheKey, candidate);
919
- return candidate;
920
- }
921
- }
922
- for (const ext of extensions) {
923
- const candidate = path.join(absolute, `index${ext}`);
924
- if (fs.existsSync(candidate)) {
925
- resolveCache.set(cacheKey, candidate);
926
- return candidate;
927
- }
928
- }
929
- resolveCache.set(cacheKey, void 0);
930
- }
1294
+ const extensionless = resolveExtensionless(source, importer);
1295
+ if (extensionless !== void 0) return extensionless;
931
1296
  },
932
1297
  load(id) {
933
1298
  if (id === "\0virtual:rn-facade" && rnFacadeExports !== null) {
@@ -936,8 +1301,17 @@ function reactNative(options) {
936
1301
  const code = [
937
1302
  `import { createRequire } from "node:module";`,
938
1303
  `const _rn = createRequire(${JSON.stringify(path.join(rnFacadeRoot, "package.json"))})("react-native");`,
939
- ...rnFacadeExports.map((n) => `export const ${n} = _rn[${JSON.stringify(n)}];`),
940
- `export default _rn;`
1304
+ ...rnFacadeExports.filter((n) => !rnFacadeDeprecated.has(n)).map((n) => `export const ${n} = _rn[${JSON.stringify(n)}];`),
1305
+ `export default _rn;`,
1306
+ ...rnFacadeDeprecated.size > 0 ? [
1307
+ `for (const name of ${JSON.stringify([...rnFacadeDeprecated])}) {`,
1308
+ ` Object.defineProperty(__vite_ssr_exports__, name, {`,
1309
+ ` enumerable: true,`,
1310
+ ` configurable: true,`,
1311
+ ` get: () => _rn[name],`,
1312
+ ` });`,
1313
+ `}`
1314
+ ] : []
941
1315
  ].join("\n");
942
1316
  virtualCodeCache.set(id, code);
943
1317
  return code;
@@ -1000,17 +1374,10 @@ function reactNative(options) {
1000
1374
  transform(code, id) {
1001
1375
  warnIfJestMockUnhoisted(code, id);
1002
1376
  if (engine === "native") {
1003
- if (!ecosystemPattern || !ecosystemPattern.test(id)) return void 0;
1004
- if (!/\.[cm]?[jt]sx?$/.test(id.split("?")[0])) return void 0;
1005
- try {
1006
- return {
1007
- code: transformEcosystem(id, code, ecosystemRoot, platform),
1008
- map: null
1009
- };
1010
- } catch (error) {
1011
- if (diagnostics) console.warn(`[vitest-native] could not compile inlined ${id} (${error?.message}); serving it untouched.`);
1012
- return;
1013
- }
1377
+ if (!nativeOwnership) return void 0;
1378
+ const conflict = findNativeOwnershipConflict(nativeOwnership, id, "vite");
1379
+ if (!conflict) return void 0;
1380
+ throw new VitestNativeError("MODULE_OWNER_CONFLICT", `Vite attempted to transform '${id}', but the native ownership policy assigns that file to Node (${conflict.decision.reason}). Evaluating it in Vite would create a second module instance with separate state. Remove the inline/noExternal rule that claimed it; Metro-source packages belong in reactNative({ transform: [...] }).`);
1014
1381
  }
1015
1382
  if (!RN_ECOSYSTEM_PATH.test(id) || !id.endsWith(".js")) return void 0;
1016
1383
  if (!code.includes("@flow")) return void 0;
@@ -1026,6 +1393,58 @@ function reactNative(options) {
1026
1393
  }
1027
1394
  }
1028
1395
  };
1396
+ const configHandler = pluginDefinition.config;
1397
+ return {
1398
+ ...pluginDefinition,
1399
+ config: {
1400
+ order: "post",
1401
+ async handler(userConfig, env) {
1402
+ const result = await configHandler.call(this, userConfig, env);
1403
+ pinInlineProjectRoots(userConfig.test, vitestRootOf(userConfig));
1404
+ const test = result?.test;
1405
+ if (Array.isArray(test?.setupFiles) && typeof test.setupFiles[0] === "string") contributedSetup.set(vitestRootOf(userConfig), test.setupFiles[0]);
1406
+ if (test) test.execArgv = [...test.execArgv ?? [], ...EXPORT_RECOVERY_ARGV];
1407
+ if (test) {
1408
+ const viteRoot = userConfig.root ? path.resolve(userConfig.root) : process.cwd();
1409
+ const viteMajor = Number(resolvePackageVersion("vite", viteRoot)?.split(".")[0]);
1410
+ const tsconfigPaths = expoTsconfigPaths(viteRoot, userConfig.resolve?.tsconfigPaths, viteMajor);
1411
+ const config = result;
1412
+ if (tsconfigPaths === "enable") config.resolve = {
1413
+ ...config.resolve,
1414
+ tsconfigPaths: true
1415
+ };
1416
+ else if (tsconfigPaths === "unsupported" && !warnedTsconfigPaths) {
1417
+ warnedTsconfigPaths = true;
1418
+ console.warn(`[vitest-native] This Expo project's tsconfig declares \`paths\`, which Expo's Metro resolves by default, but Vite ${viteMajor} cannot (Vite 8 adds \`resolve.tsconfigPaths\`). Upgrade to Vite 8, or add the vite-tsconfig-paths plugin, so imports such as \`@/…\` resolve in tests.`);
1419
+ }
1420
+ }
1421
+ return result;
1422
+ }
1423
+ },
1424
+ configureVitest({ vitest, project }) {
1425
+ const projectConfig = project.config;
1426
+ const root = projectConfig.root ? path.resolve(projectConfig.root) : process.cwd();
1427
+ const setupFile = contributedSetup.get(root);
1428
+ if (setupFile && !hasSetupFile(projectConfig.setupFiles, setupFile)) throw new VitestNativeError("SHARED_VITE_SERVER", `A Vitest project under ${root} shares a Vite server without vitest-native's test config, so React Native's setup would not run. Give the project a \`root\`, or set \`test.sharedViteServer: false\` in the top-level Vitest config.`);
1429
+ const cli = vitest._cliOptions ?? vitest.config?.cliOptions ?? {};
1430
+ if (nativeRoots.has(root) && isVmPool(cli.pool)) throw vmPoolUnsupported(cli.pool);
1431
+ const selection = hotSelections.get(root);
1432
+ if (!selection) return;
1433
+ const reason = hotOverrideReason(projectConfig, cli, selection.pool, selection.singleWorkerAccepted) ?? sharedGroupConflict(project, vitest.projects ?? [], {
1434
+ maxWorkers: vitest.config?.maxWorkers,
1435
+ watch: vitest.config?.watch
1436
+ });
1437
+ if (reason === null) return;
1438
+ if (!hotRuntimeAuto) throw hotRuntimeOverridden(reason);
1439
+ projectConfig.pool = cli.pool ?? selection.userPool ?? "threads";
1440
+ projectConfig.isolate = cli.isolate ?? true;
1441
+ projectConfig.runner = void 0;
1442
+ if (cli.maxWorkers === void 0 && !process.env.VITEST_MAX_WORKERS) projectConfig.maxWorkers = projectConfig.fileParallelism === false ? 1 : selection.userMaxWorkers === void 0 && vitest.config !== projectConfig ? void 0 : vitestMaxWorkers(selection.userMaxWorkers, vitest.config?.watch === true);
1443
+ if (projectConfig.env) delete projectConfig.env.VITEST_NATIVE_MEMORY_PLAN;
1444
+ hotSelections.delete(root);
1445
+ console.error(`[vitest-native] hot runtime off: ${reason}; Vitest's settings apply.`);
1446
+ }
1447
+ };
1029
1448
  }
1030
1449
  //#endregion
1031
1450
  export { disabledPresetNames, presets_exports as presets, reactNative };