vitest-native 0.12.0 → 0.14.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +343 -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 +51 -3
  11. package/dist/helpers.d.cts +14 -8
  12. package/dist/helpers.d.mts +14 -8
  13. package/dist/helpers.mjs +51 -4
  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 +436 -95
  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 +154 -7
  35. package/dist/native/hooks.mjs +133 -62
  36. package/dist/native/loader.mjs +52 -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 +148 -29
  47. package/dist/native/reset.mjs +305 -135
  48. package/dist/native/resolve.d.mts +14 -3
  49. package/dist/native/resolve.mjs +51 -8
  50. package/dist/native/rntl-hooks.mjs +76 -0
  51. package/dist/native/setup.mjs +82 -33
  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 +21 -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-CwO_c4aL.cjs → presets-BYHmi7-W.cjs} +125 -20
  59. package/dist/{presets-IStcJEOa.mjs → presets-DC-eM5IA.mjs} +125 -20
  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 +86 -51
  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 +5 -5
  73. package/docs/release-readiness.md +39 -13
  74. package/docs/versioning.md +19 -18
  75. package/package.json +43 -32
  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-IStcJEOa.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,10 +42,10 @@ 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
  }
49
51
  //#endregion
@@ -60,23 +62,62 @@ const PLATFORM_EXTENSIONS_ANDROID = extensionsFor("android");
60
62
  function getPlatformExtensions(platform) {
61
63
  return platform === "ios" ? PLATFORM_EXTENSIONS_IOS : PLATFORM_EXTENSIONS_ANDROID;
62
64
  }
65
+ /** Build the shared Vite/Node candidate order for a resolved Metro profile. */
66
+ function getConfiguredPlatformExtensions(platform, sourceExts) {
67
+ return extensionsFor(platform, sourceExts);
68
+ }
63
69
  //#endregion
64
- //#region src/native/apply.ts
70
+ //#region src/jest-compat/aliases.mjs
65
71
  /**
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.
72
+ * The string-to-string entries of a Vite `resolve.alias`, in either of its shapes, with
73
+ * relative replacements made absolute against `root`. Regex `find`s and custom
74
+ * resolvers cannot cross into the test worker, so they are listed as `skipped` for the
75
+ * error that explains a miss.
68
76
  *
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.
77
+ * @param {unknown} alias `resolve.alias`: an object, or an array of `{ find, replacement }`
78
+ * @param {string} root project root, for relative replacements
79
+ * @returns {{ entries: [string, string][], skipped: string[] }}
72
80
  */
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])];
81
+ function serializableAliases(alias, root) {
82
+ const entries = [];
83
+ const skipped = [];
84
+ const list = Array.isArray(alias) ? alias : alias && typeof alias === "object" ? Object.entries(alias).map(([find, replacement]) => ({
85
+ find,
86
+ replacement
87
+ })) : [];
88
+ for (const item of list) {
89
+ const find = item?.find;
90
+ const replacement = item?.replacement;
91
+ if (typeof find !== "string" || typeof replacement !== "string" || item.customResolver) {
92
+ skipped.push(String(find));
93
+ continue;
94
+ }
95
+ entries.push([find, replacement.startsWith(".") ? path.resolve(root, replacement) : replacement]);
96
+ }
97
+ return {
98
+ entries,
99
+ skipped
100
+ };
101
+ }
102
+ //#endregion
103
+ //#region src/native/apply.ts
104
+ function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [], hot, jsxTransform = { esbuild: { jsx: "automatic" } }, userPool, inlinePkgs = [], projectRoot = process.cwd(), userInlinesEverything = false, projectDirs = [], ownershipPolicy) {
105
+ const ownership = ownershipPolicy ?? createNativeOwnershipPolicy({
106
+ projectRoot,
107
+ explicitTransforms: transformPkgs,
108
+ ecosystemPackages: inlinePkgs,
109
+ projectDirs,
110
+ serverDepsInlineAll: userInlinesEverything
111
+ });
112
+ const nodeTransformed = ownership.nodeTransformPackages;
79
113
  const fullEnv = { ...env };
114
+ const ownershipManifest = ownership.manifest();
115
+ fullEnv.VITEST_NATIVE_OWNERSHIP = JSON.stringify(ownershipManifest);
116
+ if (fullEnv.VITEST_NATIVE_DIAGNOSTICS === "true") for (const line of formatNativeOwnershipManifest(ownershipManifest)) {
117
+ const report = `[vitest-native] ownership: ${line}`;
118
+ if (line.startsWith("WARNING:")) console.warn(report);
119
+ else console.log(report);
120
+ }
80
121
  if (nodeTransformed.length > 0) fullEnv.VITEST_NATIVE_TRANSFORM = JSON.stringify(nodeTransformed);
81
122
  return {
82
123
  ...jsxTransform,
@@ -111,15 +152,12 @@ function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [],
111
152
  ...hot ? {
112
153
  pool: hot.pool,
113
154
  isolate: false,
114
- runner: hot.runnerPath
155
+ runner: hot.runnerPath,
156
+ ...hot.maxWorkers == null ? {} : { maxWorkers: hot.maxWorkers }
115
157
  } : { pool: userPool ?? "threads" },
116
158
  server: { deps: {
117
- ...userInlinesEverything ? {} : { inline: TEST_ENTRY_PATTERNS },
118
- external: [
119
- REACT_NATIVE_PATH,
120
- ...extraExternal,
121
- ...ecosystemExternal
122
- ]
159
+ ...userInlinesEverything ? {} : { inline: ownership.testEntryPatterns },
160
+ external: ownership.externalPatterns
123
161
  } }
124
162
  }
125
163
  };
@@ -149,6 +187,22 @@ const DEFAULT_ASSET_EXTS = [
149
187
  "woff",
150
188
  "woff2"
151
189
  ];
