vitest-native 0.11.1 → 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.
@@ -18,16 +18,43 @@ import path from "node:path";
18
18
  import fs from "node:fs";
19
19
  import os from "node:os";
20
20
  import crypto from "node:crypto";
21
+ import vm from "node:vm";
21
22
  import { decorateTransformError } from "./explain.mjs";
22
23
  import { VitestNativeError } from "../errors.mjs";
23
24
 
24
- let _req;
25
- let _babel;
26
- let _preset;
27
- let _flowEnums;
28
- let _cacheDir;
29
- let _writeSeq = 0;
30
- const mem = new Map();
25
+ // Toolchain state is scoped PER PROJECT ROOT, not per process. It used to be a
26
+ // set of module globals initialized by the first caller — but registries for
27
+ // every project in a Vitest workspace are built in the one Vite main process,
28
+ // so the first project's resolved preset, @babel/core, and cache directory
29
+ // silently served every other project. Proven by
30
+ // tests/transform-project-scope.test.ts: a second root's file came back
31
+ // stamped with the first root's Babel toolchain. Same first-caller-wins guard
32
+ // family as the hot worker's require-hook install (see hooks.mjs).
33
+ const contexts = new Map(); // canonical project root -> toolchain context
34
+
35
+ // Memoized: transformRN runs per required file, and the realpath of a project
36
+ // root cannot change within a process. Realpath (not just resolve) so a root
37
+ // reached through a symlink — pnpm layouts, linked workspaces — shares one
38
+ // context with its real directory instead of building a twin toolchain.
39
+ const canonicalRoots = new Map();
40
+ function canonicalRoot(projectRoot) {
41
+ const hit = canonicalRoots.get(projectRoot);
42
+ if (hit) return hit;
43
+ let root;
44
+ try {
45
+ root = fs.realpathSync(projectRoot);
46
+ } catch {
47
+ root = path.resolve(projectRoot);
48
+ }
49
+ canonicalRoots.set(projectRoot, root);
50
+ return root;
51
+ }
52
+
53
+ /** Any already-built context — for parse-only helpers with no root of their own. */
54
+ function anyContext() {
55
+ for (const ctx of contexts.values()) return ctx;
56
+ return null;
57
+ }
31
58
  // 4: Flow enums are now transformed ahead of the preset's strip-types pass, so cached
32
59
  // output from 3 is missing every `export enum` declaration. Neither the preset nor
33
60
  // Babel version changed, and those are the only other inputs to the directory name, so
@@ -57,16 +84,20 @@ export function cacheRootFor(projectRoot) {
57
84
  return dir;
58
85
  }
59
86
 
