vitest-native 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +921 -0
  2. package/README.md +33 -1
  3. package/dist/cli.cjs +185 -31
  4. package/dist/cli.mjs +182 -28
  5. package/dist/ecosystem-BJzJU3Cf.cjs +568 -0
  6. package/dist/ecosystem-C4qT_vl3.mjs +506 -0
  7. package/dist/errors-B3lJK46O.cjs +75 -0
  8. package/dist/errors-CxoBUfVJ.mjs +64 -0
  9. package/dist/errors.d.mts +46 -0
  10. package/dist/errors.mjs +78 -0
  11. package/dist/helpers.cjs +6 -23
  12. package/dist/helpers.d.cts +0 -6
  13. package/dist/helpers.d.mts +0 -6
  14. package/dist/helpers.mjs +6 -23
  15. package/dist/{index-CEgRDdhd.d.cts → index-CrMeE8rd.d.mts} +14 -9
  16. package/dist/{index-j-0tueBr.d.mts → index-DIMbjH8R.d.cts} +15 -7
  17. package/dist/index.d.mts +8 -7
  18. package/dist/index.mjs +307 -91
  19. package/dist/jest-compat/interop.mjs +15 -0
  20. package/dist/jest-compat/setup.mjs +102 -7
  21. package/dist/jest-compat.cjs +4 -4
  22. package/dist/jest-compat.d.cts +0 -1
  23. package/dist/jest-compat.d.mts +0 -1
  24. package/dist/jest-compat.mjs +2 -2
  25. package/dist/matchers.cjs +16 -7
  26. package/dist/matchers.mjs +16 -7
  27. package/dist/native/hooks.mjs +152 -13
  28. package/dist/native/loader.mjs +36 -11
  29. package/dist/native/match.d.mts +33 -0
  30. package/dist/native/match.mjs +94 -22
  31. package/dist/native/module-reset.mjs +63 -0
  32. package/dist/native/registry.mjs +110 -13
  33. package/dist/native/resolve.d.mts +22 -0
  34. package/dist/native/resolve.mjs +21 -13
  35. package/dist/native/runner.mjs +21 -0
  36. package/dist/native/setup.mjs +4 -2
  37. package/dist/native/transform.mjs +108 -3
  38. package/dist/native/worker.mjs +59 -16
  39. package/dist/{pool-DzsEo9vv.cjs → pool-BU-1ecIF.cjs} +7 -6
  40. package/dist/{pool-CJmjRgsB.mjs → pool-Bcxn9a3I.mjs} +4 -3
  41. package/dist/{preset-map-CG4FMtsl.cjs → preset-map-BoG19dLa.cjs} +1 -1
  42. package/dist/{preset-map-CNsZKfvu.mjs → preset-map-DuX0ocdn.mjs} +1 -1
  43. package/dist/{presets-C4faM3ds.cjs → presets-CwO_c4aL.cjs} +224 -55
  44. package/dist/{presets-CuDrNA_W.mjs → presets-IStcJEOa.mjs} +216 -53
  45. package/dist/presets.d.mts +2 -2
  46. package/dist/presets.mjs +2 -2
  47. package/dist/rntl-matchers.d.ts +35 -0
  48. package/dist/{chunk-CjcI7cDX.mjs → rolldown-runtime-BhDjJH2R.mjs} +1 -1
  49. package/dist/{chunk-CZWwpsFl.cjs → rolldown-runtime-C0BPl7ul.cjs} +1 -1
  50. package/dist/serializer.cjs +34 -4
  51. package/dist/serializer.mjs +34 -4
  52. package/dist/setup.d.mts +1 -1
  53. package/dist/setup.mjs +237 -74
  54. package/docs/release-readiness.md +22 -5
  55. package/docs/versioning.md +133 -0
  56. package/package.json +38 -46
  57. package/dist/ecosystem-BIWaVwYL.cjs +0 -294
  58. package/dist/ecosystem-EFtHnKS9.mjs +0 -256
  59. package/dist/index.cjs +0 -788
  60. package/dist/index.d.cts +0 -14
  61. package/dist/presets.cjs +0 -18
  62. package/dist/presets.d.cts +0 -2
  63. package/dist/setup.cjs +0 -2702
  64. package/dist/setup.d.cts +0 -1