190
+ function uniqueExtensions(values) {
191
+ const seen = /* @__PURE__ */ new Set();
192
+ const result = [];
193
+ for (const value of values) {
194
+ const extension = value.replace(/^\./, "").toLowerCase();
195
+ if (extension && !seen.has(extension)) {
196
+ seen.add(extension);
197
+ result.push(extension);
198
+ }
199
+ }
200
+ return result;
201
+ }
202
+ function assetExtensionsFor(sourceExts, metroAssets, user) {
203
+ const sources = new Set(sourceExts.map((extension) => extension.toLowerCase()));
204
+ return uniqueExtensions([...uniqueExtensions(metroAssets).filter((extension) => !sources.has(extension)), ...user]);
205
+ }
152
206
  /** Strip Vite's /@fs/ prefix to get a real filesystem path. */
153
207
  function stripFsPrefix(id) {
154
208
  return id.startsWith("/@fs/") ? id.slice(4) : id;
@@ -267,13 +321,14 @@ function resolvePackageVersion(packageName, projectRoot) {
267
321
  * Written to stderr: this is the plugin's only unconditional output, and stdout
268
322
  * must stay parseable for pipelines like `vitest --reporter=json > results.json`.
269
323
  */
270
- function printEngineBanner(engine, platform, projectRoot) {
324
+ function printEngineBanner(engine, platform, projectRoot, hotRuntime = false) {
271
325
  const g = globalThis;
272
326
  if (g.__vitest_native_banner_printed) return;
273
327
  g.__vitest_native_banner_printed = true;
274
328
  if (engine === "native") {
275
329
  const rn = resolvePackageVersion("react-native", projectRoot);
276
- console.error(`[vitest-native] engine: native — real react-native${rn ? `@${rn}` : ""} (platform ${platform})`);
330
+ const runtime = hotRuntime ? ", hot runtime" : "";
331
+ console.error(`[vitest-native] engine: native — real react-native${rn ? `@${rn}` : ""} (platform ${platform}${runtime})`);
277
332
  } else console.error(`[vitest-native] engine: mock — React Native reimplementation, cross-checked against real RN (platform ${platform})`);
278
333
  }
279
334
  function getJsxTransformConfig(projectRoot) {
@@ -297,15 +352,37 @@ function getJsxTransformConfig(projectRoot) {
297
352
  * real module in the native suite, across every React Native version in CI.
298
353
  */
299
354
  function parseReactNativeExports(indexSource) {
355
+ return parseReactNativeMembers(indexSource).map((member) => member.name);
356
+ }
357
+ /**
358
+ * The members of React Native's index that announce their own deprecation.
359
+ *
360
+ * React Native marks a deprecated or extracted export by calling `warnOnce` inside
361
+ * its getter, so reading the member is what prints the notice. The facade must not
362
+ * read these while it initialises, or every file that imports `Pressable` prints
363
+ * notices for `SafeAreaView`, `Clipboard` and the rest; it exposes them as getters
364
+ * instead, and the notice appears only where a test really uses one.
365
+ */
366
+ function parseDeprecatedReactNativeExports(indexSource) {
367
+ return parseReactNativeMembers(indexSource).filter((member) => member.deprecated).map((member) => member.name);
368
+ }
369
+ function parseReactNativeMembers(indexSource) {
300
370
  const start = indexSource.indexOf("module.exports = {");
301
371
  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)) {
372
+ const end = indexSource.slice(start).search(/^\}/m);
373
+ const body = end === -1 ? indexSource.slice(start) : indexSource.slice(start, start + end);
374
+ const matches = [...body.matchAll(/^ {2}(?:get\s+)?([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*[(:,]/gm)];
375
+ const members = /* @__PURE__ */ new Map();
376
+ matches.forEach((match, i) => {
305
377
  const name = match[1];
306
- if (name !== "default" && name !== "__esModule" && name !== "get") names.add(name);
307
- }
308
- return [...names];
378
+ if (name === "default" || name === "__esModule" || name === "get") return;
379
+ const text = body.slice(match.index, matches[i + 1]?.index ?? body.length);
380
+ members.set(name, (members.get(name) ?? false) || /\bwarnOnce\s*\(/.test(text));
381
+ });
382
+ return [...members].map(([name, deprecated]) => ({
383
+ name,
384
+ deprecated
385
+ }));
309
386
  }
310
387
  /**
311
388
  * Build (or reuse) the precompiled React Native registry for a project.
@@ -319,27 +396,21 @@ function parseReactNativeExports(indexSource) {
319
396
  async function buildRegistryFor(options) {
320
397
  try {
321
398
  const dir = path.dirname(fileURLToPath(import.meta.url));
322
- return (await import(pathToFileURL(path.resolve(dir, "native/registry.mjs")).href)).buildRegistry(options);
399
+ return (await import(pathToFileURL(path.resolve(dir, "native/registry-process.mjs")).href)).buildRegistryFor(options);
323
400
  } catch (error) {
324
- if (options.diagnostics) console.warn(`[vitest-native] could not precompile the React Native registry (${error?.message}); using per-file module loading.`);
401
+ try {
402
+ const dir = path.dirname(fileURLToPath(import.meta.url));
403
+ (await import(pathToFileURL(path.resolve(dir, "native/registry.mjs")).href))._warnRegistryUnavailable(error?.message ?? error);
404
+ } catch {
405
+ console.warn(`[vitest-native] (native) could not precompile the React Native registry (${error?.message ?? error}); using slower per-file module loading.`);
406
+ }
325
407
  return null;
326
408
  }
327
409
  }
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);
410
+ /** Load declarative Metro data without retaining Metro/Expo in Vite's process. */
411
+ async function loadProjectMetroProfile(options) {
412
+ const dir = path.dirname(fileURLToPath(import.meta.url));
413
+ return (await import(pathToFileURL(path.resolve(dir, "native/metro-profile.mjs")).href)).loadMetroProfile(options);
343
414
  }
344
415
  /**
345
416
  * Vite 6/7 and Vite 8 expose mutually exclusive JSX config types:
@@ -369,11 +440,14 @@ function autoDetectPresetNames(projectRoot, diagnostics) {
369
440
  }
370
441
  return [...names];
371
442
  }
372
- async function resolveOptions(options = {}, projectRoot) {
443
+ /**
444
+ * `resolution` is the extension profile the plugin already settled on — Metro's when
445
+ * metroConfig is on, the built-in one otherwise — so it is computed in one place.
446
+ */
447
+ async function resolveOptions(options = {}, projectRoot, resolution) {
373
448
  const platform = options.platform ?? "ios";
374
449
  const diagnostics = options.diagnostics ?? false;
375
450
  const engine = options.engine === "native" ? "native" : "mock";
376
- const userExts = (options.assetExts ?? []).map((e) => e.replace(/^\./, ""));
377
451
  let presets;
378
452
  if (Array.isArray(options.presets)) presets = options.presets;
379
453
  else {
@@ -385,10 +459,10 @@ async function resolveOptions(options = {}, projectRoot) {
385
459
  platform,
386
460
  engine,
387
461
  diagnostics,
388
- extensions: getPlatformExtensions(platform),
462
+ extensions: resolution.extensions,
389
463
  presets,
390
464
  mocks: options.mocks ?? {},
391
- assetExts: [...DEFAULT_ASSET_EXTS, ...userExts]
465
+ assetExts: resolution.assetExts
392
466
  };
393
467
  }
394
468
  /**
@@ -427,6 +501,7 @@ const RN_EXPORT_NAMES = [
427
501
  "Alert",
428
502
  "Linking",
429
503
  "AppState",
504
+ "AssetRegistry",
430
505
  "Keyboard",
431
506
  "BackHandler",
432
507
  "Vibration",
@@ -609,8 +684,9 @@ const FORMAT_ONLY_FIELDS = [
609
684
  * cannot parse at all. Aligning upward would turn a wrong-value bug into a crash for
610
685
  * any package the engine does not also transform.
611
686
  *
612
- * Packages the engine inlines and transforms are left alone: Vite is meant to own
613
- * their source, and rewriting them to `main` would undo the reason they are inlined.
687
+ * Packages the engine itself virtualizes are left alone. Node-owned ecosystem
688
+ * packages are intentionally not exempt: if Vite also reaches one, aligning a
689
+ * format-only field to Node's file prevents a silent second instance.
614
690
  *
615
691
  * @returns the absolute file to use, or null to leave resolution alone
616
692
  */
@@ -645,8 +721,134 @@ function disabledPresetNames(presets) {
645
721
  if (!presets || Array.isArray(presets) || typeof presets !== "object") return /* @__PURE__ */ new Set();
646
722
  return new Set(Object.entries(presets).filter(([, enabled]) => enabled === false).map(([name]) => name));
647
723
  }
724
+ /**
725
+ * Config-time reasons that make automatic hot selection unsafe. Suites migrated from
726
+ * Jest (jestMockTransform(), the jest-compat setup) are not among them: the jest-compat
727
+ * surface has its own cross-file isolation gate under hot (tests-native/hot-jest-compat)
728
+ * and the hot runtime resets before user setup files run (tests-native/hot-user-setup).
729
+ */
730
+ function hotAutoConfigDeclineReason(userPool, userIsolate) {
731
+ if (userIsolate !== void 0) return `test.isolate is explicitly ${String(userIsolate)}`;
732
+ if (userPool != null) return `${typeof userPool === "string" ? `'${userPool}'` : "a custom pool"} is explicitly configured`;
733
+ return null;
734
+ }
735
+ /**
736
+ * Why the resolved Vitest config overrides a hot runtime chosen at config time, or
737
+ * null. Vitest 4 applies CLI flags after plugins' config hooks, so `--maxWorkers=1`,
738
+ * `--no-file-parallelism`, `--pool` and `--isolate`/`--no-isolate` arrive only in the
739
+ * resolved config. `--no-isolate` sets the same `isolate: false` the hot runtime uses,
740
+ * so it is read from the CLI options themselves.
741
+ */
742
+ function hotOverrideReason(resolved, cli, hotPool, singleWorkerAccepted = false) {
743
+ if (cli.isolate !== void 0) return `--${cli.isolate ? "" : "no-"}isolate was passed`;
744
+ const poolName = (pool) => typeof pool === "string" ? pool : pool !== null && typeof pool === "object" ? pool.name : void 0;
745
+ 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`;
746
+ if (singleWorkerAccepted) return null;
747
+ if (resolved.fileParallelism === false) return "file parallelism is off";
748
+ if (typeof resolved.maxWorkers === "number" && resolved.maxWorkers < 2) return `maxWorkers is ${resolved.maxWorkers}`;
749
+ return null;
750
+ }
751
+ /**
752
+ * The root Vitest gives a project: `test.root` over Vite's `root` (Vitest 4 and 5's
753
+ * resolveConfig). `vitest --root` arrives as `test.root`. Per-project state is keyed
754
+ * by it, since that is the root configureVitest sees.
755
+ */
756
+ function vitestRootOf(config) {
757
+ const testRoot = config.test?.root;
758
+ const root = typeof testRoot === "string" && testRoot ? testRoot : config.root;
759
+ return path.resolve(typeof root === "string" && root ? root : process.cwd());
760
+ }
761
+ /**
762
+ * Pin each inline project's `root` to the root it would inherit anyway, so Vitest 5
763
+ * resolves it through the config file with this plugin instead of sharing the
764
+ * declaring config's Vite server. A server-sharing project gets its `test` options
765
+ * from the user's raw config, captured before any plugin's config hook runs, so it
766
+ * would miss everything this plugin contributes to `test` — setup files, dependency
767
+ * ownership, env, the hot pool. Vitest shares a server only when an entry sets no
768
+ * Vite-level option; `root` is one, and pinning it to the inherited value changes
769
+ * nothing else. Unlike `sharedViteServer: false`, which Vitest reads from the
770
+ * top-level config alone, this works in a nested config too. Vitest 4 resolves every
771
+ * inline project through the config file already. Returns how many were pinned.
772
+ */
773
+ function pinInlineProjectRoots(test, declaringRoot) {
774
+ const projects = test?.projects;
775
+ if (!Array.isArray(projects)) return 0;
776
+ let pinned = 0;
777
+ for (const entry of projects) {
778
+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) continue;
779
+ const project = entry;
780
+ if (project.root !== void 0) continue;
781
+ project.root = declaringRoot;
782
+ pinned++;
783
+ }
784
+ return pinned;
785
+ }
786
+ function hasSetupFile(setupFiles, file) {
787
+ const real = (f) => {
788
+ try {
789
+ return fs.realpathSync(f);
790
+ } catch {
791
+ return path.resolve(f);
792
+ }
793
+ };
794
+ const wanted = real(file);
795
+ return Array.isArray(setupFiles) && setupFiles.some((f) => typeof f === "string" && real(f) === wanted);
796
+ }
797
+ /**
798
+ * Why this project's worker count cannot coexist with another project's, or null.
799
+ * Vitest schedules projects that share a `sequence.groupOrder` (0 unless set) as one
800
+ * group, and throws when they resolve to different `maxWorkers` ("Projects … have
801
+ * different 'maxWorkers' but same 'sequence.groupOrder'", groupSpecs in Vitest 4 and
802
+ * 5). The hot runtime's memory plan caps workers (at most four), while a project
803
+ * beside it gets Vitest's default of one fewer than the CPUs, so a native project next
804
+ * to a mock or non-React-Native project failed on any machine with more than five
805
+ * cores. Mirrors Vitest's resolveMaxWorkers and its grouping, including the exemption
806
+ * for a single-worker isolated project in the default group.
807
+ */
808
+ function sharedGroupConflict(self, others, root, cpus) {
809
+ const order = (p) => Number(p.config.sequence?.groupOrder ?? 0);
810
+ const workers = (p) => p.config.maxWorkers || root.maxWorkers || vitestMaxWorkers(void 0, root.watch === true, cpus);
811
+ const ownGroup = (p) => p.config.isolate === true && order(p) === 0 && p.config.maxWorkers === 1;
812
+ for (const other of others) {
813
+ if (other === self || ownGroup(other) || order(other) !== order(self)) continue;
814
+ 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)`;
815
+ }
816
+ return null;
817
+ }
818
+ function isVmPool(pool) {
819
+ return pool === "vmThreads" || pool === "vmForks";
820
+ }
821
+ function vmPoolUnsupported(pool) {
822
+ 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.`);
823
+ }
824
+ function hotRuntimeOverridden(reason) {
825
+ 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.`);
826
+ }
827
+ /**
828
+ * The worker count Vitest would have used had the hot runtime not capped it: the
829
+ * user's own value (a count or a percentage of the CPUs), else Vitest's default.
830
+ * Mirrors Vitest 4/5's resolveMaxWorkers and getWorkersCountByPercentage.
831
+ */
832
+ function vitestMaxWorkers(userValue, watch, cpus = os.availableParallelism?.() ?? os.cpus().length) {
833
+ if (typeof userValue === "number" && userValue > 0) return userValue;
834
+ if (typeof userValue === "string") {
835
+ const percent = /^(\d+)%$/.exec(userValue.trim());
836
+ if (percent) return Math.max(1, Math.min(cpus, Math.round(Number(percent[1]) / 100 * cpus)));
837
+ const count = Number.parseInt(userValue, 10);
838
+ if (count > 0) return count;
839
+ }
840
+ return watch ? Math.max(Math.floor(cpus / 2), 1) : Math.max(cpus - 1, 1);
841
+ }
842
+ /** Why hot cannot run here because its worker would load a different Vitest, or null. */
843
+ function workerVitestMismatchReason(workerEntry, projectRoot) {
844
+ const mismatch = workerVitestMismatch(workerEntry, projectRoot);
845
+ return mismatch ? `its worker would load vitest@${mismatch.worker.version} while this run uses vitest@${mismatch.project.version}` : null;
846
+ }
648
847
  function reactNative(options) {
649
848
  let jestMockTransformPresent = true;
849
+ const hotSelections = /* @__PURE__ */ new Map();
850
+ const nativeRoots = /* @__PURE__ */ new Set();
851
+ const contributedSetup = /* @__PURE__ */ new Map();
650
852
  let warnedMissingJestMockTransform = false;
651
853
  const warnIfJestMockUnhoisted = (code, id) => {
652
854
  if (jestMockTransformPresent || warnedMissingJestMockTransform) return;
@@ -665,10 +867,17 @@ function reactNative(options) {
665
867
  let assetPattern;
666
868
  let realRnPackageJson;
667
869
  let rnFacadeExports = null;
870
+ let rnFacadeDeprecated = /* @__PURE__ */ new Set();
668
871
  let rnFacadeRoot = "";
669
- let ecosystemPattern = null;
872
+ let nativeOwnership = null;
873
+ const assertInlineOwnership = (inline) => {
874
+ if (engine !== "native" || !nativeOwnership) return;
875
+ const conflicts = findNativeInlineConflicts(nativeOwnership, inline);
876
+ if (conflicts.length === 0) return;
877
+ const selection = conflicts.includes("*") ? "server.deps.inline:true" : `server.deps.inline overlaps Node-owned package${conflicts.length === 1 ? "" : "s"}: ${conflicts.join(", ")}`;
878
+ 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.`);
879
+ };
670
880
  let alignRoot = "";
671
- let ecosystemRoot = "";
672
881
  const alignedCache = /* @__PURE__ */ new Map();
673
882
  const alignedResolution = (source, importer) => {
674
883
  if (engine !== "native") return void 0;
@@ -713,17 +922,28 @@ function reactNative(options) {
713
922
  if (fs.existsSync(srcPath)) setupFilePath = srcPath;
714
923
  }
715
924
  const nativeSetupPath = path.resolve(thisDir, "native/setup.mjs");
925
+ const EXPORT_RECOVERY_ARGV = ["--import", pathToFileURL(path.resolve(thisDir, "native/export-condition-recovery-preload.mjs")).href];
716
926
  const nativeWorkerPath = path.resolve(thisDir, "native/worker.mjs");
717
927
  const nativeRunnerPath = path.resolve(thisDir, "native/runner.mjs");
718
928
  const platform = options?.platform ?? "ios";
719
929
  const diagnostics = options?.diagnostics ?? false;
720
930
  const requestedEngine = options?.engine ?? "auto";
721
931
  const { include: transformPkgs, exclude: neverTransform } = normalizeTransformOption(options?.transform);
722
- const hotRuntimeOpt = options?.hotRuntime ?? false;
723
- const hotRuntime = hotRuntimeOpt !== false;
932
+ const hotRuntimeExplicit = options?.hotRuntime !== void 0;
933
+ const hotRuntimeOpt = options?.hotRuntime ?? "auto";
934
+ const hotRuntimeRequested = hotRuntimeOpt !== false;
935
+ const hotRuntimeAuto = hotRuntimeOpt === "auto";
724
936
  const hotRecycle = typeof hotRuntimeOpt === "object" ? hotRuntimeOpt : {};
725
937
  let engine = requestedEngine === "native" ? "native" : "mock";
726
- const extensions = getPlatformExtensions(platform);
938
+ let sourceExts = [
939
+ "js",
940
+ "jsx",
941
+ "json",
942
+ "ts",
943
+ "tsx"
944
+ ];
945
+ let extensions = getPlatformExtensions(platform);
946
+ let assetExtList = assetExtensionsFor(sourceExts, DEFAULT_ASSET_EXTS, options?.assetExts ?? []);
727
947
  const resolvePresetId = (source) => {
728
948
  if (presetModules.has(source)) return `\0virtual:preset:${source}`;
729
949
  if (!assetPattern) return void 0;
@@ -731,29 +951,57 @@ function reactNative(options) {
731
951
  const pkg = packageNameOf(source);
732
952
  if (pkg !== source && presetModules.has(pkg)) return `\0virtual:preset:${source}`;
733
953
  };
734
- return {
954
+ const pluginDefinition = {
735
955
  name: "vitest-native",
736
956
  enforce: "pre",
737
957
  async config(userConfig, _env) {
738
958
  const resolvedRoot = userConfig.root ? path.resolve(userConfig.root) : process.cwd();
739
959
  alignRoot = resolvedRoot;
960
+ const metroOption = options?.metroConfig;
961
+ if (metroOption === true || typeof metroOption === "object") {
962
+ const metroSettings = typeof metroOption === "object" ? metroOption : {};
963
+ let metro;
964
+ try {
965
+ metro = await loadProjectMetroProfile({
966
+ projectRoot: resolvedRoot,
967
+ platform,
968
+ configFile: metroSettings.configFile
969
+ });
970
+ } catch (error) {
971
+ const code = error?.code;
972
+ if (code !== void 0 && code !== "METRO_CONFIG_LOAD_FAILED") throw error;
973
+ 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 });
974
+ }
975
+ 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.");
976
+ sourceExts = [...metro.profile.sourceExts];
977
+ extensions = getConfiguredPlatformExtensions(platform, sourceExts);
978
+ assetExtList = assetExtensionsFor(sourceExts, metro.profile.assetExts, options?.assetExts ?? []);
979
+ if (diagnostics) {
980
+ const childRss = metro.evidence.rss ? `, child RSS ${Math.ceil(metro.evidence.rss / 1024 / 1024)} MiB` : "";
981
+ 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}.`);
982
+ 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.`);
983
+ }
984
+ }
740
985
  const jsxTransform = getJsxTransformConfig(resolvedRoot);
741
986
  const decision = detectEngine(requestedEngine, resolvedRoot);
742
987
  engine = decision.engine;
743
988
  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.`);
744
989
  if (decision.notice) console.warn(decision.notice);
745
- printEngineBanner(engine, platform, resolvedRoot);
990
+ if (engine !== "native") printEngineBanner(engine, platform, resolvedRoot);
746
991
  const env = {
747
992
  VITEST_NATIVE_PLATFORM: platform,
748
993
  VITEST_NATIVE_DIAGNOSTICS: String(diagnostics),
749
994
  VITEST_NATIVE_PROJECT_ROOT: resolvedRoot
750
995
  };
996
+ const requireAliases = serializableAliases(userConfig.resolve?.alias, resolvedRoot);
997
+ if (requireAliases.entries.length > 0) env.VITEST_NATIVE_REQUIRE_ALIASES = JSON.stringify(requireAliases.entries);
998
+ if (requireAliases.skipped.length > 0) env.VITEST_NATIVE_REQUIRE_ALIASES_SKIPPED = JSON.stringify(requireAliases.skipped);
751
999
  const reactNativeVersion = resolvePackageVersion("react-native", resolvedRoot);
752
1000
  if (reactNativeVersion) env.VITEST_NATIVE_RN_VERSION = reactNativeVersion;
753
- const assetExtList = [...DEFAULT_ASSET_EXTS, ...(options?.assetExts ?? []).map((e) => e.replace(/^\./, ""))];
754
1001
  env.VITEST_NATIVE_ASSET_EXTS = JSON.stringify(assetExtList);
755
- if (hotRuntime && hotRecycle.preserveGlobals?.length) env.VITEST_NATIVE_HOT_PRESERVE_GLOBALS = JSON.stringify(hotRecycle.preserveGlobals);
756
- if (hotRuntime && hotRecycle.esmGeneration === false) env.VITEST_NATIVE_HOT_ESM_GEN = "0";
1002
+ if (metroOption === true || typeof metroOption === "object") env.VITEST_NATIVE_SOURCE_EXTS = JSON.stringify(sourceExts);
1003
+ if (hotRuntimeRequested && hotRecycle.preserveGlobals?.length) env.VITEST_NATIVE_HOT_PRESERVE_GLOBALS = JSON.stringify(hotRecycle.preserveGlobals);
1004
+ if (hotRuntimeRequested && hotRecycle.esmGeneration === false) env.VITEST_NATIVE_HOT_ESM_GEN = "0";
757
1005
  if (engine === "native") {
758
1006
  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'.");
759
1007
  const disabledNative = disabledPresetNames(options?.presets);
@@ -765,45 +1013,91 @@ function reactNative(options) {
765
1013
  if (Object.keys(presetConfig).length > 0) env.VITEST_NATIVE_PRESET_CONFIG = JSON.stringify(presetConfig);
766
1014
  }
767
1015
  const includeRoots = testIncludeRoots(userConfig.test?.include, resolvedRoot);
768
- const ecosystem = detectEcosystemPackages([resolvedRoot, ...includeRoots], transformPkgs, includeRoots, neverTransform);
1016
+ const userInline = userConfig.test?.server?.deps?.inline;
1017
+ const userInlinesEverything = userInline === true;
1018
+ const ecosystem = detectEcosystemPackages([resolvedRoot, ...includeRoots], transformPkgs, includeRoots, neverTransform, nativePresetNames);
769
1019
  const linkedDetectedDirs = ecosystem.map((name) => packageDirOf(name, resolvedRoot)).filter((dir) => dir !== null && !/[\\/]node_modules[\\/]/.test(dir));
770
1020
  const projectDirs = [...new Set([resolvedRoot, ...includeRoots].map((dir) => nearestPackageDir(dir)).filter((dir) => dir !== null))].filter((dir) => !linkedDetectedDirs.some((detected) => containsPath(dir, detected)));
771
1021
  if (projectDirs.length > 0) env.VITEST_NATIVE_PROJECT_DIRS = JSON.stringify(projectDirs);
772
- if (ecosystem.length > 0) {
773
- ecosystemRoot = resolvedRoot;
774
- ecosystemPattern = new RegExp(`[\\\\/]node_modules[\\\\/](?:${ecosystem.map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})[\\\\/]`);
775
- if (diagnostics) console.log(`[vitest-native] inlining React Native packages: ${ecosystem.join(", ")}`);
1022
+ nativeOwnership = createNativeOwnershipPolicy({
1023
+ projectRoot: resolvedRoot,
1024
+ explicitTransforms: transformPkgs,
1025
+ ecosystemPackages: ecosystem,
1026
+ runtimeTransformAugmentations: nativePresetNames.length > 0 ? ["preset-pass-through-modules"] : [],
1027
+ projectDirs,
1028
+ serverDepsInlineAll: userInlinesEverything
1029
+ });
1030
+ assertInlineOwnership(userInline);
1031
+ const userTest = userConfig.test;
1032
+ const userPool = userTest?.pool;
1033
+ if (isVmPool(userPool)) throw vmPoolUnsupported(userPool);
1034
+ nativeRoots.add(vitestRootOf(userConfig));
1035
+ let hotMemory;
1036
+ if (hotRuntimeRequested) {
1037
+ const { createHotMemoryPlan, formatHotMemoryPlan, resolveRequestedWorkers } = await import("./memory-FYbP0_gg.mjs").then((n) => n.r);
1038
+ const requestedWorkers = resolveRequestedWorkers(userTest?.maxWorkers, { fileParallelism: userTest?.fileParallelism });
1039
+ const plan = createHotMemoryPlan({ requestedWorkers });
1040
+ const allowUnboundedMemory = hotRecycle.allowUnboundedMemory === true;
1041
+ const configConflict = hotAutoConfigDeclineReason(userPool, userTest?.isolate);
1042
+ if (!hotRuntimeAuto && configConflict !== null) throw hotRuntimeOverridden(configConflict);
1043
+ const autoDeclineReason = hotRuntimeAuto ? configConflict ?? workerVitestMismatchReason(nativeWorkerPath, resolvedRoot) ?? (plan.maxWorkers < 2 ? `the ${plan.source} memory/scheduler plan selects only one unrecyclable worker` : null) : null;
1044
+ if (autoDeclineReason !== null) {
1045
+ if (hotRuntimeExplicit || diagnostics) console.warn(`[vitest-native] hotRuntime:'auto' kept default isolation: ${autoDeclineReason}.`);
1046
+ } 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 }.`);
1047
+ 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.`);
1048
+ if (autoDeclineReason === null && diagnostics) {
1049
+ for (const line of formatHotMemoryPlan(plan)) console.log(`[vitest-native] memory: ${line}`);
1050
+ if (allowUnboundedMemory) console.warn("[vitest-native] memory: allowUnboundedMemory:true disables the automatic worker cap and process-RSS enforcement.");
1051
+ }
1052
+ if (autoDeclineReason === null) {
1053
+ env.VITEST_NATIVE_MEMORY_PLAN = JSON.stringify({
1054
+ ...plan,
1055
+ enforced: !allowUnboundedMemory
1056
+ });
1057
+ hotMemory = {
1058
+ plan,
1059
+ memoryLimit: hotRecycle.memoryLimit ?? plan.workerHeapLimit,
1060
+ allowUnboundedMemory
1061
+ };
1062
+ }
776
1063
  }
777
1064
  const registryFile = await buildRegistryFor({
778
1065
  projectRoot: resolvedRoot,
779
1066
  platform,
780
1067
  reactNativeVersion: reactNativeVersion ?? "0.0.0",
781
1068
  assetExts: assetExtList,
1069
+ sourceExts,
782
1070
  diagnostics
783
1071
  });
784
1072
  if (registryFile) env.VITEST_NATIVE_RN_REGISTRY = registryFile;
785
1073
  let hot;
786
- if (hotRuntime) {
787
- const { nativePool, defaultHotMemoryLimit } = await import("./pool-Bcxn9a3I.mjs");
788
- const memoryLimit = hotRecycle.memoryLimit ?? (hotRecycle.recycleAfterFiles == null ? defaultHotMemoryLimit() : void 0);
1074
+ if (hotMemory) {
1075
+ const { nativePool } = await import("./pool-DjpOjOf3.mjs");
789
1076
  hot = {
790
1077
  pool: nativePool({
791
1078
  workerEntry: nativeWorkerPath,
792
1079
  projectRoot: resolvedRoot,
793
1080
  recycleAfterFiles: hotRecycle.recycleAfterFiles,
794
- memoryLimit,
1081
+ memoryLimit: hotMemory.memoryLimit,
1082
+ memoryPlan: hotMemory.plan,
1083
+ allowUnboundedMemory: hotMemory.allowUnboundedMemory,
795
1084
  diagnostics
796
1085
  }),
797
- runnerPath: nativeRunnerPath
1086
+ runnerPath: nativeRunnerPath,
1087
+ maxWorkers: hotMemory.allowUnboundedMemory ? void 0 : hotMemory.plan.maxWorkers
798
1088
  };
799
1089
  }
800
- const userPool = userConfig.test?.pool;
801
- const userInlinesEverything = userConfig.test?.server?.deps?.inline === true;
802
- 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.`);
803
- if (hot && userPool) console.warn(`[vitest-native] 'hotRuntime' supplies its own pool, overriding the configured pool '${typeof userPool === "string" ? userPool : "(custom)"}'.`);
804
- return asCompatibleViteConfig(nativeEngineConfig(nativeSetupPath, env, extensions, transformPkgs, hot, jsxTransform, userPool, ecosystem, resolvedRoot, userInlinesEverything));
1090
+ printEngineBanner(engine, platform, resolvedRoot, hot !== void 0);
1091
+ if (hot) hotSelections.set(vitestRootOf(userConfig), {
1092
+ pool: hot.pool,
1093
+ userPool,
1094
+ userMaxWorkers: userTest?.maxWorkers,
1095
+ singleWorkerAccepted: hotMemory?.allowUnboundedMemory === true
1096
+ });
1097
+ else hotSelections.delete(vitestRootOf(userConfig));
1098
+ return asCompatibleViteConfig(nativeEngineConfig(nativeSetupPath, env, extensions, transformPkgs, hot, jsxTransform, userPool, ecosystem, resolvedRoot, userInlinesEverything, projectDirs, nativeOwnership));
805
1099
  }
806
- if (hotRuntime) console.warn(`[vitest-native] 'hotRuntime' only applies to engine:'native' (resolved engine: '${engine}'); ignoring.`);
1100
+ if (hotRuntimeRequested && hotRuntimeExplicit) console.warn(`[vitest-native] 'hotRuntime' only applies to engine:'native' (resolved engine: '${engine}'); ignoring.`);
807
1101
  if (options?.mocks && Object.keys(options.mocks).length > 0) env.VITEST_NATIVE_MOCKS = JSON.stringify(options.mocks);
808
1102
  if (Array.isArray(options?.presets)) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(options.presets.map((p) => p.name));
809
1103
  else {
@@ -845,6 +1139,8 @@ function reactNative(options) {
845
1139
  },
846
1140
  async configResolved(config) {
847
1141
  jestMockTransformPresent = (config.plugins ?? []).some((plugin) => plugin?.name === "vitest-native:jest-mock-hoist");
1142
+ const finalInline = config.test?.server?.deps?.inline;
1143
+ assertInlineOwnership(finalInline);
848
1144
  const duplicateReact = findDuplicateReact((specifier, from) => {
849
1145
  try {
850
1146
  return createRequire(path.join(from, "package.json")).resolve(specifier);
@@ -869,7 +1165,10 @@ function reactNative(options) {
869
1165
  const error = validatePeerDependency(name, minimum, config.root, maximumMajor, minimumByMajor);
870
1166
  if (error && !error.includes("not found")) console.warn(`[vitest-native] ${error}`);
871
1167
  }
872
- resolved = await resolveOptions(options, config.root);
1168
+ resolved = await resolveOptions(options, config.root, {
1169
+ extensions,
1170
+ assetExts: assetExtList
1171
+ });
873
1172
  try {
874
1173
  realRnPackageJson = createRequire(path.join(config.root, "package.json")).resolve("react-native/package.json");
875
1174
  } catch {}
@@ -882,8 +1181,10 @@ function reactNative(options) {
882
1181
  rnFacadeRoot = config.root;
883
1182
  try {
884
1183
  const indexPath = createRequire(path.join(config.root, "package.json")).resolve("react-native");
885
- const names = parseReactNativeExports(fs.readFileSync(indexPath, "utf8"));
1184
+ const indexSource = fs.readFileSync(indexPath, "utf8");
1185
+ const names = parseReactNativeExports(indexSource);
886
1186
  rnFacadeExports = names.length > 0 ? names : null;
1187
+ rnFacadeDeprecated = new Set(parseDeprecatedReactNativeExports(indexSource));
887
1188
  } catch {
888
1189
  rnFacadeExports = null;
889
1190
  }
@@ -935,8 +1236,17 @@ function reactNative(options) {
935
1236
  const code = [
936
1237
  `import { createRequire } from "node:module";`,
937
1238
  `const _rn = createRequire(${JSON.stringify(path.join(rnFacadeRoot, "package.json"))})("react-native");`,
938
- ...rnFacadeExports.map((n) => `export const ${n} = _rn[${JSON.stringify(n)}];`),
939
- `export default _rn;`
1239
+ ...rnFacadeExports.filter((n) => !rnFacadeDeprecated.has(n)).map((n) => `export const ${n} = _rn[${JSON.stringify(n)}];`),
1240
+ `export default _rn;`,
1241
+ ...rnFacadeDeprecated.size > 0 ? [
1242
+ `for (const name of ${JSON.stringify([...rnFacadeDeprecated])}) {`,
1243
+ ` Object.defineProperty(__vite_ssr_exports__, name, {`,
1244
+ ` enumerable: true,`,
1245
+ ` configurable: true,`,
1246
+ ` get: () => _rn[name],`,
1247
+ ` });`,
1248
+ `}`
1249
+ ] : []
940
1250
  ].join("\n");
941
1251
  virtualCodeCache.set(id, code);
942
1252
  return code;
@@ -999,17 +1309,10 @@ function reactNative(options) {
999
1309
  transform(code, id) {
1000
1310
  warnIfJestMockUnhoisted(code, id);
1001
1311
  if (engine === "native") {
1002
- if (!ecosystemPattern || !ecosystemPattern.test(id)) return void 0;
1003
- if (!/\.[cm]?[jt]sx?$/.test(id.split("?")[0])) return void 0;
1004
- try {
1005
- return {
1006
- code: transformEcosystem(id, code, ecosystemRoot, platform),
1007
- map: null
1008
- };
1009
- } catch (error) {
1010
- if (diagnostics) console.warn(`[vitest-native] could not compile inlined ${id} (${error?.message}); serving it untouched.`);
1011
- return;
1012
- }
1312
+ if (!nativeOwnership) return void 0;
1313
+ const conflict = findNativeOwnershipConflict(nativeOwnership, id, "vite");
1314
+ if (!conflict) return void 0;
1315
+ 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: [...] }).`);
1013
1316
  }
1014
1317
  if (!RN_ECOSYSTEM_PATH.test(id) || !id.endsWith(".js")) return void 0;
1015
1318
  if (!code.includes("@flow")) return void 0;
@@ -1025,6 +1328,44 @@ function reactNative(options) {
1025
1328
  }
1026
1329
  }
1027
1330
  };
1331
+ const configHandler = pluginDefinition.config;
1332
+ return {
1333
+ ...pluginDefinition,
1334
+ config: {
1335
+ order: "post",
1336
+ async handler(userConfig, env) {
1337
+ const result = await configHandler.call(this, userConfig, env);
1338
+ pinInlineProjectRoots(userConfig.test, vitestRootOf(userConfig));
1339
+ const test = result?.test;
1340
+ if (Array.isArray(test?.setupFiles) && typeof test.setupFiles[0] === "string") contributedSetup.set(vitestRootOf(userConfig), test.setupFiles[0]);
1341
+ if (test) test.execArgv = [...test.execArgv ?? [], ...EXPORT_RECOVERY_ARGV];
1342
+ return result;
1343
+ }
1344
+ },
1345
+ configureVitest({ vitest, project }) {
1346
+ const projectConfig = project.config;
1347
+ const root = projectConfig.root ? path.resolve(projectConfig.root) : process.cwd();
1348
+ const setupFile = contributedSetup.get(root);
1349
+ 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.`);
1350
+ const cli = vitest._cliOptions ?? vitest.config?.cliOptions ?? {};
1351
+ if (nativeRoots.has(root) && isVmPool(cli.pool)) throw vmPoolUnsupported(cli.pool);
1352
+ const selection = hotSelections.get(root);
1353
+ if (!selection) return;
1354
+ const reason = hotOverrideReason(projectConfig, cli, selection.pool, selection.singleWorkerAccepted) ?? sharedGroupConflict(project, vitest.projects ?? [], {
1355
+ maxWorkers: vitest.config?.maxWorkers,
1356
+ watch: vitest.config?.watch
1357
+ });
1358
+ if (reason === null) return;
1359
+ if (!hotRuntimeAuto) throw hotRuntimeOverridden(reason);
1360
+ projectConfig.pool = cli.pool ?? selection.userPool ?? "threads";
1361
+ projectConfig.isolate = cli.isolate ?? true;
1362
+ projectConfig.runner = void 0;
1363
+ 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);
1364
+ if (projectConfig.env) delete projectConfig.env.VITEST_NATIVE_MEMORY_PLAN;
1365
+ hotSelections.delete(root);
1366
+ console.error(`[vitest-native] hot runtime off: ${reason}; Vitest's settings apply.`);
1367
+ }
1368
+ };
1028
1369
  }
1029
1370
  //#endregion
1030
1371
  export { disabledPresetNames, presets_exports as presets, reactNative };