60
- function init(projectRoot) {
61
- if (_cacheDir) return;
62
- _req = createRequire(path.join(projectRoot, "package.json"));
87
+ function ctxFor(projectRoot) {
88
+ const root = canonicalRoot(projectRoot);
89
+ const existing = contexts.get(root);
90
+ if (existing) return existing;
91
+ const req = createRequire(path.join(root, "package.json"));
92
+ let preset;
93
+ let flowEnums;
63
94
  let presetVersion;
64
95
  let babelVersion;
65
96
  try {
66
97
  // Resolve-only here (cheap); the actual require of @babel/core happens
67
98
  // lazily on the first cache miss.
68
- _preset = _req.resolve("@react-native/babel-preset");
69
- _req.resolve("@babel/core");
99
+ preset = req.resolve("@react-native/babel-preset");
100
+ req.resolve("@babel/core");
70
101
  // Flow enums must be transformed BEFORE @babel/plugin-transform-flow-strip-types
71
102
  // sees them, or the declaration is removed as if it were a type annotation. The
72
103
  // React Native preset carries both, but in separate `overrides` entries that Babel
@@ -79,16 +110,16 @@ function init(projectRoot) {
79
110
  // and the enum survives. Resolved from the preset, which depends on it, so no new
80
111
  // dependency is required.
81
112
  try {
82
- _flowEnums = createRequire(_req.resolve("@react-native/babel-preset/package.json")).resolve(
113
+ flowEnums = createRequire(req.resolve("@react-native/babel-preset/package.json")).resolve(
83
114
  "babel-plugin-transform-flow-enums",
84
115
  );
85
116
  } catch {
86
117
  // A preset layout without it: fall back to the preset's own handling rather than
87
118
  // failing the run. Flow enums are rare and only two React Native files use them.
88
- _flowEnums = null;
119
+ flowEnums = null;
89
120
  }
90
- presetVersion = _req("@react-native/babel-preset/package.json").version;
91
- babelVersion = _req("@babel/core/package.json").version;
121
+ presetVersion = req("@react-native/babel-preset/package.json").version;
122
+ babelVersion = req("@babel/core/package.json").version;
92
123
  } catch {
93
124
  throw new VitestNativeError(
94
125
  "ENGINE_REQUIRES_BABEL",
@@ -103,16 +134,19 @@ function init(projectRoot) {
103
134
  // output (e.g. _jsxFileName injection) under NODE_ENV=development than under
104
135
  // test/production.
105
136
  const babelEnv = process.env.BABEL_ENV || process.env.NODE_ENV || "none";
106
- _cacheDir = path.join(
107
- cacheRootFor(projectRoot),
137
+ const cacheDir = path.join(
138
+ cacheRootFor(root),
108
139
  `transform-${presetVersion}-b${babelVersion}-${babelEnv}-v${TRANSFORM_CACHE_VERSION}`,
109
140
  );
110
- fs.mkdirSync(_cacheDir, { recursive: true });
141
+ fs.mkdirSync(cacheDir, { recursive: true });
142
+ const ctx = { req, preset, flowEnums, cacheDir, babel: null, mem: new Map(), writeSeq: 0 };
143
+ contexts.set(root, ctx);
144
+ return ctx;
111
145
  }
112
146
 
113
- /** The active transform disk-cache directory (resolved on first use). Test hook. */
114
- export function transformCacheDir() {
115
- return _cacheDir ?? null;
147
+ /** A project's transform disk-cache directory, once resolved. Test hook. */
148
+ export function transformCacheDir(projectRoot) {
149
+ return contexts.get(canonicalRoot(projectRoot))?.cacheDir ?? null;
116
150
  }
117
151
 
118
152
  /** Returns true if the source contains RN Flow syntax that must be transformed. */
@@ -138,13 +172,15 @@ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
138
172
  * someValue`), which leaves Node's own detection in charge — no worse than before.
139
173
  */
140
174
  export function cjsExportNames(code) {
141
- if (!_babel) {
142
- if (!_req) return [];
143
- _babel = _req("@babel/core");
144
- }
175
+ // Parse-only, so any project's @babel/core serves: the input is this module's
176
+ // own transformed output, and parsing is toolchain-neutral across the versions
177
+ // in play. Callers have no project root of their own to hand over.
178
+ const ctx = anyContext();
179
+ if (!ctx) return [];
180
+ if (!ctx.babel) ctx.babel = ctx.req("@babel/core");
145
181
  let ast;
146
182
  try {
147
- ast = _babel.parseSync(code, { babelrc: false, configFile: false, sourceType: "script" });
183
+ ast = ctx.babel.parseSync(code, { babelrc: false, configFile: false, sourceType: "script" });
148
184
  } catch {
149
185
  return [];
150
186
  }
@@ -197,9 +233,85 @@ export function isFlow(src) {
197
233
  return /@flow|import typeof|\bcomponent\s+\w/.test(src);
198
234
  }
199
235
 
236
+ /**
237
+ * Does this file need compiling, or can Node run it as published?
238
+ *
239
+ * The engine used to answer this by NAME: a package was compiled because detection or
240
+ * a closure walk selected it. That guess was wrong far more often than it was right,
241
+ * and every way of being wrong looked the same — a parse error deep inside a package
242
+ * the project never mentioned. `@babel/runtime`, Metro's `lru-cache` chain and a
243
+ * pure-ESM validator all arrived that way, and each was answered with another name to
244
+ * exclude.
245
+ *
246
+ * The file itself answers precisely. If V8 can parse it, Node can run it, so compiling
247
+ * is optional; if V8 cannot, Node cannot, so compiling is required. That is not a
248
+ * heuristic — it is the same question Node is about to ask.
249
+ *
250
+ * Measured on a 41 KB file: the check costs 0.02 ms against 91 ms for the transform it
251
+ * avoids. That is NOT a speed win in practice and should not be sold as one — on this
252
+ * repository's own native suite, cold cache, it measured 7.68 s against 7.35 s without
253
+ * the check, because React Native's own sources need compiling either way (440 of 450
254
+ * fail to parse) and the check adds a parse to each. The win is that a package Node can
255
+ * already run is never handed to Babel, whatever selected it.
256
+ *
257
+ * What is lost by skipping is downleveling for Hermes — `const` to `var`, destructuring
258
+ * lowered. Verified against React Native's own sources and the installed ecosystem:
259
+ * that is all the preset does to a file V8 accepts. It is behaviour-preserving on
260
+ * Node, and if anything closer to what the package published. `__DEV__` is left
261
+ * standing and top-level requires are not inlined, so neither observable transform
262
+ * applies here.
263
+ *
264
+ * SCRIPT GOAL ONLY. A `type: module` package is still compiled as before: the loader
265
+ * hands those to Node as CommonJS today, and changing that is an interop question
266
+ * about named exports and live bindings that this check does not answer.
267
+ */
268
+ export function needsTransform(file, src) {
269
+ if (file.endsWith(".mjs") || moduleGoal(file)) return true; // Not this check's business.
270
+ try {
271
+ // Parsed for the verdict only; the compiled script is never run.
272
+ const parsed = new vm.Script(src, { filename: file });
273
+ return parsed === undefined;
274
+ } catch {
275
+ return true;
276
+ }
277
+ }
278
+
279
+ /** Is this file's nearest package.json `type: module`? Cached per directory. */
280
+ const goalCache = new Map();
281
+ function moduleGoal(file) {
282
+ if (file.endsWith(".cjs")) return false;
283
+ let dir = path.dirname(file);
284
+ const seen = [];
285
+ for (;;) {
286
+ const cached = goalCache.get(dir);
287
+ if (cached !== undefined) {
288
+ for (const d of seen) goalCache.set(d, cached);
289
+ return cached;
290
+ }
291
+ seen.push(dir);
292
+ let verdict;
293
+ try {
294
+ verdict =
295
+ JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8")).type === "module";
296
+ } catch {
297
+ verdict = undefined;
298
+ }
299
+ if (verdict !== undefined) {
300
+ for (const d of seen) goalCache.set(d, verdict);
301
+ return verdict;
302
+ }
303
+ const parent = path.dirname(dir);
304
+ if (parent === dir) {
305
+ for (const d of seen) goalCache.set(d, false);
306
+ return false;
307
+ }
308
+ dir = parent;
309
+ }
310
+ }
311
+
200
312
  /** Transform an RN source file to runnable CJS. Cached in-memory + on disk. */
201
313
  export function transformRN(file, src, projectRoot, platform = "ios") {
202
- init(projectRoot);
314
+ const ctx = ctxFor(projectRoot);
203
315
  // The in-memory key uses mtime+size (one statSync) so the hot path skips
204
316
  // hashing; the DISK key hashes the actual content, so entries stay valid
205
317
  // across fresh installs, Docker mtime normalization, and CI cache restores —
@@ -209,7 +321,7 @@ export function transformRN(file, src, projectRoot, platform = "ios") {
209
321
  // identical sources at different paths must not share an entry.
210
322
  const st = fs.statSync(file);
211
323
  const memKey = `${platform}\0${file}\0${st.mtimeMs}\0${st.size}`;
212
- const memHit = mem.get(memKey);
324
+ const memHit = ctx.mem.get(memKey);
213
325
  if (memHit !== undefined) return memHit;
214
326
 
215
327
  const key = crypto
@@ -220,20 +332,20 @@ export function transformRN(file, src, projectRoot, platform = "ios") {
220
332
  .update("\0")
221
333
  .update(src)
222
334
  .digest("hex");
223
- const cachePath = path.join(_cacheDir, key + ".js");
335
+ const cachePath = path.join(ctx.cacheDir, key + ".js");
224
336
  try {
225
337
  const cached = fs.readFileSync(cachePath, "utf8");
226
- mem.set(memKey, cached);
338
+ ctx.mem.set(memKey, cached);
227
339
  return cached;
228
340
  } catch {}
229
341
 
230
- if (!_babel) _babel = _req("@babel/core");
342
+ if (!ctx.babel) ctx.babel = ctx.req("@babel/core");
231
343
  let out;
232
344
  try {
233
- out = _babel.transformSync(src, {
345
+ out = ctx.babel.transformSync(src, {
234
346
  filename: file,
235
- plugins: _flowEnums ? [_flowEnums] : [],
236
- presets: [[_preset, { disableStaticViewConfigsCodegen: true }]],
347
+ plugins: ctx.flowEnums ? [ctx.flowEnums] : [],
348
+ presets: [[ctx.preset, { disableStaticViewConfigsCodegen: true }]],
237
349
  babelrc: false,
238
350
  configFile: false,
239
351
  caller: { name: "metro", bundler: "metro", platform, supportsStaticESM: false },
@@ -247,7 +359,7 @@ export function transformRN(file, src, projectRoot, platform = "ios") {
247
359
  // Atomic write: multiple worker threads may transform the same RN file
248
360
  // concurrently on a cold cache. Write to a unique temp file then rename
249
361
  // (atomic on POSIX same-dir) so a concurrent reader never sees a partial file.
250
- const tmp = `${cachePath}.${process.pid}.${_writeSeq++}.tmp`;
362
+ const tmp = `${cachePath}.${process.pid}.${ctx.writeSeq++}.tmp`;
251
363
  try {
252
364
  fs.writeFileSync(tmp, out);
253
365
  fs.renameSync(tmp, cachePath);
@@ -256,6 +368,6 @@ export function transformRN(file, src, projectRoot, platform = "ios") {
256
368
  fs.rmSync(tmp, { force: true });
257
369
  } catch {}
258
370
  }
259
- mem.set(memKey, out);
371
+ ctx.mem.set(memKey, out);
260
372
  return out;
261
373
  }
@@ -107,6 +107,11 @@ const resetModules = captureModuleBaseline();
107
107
  const { hotReset, bless } = installHotReset({ projectRoot, diagnostics, preserveGlobals });
108
108
  globalThis.__vitest_native_hot_reset = () => {
109
109
  globalThis.__vitest_native_registry_reset?.();
110
+ // Advance the ESM generation so externalized packages a test file `import`s are
111
+ // re-evaluated instead of served from Node's uninvalidatable ESM registry.
112
+ if (globalThis.__vitest_native_hot_generation) {
113
+ Atomics.add(globalThis.__vitest_native_hot_generation, 0, 1);
114
+ }
110
115
  const dropped = resetModules();
111
116
  hotReset();
112
117
  if (diagnostics) console.log(`[vitest-native] hot reset: dropped ${dropped} modules`);
@@ -1,2 +1,2 @@
1
- import { _ as gestureHandler, a as flashList, c as svg, d as deviceInfo, f as expo, g as safeAreaContext, h as navigation, i as bottomSheet, l as netInfo, m as asyncStorage, n as worklets, o as vectorIcons, p as screens, r as keyboardController, s as webview, u as mmkv, v as reanimated } from "./index-CrMeE8rd.mjs";
1
+ import { _ as gestureHandler, a as flashList, c as svg, d as deviceInfo, f as expo, g as safeAreaContext, h as navigation, i as bottomSheet, l as netInfo, m as asyncStorage, n as worklets, o as vectorIcons, p as screens, r as keyboardController, s as webview, u as mmkv, v as reanimated } from "./index-CmETArCM.mjs";
2
2
  export { asyncStorage, bottomSheet, deviceInfo, expo, flashList, gestureHandler, keyboardController, mmkv, navigation, netInfo, reanimated, safeAreaContext, screens, svg, vectorIcons, webview, worklets };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vitest-native",
3
- "version": "0.11.1",
3
+ "version": "0.12.0",
4
4
  "type": "module",
5
5
  "description": "Run real React Native tests under Vitest. One install, zero config.",
6
6
  "license": "MIT",
@@ -151,6 +151,7 @@
151
151
  "ext-platform-lib": "file:./tests-native/fixtures/ext-platform-lib",
152
152
  "ext-rn-named-lib": "file:./tests-native/fixtures/ext-rn-named-lib",
153
153
  "generic-mainfield-lib": "file:./tests-native/fixtures/generic-mainfield-lib",
154
+ "metro-resolver": "0.87.0",
154
155
  "react": "^19.2.8",
155
156
  "react-native": "^0.86.0",
156
157
  "react-native-gesture-handler": "3.1.0",