@@ -19,14 +19,20 @@ import fs from "node:fs";
19
19
  import os from "node:os";
20
20
  import crypto from "node:crypto";
21
21
  import { decorateTransformError } from "./explain.mjs";
22
+ import { VitestNativeError } from "../errors.mjs";
22
23
 
23
24
  let _req;
24
25
  let _babel;
25
26
  let _preset;
27
+ let _flowEnums;
26
28
  let _cacheDir;
27
29
  let _writeSeq = 0;
28
30
  const mem = new Map();
29
- const TRANSFORM_CACHE_VERSION = 3;
31
+ // 4: Flow enums are now transformed ahead of the preset's strip-types pass, so cached
32
+ // output from 3 is missing every `export enum` declaration. Neither the preset nor
33
+ // Babel version changed, and those are the only other inputs to the directory name, so
34
+ // without this bump a warm cache would keep serving the broken modules.
35
+ export const TRANSFORM_CACHE_VERSION = 4;
30
36
 
31
37
  /**
32
38
  * Root directory for vitest-native's on-disk caches. Prefers the project's
@@ -61,11 +67,32 @@ function init(projectRoot) {
61
67
  // lazily on the first cache miss.
62
68
  _preset = _req.resolve("@react-native/babel-preset");
63
69
  _req.resolve("@babel/core");
70
+ // Flow enums must be transformed BEFORE @babel/plugin-transform-flow-strip-types
71
+ // sees them, or the declaration is removed as if it were a type annotation. The
72
+ // React Native preset carries both, but in separate `overrides` entries that Babel
73
+ // merges into ONE pass with strip-types first — so `export enum Foo {}` is deleted
74
+ // while the code referencing Foo survives, leaving a module that throws
75
+ // ReferenceError on a path nothing warned about. Measured identical on preset
76
+ // 0.85.3 and 0.86.1, so this is the preset's ordering rather than version skew.
77
+ //
78
+ // Babel applies `plugins` before `presets`, so naming the plugin here runs it first
79
+ // and the enum survives. Resolved from the preset, which depends on it, so no new
80
+ // dependency is required.
81
+ try {
82
+ _flowEnums = createRequire(_req.resolve("@react-native/babel-preset/package.json")).resolve(
83
+ "babel-plugin-transform-flow-enums",
84
+ );
85
+ } catch {
86
+ // A preset layout without it: fall back to the preset's own handling rather than
87
+ // failing the run. Flow enums are rare and only two React Native files use them.
88
+ _flowEnums = null;
89
+ }
64
90
  presetVersion = _req("@react-native/babel-preset/package.json").version;
65
91
  babelVersion = _req("@babel/core/package.json").version;
66
92
  } catch {
67
- throw new Error(
68
- "[vitest-native] engine 'native' requires '@react-native/babel-preset' and " +
93
+ throw new VitestNativeError(
94
+ "ENGINE_REQUIRES_BABEL",
95
+ "engine 'native' requires '@react-native/babel-preset' and " +
69
96
  "'@babel/core' in your project. Install them as devDependencies " +
70
97
  "(they ship with React Native projects by default).",
71
98
  );
@@ -89,6 +116,83 @@ export function transformCacheDir() {
89
116
  }
90
117
 
91
118
  /** Returns true if the source contains RN Flow syntax that must be transformed. */
