vitest-native 0.8.0 → 0.10.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.
- package/CHANGELOG.md +1063 -0
- package/README.md +47 -2
- package/dist/cli.cjs +642 -0
- package/dist/cli.d.cts +4 -0
- package/dist/cli.d.mts +4 -0
- package/dist/cli.mjs +638 -0
- package/dist/ecosystem-CO5vqExO.mjs +318 -0
- package/dist/ecosystem-IuZ-Gv0R.cjs +356 -0
- package/dist/errors-Dm5yLNTF.mjs +64 -0
- package/dist/errors-flXDIeWk.cjs +75 -0
- package/dist/errors.d.mts +46 -0
- package/dist/errors.mjs +78 -0
- package/dist/helpers.cjs +6 -23
- package/dist/helpers.d.cts +0 -6
- package/dist/helpers.d.mts +0 -6
- package/dist/helpers.mjs +6 -23
- package/dist/{index-vlK4zxuK.d.mts → index-BJL4cQ-l.d.cts} +22 -7
- package/dist/{index-YjjYELG7.d.cts → index-CvCU0cLl.d.mts} +20 -9
- package/dist/index.d.mts +8 -6
- package/dist/index.mjs +563 -232
- package/dist/jest-compat/interop.mjs +15 -0
- package/dist/jest-compat/setup.mjs +164 -5
- package/dist/matchers.cjs +16 -7
- package/dist/matchers.mjs +16 -7
- package/dist/native/boundary.mjs +108 -30
- package/dist/native/compile-cache.mjs +10 -5
- package/dist/native/explain.mjs +69 -0
- package/dist/native/hooks.mjs +151 -4
- package/dist/native/loader.mjs +61 -12
- package/dist/native/match.mjs +107 -8
- package/dist/native/module-reset.mjs +63 -0
- package/dist/native/registry.mjs +540 -0
- package/dist/native/reset.mjs +18 -12
- package/dist/native/resolve.d.mts +22 -0
- package/dist/native/resolve.mjs +21 -13
- package/dist/native/runner.mjs +34 -7
- package/dist/native/setup.mjs +19 -3
- package/dist/native/transform.mjs +195 -21
- package/dist/native/worker.mjs +69 -17
- package/dist/pool-Bcxp4Qrg.mjs +118 -0
- package/dist/pool-CFND7plG.cjs +122 -0
- package/dist/{preset-map-DCWaM08s.mjs → preset-map-BpDG_D5m.mjs} +1 -1
- package/dist/{preset-map-BY9zk9Pj.cjs → preset-map-DxilQ4pI.cjs} +1 -1
- package/dist/{presets-7eMfp7o2.cjs → presets-BGTqVH6C.cjs} +227 -52
- package/dist/{presets-23FJ76O4.mjs → presets-CK85x8ey.mjs} +222 -53
- package/dist/presets.d.mts +2 -2
- package/dist/presets.mjs +2 -2
- package/dist/rntl-matchers.d.ts +35 -0
- package/dist/serializer.cjs +33 -3
- package/dist/serializer.mjs +33 -3
- package/dist/setup.mjs +544 -193
- package/docs/hot-default-design.md +129 -0
- package/docs/migrating-from-jest.md +43 -7
- package/docs/migrating-from-vitest-react-native.md +1 -1
- package/docs/release-readiness.md +24 -6
- package/docs/versioning.md +133 -0
- package/package.json +40 -38
- package/dist/index.cjs +0 -643
- package/dist/index.d.cts +0 -14
- package/dist/pool-B7LBfcMQ.mjs +0 -67
- package/dist/pool-p54QV1dQ.cjs +0 -69
- package/dist/presets.cjs +0 -17
- package/dist/presets.d.cts +0 -2
- package/dist/setup.cjs +0 -2514
- package/dist/setup.d.cts +0 -1
package/dist/native/runner.mjs
CHANGED
|
@@ -8,20 +8,47 @@
|
|
|
8
8
|
// (resident-library lazy init — must be preserved across files, it never
|
|
9
9
|
// re-runs) and test-phase state (pollution the next file's reset removes).
|
|
10
10
|
// See reset.mjs for the full attribution model.
|
|
11
|
-
// vitest >=4.1 exports TestRunner from the main entry;
|
|
12
|
-
// VitestTestRunner via the
|
|
13
|
-
// main entry
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
//
|
|
11
|
+
// vitest >=4.1 exports TestRunner from the main entry; 4.0.x only exposes it as
|
|
12
|
+
// VitestTestRunner via the "vitest/runners" subpath, which vitest 5 REMOVED.
|
|
13
|
+
// Prefer the main entry, and reach for the old subpath only when the main export
|
|
14
|
+
// is absent.
|
|
15
|
+
//
|
|
16
|
+
// The fallback specifier is computed rather than written literally, because a
|
|
17
|
+
// literal is resolved when this module is TRANSFORMED, not when the branch runs.
|
|
18
|
+
// Against vitest 5 that resolution fails ("./runners" is not exported), and the
|
|
19
|
+
// failure is silent in the worst way: the run reports unhandled errors, executes
|
|
20
|
+
// no tests, and still exits 0. A computed specifier keeps the branch invisible to
|
|
21
|
+
// the resolver, so 4.0.x keeps its fallback and 5 never looks for it.
|
|
17
22
|
import * as vitest from "vitest";
|
|
18
23
|
|
|
19
24
|
let TestRunner = vitest.TestRunner;
|
|
20
25
|
if (!TestRunner) {
|
|
21
|
-
|
|
26
|
+
const legacyRunners = ["vitest", "runners"].join("/");
|
|
27
|
+
({ VitestTestRunner: TestRunner } = await import(/* @vite-ignore */ legacyRunners));
|
|
22
28
|
}
|
|
23
29
|
|
|
24
30
|
export default class NativeHotRunner extends TestRunner {
|
|
31
|
+
// Fires once per test file, before its setup files and its own modules are
|
|
32
|
+
// imported — the point where Vitest resets the module graph when isolation is on.
|
|
33
|
+
// The hot pool runs with isolation off so the worker survives, so the reset happens
|
|
34
|
+
// here instead, through public API rather than by mutating Vitest's worker state.
|
|
35
|
+
//
|
|
36
|
+
// onBeforeCollect, not onCollectStart. Vitest AWAITS this one; it calls
|
|
37
|
+
// onCollectStart without awaiting, and the worker wraps that hook in an async
|
|
38
|
+
// function that first awaits an RPC to the main thread. The reset therefore landed
|
|
39
|
+
// some indeterminate time after collection had already started — measured at ~0.2ms
|
|
40
|
+
// against a 1-45ms head start on the setup-file import, so it always won in
|
|
41
|
+
// practice, but nothing ordered it. Losing that race would have reset the graph
|
|
42
|
+
// mid-import and dropped any mock a setup file had just registered.
|
|
43
|
+
//
|
|
44
|
+
// Vitest passes an array because the hook is shaped for a batch, but its per-file
|
|
45
|
+
// loop invokes the run through startTests([file]) one file at a time, which is the
|
|
46
|
+
// cadence the reset needs.
|
|
47
|
+
async onBeforeCollect(paths) {
|
|
48
|
+
globalThis.__vitest_native_reset_module_runner?.();
|
|
49
|
+
return super.onBeforeCollect?.(paths);
|
|
50
|
+
}
|
|
51
|
+
|
|
25
52
|
async onBeforeRunFiles(files) {
|
|
26
53
|
globalThis.__vitest_native_hot_bless?.();
|
|
27
54
|
return super.onBeforeRunFiles?.(files);
|
package/dist/native/setup.mjs
CHANGED
|
@@ -6,10 +6,12 @@ import path from "node:path";
|
|
|
6
6
|
import { expect, vi } from "vitest";
|
|
7
7
|
import { installGlobals } from "./globals.mjs";
|
|
8
8
|
import { installRequireHooks } from "./hooks.mjs";
|
|
9
|
+
import { installRegistry } from "./registry.mjs";
|
|
9
10
|
import { enableV8CompileCache } from "./compile-cache.mjs";
|
|
10
11
|
import * as presetFactories from "../presets.mjs";
|
|
11
12
|
import { animatedMatchers } from "../matchers.mjs";
|
|
12
13
|
import { serializer as rnSerializer } from "../serializer.mjs";
|
|
14
|
+
import { VitestNativeError } from "../errors.mjs";
|
|
13
15
|
|
|
14
16
|
// Hot runtime: surgical reset of state left by the PREVIOUS file. Setup files
|
|
15
17
|
// are force-inlined by Vitest, so this body re-runs per test file even when the
|
|
@@ -99,7 +101,7 @@ for (const name of presetNames) {
|
|
|
99
101
|
// Enable the V8 compile cache before RN is compiled (it loads when the test file
|
|
100
102
|
// imports react-native, after this setup runs) so its bytecode is cached to disk
|
|
101
103
|
// and reused on the next file/worker/run. Covers the stock (non-hot) path.
|
|
102
|
-
enableV8CompileCache();
|
|
104
|
+
enableV8CompileCache(projectRoot);
|
|
103
105
|
installGlobals();
|
|
104
106
|
// RNTL 13+ auto-registers matchers through the global expect when imported.
|
|
105
107
|
// Expose Vitest's expect only when the consumer has not enabled globals.
|
|
@@ -121,6 +123,19 @@ if (!globalThis.__vitest_native_loader_registered) {
|
|
|
121
123
|
data: { projectRoot, platform, reactNativeVersion, transformPkgs, presetExports, assetExts },
|
|
122
124
|
});
|
|
123
125
|
}
|
|
126
|
+
// Serve React Native from the precompiled registry when the plugin produced one
|
|
127
|
+
// (see registry.mjs). Installed BEFORE the require hooks so their preset-mock
|
|
128
|
+
// redirect wraps this one and keeps precedence. Any module the registry cannot
|
|
129
|
+
// serve — a computed require, a package in `transform` — falls through to the
|
|
130
|
+
// hooks below, so this is purely a faster path to the same modules.
|
|
131
|
+
if (process.env.VITEST_NATIVE_RN_REGISTRY) {
|
|
132
|
+
const installed = installRegistry(process.env.VITEST_NATIVE_RN_REGISTRY, projectRoot);
|
|
133
|
+
if (diagnostics) {
|
|
134
|
+
console.log(
|
|
135
|
+
`[vitest-native] (native) precompiled RN registry ${installed ? "installed" : "unavailable; using per-file module loading"}`,
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
124
139
|
installRequireHooks(projectRoot, transformPkgs, platform, reactNativeVersion, assetExts);
|
|
125
140
|
|
|
126
141
|
// Build the mock objects now that the require hooks are installed (preset
|
|
@@ -156,8 +171,9 @@ function emitColorScheme(colorScheme) {
|
|
|
156
171
|
g.__vitest_native_control = {
|
|
157
172
|
engine: "native",
|
|
158
173
|
setPlatform() {
|
|
159
|
-
throw new
|
|
160
|
-
|
|
174
|
+
throw new VitestNativeError(
|
|
175
|
+
"WRONG_ENGINE_FOR_HELPER",
|
|
176
|
+
`setPlatform() is only available with engine:'mock'. ` +
|
|
161
177
|
`The native engine selects platform files when the module graph loads. ` +
|
|
162
178
|
`Use reactNative({ platform: 'ios' | 'android' }) or separate Vitest projects.`,
|
|
163
179
|
);
|
|
@@ -2,44 +2,197 @@
|
|
|
2
2
|
// (the only transformer that lowers RN's `component` syntax). Used by BOTH the loader
|
|
3
3
|
// hook (import) and the require hook, which run in separate threads: each gets its own
|
|
4
4
|
// instance of this module, so the in-memory `mem` cache below is per-thread (no shared
|
|
5
|
-
// mutable state to race on). The disk cache — keyed by
|
|
6
|
-
//
|
|
5
|
+
// mutable state to race on). The disk cache — keyed by CONTENT hash + platform, in a
|
|
6
|
+
// directory versioned by preset + @babel/core versions — is the layer shared across
|
|
7
|
+
// threads, workers, runs, and (because content-keyed entries survive fresh installs
|
|
8
|
+
// and mtime normalization) CI cache restores. The path is part of the key too —
|
|
9
|
+
// Babel output embeds the filename — so restores are valid wherever the checkout
|
|
10
|
+
// path is stable (CI runners use a fixed workspace path).
|
|
11
|
+
//
|
|
12
|
+
// @babel/core itself is loaded lazily, only on a cache MISS: on a warm cache the
|
|
13
|
+
// default engine pays this module's init in every isolated worker, and requiring
|
|
14
|
+
// Babel costs ~35ms vs ~0.5ms for resolving versions — pure waste when every file
|
|
15
|
+
// is served from disk.
|
|
7
16
|
import { createRequire } from "node:module";
|
|
8
17
|
import path from "node:path";
|
|
9
18
|
import fs from "node:fs";
|
|
10
19
|
import os from "node:os";
|
|
11
20
|
import crypto from "node:crypto";
|
|
21
|
+
import { decorateTransformError } from "./explain.mjs";
|
|
22
|
+
import { VitestNativeError } from "../errors.mjs";
|
|
12
23
|
|
|
24
|
+
let _req;
|
|
13
25
|
let _babel;
|
|
14
26
|
let _preset;
|
|
27
|
+
let _flowEnums;
|
|
15
28
|
let _cacheDir;
|
|
16
29
|
let _writeSeq = 0;
|
|
17
30
|
const mem = new Map();
|
|
18
|
-
|
|
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;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Root directory for vitest-native's on-disk caches. Prefers the project's
|
|
39
|
+
* node_modules/.cache — persistent across runs, per-project, and restorable by
|
|
40
|
+
* standard CI dependency-cache actions (unlike os.tmpdir(), which is ephemeral
|
|
41
|
+
* on CI runners and periodically purged on macOS). Falls back to tmpdir when
|
|
42
|
+
* node_modules is absent or unwritable.
|
|
43
|
+
*/
|
|
44
|
+
export function cacheRootFor(projectRoot) {
|
|
45
|
+
const nm = path.join(projectRoot, "node_modules");
|
|
46
|
+
if (fs.existsSync(nm)) {
|
|
47
|
+
try {
|
|
48
|
+
const dir = path.join(nm, ".cache", "vitest-native");
|
|
49
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
50
|
+
return dir;
|
|
51
|
+
} catch {
|
|
52
|
+
// Read-only node_modules (some CI sandboxes) — fall through to tmpdir.
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const dir = path.join(os.tmpdir(), "vitest-native-cache");
|
|
56
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
57
|
+
return dir;
|
|
58
|
+
}
|
|
19
59
|
|
|
20
60
|
function init(projectRoot) {
|
|
21
|
-
if (
|
|
22
|
-
|
|
61
|
+
if (_cacheDir) return;
|
|
62
|
+
_req = createRequire(path.join(projectRoot, "package.json"));
|
|
63
|
+
let presetVersion;
|
|
64
|
+
let babelVersion;
|
|
23
65
|
try {
|
|
24
|
-
|
|
25
|
-
|
|
66
|
+
// Resolve-only here (cheap); the actual require of @babel/core happens
|
|
67
|
+
// lazily on the first cache miss.
|
|
68
|
+
_preset = _req.resolve("@react-native/babel-preset");
|
|
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
|
+
}
|
|
90
|
+
presetVersion = _req("@react-native/babel-preset/package.json").version;
|
|
91
|
+
babelVersion = _req("@babel/core/package.json").version;
|
|
26
92
|
} catch {
|
|
27
|
-
throw new
|
|
28
|
-
"
|
|
93
|
+
throw new VitestNativeError(
|
|
94
|
+
"ENGINE_REQUIRES_BABEL",
|
|
95
|
+
"engine 'native' requires '@react-native/babel-preset' and " +
|
|
29
96
|
"'@babel/core' in your project. Install them as devDependencies " +
|
|
30
97
|
"(they ship with React Native projects by default).",
|
|
31
98
|
);
|
|
32
99
|
}
|
|
33
|
-
|
|
100
|
+
// Both transformer versions key the directory — a preset or Babel upgrade
|
|
101
|
+
// must never serve output produced by the previous version — and so does the
|
|
102
|
+
// Babel environment: the preset's dev-mode JSX transform produces different
|
|
103
|
+
// output (e.g. _jsxFileName injection) under NODE_ENV=development than under
|
|
104
|
+
// test/production.
|
|
105
|
+
const babelEnv = process.env.BABEL_ENV || process.env.NODE_ENV || "none";
|
|
34
106
|
_cacheDir = path.join(
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
`${presetVersion}-v${TRANSFORM_CACHE_VERSION}`,
|
|
107
|
+
cacheRootFor(projectRoot),
|
|
108
|
+
`transform-${presetVersion}-b${babelVersion}-${babelEnv}-v${TRANSFORM_CACHE_VERSION}`,
|
|
38
109
|
);
|
|
39
110
|
fs.mkdirSync(_cacheDir, { recursive: true });
|
|
40
111
|
}
|
|
41
112
|
|
|
113
|
+
/** The active transform disk-cache directory (resolved on first use). Test hook. */
|
|
114
|
+
export function transformCacheDir() {
|
|
115
|
+
return _cacheDir ?? null;
|
|
116
|
+
}
|
|
117
|
+
|
|
42
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
|
+
|
|
43
196
|
export function isFlow(src) {
|
|
44
197
|
return /@flow|import typeof|\bcomponent\s+\w/.test(src);
|
|
45
198
|
}
|
|
@@ -47,6 +200,13 @@ export function isFlow(src) {
|
|
|
47
200
|
/** Transform an RN source file to runnable CJS. Cached in-memory + on disk. */
|
|
48
201
|
export function transformRN(file, src, projectRoot, platform = "ios") {
|
|
49
202
|
init(projectRoot);
|
|
203
|
+
// The in-memory key uses mtime+size (one statSync) so the hot path skips
|
|
204
|
+
// hashing; the DISK key hashes the actual content, so entries stay valid
|
|
205
|
+
// across fresh installs, Docker mtime normalization, and CI cache restores —
|
|
206
|
+
// and a same-path file with different content can never produce a wrong hit.
|
|
207
|
+
// The FILENAME is part of the key because Babel's output depends on it: the
|
|
208
|
+
// preset embeds the absolute path (_jsxFileName) in transformed JSX, so two
|
|
209
|
+
// identical sources at different paths must not share an entry.
|
|
50
210
|
const st = fs.statSync(file);
|
|
51
211
|
const memKey = `${platform}\0${file}\0${st.mtimeMs}\0${st.size}`;
|
|
52
212
|
const memHit = mem.get(memKey);
|
|
@@ -54,7 +214,11 @@ export function transformRN(file, src, projectRoot, platform = "ios") {
|
|
|
54
214
|
|
|
55
215
|
const key = crypto
|
|
56
216
|
.createHash("sha1")
|
|
57
|
-
.update(platform
|
|
217
|
+
.update(platform)
|
|
218
|
+
.update("\0")
|
|
219
|
+
.update(file)
|
|
220
|
+
.update("\0")
|
|
221
|
+
.update(src)
|
|
58
222
|
.digest("hex");
|
|
59
223
|
const cachePath = path.join(_cacheDir, key + ".js");
|
|
60
224
|
try {
|
|
@@ -63,13 +227,23 @@ export function transformRN(file, src, projectRoot, platform = "ios") {
|
|
|
63
227
|
return cached;
|
|
64
228
|
} catch {}
|
|
65
229
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
230
|
+
if (!_babel) _babel = _req("@babel/core");
|
|
231
|
+
let out;
|
|
232
|
+
try {
|
|
233
|
+
out = _babel.transformSync(src, {
|
|
234
|
+
filename: file,
|
|
235
|
+
plugins: _flowEnums ? [_flowEnums] : [],
|
|
236
|
+
presets: [[_preset, { disableStaticViewConfigsCodegen: true }]],
|
|
237
|
+
babelrc: false,
|
|
238
|
+
configFile: false,
|
|
239
|
+
caller: { name: "metro", bundler: "metro", platform, supportsStaticESM: false },
|
|
240
|
+
}).code;
|
|
241
|
+
} catch (err) {
|
|
242
|
+
// Decorate here, at the single choke point, so every caller — the ESM
|
|
243
|
+
// loader, the CJS require hook, requireActual's .ts handlers — surfaces
|
|
244
|
+
// the file, platform, and owning package instead of a bare Babel stack.
|
|
245
|
+
throw decorateTransformError(err, file, platform);
|
|
246
|
+
}
|
|
73
247
|
// Atomic write: multiple worker threads may transform the same RN file
|
|
74
248
|
// concurrently on a cold cache. Write to a unique temp file then rename
|
|
75
249
|
// (atomic on POSIX same-dir) so a concurrent reader never sees a partial file.
|
package/dist/native/worker.mjs
CHANGED
|
@@ -16,10 +16,13 @@ import { init, runBaseTests, setupEnvironment } from "vitest/worker";
|
|
|
16
16
|
import { installGlobals } from "./globals.mjs";
|
|
17
17
|
import { installRequireHooks } from "./hooks.mjs";
|
|
18
18
|
import { installHotReset } from "./reset.mjs";
|
|
19
|
+
import { installRegistry } from "./registry.mjs";
|
|
20
|
+
import { captureModuleBaseline } from "./module-reset.mjs";
|
|
19
21
|
import { enableV8CompileCache } from "./compile-cache.mjs";
|
|
22
|
+
import { VitestNativeError } from "../errors.mjs";
|
|
20
23
|
|
|
21
24
|
if (isMainThread || !parentPort) {
|
|
22
|
-
throw new
|
|
25
|
+
throw new VitestNativeError("HOT_WORKER_ENV", "hot worker entry must run in node:worker_threads");
|
|
23
26
|
}
|
|
24
27
|
|
|
25
28
|
const projectRoot = process.env.VITEST_NATIVE_PROJECT_ROOT || process.cwd();
|
|
@@ -55,8 +58,16 @@ if (diagnostics) {
|
|
|
55
58
|
// per-file resets rather than wrongly torn down with test pollution.
|
|
56
59
|
// Enable the V8 compile cache before any RN module compiles, so the resident
|
|
57
60
|
// graph's bytecode is cached to disk for the next worker/run.
|
|
58
|
-
enableV8CompileCache();
|
|
61
|
+
enableV8CompileCache(projectRoot);
|
|
59
62
|
installGlobals();
|
|
63
|
+
// The registry must be installed BEFORE the preload below, not just by the setup
|
|
64
|
+
// file: whichever path first resolves react-native decides which instance the
|
|
65
|
+
// worker keeps resident, and a preload that bypassed the registry would leave the
|
|
66
|
+
// worker holding a second, separate copy of RN's singletons from the one every
|
|
67
|
+
// test file sees.
|
|
68
|
+
if (process.env.VITEST_NATIVE_RN_REGISTRY) {
|
|
69
|
+
installRegistry(process.env.VITEST_NATIVE_RN_REGISTRY, projectRoot);
|
|
70
|
+
}
|
|
60
71
|
installRequireHooks(projectRoot, transformPkgs, platform, reactNativeVersion, assetExts);
|
|
61
72
|
try {
|
|
62
73
|
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
@@ -86,24 +97,62 @@ try {
|
|
|
86
97
|
RN.Appearance.getColorScheme?.();
|
|
87
98
|
} catch {}
|
|
88
99
|
} catch (error) {
|
|
89
|
-
throw new
|
|
90
|
-
|
|
100
|
+
throw new VitestNativeError(
|
|
101
|
+
"HOT_WORKER_PRELOAD",
|
|
102
|
+
`hot worker failed to preload react-native from ${projectRoot}: ${error?.message}`,
|
|
91
103
|
{ cause: error },
|
|
92
104
|
);
|
|
93
105
|
}
|
|
106
|
+
const resetModules = captureModuleBaseline();
|
|
94
107
|
const { hotReset, bless } = installHotReset({ projectRoot, diagnostics, preserveGlobals });
|
|
95
|
-
globalThis.__vitest_native_hot_reset =
|
|
96
|
-
globalThis.
|
|
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;
|
|
97
115
|
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
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
|
+
};
|
|
107
156
|
|
|
108
157
|
init({
|
|
109
158
|
// oxlint-disable-next-line unicorn/require-post-message-target-origin -- worker_threads MessagePort, not window
|
|
@@ -111,7 +160,10 @@ init({
|
|
|
111
160
|
on: (callback) => parentPort.on("message", callback),
|
|
112
161
|
off: (callback) => parentPort.off("message", callback),
|
|
113
162
|
teardown: () => parentPort.removeAllListeners("message"),
|
|
114
|
-
runTests:
|
|
115
|
-
collectTests:
|
|
163
|
+
runTests: (state, traces) => runBaseTests("run", state, traces),
|
|
164
|
+
collectTests: (state, traces) => runBaseTests("collect", state, traces),
|
|
165
|
+
onModuleRunner: (runner) => {
|
|
166
|
+
moduleRunner = runner;
|
|
167
|
+
},
|
|
116
168
|
setup: setupEnvironment,
|
|
117
169
|
});
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { t as VitestNativeError } from "./errors-Dm5yLNTF.mjs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import { ThreadsPoolWorker } from "vitest/node";
|
|
6
|
+
//#region src/native/pool.ts
|
|
7
|
+
function deepEqual(a, b) {
|
|
8
|
+
if (a === b) return true;
|
|
9
|
+
if (a == null || b == null || typeof a !== "object" || typeof b !== "object") return false;
|
|
10
|
+
const ka = Object.keys(a);
|
|
11
|
+
const kb = Object.keys(b);
|
|
12
|
+
if (ka.length !== kb.length) return false;
|
|
13
|
+
return ka.every((k) => kb.includes(k) && deepEqual(a[k], b[k]));
|
|
14
|
+
}
|
|
15
|
+
var NativePoolWorker = class extends ThreadsPoolWorker {
|
|
16
|
+
name = "vitest-native";
|
|
17
|
+
reportMemory;
|
|
18
|
+
entrypoint;
|
|
19
|
+
environment;
|
|
20
|
+
recycleAfterFiles;
|
|
21
|
+
memoryLimit;
|
|
22
|
+
diagnostics;
|
|
23
|
+
filesRun = 0;
|
|
24
|
+
lastHeapUsed = 0;
|
|
25
|
+
memoryListenerAttached = false;
|
|
26
|
+
batchWarningShown = false;
|
|
27
|
+
constructor(options, native) {
|
|
28
|
+
super(options);
|
|
29
|
+
this.entrypoint = path.resolve(native.workerEntry);
|
|
30
|
+
this.environment = options.environment;
|
|
31
|
+
this.recycleAfterFiles = native.recycleAfterFiles ?? 0;
|
|
32
|
+
this.memoryLimit = native.memoryLimit ?? 0;
|
|
33
|
+
this.diagnostics = native.diagnostics ?? false;
|
|
34
|
+
this.reportMemory = this.memoryLimit > 0;
|
|
35
|
+
}
|
|
36
|
+
async start() {
|
|
37
|
+
await super.start();
|
|
38
|
+
if (this.reportMemory && !this.memoryListenerAttached) {
|
|
39
|
+
this.memoryListenerAttached = true;
|
|
40
|
+
this.on("message", (message) => {
|
|
41
|
+
if (message?.__vitest_worker_response__ && typeof message.usedMemory === "number") this.lastHeapUsed = message.usedMemory;
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
send(message) {
|
|
46
|
+
if (message.type === "run" || message.type === "collect") {
|
|
47
|
+
if (!this.batchWarningShown && message.context.files.length > 1 && (this.recycleAfterFiles > 0 || this.memoryLimit > 0)) {
|
|
48
|
+
this.batchWarningShown = true;
|
|
49
|
+
console.warn(`[vitest-native] hotRuntime recycling (memoryLimit/recycleAfterFiles) is INACTIVE here: Vitest batched ${message.context.files.length} files into one task, which happens in single-worker mode (maxWorkers: 1) — so a worker can never be retired between files and the memory bound cannot be enforced. Run with maxWorkers >= 2 (or remove maxWorkers/fileParallelism: false) so each file is its own task and recycling can fire.`);
|
|
50
|
+
}
|
|
51
|
+
this.filesRun += message.context.files.length;
|
|
52
|
+
}
|
|
53
|
+
super.send(message);
|
|
54
|
+
}
|
|
55
|
+
canReuse(task) {
|
|
56
|
+
if (this.recycleAfterFiles > 0 && this.filesRun >= this.recycleAfterFiles) return false;
|
|
57
|
+
if (this.memoryLimit > 0 && this.lastHeapUsed >= this.memoryLimit) return false;
|
|
58
|
+
const env = task.context.environment;
|
|
59
|
+
return env.name === this.environment.name && deepEqual(env.options, this.environment.options);
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
const HOT_MEMORY_MIN_BYTES = 768 * 1024 * 1024;
|
|
63
|
+
const HOT_MEMORY_MAX_BYTES = 1536 * 1024 * 1024;
|
|
64
|
+
const HOT_MEMORY_FRACTION = .25;
|
|
65
|
+
/**
|
|
66
|
+
* Default per-worker hot `memoryLimit` (bytes): `clamp(totalmem * 0.25, 768MB, 1.5GB)`.
|
|
67
|
+
* Applied only when hot is enabled and neither `memoryLimit` nor
|
|
68
|
+
* `recycleAfterFiles` was set explicitly. `totalmem` is injectable for tests.
|
|
69
|
+
*/
|
|
70
|
+
function defaultHotMemoryLimit(totalmem = os.totalmem()) {
|
|
71
|
+
const budget = Math.floor(totalmem * HOT_MEMORY_FRACTION);
|
|
72
|
+
return Math.min(HOT_MEMORY_MAX_BYTES, Math.max(HOT_MEMORY_MIN_BYTES, budget));
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Fail fast when the hot worker would load a different Vitest VERSION from the
|
|
76
|
+
* project's.
|
|
77
|
+
*
|
|
78
|
+
* The worker entry ships inside this package, so its `import 'vitest/worker'`
|
|
79
|
+
* resolves from THIS package's location rather than the project's. Where a monorepo
|
|
80
|
+
* has more than one Vitest install — a linked package, a hoisted `node_modules`,
|
|
81
|
+
* mixed versions across workspaces — the two can differ, and a version difference is
|
|
82
|
+
* invisible at runtime: the start handshake succeeds, the run request is accepted,
|
|
83
|
+
* and no result is ever reported. Vitest then prints "No test files found" with no
|
|
84
|
+
* error at all, and on some paths still exits 0 — a green run that tested nothing.
|
|
85
|
+
*
|
|
86
|
+
* Only a VERSION difference is an error. Two installs of the same version are two
|
|
87
|
+
* module registries but identical code, and they talk to each other perfectly well;
|
|
88
|
+
* failing on the paths alone would block working monorepos where the same version is
|
|
89
|
+
* simply installed twice.
|
|
90
|
+
*/
|
|
91
|
+
function assertWorkerVitestMatchesProject(workerEntry, projectRoot) {
|
|
92
|
+
const resolveVitest = (from) => {
|
|
93
|
+
try {
|
|
94
|
+
const require_ = createRequire(from);
|
|
95
|
+
const pkgPath = require_.resolve("vitest/package.json");
|
|
96
|
+
return {
|
|
97
|
+
path: pkgPath,
|
|
98
|
+
version: require_(pkgPath).version
|
|
99
|
+
};
|
|
100
|
+
} catch {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
const worker = resolveVitest(workerEntry);
|
|
105
|
+
const project = resolveVitest(path.join(projectRoot, "package.json"));
|
|
106
|
+
if (worker === null || project === null || worker.version === project.version) return;
|
|
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'.`);
|
|
108
|
+
}
|
|
109
|
+
/** Pool initializer for `test.pool` — keeps RN-hot workers alive across files. */
|
|
110
|
+
function nativePool(options) {
|
|
111
|
+
assertWorkerVitestMatchesProject(path.resolve(options.workerEntry), options.projectRoot);
|
|
112
|
+
return {
|
|
113
|
+
name: "vitest-native",
|
|
114
|
+
createPoolWorker: (poolOptions) => new NativePoolWorker(poolOptions, options)
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
//#endregion
|
|
118
|
+
export { defaultHotMemoryLimit, nativePool };
|