vitest-native 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,7 +17,8 @@ const KNOWN_OPTIONS = [
17
17
  const KNOWN_HOT_RUNTIME_OPTIONS = [
18
18
  "recycleAfterFiles",
19
19
  "memoryLimit",
20
- "preserveGlobals"
20
+ "preserveGlobals",
21
+ "esmGeneration"
21
22
  ];
22
23
  function assertStringArray(value, option) {
23
24
  if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string" || entry.length === 0)) throw new VitestNativeTypeError("INVALID_OPTION", `"${option}" must be an array of non-empty strings.`);
@@ -30,7 +31,14 @@ function validateOptions(options) {
30
31
  if (options.platform !== void 0 && options.platform !== "ios" && options.platform !== "android") throw new VitestNativeTypeError("INVALID_OPTION", `"platform" must be "ios" or "android".`);
31
32
  if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") throw new VitestNativeTypeError("INVALID_OPTION", `"diagnostics" must be a boolean.`);
32
33
  if (options.assetExts !== void 0) assertStringArray(options.assetExts, "assetExts");
33
- if (options.transform !== void 0) assertStringArray(options.transform, "transform");
34
+ if (options.transform !== void 0) if (Array.isArray(options.transform)) assertStringArray(options.transform, "transform");
35
+ else if (options.transform !== null && typeof options.transform === "object") {
36
+ const shape = options.transform;
37
+ const unknownKeys = Object.keys(shape).filter((k) => k !== "include" && k !== "exclude");
38
+ if (unknownKeys.length > 0) throw new VitestNativeTypeError("INVALID_OPTION", `"transform" accepts only "include" and "exclude"; received ${unknownKeys.map((k) => `"${k}"`).join(", ")}.`);
39
+ if (shape.include !== void 0) assertStringArray(shape.include, "transform.include");
40
+ if (shape.exclude !== void 0) assertStringArray(shape.exclude, "transform.exclude");
41
+ } else throw new VitestNativeTypeError("INVALID_OPTION", `"transform" must be an array of package names, or an object with "include" and/or "exclude".`);
34
42
  if (options.presets !== void 0 && !Array.isArray(options.presets)) {
35
43
  if (!(options.presets !== null && typeof options.presets === "object" && Object.values(options.presets).every((v) => typeof v === "boolean"))) throw new VitestNativeTypeError("INVALID_OPTION", "\"presets\" must be an array of presets, or an object of booleans to switch auto-detected presets off (for example { navigation: false }).");
36
44
  }
@@ -46,6 +54,7 @@ function validateOptions(options) {
46
54
  if (hotOptions.recycleAfterFiles !== void 0) assertNonNegativeInteger(hotOptions.recycleAfterFiles, "hotRuntime.recycleAfterFiles");
47
55
  if (hotOptions.memoryLimit !== void 0) assertNonNegativeInteger(hotOptions.memoryLimit, "hotRuntime.memoryLimit");
48
56
  if (hotOptions.preserveGlobals !== void 0) assertStringArray(hotOptions.preserveGlobals, "hotRuntime.preserveGlobals");
57
+ if (hotOptions.esmGeneration !== void 0 && typeof hotOptions.esmGeneration !== "boolean") throw new VitestNativeTypeError("INVALID_OPTION", `"hotRuntime.esmGeneration" must be a boolean.`);
49
58
  }
50
59
  function satisfiesMinimum(version, minimum) {
51
60
  const parse = (v) => v.replace(/^[^0-9]*/, "").split(/[-+]/)[0].split(".").map(Number);
@@ -245,44 +254,71 @@ function packagePatterns(name, projectRoot) {
245
254
  if (dir && !containsPath(dir, projectRoot)) patterns.push(new RegExp(`^${escapeRe(toPosix(dir).replace(/\/$/, ""))}[\\\\/]`));
246
255
  return patterns;
247
256
  }
248
- /** Can this project run the native engine? (Both transform deps resolvable.) */
249
- function isNativeCapable(projectRoot) {
250
- try {
251
- const req = createRequire(path.join(projectRoot, "package.json"));
252
- req.resolve("@react-native/babel-preset");
253
- req.resolve("@babel/core");
254
- return true;
257
+ /**
258
+ * The native engine's dependencies that do NOT resolve from the project root.
259
+ *
260
+ * react-native itself is part of the check: the Babel toolchain alone chose
261
+ * native mode in a project with the preset installed but no react-native — an
262
+ * incomplete install, a babel-only workspace — which then failed later at RN
263
+ * resolution with nothing pointing at the cause. Resolution, not declaration:
264
+ * every check walks node_modules upward from the root — so a hoisted workspace
265
+ * install or Expo's transitive react-native counts, and a project does not need
266
+ * react-native in its own manifest.
267
+ */
268
+ function missingNativeDeps(projectRoot) {
269
+ const req = createRequire(path.join(projectRoot, "package.json"));
270
+ const missing = [];
271
+ if (!reactNativeInstalledNear(projectRoot)) missing.push("react-native");
272
+ for (const dep of ["@react-native/babel-preset", "@babel/core"]) try {
273
+ req.resolve(dep);
255
274
  } catch {
256
- return false;
275
+ missing.push(dep);
276
+ }
277
+ return missing;
278
+ }
279
+ /** Does node_modules/react-native exist in projectRoot or any ancestor? */
280
+ function reactNativeInstalledNear(projectRoot) {
281
+ let dir = path.resolve(projectRoot);
282
+ for (;;) {
283
+ if (fs.existsSync(path.join(dir, "node_modules", "react-native", "package.json"))) return true;
284
+ const parent = path.dirname(dir);
285
+ if (parent === dir) return false;
286
+ dir = parent;
257
287
  }
258
288
  }
259
289
  /** Resolve the concrete engine for a run. Pure; never throws. */
260
290
  function detectEngine(requested, projectRoot, opts) {
261
- const nativeAvailable = isNativeCapable(projectRoot);
291
+ const missing = missingNativeDeps(projectRoot);
292
+ const nativeAvailable = missing.length === 0;
262
293
  if (requested === "native") return {
263
294
  engine: "native",
264
295
  nativeAvailable,
296
+ missing,
265
297
  notice: null
266
298
  };
267
299
  if (requested === "mock") return {
268
300
  engine: "mock",
269
301
  nativeAvailable,
302
+ missing,
270
303
  notice: null
271
304
  };
272
305
  const prefersNative = opts?.autoPrefersNative ?? true;
273
306
  if (prefersNative && nativeAvailable) return {
274
307
  engine: "native",
275
308
  nativeAvailable,
309
+ missing,
276
310
  notice: null
277
311
  };
278
312
  if (prefersNative) return {
279
313
  engine: "mock",
280
314
  nativeAvailable: false,
281
- notice: "[vitest-native] @react-native/babel-preset not found — using the mock engine. Install it (and @babel/core) to run real React Native, or set engine:'mock' to silence this."
315
+ missing,
316
+ notice: `[vitest-native] ${missing.join(", ")} not found — using the mock engine. Install what's missing to run real React Native, or set engine:'mock' to silence this.`
282
317
  };
283
318
  return {
284
319
  engine: "mock",
285
320
  nativeAvailable,
321
+ missing,
286
322
  notice: null
287
323
  };
288
324
  }
@@ -307,6 +343,41 @@ const NEVER_INLINE = /* @__PURE__ */ new Set([
307
343
  "react",
308
344
  "react-is"
309
345
  ]);
346
+ /** Does this manifest offer a React Native build, by legacy field or export condition? */
347
+ function hasReactNativeBuild(manifest) {
348
+ if (typeof manifest["react-native"] === "string") return true;
349
+ const seen = /* @__PURE__ */ new Set();
350
+ const search = (node) => {
351
+ if (!node || typeof node !== "object" || seen.has(node)) return false;
352
+ seen.add(node);
353
+ for (const [key, value] of Object.entries(node)) {
354
+ if (key === "react-native") return true;
355
+ if (search(value)) return true;
356
+ }
357
+ return false;
358
+ };
359
+ return search(manifest.exports);
360
+ }
361
+ /**
362
+ * A package that ships ES modules and nothing React Native.
363
+ *
364
+ * The closure walk is a guess: a detected package's dependencies MIGHT be untranspiled
365
+ * React Native source, because the ecosystem publishes that way and the dependency's
366
+ * own manifest cannot say so. `"type": "module"` is the manifest saying the opposite —
367
+ * this is runnable ES modules — and with no React Native build anywhere in it, there is
368
+ * nothing for the preset to do. Compiling it anyway rewrites a package that publishes
369
+ * ESM into CommonJS and hands it to Node under that format, which is how a dependency
370
+ * reached this way (`zod`) failed to parse and took fourteen test files down with it.
371
+ *
372
+ * A genuine React Native library is unaffected: declaring `react-native` by field or
373
+ * export condition keeps it in the closure however it publishes.
374
+ *
375
+ * Only closure MEMBERS are judged this way. A package detected on its own manifest, or
376
+ * named in `transform: [...]`, was asked for explicitly and is still compiled.
377
+ */
378
+ function publishesOnlyEsm(manifest) {
379
+ return manifest.type === "module" && !hasReactNativeBuild(manifest);
380
+ }
310
381
  /** Manifest fields that make a package part of the React Native ecosystem. */
311
382
  function dependsOnReactNative(manifest) {
312
383
  for (const field of ["dependencies", "peerDependencies"]) {
@@ -411,12 +482,13 @@ function manifestsFrom(projectRoot) {
411
482
  * test infrastructure in NEVER_INLINE, and anything the consumer listed explicitly
412
483
  * in `transform` — that option keeps its existing meaning and takes precedence.
413
484
  */
414
- function detectEcosystemPackages(projectRoot, explicit = [], testRoots = []) {
485
+ function detectEcosystemPackages(projectRoot, explicit = [], testRoots = [], neverTransform = []) {
415
486
  const roots = (Array.isArray(projectRoot) ? projectRoot : [projectRoot]).filter(Boolean);
416
487
  const skip = /* @__PURE__ */ new Set([
417
488
  ...NEVER_INLINE,
418
489
  ...Object.keys(AUTO_DETECT_PRESETS),
419
- ...explicit
490
+ ...explicit,
491
+ ...neverTransform
420
492
  ]);
421
493
  const candidates = /* @__PURE__ */ new Set();
422
494
  const found = roots.flatMap((root) => manifestsFrom(root));
@@ -484,9 +556,26 @@ function detectEcosystemPackages(projectRoot, explicit = [], testRoots = []) {
484
556
  }
485
557
  return seen;
486
558
  };
487
- const toolchain = closureOf(["@babel/core", "@react-native/babel-preset"]);
559
+ const toolchain = closureOf([
560
+ "@babel/core",
561
+ "@react-native/babel-preset",
562
+ "@babel/runtime",
563
+ "metro"
564
+ ]);
565
+ const projectDeclared = /* @__PURE__ */ new Set();
566
+ for (const { dir, manifest } of found) {
567
+ if (!ownerRoots.some((root) => containsPath(dir, root))) continue;
568
+ for (const field of [
569
+ "dependencies",
570
+ "devDependencies",
571
+ "optionalDependencies"
572
+ ]) {
573
+ const deps = manifest[field];
574
+ if (deps && typeof deps === "object") for (const name of Object.keys(deps)) projectDeclared.add(name);
575
+ }
576
+ }
488
577
  const inClosure = new Set(detected);
489
- const queue = [...detected];
578
+ const queue = detected.filter((name) => projectDeclared.has(name));
490
579
  while (queue.length > 0) {
491
580
  const deps = manifestOf(queue.pop())?.dependencies;
492
581
  if (!deps || typeof deps !== "object") continue;
@@ -495,7 +584,9 @@ function detectEcosystemPackages(projectRoot, explicit = [], testRoots = []) {
495
584
  if (rnOwned.has(dep)) continue;
496
585
  if (toolchain.has(dep)) continue;
497
586
  if (ownsTheRun(dep)) continue;
498
- if (!manifestOf(dep)) continue;
587
+ const depManifest = manifestOf(dep);
588
+ if (!depManifest) continue;
589
+ if (publishesOnlyEsm(depManifest)) continue;
499
590
  inClosure.add(dep);
500
591
  queue.push(dep);
501
592
  }
@@ -287,12 +287,37 @@ interface VitestNativeOptions {
287
287
  * (e.g. `react-native-reanimated`, `react-native-safe-area-context`) need to
288
288
  * be listed here, analogous to Jest's `transformIgnorePatterns` allowlist.
289
289
  *
290
+ * The object form adds `exclude`, which names packages the engine must NEVER
291
+ * transform, whatever else would have selected them — auto-detection, a detected
292
+ * package's dependency closure, or the engine's own built-in lists.
293
+ *
294
+ * `exclude` exists because the engine's judgement about what is React Native source
295
+ * is a heuristic, and when it guesses wrong the failure is a parse error deep inside
296
+ * a package the project never named. Build toolchains are the recurring case:
297
+ * compiling one re-enters Babel while it is loading. The engine excludes the ones it
298
+ * knows about, but that list is only as current as the last release — `exclude` is
299
+ * how a project unblocks itself the same day, without waiting for one.
300
+ *
301
+ * Run with `diagnostics: true` to print the packages the engine chose to compile;
302
+ * that list is what `exclude` subtracts from.
303
+ *
290
304
  * @example
291
305
  * ```ts
292
306
  * reactNative({ engine: 'native', transform: ['react-native-reanimated'] })
307
+ *
308
+ * reactNative({
309
+ * engine: 'native',
310
+ * transform: {
311
+ * include: ['react-native-reanimated'],
312
+ * exclude: ['some-build-tool'], // never hand this to the Babel preset
313
+ * },
314
+ * })
293
315
  * ```
294
316
  */
295
- transform?: string[];
317
+ transform?: string[] | {
318
+ include?: string[];
319
+ exclude?: string[];
320
+ };
296
321
  /**
297
322
  * `engine: 'native'` only. **Experimental.** Run tests in persistent
298
323
  * RN-hot workers: React Native's module graph loads once per worker and
@@ -315,6 +340,15 @@ interface VitestNativeOptions {
315
340
  * - `preserveGlobals`: exact globalThis property names intentionally owned
316
341
  * by resident external libraries. App/test globals are otherwise removed
317
342
  * between files. Storybook's preview registry is preserved automatically.
343
+ * - `esmGeneration`: re-evaluate externalized packages a test file `import`s,
344
+ * so their module-level state does not carry into the next file. Node's ESM
345
+ * registry cannot be invalidated, so the loader stamps a per-file generation
346
+ * onto the resolved URL instead. On by default, because without it those
347
+ * packages behave differently under hot than under stock isolation. It costs
348
+ * re-execution: a suite whose files import many externalized (non-React
349
+ * Native) packages measured 55% more wall clock at the extreme — still 9x
350
+ * stock isolation, against 13.9x with it off. Set false to trade that back,
351
+ * accepting that a package holding state across files will keep it.
318
352
  *
319
353
  * Default: false (each file runs in a fresh worker; RN reloads per file).
320
354
  */
@@ -322,6 +356,7 @@ interface VitestNativeOptions {
322
356
  recycleAfterFiles?: number;
323
357
  memoryLimit?: number;
324
358
  preserveGlobals?: string[];
359
+ esmGeneration?: boolean;
325
360
  };
326
361
  }
327
362
  //#endregion
@@ -286,12 +286,37 @@ interface VitestNativeOptions {
286
286
  * (e.g. `react-native-reanimated`, `react-native-safe-area-context`) need to
287
287
  * be listed here, analogous to Jest's `transformIgnorePatterns` allowlist.
288
288
  *
289
+ * The object form adds `exclude`, which names packages the engine must NEVER
290
+ * transform, whatever else would have selected them — auto-detection, a detected
291
+ * package's dependency closure, or the engine's own built-in lists.
292
+ *
293
+ * `exclude` exists because the engine's judgement about what is React Native source
294
+ * is a heuristic, and when it guesses wrong the failure is a parse error deep inside
295
+ * a package the project never named. Build toolchains are the recurring case:
296
+ * compiling one re-enters Babel while it is loading. The engine excludes the ones it
297
+ * knows about, but that list is only as current as the last release — `exclude` is
298
+ * how a project unblocks itself the same day, without waiting for one.
299
+ *
300
+ * Run with `diagnostics: true` to print the packages the engine chose to compile;
301
+ * that list is what `exclude` subtracts from.
302
+ *
289
303
  * @example
290
304
  * ```ts
291
305
  * reactNative({ engine: 'native', transform: ['react-native-reanimated'] })
306
+ *
307
+ * reactNative({
308
+ * engine: 'native',
309
+ * transform: {
310
+ * include: ['react-native-reanimated'],
311
+ * exclude: ['some-build-tool'], // never hand this to the Babel preset
312
+ * },
313
+ * })
292
314
  * ```
293
315
  */
294
- transform?: string[];
316
+ transform?: string[] | {
317
+ include?: string[];
318
+ exclude?: string[];
319
+ };
295
320
  /**
296
321
  * `engine: 'native'` only. **Experimental.** Run tests in persistent
297
322
  * RN-hot workers: React Native's module graph loads once per worker and
@@ -314,6 +339,15 @@ interface VitestNativeOptions {
314
339
  * - `preserveGlobals`: exact globalThis property names intentionally owned
315
340
  * by resident external libraries. App/test globals are otherwise removed
316
341
  * between files. Storybook's preview registry is preserved automatically.
342
+ * - `esmGeneration`: re-evaluate externalized packages a test file `import`s,
343
+ * so their module-level state does not carry into the next file. Node's ESM
344
+ * registry cannot be invalidated, so the loader stamps a per-file generation
345
+ * onto the resolved URL instead. On by default, because without it those
346
+ * packages behave differently under hot than under stock isolation. It costs
347
+ * re-execution: a suite whose files import many externalized (non-React
348
+ * Native) packages measured 55% more wall clock at the extreme — still 9x
349
+ * stock isolation, against 13.9x with it off. Set false to trade that back,
350
+ * accepting that a package holding state across files will keep it.
317
351
  *
318
352
  * Default: false (each file runs in a fresh worker; RN reloads per file).
319
353
  */
@@ -321,6 +355,7 @@ interface VitestNativeOptions {
321
355
  recycleAfterFiles?: number;
322
356
  memoryLimit?: number;
323
357
  preserveGlobals?: string[];
358
+ esmGeneration?: boolean;
324
359
  };
325
360
  }
326
361
  //#endregion
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { b as ReactNativeMock, t as index_d_exports, x as VitestNativeOptions, y as Preset } from "./index-CrMeE8rd.mjs";
1
+ import { b as ReactNativeMock, t as index_d_exports, x as VitestNativeOptions, y as Preset } from "./index-CmETArCM.mjs";
2
2
  import { Plugin } from "vite";
3
3
  //#region src/plugin.d.ts
4
4
  /**
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
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-C4qT_vl3.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";
3
3
  import { t as AUTO_DETECT_PRESETS } from "./preset-map-DuX0ocdn.mjs";
4
4
  import { t as presets_exports } from "./presets-IStcJEOa.mjs";
5
5
  import { createRequire } from "node:module";
@@ -27,16 +27,24 @@ const METRO_SOURCE_EXTS = [
27
27
  "tsx"
28
28
  ];
29
29
  /**
30
- * Metro tries every platform-suffixed variant first, then every `.native` one,
31
- * then the bare extensions — not extension-major.
30
+ * Extension-MAJOR, exactly as Metro resolves: for each source extension in order,
31
+ * try the platform variant, then `.native`, then bare — `.ios.js`, `.native.js`,
32
+ * `.js`, `.ios.jsx`, … (metro-resolver's `resolveSourceFile` loops `sourceExts`
33
+ * in the outer loop and the platform variants inside it).
34
+ *
35
+ * This order previously interleaved the other way — every `.ios.*` before any
36
+ * `.native.*` before any bare extension — and the difference is not stylistic:
37
+ * a module shipping `Foo.native.js` beside `Foo.ios.tsx` resolves to
38
+ * `.native.js` under Metro (the `js` round wins before `tsx` is ever tried) but
39
+ * resolved to `.ios.tsx` here, so the test ran a different file than the app
40
+ * ships. The order is asserted against real metro-resolver by
41
+ * tests/metro-resolver-oracle.test.ts, not just against these literals.
32
42
  */
33
43
  function extensionsFor(platform) {
34
44
  const suffix = platform === "android" ? "android" : "ios";
35
- return [
36
- ...METRO_SOURCE_EXTS.map((e) => `.${suffix}.${e}`),
37
- ...METRO_SOURCE_EXTS.map((e) => `.native.${e}`),
38
- ...METRO_SOURCE_EXTS.map((e) => `.${e}`)
39
- ];
45
+ const exts = [];
46
+ for (const e of METRO_SOURCE_EXTS) exts.push(`.${suffix}.${e}`, `.native.${e}`, `.${e}`);
47
+ return exts;
40
48
  }
41
49
  //#endregion
42
50
  //#region src/resolve.ts
@@ -213,6 +221,34 @@ function nearestPackageDir(from) {
213
221
  dir = parent;
214
222
  }
215
223
  }
224
+ /**
225
+ * The `transform` option in either shape: an array of packages to compile, or an
226
+ * object naming those and the ones to leave alone.
227
+ *
228
+ * `exclude` overrides everything — auto-detection, the closure walk, and the engine's
229
+ * built-in toolchain and infrastructure lists. Those built-in lists are names the
230
+ * engine learned from packages that broke, which means they are only ever as current
231
+ * as the last release; `exclude` is the same decision, handed to the project.
232
+ */
233
+ function normalizeTransformOption(option) {
234
+ const names = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string" && v !== "") : [];
235
+ if (Array.isArray(option)) return {
236
+ include: names(option),
237
+ exclude: []
238
+ };
239
+ if (option && typeof option === "object") {
240
+ const shape = option;
241
+ const exclude = names(shape.exclude);
242
+ return {
243
+ include: names(shape.include).filter((n) => !exclude.includes(n)),
244
+ exclude
245
+ };
246
+ }
247
+ return {
248
+ include: [],
249
+ exclude: []
250
+ };
251
+ }
216
252
  function resolvePackageVersion(packageName, projectRoot) {
217
253
  const req = createRequire(path.join(projectRoot, "package.json"));
218
254
  try {
@@ -682,7 +718,7 @@ function reactNative(options) {
682
718
  const platform = options?.platform ?? "ios";
683
719
  const diagnostics = options?.diagnostics ?? false;
684
720
  const requestedEngine = options?.engine ?? "auto";
685
- const transformPkgs = (options?.transform ?? []).filter((p) => typeof p === "string" && p.length > 0);
721
+ const { include: transformPkgs, exclude: neverTransform } = normalizeTransformOption(options?.transform);
686
722
  const hotRuntimeOpt = options?.hotRuntime ?? false;
687
723
  const hotRuntime = hotRuntimeOpt !== false;
688
724
  const hotRecycle = typeof hotRuntimeOpt === "object" ? hotRuntimeOpt : {};
@@ -704,7 +740,7 @@ function reactNative(options) {
704
740
  const jsxTransform = getJsxTransformConfig(resolvedRoot);
705
741
  const decision = detectEngine(requestedEngine, resolvedRoot);
706
742
  engine = decision.engine;
707
- if (engine === "native" && !decision.nativeAvailable) throw new VitestNativeError("ENGINE_REQUIRES_BABEL", `engine:'native' requires '@react-native/babel-preset' and '@babel/core' to resolve from ${resolvedRoot}. Install them as devDependencies (React Native projects ship them by default):\n\n npm install -D @react-native/babel-preset @babel/core\n\nOr set engine:'mock' to run without a React Native install.`);
743
+ 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.`);
708
744
  if (decision.notice) console.warn(decision.notice);
709
745
  printEngineBanner(engine, platform, resolvedRoot);
710
746
  const env = {
@@ -717,6 +753,7 @@ function reactNative(options) {
717
753
  const assetExtList = [...DEFAULT_ASSET_EXTS, ...(options?.assetExts ?? []).map((e) => e.replace(/^\./, ""))];
718
754
  env.VITEST_NATIVE_ASSET_EXTS = JSON.stringify(assetExtList);
719
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";
720
757
  if (engine === "native") {
721
758
  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'.");
722
759
  const disabledNative = disabledPresetNames(options?.presets);
@@ -728,7 +765,7 @@ function reactNative(options) {
728
765
  if (Object.keys(presetConfig).length > 0) env.VITEST_NATIVE_PRESET_CONFIG = JSON.stringify(presetConfig);
729
766
  }
730
767
  const includeRoots = testIncludeRoots(userConfig.test?.include, resolvedRoot);
731
- const ecosystem = detectEcosystemPackages([resolvedRoot, ...includeRoots], transformPkgs, includeRoots);
768
+ const ecosystem = detectEcosystemPackages([resolvedRoot, ...includeRoots], transformPkgs, includeRoots, neverTransform);
732
769
  const linkedDetectedDirs = ecosystem.map((name) => packageDirOf(name, resolvedRoot)).filter((dir) => dir !== null && !/[\\/]node_modules[\\/]/.test(dir));
733
770
  const projectDirs = [...new Set([resolvedRoot, ...includeRoots].map((dir) => nearestPackageDir(dir)).filter((dir) => dir !== null))].filter((dir) => !linkedDetectedDirs.some((detected) => containsPath(dir, detected)));
734
771
  if (projectDirs.length > 0) env.VITEST_NATIVE_PROJECT_DIRS = JSON.stringify(projectDirs);
@@ -44,21 +44,42 @@ export function decorateTransformError(err, file, platform) {
44
44
  const UNTRANSPILED_SYNTAX =
45
45
  /Unexpected token '?<'?|Unexpected identifier|Unexpected reserved word|Missing initializer in const|Unexpected token ':'/;
46
46
 
47
+ // Node's ReferenceError when a MIXED-SYNTAX file runs: top-level `import` makes the
48
+ // CJS parse fail, Node retries the file as an ES module (require(esm)), and the
49
+ // CommonJS half then dereferences a wrapper variable that ESM scope never defines.
50
+ // Metro compiles both halves, so packages ship this shape — react-native-worklets'
51
+ // lib/module/mock.js ends in `module.exports = ...` under a header of `import`s.
52
+ // It is the runtime sibling of the SyntaxError class above: same cause, same fix,
53
+ // but it parses cleanly and so fails AFTER compilation, as a ReferenceError.
54
+ const ESM_SCOPE_REFERENCE =
55
+ /\b(?:module|exports|require|__dirname|__filename) is not defined in ES module scope/;
56
+
47
57
  /**
48
- * When Node throws a SyntaxError compiling a node_modules file that vitest-native
49
- * did NOT transform, explain the (very common) real cause: the package ships
50
- * untranspiled JSX/Flow/TS and needs to be added to `transform: [...]`.
58
+ * When Node throws compiling or running a node_modules file that vitest-native did
59
+ * NOT transform, explain the (very common) real cause: the package ships source
60
+ * only Metro can run — untranspiled JSX/Flow/TS (a SyntaxError), or mixed
61
+ * ESM-import/CommonJS-exports (a ReferenceError from the require(esm) retry) —
62
+ * and needs to be added to `transform: [...]`.
51
63
  * Returns a decorated error, or null when the failure doesn't match the pattern.
52
64
  */
53
65
  export function explainUntransformedSyntaxError(err, file) {
54
- if (!err || err.name !== "SyntaxError") return null;
55
- if (!UNTRANSPILED_SYNTAX.test(String(err.message))) return null;
66
+ if (!err) return null;
67
+ const matches =
68
+ (err.name === "SyntaxError" && UNTRANSPILED_SYNTAX.test(String(err.message))) ||
69
+ (err.name === "ReferenceError" && ESM_SCOPE_REFERENCE.test(String(err.message)));
70
+ if (!matches) return null;
56
71
  const pkg = packageNameFromPath(file);
57
72
  if (!pkg) return null;
58
- const wrapped = new SyntaxError(
73
+ const cause =
74
+ err.name === "ReferenceError"
75
+ ? `This usually means the package publishes mixed ES-module/CommonJS source ` +
76
+ `that only a bundler like Metro can run.`
77
+ : `This usually means the package publishes untranspiled JSX, Flow, or TypeScript.`;
78
+ const Ctor = err.name === "ReferenceError" ? ReferenceError : SyntaxError;
79
+ const wrapped = new Ctor(
59
80
  `[vitest-native] '${pkg}' shipped source Node can't run directly ` +
60
81
  `(${err.message} in ${file}).\n` +
61
- `This usually means the package publishes untranspiled JSX, Flow, or TypeScript. ` +
82
+ `${cause} ` +
62
83
  `Ask vitest-native to transform it:\n\n` +
63
84
  ` reactNative({ transform: ['${pkg}'] })\n\n` +
64
85
  `in your vitest config. See https://github.com/danfry1/vitest-native` +
@@ -3,7 +3,7 @@
3
3
  import Module from "node:module";
4
4
  import path from "node:path";
5
5
  import fs from "node:fs";
6
- import { transformRN, isFlow } from "./transform.mjs";
6
+ import { transformRN, isFlow, needsTransform } from "./transform.mjs";
7
7
  import { boundarySourceFor } from "./boundary.mjs";
8
8
  import { resolvePlatformFile } from "./resolve.mjs";
9
9
  import {
@@ -163,7 +163,17 @@ export function installRequireHooks(
163
163
  reactNativeVersion = "0.0.0",
164
164
  assetExts = [],
165
165
  ) {
166
- if (globalThis.__vitest_native_require_hooks_installed) return;
166
+ if (globalThis.__vitest_native_require_hooks_installed) {
167
+ // Install once per worker — but not with a frozen transform list. The hot
168
+ // worker installs the hooks at BOOT, before the setup file has built the
169
+ // preset mocks and can extend the list with preset-shadowed packages (their
170
+ // pass-through entries are compiled only if named here); a pure no-op would
171
+ // pin the boot-time env list forever, and the divergence is hot-only because
172
+ // under stock the setup file IS the first caller. Rebuild the matcher when
173
+ // a later caller brings a different list; hook layers are never stacked.
174
+ globalThis.__vitest_native_require_hooks_update?.(transformPkgs);
175
+ return;
176
+ }
167
177
  globalThis.__vitest_native_require_hooks_installed = true;
168
178
 
169
179
  // Asset requires (`require('./logo.png')`, `require('./Icon.ttf')`) reaching
@@ -186,7 +196,16 @@ export function installRequireHooks(
186
196
  }
187
197
 
188
198
  // Configured third-party packages to also transform (Flow/TS/JSX stripped).
189
- const isExtra = buildPkgMatcher(transformPkgs, projectRoot);
199
+ // `let` + the updater below: the hot worker installs the hooks at boot with the
200
+ // raw env list, and the setup file re-calls with the preset-extended one.
201
+ let isExtra = buildPkgMatcher(transformPkgs, projectRoot);
202
+ let isExtraKey = JSON.stringify(transformPkgs);
203
+ globalThis.__vitest_native_require_hooks_update = (pkgs) => {
204
+ const key = JSON.stringify(pkgs);
205
+ if (key === isExtraKey) return;
206
+ isExtraKey = key;
207
+ isExtra = buildPkgMatcher(pkgs, projectRoot);
208
+ };
190
209
 
191
210
  // Preset redirect (CJS): when an externalized third-party module require()s a
192
211
  // preset package by its bare name (e.g. @gorhom/bottom-sheet → require(
@@ -289,10 +308,15 @@ export function installRequireHooks(
289
308
  if (isFlow(src))
290
309
  return mod._compile(transformRN(filename, src, projectRoot, platform), filename);
291
310
  } else if (isExtra(norm)) {
292
- // Configured third-party packages: transform unconditionally — TS `import
293
- // type`/JSX aren't caught by isFlow, and babel passes plain JS through.
311
+ // Selected for compiling — but only compile what Node cannot run as published.
312
+ // `isFlow` is not enough here (TS `import type` and JSX slip past it), and
313
+ // compiling everything is what handed Babel its own toolchain. See
314
+ // needsTransform: V8 answers the question Node is about to ask.
294
315
  const src = fs.readFileSync(filename, "utf8");
295
- return mod._compile(transformRN(filename, src, projectRoot, platform), filename);
316
+ if (needsTransform(filename, src)) {
317
+ return mod._compile(transformRN(filename, src, projectRoot, platform), filename);
318
+ }
319
+ return origJs(mod, filename);
296
320
  }
297
321
  if (NODE_MODULES_PATH.test(norm)) {
298
322
  // A node_modules package we did NOT transform: when Node's compile throws a