119
+ /** A valid identifier, so a name can appear in the shorthand export hint. */
120
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
121
+
122
+ /**
123
+ * Named exports of already-transformed CommonJS code, read from its AST.
124
+ *
125
+ * Node decides a CommonJS module's named exports with cjs-module-lexer, which reads
126
+ * the source statically and stops at shapes it cannot follow. `module.exports = {
127
+ * A() {}, b: () => 1 }` — ordinary hand-written CommonJS, and common across the React
128
+ * Native ecosystem — yields `["A", "default", "module.exports"]`: `b` is missing, and
129
+ * a name that is not an export appears. That is plain Node behaviour, reproducible
130
+ * with no plugin involved.
131
+ *
132
+ * Reading it properly is possible here because Babel is already loaded to do the
133
+ * transform, and because the input is the transform's own output rather than
134
+ * arbitrary source. Names are used only to emit a dead `0 && (module.exports = {…})`
135
+ * hint, which is the form the lexer does understand.
136
+ *
137
+ * Returns an empty array when the shape is not statically knowable (`module.exports =
138
+ * someValue`), which leaves Node's own detection in charge — no worse than before.
139
+ */
140
+ export function cjsExportNames(code) {
141
+ if (!_babel) {
142
+ if (!_req) return [];
143
+ _babel = _req("@babel/core");
144
+ }
145
+ let ast;
146
+ try {
147
+ ast = _babel.parseSync(code, { babelrc: false, configFile: false, sourceType: "script" });
148
+ } catch {
149
+ return [];
150
+ }
151
+ const names = new Set();
152
+ const isExportsTarget = (node, wantMember) => {
153
+ if (!node) return false;
154
+ if (node.type === "Identifier") return !wantMember && node.name === "exports";
155
+ if (node.type !== "MemberExpression" || node.computed) return false;
156
+ return (
157
+ node.object.type === "Identifier" &&
158
+ node.object.name === "module" &&
159
+ node.property.type === "Identifier" &&
160
+ node.property.name === "exports"
161
+ );
162
+ };
163
+ for (const statement of ast.program.body) {
164
+ if (statement.type !== "ExpressionStatement") continue;
165
+ const expression = statement.expression;
166
+ if (expression.type !== "AssignmentExpression" || expression.operator !== "=") continue;
167
+ const target = expression.left;
168
+ // `module.exports = { … }` / `exports = { … }` — take the literal's own keys.
169
+ if (isExportsTarget(target, true) || isExportsTarget(target, false)) {
170
+ if (expression.right.type !== "ObjectExpression") continue;
171
+ for (const property of expression.right.properties) {
172
+ if (property.type === "SpreadElement" || property.computed) continue;
173
+ const key = property.key;
174
+ if (key.type === "Identifier") names.add(key.name);
175
+ else if (key.type === "StringLiteral" && IDENTIFIER.test(key.value)) names.add(key.value);
176
+ }
177
+ continue;
178
+ }
179
+ // `exports.foo = …` / `module.exports.foo = …` — the lexer handles these, but
180
+ // a module can mix both forms and the object-literal branch would miss them.
181
+ if (target.type === "MemberExpression" && !target.computed) {
182
+ const owner = target.object;
183
+ if (
184
+ (owner.type === "Identifier" && owner.name === "exports") ||
185
+ isExportsTarget(owner, true)
186
+ ) {
187
+ if (target.property.type === "Identifier") names.add(target.property.name);
188
+ }
189
+ }
190
+ }
191
+ names.delete("default");
192
+ names.delete("__esModule");
193
+ return [...names].filter((name) => IDENTIFIER.test(name));
194
+ }
195
+
92
196
  export function isFlow(src) {
93
197
  return /@flow|import typeof|\bcomponent\s+\w/.test(src);
94
198
  }
