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/hooks.mjs
CHANGED
|
@@ -6,7 +6,8 @@ import fs from "node:fs";
|
|
|
6
6
|
import { transformRN, isFlow } from "./transform.mjs";
|
|
7
7
|
import { boundarySourceFor } from "./boundary.mjs";
|
|
8
8
|
import { resolvePlatformFile } from "./resolve.mjs";
|
|
9
|
-
import { buildPkgMatcher } from "./match.mjs";
|
|
9
|
+
import { buildPkgMatcher, packageNameOf, subpathLeafOf, isUtilitySubpath } from "./match.mjs";
|
|
10
|
+
import { explainUntransformedSyntaxError } from "./explain.mjs";
|
|
10
11
|
|
|
11
12
|
const RN_PATH = /[\\/]node_modules[\\/](react-native|@react-native)[\\/]/;
|
|
12
13
|
// Any file under a node_modules directory. Platform-extension resolution
|
|
@@ -19,6 +20,78 @@ const NODE_MODULES = /[\\/]node_modules[\\/]/;
|
|
|
19
20
|
// can be evaluated twice in one worker (once by the worker entry through Node's
|
|
20
21
|
// loader, once through Vitest's module runner when the setup file is inlined),
|
|
21
22
|
// and the hooks must still install exactly once per worker.
|
|
23
|
+
/**
|
|
24
|
+
* Packages Vite executes itself (see ecosystem.ts). If Node also resolves one of
|
|
25
|
+
* these, the module exists TWICE in the process — once in Vite's graph, once in
|
|
26
|
+
* Node's — and module-level state does not cross between them.
|
|
27
|
+
*
|
|
28
|
+
* This is silent by construction: nothing fails, nothing is logged, the second
|
|
29
|
+
* copy simply starts empty. A store configured through one copy reads back
|
|
30
|
+
* unset through the other, so a translated label renders as "" and the test
|
|
31
|
+
* compares empty output against expected output with nothing pointing at the
|
|
32
|
+
* cause. Reported once per package, with both files, because the two paths are
|
|
33
|
+
* what makes it recognisable.
|
|
34
|
+
*/
|
|
35
|
+
// The fields Vite is configured with for React Native (see plugin.ts), in order.
|
|
36
|
+
// Node's CJS resolver uses `main`, which is not in this list at all.
|
|
37
|
+
const VITE_MAIN_FIELDS = ["react-native", "module", "jsnext:main", "jsnext"];
|
|
38
|
+
|
|
39
|
+
const reportedDuplicates = new Set();
|
|
40
|
+
|
|
41
|
+
/** Test seam: the warning is once per package for the life of the worker. */
|
|
42
|
+
export function _resetDuplicateReports() {
|
|
43
|
+
reportedDuplicates.clear();
|
|
44
|
+
}
|
|
45
|
+
function reportDuplicateInstance(pkg, nodeFile, viteFile, field) {
|
|
46
|
+
reportedDuplicates.add(pkg);
|
|
47
|
+
console.warn(
|
|
48
|
+
`[vitest-native] '${pkg}' resolves to two different files.\n` +
|
|
49
|
+
` Node (require) -> ${nodeFile}\n` +
|
|
50
|
+
` Vite ("${field}") -> ${viteFile}\n` +
|
|
51
|
+
" If both module systems load it, the package exists twice and module-level state —\n" +
|
|
52
|
+
" stores, React contexts, event emitters, registries — is not shared between the copies.\n" +
|
|
53
|
+
" Nothing throws: writes through one are simply invisible to the other, so values read\n" +
|
|
54
|
+
" back unset. Set `resolve.mainFields` so both resolvers agree, or import the package\n" +
|
|
55
|
+
" from one side only.",
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Compare what Node just resolved against what Vite's field order would pick for
|
|
61
|
+
* the same package. A difference means the two module systems have different
|
|
62
|
+
* files for one package id, so anything importing it from both sides gets two
|
|
63
|
+
* copies with separate state.
|
|
64
|
+
*/
|
|
65
|
+
export function checkResolverAgreement(request, resolved) {
|
|
66
|
+
const pkg = packageOf(request);
|
|
67
|
+
if (!pkg || typeof resolved !== "string") return;
|
|
68
|
+
if (reportedDuplicates.has(pkg)) return;
|
|
69
|
+
const marker = `${path.sep}node_modules${path.sep}`;
|
|
70
|
+
const at = resolved.lastIndexOf(marker + pkg.split("/").join(path.sep) + path.sep);
|
|
71
|
+
if (at === -1) return;
|
|
72
|
+
const dir = resolved.slice(0, at + marker.length + pkg.length);
|
|
73
|
+
let manifest;
|
|
74
|
+
try {
|
|
75
|
+
manifest = JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"));
|
|
76
|
+
} catch {
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
const field = VITE_MAIN_FIELDS.find((f) => typeof manifest[f] === "string");
|
|
80
|
+
if (!field) return;
|
|
81
|
+
const viteFile = path.resolve(dir, manifest[field]);
|
|
82
|
+
if (viteFile === resolved) return;
|
|
83
|
+
reportDuplicateInstance(pkg, resolved, viteFile, field);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The npm package a bare specifier belongs to, or null for relative/absolute ones. */
|
|
87
|
+
function packageOf(request) {
|
|
88
|
+
if (!request || request.startsWith(".") || request.startsWith("/") || request.startsWith("\\")) {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
const parts = request.split("/");
|
|
92
|
+
return request.startsWith("@") ? (parts[1] ? `${parts[0]}/${parts[1]}` : null) : parts[0];
|
|
93
|
+
}
|
|
94
|
+
|
|
22
95
|
export function installRequireHooks(
|
|
23
96
|
projectRoot,
|
|
24
97
|
transformPkgs = [],
|
|
@@ -38,6 +111,7 @@ export function installRequireHooks(
|
|
|
38
111
|
// @react-native-vector-icons are shadowed by their preset, so they never inspect
|
|
39
112
|
// the stubbed font require.)
|
|
40
113
|
const NON_ASSET = new Set([".js", ".cjs", ".mjs", ".ts", ".tsx", ".json", ".node"]);
|
|
114
|
+
const assetExtSet = new Set(assetExts.map((e) => String(e).replace(/^\./, "").toLowerCase()));
|
|
41
115
|
for (const raw of assetExts) {
|
|
42
116
|
const ext = "." + String(raw).replace(/^\./, "");
|
|
43
117
|
if (NON_ASSET.has(ext) || Module._extensions[ext]) continue;
|
|
@@ -48,7 +122,7 @@ export function installRequireHooks(
|
|
|
48
122
|
}
|
|
49
123
|
|
|
50
124
|
// Configured third-party packages to also transform (Flow/TS/JSX stripped).
|
|
51
|
-
const isExtra = buildPkgMatcher(transformPkgs);
|
|
125
|
+
const isExtra = buildPkgMatcher(transformPkgs, projectRoot);
|
|
52
126
|
|
|
53
127
|
// Preset redirect (CJS): when an externalized third-party module require()s a
|
|
54
128
|
// preset package by its bare name (e.g. @gorhom/bottom-sheet → require(
|
|
@@ -59,10 +133,62 @@ export function installRequireHooks(
|
|
|
59
133
|
// the real package's native runtime. The lookup is dynamic (no preset-name list
|
|
60
134
|
// captured at install time) so the hooks can install at hot-worker boot, before
|
|
61
135
|
// the setup file has built the preset mocks.
|
|
136
|
+
// Subpath requires of a preset package (pkg/Swipeable) get the mock export
|
|
137
|
+
// matching the leaf name, wrapped in Babel-CJS interop shape ({ __esModule,
|
|
138
|
+
// default }) like the real compiled deep entry — served via a live Proxy so
|
|
139
|
+
// direct-property consumers (`require('pkg/Sub').X`) work too. Memoized per
|
|
140
|
+
// request for identity stability. The memo is keyed by the PER-PACKAGE mock
|
|
141
|
+
// object, not the __vitest_native_preset_mocks container: the hot runtime
|
|
142
|
+
// rebuilds each package's mock per test file while reusing the container, so
|
|
143
|
+
// keying by the container would serve file 1's mocks to every later file in
|
|
144
|
+
// the worker.
|
|
145
|
+
const subpathMemo = new WeakMap();
|
|
146
|
+
function presetSubpathExports(mocks, pkg, request) {
|
|
147
|
+
const mock = mocks[pkg];
|
|
148
|
+
if (mock === null || (typeof mock !== "object" && typeof mock !== "function")) return mock;
|
|
149
|
+
let memo = subpathMemo.get(mock);
|
|
150
|
+
if (!memo) subpathMemo.set(mock, (memo = new Map()));
|
|
151
|
+
if (memo.has(request)) return memo.get(request);
|
|
152
|
+
const leaf = subpathLeafOf(request);
|
|
153
|
+
let exportsValue = mock;
|
|
154
|
+
if (leaf && Object.prototype.hasOwnProperty.call(mock, leaf)) {
|
|
155
|
+
const value = mock[leaf];
|
|
156
|
+
exportsValue =
|
|
157
|
+
value !== null && (typeof value === "object" || typeof value === "function")
|
|
158
|
+
? new Proxy(value, {
|
|
159
|
+
get: (t, p, r) =>
|
|
160
|
+
p === "default" ? t : p === "__esModule" ? true : Reflect.get(t, p, r),
|
|
161
|
+
has: (t, p) => p === "default" || p === "__esModule" || Reflect.has(t, p),
|
|
162
|
+
})
|
|
163
|
+
: { __esModule: true, default: value };
|
|
164
|
+
} else if (process.env.VITEST_NATIVE_DIAGNOSTICS === "true") {
|
|
165
|
+
console.warn(
|
|
166
|
+
`[vitest-native] '${request}' has no matching export on the '${pkg}' preset mock; serving the root mock namespace.`,
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
memo.set(request, exportsValue);
|
|
170
|
+
return exportsValue;
|
|
171
|
+
}
|
|
172
|
+
|
|
62
173
|
const origLoad = Module._load;
|
|
63
174
|
Module._load = function (request, parent, ...rest) {
|
|
64
175
|
const mocks = globalThis.__vitest_native_preset_mocks;
|
|
65
|
-
if (mocks
|
|
176
|
+
if (mocks) {
|
|
177
|
+
if (Object.prototype.hasOwnProperty.call(mocks, request)) return mocks[request];
|
|
178
|
+
// Subpath require of a preset package — the real deep entry would load the
|
|
179
|
+
// package's native runtime. Exempt: JSON subpaths (package.json version
|
|
180
|
+
// gates), asset subpaths (fonts/images, stubbed from their real files by
|
|
181
|
+
// the Module._extensions handlers above), and Node-safe utility entries
|
|
182
|
+
// (jest-utils, mock, plugin) — those fall through to the real file.
|
|
183
|
+
const reqExtMatch = /\.([a-z0-9]+)$/i.exec(request);
|
|
184
|
+
const reqExt = reqExtMatch ? reqExtMatch[1].toLowerCase() : "";
|
|
185
|
+
if (reqExt !== "json" && !assetExtSet.has(reqExt) && !isUtilitySubpath(request)) {
|
|
186
|
+
const pkg = packageNameOf(request);
|
|
187
|
+
if (pkg !== request && Object.prototype.hasOwnProperty.call(mocks, pkg)) {
|
|
188
|
+
return presetSubpathExports(mocks, pkg, request);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
66
192
|
return origLoad.call(this, request, parent, ...rest);
|
|
67
193
|
};
|
|
68
194
|
|
|
@@ -83,7 +209,9 @@ export function installRequireHooks(
|
|
|
83
209
|
);
|
|
84
210
|
if (hit) return hit;
|
|
85
211
|
}
|
|
86
|
-
|
|
212
|
+
const resolved = origResolve.call(this, request, parent, ...rest);
|
|
213
|
+
checkResolverAgreement(request, resolved);
|
|
214
|
+
return resolved;
|
|
87
215
|
};
|
|
88
216
|
|
|
89
217
|
const origJs = Module._extensions[".js"];
|
|
@@ -101,6 +229,17 @@ export function installRequireHooks(
|
|
|
101
229
|
const src = fs.readFileSync(filename, "utf8");
|
|
102
230
|
return mod._compile(transformRN(filename, src, projectRoot, platform), filename);
|
|
103
231
|
}
|
|
232
|
+
if (NODE_MODULES.test(norm)) {
|
|
233
|
+
// A node_modules package we did NOT transform: when Node's compile throws a
|
|
234
|
+
// SyntaxError that fingerprints as untranspiled JSX/Flow/TS, explain the
|
|
235
|
+
// real fix (add the package to `transform: [...]`) instead of leaving a
|
|
236
|
+
// bare "Unexpected token '<'" — the single most common migration blocker.
|
|
237
|
+
try {
|
|
238
|
+
return origJs(mod, filename);
|
|
239
|
+
} catch (err) {
|
|
240
|
+
throw explainUntransformedSyntaxError(err, filename) ?? err;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
104
243
|
return origJs(mod, filename);
|
|
105
244
|
};
|
|
106
245
|
|
|
@@ -113,6 +252,14 @@ export function installRequireHooks(
|
|
|
113
252
|
for (const ext of [".ts", ".tsx"]) {
|
|
114
253
|
if (Module._extensions[ext]) continue;
|
|
115
254
|
Module._extensions[ext] = function (mod, filename) {
|
|
255
|
+
// Boundary stubs can live in TS sources too (expo publishes src/ alongside
|
|
256
|
+
// build/, and some resolution paths reach the .ts files directly).
|
|
257
|
+
const boundary = boundarySourceFor(
|
|
258
|
+
filename.replace(/\\/g, "/"),
|
|
259
|
+
platform,
|
|
260
|
+
reactNativeVersion,
|
|
261
|
+
);
|
|
262
|
+
if (boundary != null) return mod._compile(boundary, filename);
|
|
116
263
|
const src = fs.readFileSync(filename, "utf8");
|
|
117
264
|
return mod._compile(transformRN(filename, src, projectRoot, platform), filename);
|
|
118
265
|
};
|
package/dist/native/loader.mjs
CHANGED
|
@@ -3,10 +3,10 @@
|
|
|
3
3
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
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, cjsExportNames } from "./transform.mjs";
|
|
7
7
|
import { boundarySourceFor } from "./boundary.mjs";
|
|
8
8
|
import { resolvePlatformFile } from "./resolve.mjs";
|
|
9
|
-
import { buildPkgMatcher } from "./match.mjs";
|
|
9
|
+
import { buildPkgMatcher, packageNameOf, subpathLeafOf, isUtilitySubpath } from "./match.mjs";
|
|
10
10
|
|
|
11
11
|
const RN_PATH = /[\\/]node_modules[\\/](react-native|@react-native)[\\/]/;
|
|
12
12
|
// Any file living under a node_modules directory. Platform-extension resolution
|
|
@@ -54,7 +54,7 @@ export async function initialize(data) {
|
|
|
54
54
|
if (data && data.projectRoot) PROJECT_ROOT = data.projectRoot;
|
|
55
55
|
if (data && data.platform === "android") PLATFORM = "android";
|
|
56
56
|
if (data && data.reactNativeVersion) REACT_NATIVE_VERSION = data.reactNativeVersion;
|
|
57
|
-
if (data && data.transformPkgs) isExtra = buildPkgMatcher(data.transformPkgs);
|
|
57
|
+
if (data && data.transformPkgs) isExtra = buildPkgMatcher(data.transformPkgs, PROJECT_ROOT);
|
|
58
58
|
if (data && data.presetExports) presetExports = data.presetExports;
|
|
59
59
|
if (data && data.assetExts)
|
|
60
60
|
assetExtSet = new Set(data.assetExts.map((e) => String(e).replace(/^\./, "").toLowerCase()));
|
|
@@ -65,14 +65,29 @@ export async function resolve(specifier, context, nextResolve) {
|
|
|
65
65
|
// test graph or, crucially, nested inside an externalized third-party lib — is
|
|
66
66
|
// redirected to a synthetic module that re-exports the runtime preset mock. This
|
|
67
67
|
// mirrors the Vite plugin's virtual:preset modules for the Node ESM path.
|
|
68
|
+
// Subpath imports (e.g. react-native-gesture-handler/Swipeable) are redirected
|
|
69
|
+
// too — the real deep entry would pull in the package's native runtime.
|
|
70
|
+
// Exempt: JSON subpaths (package.json version gates), asset subpaths, and
|
|
71
|
+
// Node-safe utility entries (jest-utils, mock, plugin) — those pass through
|
|
72
|
+
// to the real file.
|
|
68
73
|
if (Object.prototype.hasOwnProperty.call(presetExports, specifier)) {
|
|
69
74
|
return { url: PRESET_SCHEME + specifier, shortCircuit: true };
|
|
70
75
|
}
|
|
76
|
+
if (!specifier.endsWith(".json") && !isUtilitySubpath(specifier)) {
|
|
77
|
+
const specExt = /\.([a-z0-9]+)$/i.exec(specifier);
|
|
78
|
+
if (!specExt || !assetExtSet.has(specExt[1].toLowerCase())) {
|
|
79
|
+
const pkg = packageNameOf(specifier);
|
|
80
|
+
if (pkg !== specifier && Object.prototype.hasOwnProperty.call(presetExports, pkg)) {
|
|
81
|
+
return { url: PRESET_SCHEME + specifier, shortCircuit: true };
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
71
85
|
|
|
72
86
|
const parent =
|
|
73
87
|
context.parentURL && context.parentURL.startsWith("file:")
|
|
74
88
|
? fileURLToPath(context.parentURL)
|
|
75
89
|
: null;
|
|
90
|
+
let resolved;
|
|
76
91
|
if (
|
|
77
92
|
parent &&
|
|
78
93
|
(NODE_MODULES.test(parent) || RN_PATH.test(parent) || isExtra(parent)) &&
|
|
@@ -80,12 +95,13 @@ export async function resolve(specifier, context, nextResolve) {
|
|
|
80
95
|
!path.extname(specifier)
|
|
81
96
|
) {
|
|
82
97
|
const hit = resolvePlatformFile(path.resolve(path.dirname(parent), specifier), PLATFORM);
|
|
83
|
-
|
|
98
|
+
// Not returned directly: `json` is a Metro source extension, so this can now
|
|
99
|
+
// land on a .json file, which still needs the import attribute injected below.
|
|
100
|
+
if (hit) resolved = { url: pathToFileURL(hit).href, shortCircuit: true };
|
|
84
101
|
}
|
|
85
102
|
|
|
86
|
-
let resolved;
|
|
87
103
|
try {
|
|
88
|
-
resolved
|
|
104
|
+
resolved ??= await nextResolve(specifier, context);
|
|
89
105
|
} catch (err) {
|
|
90
106
|
// Fallback: an extensionless relative import that Node's ESM resolver rejected
|
|
91
107
|
// but a bundler (Metro) would accept. Common in externalized RN libs shipping
|
|
@@ -120,14 +136,29 @@ export async function load(url, context, nextLoad) {
|
|
|
120
136
|
// by the native setup file from globalThis (this source executes in the main
|
|
121
137
|
// realm, so globalThis is the populated one), mirroring the Vite virtual:preset.
|
|
122
138
|
if (url.startsWith(PRESET_SCHEME)) {
|
|
123
|
-
const
|
|
139
|
+
const specifier = url.slice(PRESET_SCHEME.length);
|
|
140
|
+
const pkg = packageNameOf(specifier);
|
|
124
141
|
const names = presetExports[pkg] || [];
|
|
142
|
+
// For a subpath import, prefer the mock export matching the leaf module name
|
|
143
|
+
// (pkg/lib/Swipeable → mock.Swipeable) — real deep entries export that one
|
|
144
|
+
// thing as their default. Root imports (and unknown leaves) keep the
|
|
145
|
+
// factory-default-then-namespace behavior; unknown leaves warn under
|
|
146
|
+
// diagnostics since the namespace default is usually not what the importer
|
|
147
|
+
// wanted.
|
|
148
|
+
const leaf = specifier === pkg ? null : subpathLeafOf(specifier);
|
|
149
|
+
const fallback = `("default" in _m ? _m["default"] : _m)`;
|
|
125
150
|
const source = [
|
|
126
151
|
`const _m = (globalThis.__vitest_native_preset_mocks || {})[${JSON.stringify(pkg)}] || {};`,
|
|
127
152
|
...names.map((n) => `export const ${n} = _m[${JSON.stringify(n)}];`),
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
153
|
+
...(leaf
|
|
154
|
+
? [
|
|
155
|
+
`const _hit = ${JSON.stringify(leaf)} in _m;`,
|
|
156
|
+
`if (!_hit && process.env.VITEST_NATIVE_DIAGNOSTICS === "true") console.warn(${JSON.stringify(
|
|
157
|
+
`[vitest-native] '${specifier}' has no matching export on the '${pkg}' preset mock; serving the root mock namespace.`,
|
|
158
|
+
)});`,
|
|
159
|
+
`export default (_hit ? _m[${JSON.stringify(leaf)}] : ${fallback});`,
|
|
160
|
+
]
|
|
161
|
+
: [`export default ${fallback};`]),
|
|
131
162
|
].join("\n");
|
|
132
163
|
return { format: "module", source, shortCircuit: true };
|
|
133
164
|
}
|
|
@@ -193,12 +224,30 @@ export async function load(url, context, nextLoad) {
|
|
|
193
224
|
return nextLoad(url, context);
|
|
194
225
|
}
|
|
195
226
|
|
|
196
|
-
// Configured third-party package: transform any JS/TS/JSX source to CJS
|
|
227
|
+
// Configured third-party package: transform any JS/TS/JSX source to CJS, and tell
|
|
228
|
+
// Node what it exports.
|
|
229
|
+
//
|
|
230
|
+
// When Node imports a CommonJS module from ESM it decides the named exports with
|
|
231
|
+
// cjs-module-lexer, which reads the source statically and gives up partway through
|
|
232
|
+
// shapes it cannot follow. `module.exports = { A() {}, b: () => 1 }` — ordinary
|
|
233
|
+
// hand-written CommonJS, and common in this ecosystem — yields
|
|
234
|
+
// ["A", "default", "module.exports"]: `b` is missing and a name that is not an
|
|
235
|
+
// export appears. Plain Node behaviour, reproducible with no plugin involved; it
|
|
236
|
+
// became reachable when these packages moved from Vite's graph (whose interop
|
|
237
|
+
// enumerates the real object at run time) to Node's.
|
|
238
|
+
//
|
|
239
|
+
// The dead `0 && (module.exports = { … })` hint is the form the lexer does
|
|
240
|
+
// understand — the same trick react-native's index facade uses below. Names are
|
|
241
|
+
// read from the transform's own output rather than by requiring the module: this
|
|
242
|
+
// hook runs on the module-loader thread, where the CJS require hooks that compile
|
|
243
|
+
// JSX are not installed, so a require here fails with "Unexpected token '<'".
|
|
197
244
|
if (TRANSFORMABLE.test(norm)) {
|
|
198
245
|
const src = fs.readFileSync(file, "utf8");
|
|
246
|
+
const code = transformRN(file, src, PROJECT_ROOT, PLATFORM);
|
|
247
|
+
const names = cjsExportNames(code);
|
|
199
248
|
return {
|
|
200
249
|
format: "commonjs",
|
|
201
|
-
source:
|
|
250
|
+
source: names.length > 0 ? `${code}\n0 && (module.exports = { ${names.join(", ")} });` : code,
|
|
202
251
|
shortCircuit: true,
|
|
203
252
|
};
|
|
204
253
|
}
|
package/dist/native/match.mjs
CHANGED
|
@@ -1,9 +1,108 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
/** Escape a string for literal use inside a RegExp. */
|
|
5
|
+
function escapeRe(value) {
|
|
6
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The on-disk directory a package resolves to, or null.
|
|
11
|
+
*
|
|
12
|
+
* `pkg/package.json` is tried first because it names the package root exactly; some
|
|
13
|
+
* packages do not export it, so fall back to resolving the entry and walking up to
|
|
14
|
+
* the manifest that names them. Symlinked and workspace packages resolve to their
|
|
15
|
+
* real location, which is the whole point — see buildPkgMatcher.
|
|
16
|
+
*/
|
|
17
|
+
function packageDirOf(name, projectRoot) {
|
|
18
|
+
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
19
|
+
try {
|
|
20
|
+
return path.dirname(req.resolve(`${name}/package.json`));
|
|
21
|
+
} catch {}
|
|
22
|
+
let dir;
|
|
23
|
+
try {
|
|
24
|
+
dir = path.dirname(req.resolve(name));
|
|
25
|
+
} catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
for (;;) {
|
|
29
|
+
try {
|
|
30
|
+
if (createRequire(path.join(dir, "index.js"))("./package.json").name === name) return dir;
|
|
31
|
+
} catch {}
|
|
32
|
+
const parent = path.dirname(dir);
|
|
33
|
+
if (parent === dir) return null;
|
|
34
|
+
dir = parent;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Builds a predicate matching files that belong to any of the given packages.
|
|
40
|
+
*
|
|
41
|
+
* A bare `[/\]name[/\]` test — what this used to do — also matches any DIRECTORY
|
|
42
|
+
* that happens to share a package's name. A project folder called `expo`, or a source
|
|
43
|
+
* directory named after the library it implements, made every file beneath it look
|
|
44
|
+
* like third-party source to be compiled. That mis-compiled unrelated files, this
|
|
45
|
+
* package's own runtime among them.
|
|
46
|
+
*
|
|
47
|
+
* Anchoring on `node_modules` alone would fix that and break linked packages: a
|
|
48
|
+
* workspace or `file:` dependency resolves to its real path, which has no
|
|
49
|
+
* `node_modules` segment at all. So a file matches if it is either
|
|
50
|
+
*
|
|
51
|
+
* - inside the package's resolved directory (exact; covers workspace links, and
|
|
52
|
+
* stores like pnpm's and bun's), or
|
|
53
|
+
* - under `node_modules/<name>/` (covers additional copies of a package that the
|
|
54
|
+
* single resolution above cannot see, and projects where resolution fails).
|
|
55
|
+
*
|
|
56
|
+
* `projectRoot` is optional so existing callers keep working; without it only the
|
|
57
|
+
* `node_modules`-anchored rule applies.
|
|
58
|
+
*/
|
|
59
|
+
export function buildPkgMatcher(pkgs, projectRoot) {
|
|
60
|
+
const names = pkgs || [];
|
|
61
|
+
const anchored = names.map((p) => new RegExp(`[\\\\/]node_modules[\\\\/]${escapeRe(p)}[\\\\/]`));
|
|
62
|
+
const dirs = [];
|
|
63
|
+
if (projectRoot) {
|
|
64
|
+
for (const name of names) {
|
|
65
|
+
const dir = packageDirOf(name, projectRoot);
|
|
66
|
+
if (dir) dirs.push(dir.replace(/\\/g, "/").replace(/\/$/, "") + "/");
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return (normPath) => {
|
|
70
|
+
if (anchored.some((re) => re.test(normPath))) return true;
|
|
71
|
+
if (dirs.length === 0) return false;
|
|
72
|
+
const norm = normPath.replace(/\\/g, "/");
|
|
73
|
+
return dirs.some((dir) => norm.startsWith(dir));
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// The bare package name of an import specifier ("@scope/pkg/sub" → "@scope/pkg",
|
|
78
|
+
// "pkg/sub" → "pkg"). Relative/absolute specifiers yield strings that can never
|
|
79
|
+
// collide with a package name, so callers only need an equality check.
|
|
80
|
+
export function packageNameOf(specifier) {
|
|
81
|
+
if (specifier.startsWith("@")) {
|
|
82
|
+
const [scope, name] = specifier.split("/");
|
|
83
|
+
return name ? `${scope}/${name}` : specifier;
|
|
84
|
+
}
|
|
85
|
+
return specifier.split("/")[0];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// The leaf module name a subpath import points at ("pkg/lib/Swipeable" or
|
|
89
|
+
// "pkg/Swipeable.ios.js" → "Swipeable"), used to pick the matching export off a
|
|
90
|
+
// preset/RN mock. Returns null when there is no usable leaf (trailing slash).
|
|
91
|
+
export function subpathLeafOf(specifier) {
|
|
92
|
+
const base = specifier.split("/").pop();
|
|
93
|
+
if (!base) return null;
|
|
94
|
+
return base.split(".")[0] || null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Deep entries of preset packages that are deliberately Node-safe and must NOT
|
|
98
|
+
// be shadowed by the preset mock: test utilities and tooling entry points
|
|
99
|
+
// (react-native-gesture-handler/jest-utils, react-native-reanimated/mock,
|
|
100
|
+
// */jestSetup, babel `*/plugin` entries). They are designed to run under a
|
|
101
|
+
// Node test runner, and shadowing them replaces working code with undefined
|
|
102
|
+
// exports.
|
|
103
|
+
const UTILITY_SUBPATH_LEAVES = new Set(["jest-utils", "jestSetup", "mock", "plugin"]);
|
|
104
|
+
|
|
105
|
+
export function isUtilitySubpath(specifier) {
|
|
106
|
+
const leaf = subpathLeafOf(specifier);
|
|
107
|
+
return leaf !== null && UTILITY_SUBPATH_LEAVES.has(leaf);
|
|
9
108
|
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Per-file reset of the worker's Node module graph (hot runtime).
|
|
2
|
+
//
|
|
3
|
+
// The hot runtime keeps a worker alive across test files — that is where its speed
|
|
4
|
+
// comes from, since a fresh worker costs ~200ms of boot and that dominates a run at
|
|
5
|
+
// scale. What it must not keep is state. Vitest's own per-file reset covers the
|
|
6
|
+
// module-runner graph; everything Vitest externalizes lives in Node's require cache,
|
|
7
|
+
// outside its reach.
|
|
8
|
+
//
|
|
9
|
+
// Anything the worker loaded to bootstrap ITSELF stays; anything a TEST FILE caused
|
|
10
|
+
// to load is dropped and runs again on the next file.
|
|
11
|
+
import Module from "node:module";
|
|
12
|
+
|
|
13
|
+
// Native addons cannot be unloaded — dropping one and requiring it again
|
|
14
|
+
// re-initialises native state in the same process, which crashes some addons.
|
|
15
|
+
const UNRESETTABLE = /\.node$/;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Modules that must NOT be dropped, because dropping them creates a second copy
|
|
19
|
+
* rather than a fresh one.
|
|
20
|
+
*
|
|
21
|
+
* Test files reach these through ESM `import`, which caches them in Node's ESM
|
|
22
|
+
* registry — and that registry has no invalidation API, so the copy a test holds
|
|
23
|
+
* survives any reset. Dropping the CJS entry therefore does not replace the module;
|
|
24
|
+
* it adds a twin, and the two halves of the test stack stop recognising each other.
|
|
25
|
+
* The symptom is not an error about modules: it is RNTL's matchers failing to see
|
|
26
|
+
* elements that a resident renderer produced.
|
|
27
|
+
*
|
|
28
|
+
* Which entries carry weight depends on the RNTL version, so the list is bisected
|
|
29
|
+
* rather than assumed. Measured one entry at a time:
|
|
30
|
+
*
|
|
31
|
+
* @testing-library/react-native RNTL 14: parity 135/135 -> 81/135, 10.4x -> 7.8x.
|
|
32
|
+
* The dominant case on every version.
|
|
33
|
+
* react-test-renderer, RNTL 13: `test:native:hot` 175 -> 173 passing.
|
|
34
|
+
* test-renderer RNTL 14 does not use them and is unaffected —
|
|
35
|
+
* which is why a single-version check calls them
|
|
36
|
+
* dead and is wrong.
|
|
37
|
+
* react, react-is, react-dom, No measured effect on either suite under RNTL 13
|
|
38
|
+
* scheduler, react-reconciler or 14: React is already loaded by the worker's
|
|
39
|
+
* boot-time RN preload, so the baseline snapshot
|
|
40
|
+
* below protects it before this pattern is
|
|
41
|
+
* consulted. Kept because that protection is a
|
|
42
|
+
* side effect of preload contents, not a contract.
|
|
43
|
+
*
|
|
44
|
+
* Note for anyone re-testing this: the two suites disagree, so run both.
|
|
45
|
+
* `validate:hot-parity` is the only one that sees the RNTL regression (it is
|
|
46
|
+
* app-shaped rendering); `test:native:hot` is the only one that sees the
|
|
47
|
+
* react-test-renderer regression (it is engine mechanics).
|
|
48
|
+
*/
|
|
49
|
+
const KEEP_RESIDENT =
|
|
50
|
+
/[\\/]node_modules[\\/](react|react-is|react-dom|scheduler|react-reconciler|react-test-renderer|test-renderer|@testing-library[\\/]react-native)[\\/]/;
|
|
51
|
+
|
|
52
|
+
export function captureModuleBaseline() {
|
|
53
|
+
const baseline = new Set(Object.keys(Module._cache));
|
|
54
|
+
return function resetModules() {
|
|
55
|
+
let dropped = 0;
|
|
56
|
+
for (const id of Object.keys(Module._cache)) {
|
|
57
|
+
if (baseline.has(id) || UNRESETTABLE.test(id) || KEEP_RESIDENT.test(id)) continue;
|
|
58
|
+
delete Module._cache[id];
|
|
59
|
+
dropped++;
|
|
60
|
+
}
|
|
61
|
+
return dropped;
|
|
62
|
+
};
|
|
63
|
+
}
|