@@ -128,6 +232,7 @@ export function transformRN(file, src, projectRoot, platform = "ios") {
128
232
  try {
129
233
  out = _babel.transformSync(src, {
130
234
  filename: file,
235
+ plugins: _flowEnums ? [_flowEnums] : [],
131
236
  presets: [[_preset, { disableStaticViewConfigsCodegen: true }]],
132
237
  babelrc: false,
133
238
  configFile: false,
@@ -17,10 +17,12 @@ import { installGlobals } from "./globals.mjs";
17
17
  import { installRequireHooks } from "./hooks.mjs";
18
18
  import { installHotReset } from "./reset.mjs";
19
19
  import { installRegistry } from "./registry.mjs";
20
+ import { captureModuleBaseline } from "./module-reset.mjs";
20
21
  import { enableV8CompileCache } from "./compile-cache.mjs";
22
+ import { VitestNativeError } from "../errors.mjs";
21
23
 
22
24
  if (isMainThread || !parentPort) {
23
- throw new Error("[vitest-native] hot worker entry must run in node:worker_threads");
25
+ throw new VitestNativeError("HOT_WORKER_ENV", "hot worker entry must run in node:worker_threads");
24
26
  }
25
27
 
26
28
  const projectRoot = process.env.VITEST_NATIVE_PROJECT_ROOT || process.cwd();
@@ -95,24 +97,62 @@ try {
95
97
  RN.Appearance.getColorScheme?.();
96
98
  } catch {}
97
99
  } catch (error) {
98
- throw new Error(
99
- `[vitest-native] hot worker failed to preload react-native from ${projectRoot}: ${error?.message}`,
100
+ throw new VitestNativeError(
101
+ "HOT_WORKER_PRELOAD",
102
+ `hot worker failed to preload react-native from ${projectRoot}: ${error?.message}`,
100
103
  { cause: error },
101
104
  );
102
105
  }
106
+ const resetModules = captureModuleBaseline();
103
107
  const { hotReset, bless } = installHotReset({ projectRoot, diagnostics, preserveGlobals });
104
- globalThis.__vitest_native_hot_reset = hotReset; // invoked by setup.mjs per file
105
- globalThis.__vitest_native_hot_bless = bless; // invoked by runner.mjs after each import phase
108
+ globalThis.__vitest_native_hot_reset = () => {
109
+ globalThis.__vitest_native_registry_reset?.();
110
+ const dropped = resetModules();
111
+ hotReset();
112
+ if (diagnostics) console.log(`[vitest-native] hot reset: dropped ${dropped} modules`);
113
+ };
114
+ globalThis.__vitest_native_hot_bless = bless;
106
115
 
107
- function runWithPerFileIsolation(method) {
108
- return (state, traces) => {
109
- // Vitest's worker-side per-file reset clears only the module-runner graph;
110
- // externalized RN in the Node require cache is untouched — exactly the
111
- // "fresh user modules, resident RN" split the native engine needs.
112
- state.ctx.config.isolate = true;
113
- return runBaseTests(method, state, traces);
114
- };
115
- }
116
+ // Vitest's own per-file isolation — mocker reset plus a clear of the evaluated
117
+ // module graph — is gated on `config.isolate`, which the pool sets to false so the
118
+ // scheduler keeps this worker alive. Doing the two steps ourselves gives the same
119
+ // result without touching Vitest's worker state.
120
+ //
121
+ // This used to be done by mutating `state.ctx.config.isolate = true` inside the
122
+ // worker. That read a shape nothing contracts, and it broke on a PATCH release:
123
+ // vitest 4.1.9 on Node 24 produced "Cannot read properties of undefined (reading
124
+ // 'config')" for every test file and a run that reported no tests at all. The two
125
+ // operations below are public API — `mocker.reset()` and Vite's
126
+ // `ModuleRunner.clearCache()` — so a Vitest internal moving cannot silently take the
127
+ // hot runtime with it.
128
+ let moduleRunner = null;
129
+
130
+ /**
131
+ * Reset the module-runner graph for the next test file.
132
+ *
133
+ * Called from the runner's per-file hook rather than here, because a single task can
134
+ * carry several files (Vitest batches them in single-worker mode) and each one needs
135
+ * its own reset — the same cadence Vitest uses when isolation is on. See runner.mjs
136
+ * for why that hook is onBeforeCollect and not onCollectStart.
137
+ */
138
+ // Vitest's own reset deliberately leaves its runtime modules evaluated and only
139
+ // clears evaluation state on the rest; it does not throw the module graph away.
140
+ // `ModuleRunner.clearCache()` does throw it away, Vitest's own dist included, which
141
+ // measured 29% more peak memory and ~6% slower at 200 files — every file re-creating
142
+ // module nodes, and re-evaluating Vitest itself, for nothing.
143
+ const VITEST_RUNTIME = [/\/vitest\/dist\//, /vitest-virtual-\w+\/dist/, /@vitest\/dist/];
144
+
145
+ globalThis.__vitest_native_reset_module_runner = () => {
146
+ if (!moduleRunner) return;
147
+ moduleRunner.mocker?.reset();
148
+ for (const [id, node] of moduleRunner.evaluatedModules.idToModuleMap) {
149
+ if (VITEST_RUNTIME.some((re) => re.test(id))) continue;
150
+ node.promise = undefined;
151
+ node.exports = undefined;
152
+ node.evaluated = false;
153
+ node.importers.clear();
154
+ }
155
+ };
116
156
 
117
157
  init({
118
158
  // oxlint-disable-next-line unicorn/require-post-message-target-origin -- worker_threads MessagePort, not window
@@ -120,7 +160,10 @@ init({
120
160
  on: (callback) => parentPort.on("message", callback),
121
161
  off: (callback) => parentPort.off("message", callback),
122
162
  teardown: () => parentPort.removeAllListeners("message"),
123
- runTests: runWithPerFileIsolation("run"),
124
- collectTests: runWithPerFileIsolation("collect"),
163
+ runTests: (state, traces) => runBaseTests("run", state, traces),
164
+ collectTests: (state, traces) => runBaseTests("collect", state, traces),
165
+ onModuleRunner: (runner) => {
166
+ moduleRunner = runner;
167
+ },
125
168
  setup: setupEnvironment,
126
169
  });
@@ -1,9 +1,10 @@
1
- const require_chunk = require("./chunk-CZWwpsFl.cjs");
1
+ const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
2
+ const require_errors = require("./errors-B3lJK46O.cjs");
2
3
  let node_path = require("node:path");
3
- node_path = require_chunk.__toESM(node_path, 1);
4
+ node_path = require_rolldown_runtime.__toESM(node_path, 1);
4
5
  let node_module = require("node:module");
5
6
  let node_os = require("node:os");
6
- node_os = require_chunk.__toESM(node_os, 1);
7
+ node_os = require_rolldown_runtime.__toESM(node_os, 1);
7
8
  let vitest_node = require("vitest/node");
8
9
  //#region src/native/pool.ts
9
10
  function deepEqual(a, b) {
@@ -61,8 +62,8 @@ var NativePoolWorker = class extends vitest_node.ThreadsPoolWorker {
61
62
  return env.name === this.environment.name && deepEqual(env.options, this.environment.options);
62
63
  }
63
64
  };
64
- const HOT_MEMORY_MIN_BYTES = 768 * 1024 * 1024;
65
- const HOT_MEMORY_MAX_BYTES = 1536 * 1024 * 1024;
65
+ const HOT_MEMORY_MIN_BYTES = 805306368;
66
+ const HOT_MEMORY_MAX_BYTES = 1610612736;
66
67
  const HOT_MEMORY_FRACTION = .25;
67
68
  /**
68
69
  * Default per-worker hot `memoryLimit` (bytes): `clamp(totalmem * 0.25, 768MB, 1.5GB)`.
@@ -106,7 +107,7 @@ function assertWorkerVitestMatchesProject(workerEntry, projectRoot) {
106
107
  const worker = resolveVitest(workerEntry);
107
108
  const project = resolveVitest(node_path.default.join(projectRoot, "package.json"));
108
109
  if (worker === null || project === null || worker.version === project.version) return;
109
- throw new Error(`[vitest-native] 'hotRuntime' cannot run: its worker would load vitest@${worker.version}, but this run is driven by vitest@${project.version}. They talk over Vitest's worker protocol, and a version mismatch reports no results at all rather than failing.\n worker would load: ${worker.path}\n project resolves: ${project.path}\nThis happens when vitest-native and vitest resolve to different node_modules trees (linked packages, hoisted monorepo installs, mixed Vitest versions). Install one Vitest version reachable from vitest-native, or set 'hotRuntime: false'.`);
110
+ throw new require_errors.VitestNativeError("HOT_RUNTIME_UNAVAILABLE", `'hotRuntime' cannot run: its worker would load vitest@${worker.version}, but this run is driven by vitest@${project.version}. They talk over Vitest's worker protocol, and a version mismatch reports no results at all rather than failing.\n worker would load: ${worker.path}\n project resolves: ${project.path}\nThis happens when vitest-native and vitest resolve to different node_modules trees (linked packages, hoisted monorepo installs, mixed Vitest versions). Install one Vitest version reachable from vitest-native, or set 'hotRuntime: false'.`);
110
111
  }
111
112
  /** Pool initializer for `test.pool` — keeps RN-hot workers alive across files. */
112
113
  function nativePool(options) {
@@ -1,3 +1,4 @@
1
+ import { t as VitestNativeError } from "./errors-CxoBUfVJ.mjs";
1
2
  import { createRequire } from "node:module";
2
3
  import path from "node:path";
3
4
  import os from "node:os";
@@ -58,8 +59,8 @@ var NativePoolWorker = class extends ThreadsPoolWorker {
58
59
  return env.name === this.environment.name && deepEqual(env.options, this.environment.options);
59
60
  }
60
61
  };
61
- const HOT_MEMORY_MIN_BYTES = 768 * 1024 * 1024;
62
- const HOT_MEMORY_MAX_BYTES = 1536 * 1024 * 1024;
62
+ const HOT_MEMORY_MIN_BYTES = 805306368;
63
+ const HOT_MEMORY_MAX_BYTES = 1610612736;
63
64
  const HOT_MEMORY_FRACTION = .25;
64
65
  /**
65
66
  * Default per-worker hot `memoryLimit` (bytes): `clamp(totalmem * 0.25, 768MB, 1.5GB)`.
@@ -103,7 +104,7 @@ function assertWorkerVitestMatchesProject(workerEntry, projectRoot) {
103
104
  const worker = resolveVitest(workerEntry);
104
105
  const project = resolveVitest(path.join(projectRoot, "package.json"));
105
106
  if (worker === null || project === null || worker.version === project.version) return;
106
- throw new Error(`[vitest-native] 'hotRuntime' cannot run: its worker would load vitest@${worker.version}, but this run is driven by vitest@${project.version}. They talk over Vitest's worker protocol, and a version mismatch reports no results at all rather than failing.\n worker would load: ${worker.path}\n project resolves: ${project.path}\nThis happens when vitest-native and vitest resolve to different node_modules trees (linked packages, hoisted monorepo installs, mixed Vitest versions). Install one Vitest version reachable from vitest-native, or set 'hotRuntime: false'.`);
107
+ throw new VitestNativeError("HOT_RUNTIME_UNAVAILABLE", `'hotRuntime' cannot run: its worker would load vitest@${worker.version}, but this run is driven by vitest@${project.version}. They talk over Vitest's worker protocol, and a version mismatch reports no results at all rather than failing.\n worker would load: ${worker.path}\n project resolves: ${project.path}\nThis happens when vitest-native and vitest resolve to different node_modules trees (linked packages, hoisted monorepo installs, mixed Vitest versions). Install one Vitest version reachable from vitest-native, or set 'hotRuntime: false'.`);
107
108
  }
108
109
  /** Pool initializer for `test.pool` — keeps RN-hot workers alive across files. */
109
110
  function nativePool(options) {
@@ -18,10 +18,10 @@ const AUTO_DETECT_PRESETS = {
18
18
  "expo-constants": "expo",
19
19
  "react-native-device-info": "deviceInfo",
20
20
  "react-native-mmkv": "mmkv",
21
+ "@react-native-community/netinfo": "netInfo",
21
22
  "react-native-svg": "svg",
22
23
  "react-native-webview": "webview",
23
24
  "@react-native-vector-icons/common": "vectorIcons",
24
- "react-native-vector-icons": "vectorIcons",
25
25
  "@shopify/flash-list": "flashList",
26
26
  "@gorhom/bottom-sheet": "bottomSheet",
27
27
  "react-native-keyboard-controller": "keyboardController"
@@ -18,10 +18,10 @@ const AUTO_DETECT_PRESETS = {
18
18
  "expo-constants": "expo",
19
19
  "react-native-device-info": "deviceInfo",
20
20
  "react-native-mmkv": "mmkv",
21
+ "@react-native-community/netinfo": "netInfo",
21
22
  "react-native-svg": "svg",
22
23
  "react-native-webview": "webview",
23
24
  "@react-native-vector-icons/common": "vectorIcons",
24
- "react-native-vector-icons": "vectorIcons",
25
25
  "@shopify/flash-list": "flashList",
26
26
  "@gorhom/bottom-sheet": "bottomSheet",
27
27
  "react-native-keyboard-controller": "keyboardController"