vitest-native 0.13.0 → 0.14.0-rc.10
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 +746 -0
- package/README.md +205 -88
- package/dist/cli.cjs +1478 -145
- package/dist/cli.d.cts +2 -3
- package/dist/cli.d.mts +2 -3
- package/dist/cli.mjs +1475 -142
- package/dist/context.d.mts +40 -0
- package/dist/context.mjs +238 -0
- package/dist/errors.d.mts +19 -0
- package/dist/helpers.cjs +6 -9
- package/dist/helpers.d.cts +8 -9
- package/dist/helpers.d.mts +8 -9
- package/dist/helpers.mjs +6 -9
- package/dist/host-D3wzmsw8.cjs +1296 -0
- package/dist/host-DCPzgC3D.mjs +1180 -0
- package/dist/{index-CPGq6p95.d.cts → index-CPEAYjaQ.d.mts} +88 -19
- package/dist/{index-CmETArCM.d.mts → index-D5cOy_iY.d.cts} +89 -18
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +1366 -210
- package/dist/jest-compat/aliases.d.mts +5 -0
- package/dist/jest-compat/aliases.mjs +65 -0
- package/dist/jest-compat/caller.mjs +53 -0
- package/dist/jest-compat/error-equality.mjs +127 -0
- package/dist/jest-compat/interop.mjs +78 -4
- package/dist/jest-compat/jest-globals.mjs +5 -2
- package/dist/jest-compat/jest-object.mjs +348 -0
- package/dist/jest-compat/node-registry.mjs +489 -0
- package/dist/jest-compat/setup.mjs +167 -66
- package/dist/jest-compat.cjs +35 -5
- package/dist/jest-compat.d.cts +9 -5
- package/dist/jest-compat.d.mts +9 -5
- package/dist/jest-compat.mjs +35 -3
- package/dist/matchers.d.cts +9 -8
- package/dist/matchers.d.mts +9 -8
- package/dist/memory-BFxB285Z.mjs +137 -0
- package/dist/memory-bBnzadf6.cjs +155 -0
- package/dist/native/assets.d.mts +39 -0
- package/dist/native/assets.mjs +431 -0
- package/dist/native/babel-preset.d.mts +14 -0
- package/dist/native/babel-preset.mjs +56 -0
- package/dist/native/boundary.mjs +71 -8
- package/dist/native/bounded-process.mjs +165 -0
- package/dist/native/compile-cache.mjs +21 -9
- package/dist/native/expo-module-mocks.mjs +432 -0
- package/dist/native/expo-module-table-57.mjs +1925 -0
- package/dist/native/expo-module-table-58.mjs +2045 -0
- package/dist/native/expo-module-tables.mjs +6 -0
- package/dist/native/expo-native-modules.mjs +66 -0
- package/dist/native/export-condition-recovery-preload.mjs +5 -0
- package/dist/native/export-condition-recovery.mjs +195 -0
- package/dist/native/globals.mjs +289 -9
- package/dist/native/hooks.mjs +392 -114
- package/dist/native/loader.mjs +346 -75
- package/dist/native/match.d.mts +13 -0
- package/dist/native/match.mjs +127 -2
- package/dist/native/metro-profile-compiler.mjs +234 -0
- package/dist/native/metro-profile.mjs +115 -0
- package/dist/native/module-reset.mjs +172 -6
- package/dist/native/native-modules.d.mts +15 -0
- package/dist/native/native-modules.mjs +228 -0
- package/dist/native/nitro.mjs +60 -0
- package/dist/native/ownership.d.mts +105 -0
- package/dist/native/ownership.mjs +474 -0
- package/dist/native/registry-compiler.mjs +43 -0
- package/dist/native/registry-process.mjs +124 -0
- package/dist/native/registry.mjs +197 -39
- package/dist/native/reset.mjs +334 -135
- package/dist/native/resolve.d.mts +20 -3
- package/dist/native/resolve.mjs +103 -17
- package/dist/native/rntl-hooks.mjs +227 -0
- package/dist/native/rntl-text-host.mjs +64 -0
- package/dist/native/runner.mjs +33 -1
- package/dist/native/setup.mjs +284 -96
- package/dist/native/state-manifest.d.mts +22 -0
- package/dist/native/state-manifest.mjs +138 -0
- package/dist/native/transform.d.mts +2 -0
- package/dist/native/transform.mjs +270 -47
- package/dist/native/tsconfig-paths.d.mts +5 -0
- package/dist/native/tsconfig-paths.mjs +163 -0
- package/dist/native/worker.mjs +151 -40
- package/dist/pool-DUOe-n1k.mjs +125 -0
- package/dist/pool-DaTJRKJb.cjs +127 -0
- package/dist/preset-map-BlBriTA0.mjs +197 -0
- package/dist/preset-map-jSFsNy1Q.cjs +241 -0
- package/dist/preset-modules-Bt6k_Wdw.mjs +31 -0
- package/dist/preset-modules-C7gu3bPn.cjs +48 -0
- package/dist/preset-modules.d.mts +16 -0
- package/dist/preset-modules.mjs +92 -0
- package/dist/preset-ready.mjs +9 -0
- package/dist/{presets-CoNf4ByH.cjs → presets-DH7fC0YV.cjs} +1125 -102
- package/dist/{presets-DGProTaA.mjs → presets-DuXiUNAx.mjs} +1107 -103
- package/dist/presets.d.mts +2 -2
- package/dist/presets.mjs +1 -2
- package/dist/report-error.d.mts +20 -0
- package/dist/report-error.mjs +145 -0
- package/dist/rntl-matchers.d.ts +58 -12
- package/dist/rntl-support.d.mts +12 -0
- package/dist/rntl-support.mjs +189 -0
- package/dist/serializer.cjs +4 -2
- package/dist/serializer.d.cts +3 -4
- package/dist/serializer.d.mts +3 -4
- package/dist/serializer.mjs +4 -2
- package/dist/setup.mjs +463 -97
- package/dist/worker-vitest-BGPo0ek6.mjs +49 -0
- package/dist/worker-vitest-BfiQB8ND.cjs +62 -0
- package/docs/hot-default-design.md +181 -88
- package/docs/migrating-from-jest.md +74 -16
- package/docs/migrating-from-vitest-react-native.md +5 -5
- package/docs/release-readiness.md +55 -15
- package/docs/versioning.md +31 -22
- package/package.json +122 -98
- package/dist/ecosystem-CEIF_-jq.cjs +0 -659
- package/dist/ecosystem-Duw40-mO.mjs +0 -597
- package/dist/pool-BU-1ecIF.cjs +0 -122
- package/dist/pool-Bcxn9a3I.mjs +0 -118
- package/dist/preset-map-BoG19dLa.cjs +0 -35
- package/dist/preset-map-DuX0ocdn.mjs +0 -30
package/dist/cli.cjs
CHANGED
|
@@ -1,13 +1,342 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
3
|
const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
|
|
4
|
-
const
|
|
5
|
-
const require_preset_map = require("./preset-map-
|
|
4
|
+
const require_host = require("./host-D3wzmsw8.cjs");
|
|
5
|
+
const require_preset_map = require("./preset-map-jSFsNy1Q.cjs");
|
|
6
|
+
const require_memory = require("./memory-bBnzadf6.cjs");
|
|
6
7
|
let node_fs = require("node:fs");
|
|
7
8
|
node_fs = require_rolldown_runtime.__toESM(node_fs, 1);
|
|
8
9
|
let node_path = require("node:path");
|
|
9
10
|
node_path = require_rolldown_runtime.__toESM(node_path, 1);
|
|
10
11
|
let node_module = require("node:module");
|
|
12
|
+
//#region src/native/state-manifest.mjs
|
|
13
|
+
const HOT_STATE_MANIFEST_ENTRIES = Object.freeze([
|
|
14
|
+
"vitest-runtime",
|
|
15
|
+
"native-boundary-mocks",
|
|
16
|
+
"native-module-mocks",
|
|
17
|
+
"react-native.dimensions",
|
|
18
|
+
"react-native.appearance",
|
|
19
|
+
"react-native.event-listeners",
|
|
20
|
+
"process.env",
|
|
21
|
+
"process.listeners",
|
|
22
|
+
"global.descriptors",
|
|
23
|
+
"console.descriptors",
|
|
24
|
+
"react-native.error-utils",
|
|
25
|
+
"expo.runtime",
|
|
26
|
+
"jest-compat.node-mocks"
|
|
27
|
+
]);
|
|
28
|
+
//#endregion
|
|
29
|
+
//#region src/cli/manifest.ts
|
|
30
|
+
/**
|
|
31
|
+
* Installed-package facts for the CLI, read from disk.
|
|
32
|
+
*
|
|
33
|
+
* `require.resolve('<pkg>/package.json')` is not a presence test: a package whose
|
|
34
|
+
* `exports` does not list `./package.json` throws ERR_PACKAGE_PATH_NOT_EXPORTED
|
|
35
|
+
* (@rolldown/plugin-babel 0.2.4 exports only "./dist/index.mjs"), so an installed
|
|
36
|
+
* package read as missing. And a process with module hooks (the mock engine's test
|
|
37
|
+
* runtime) answers `require.resolve` for preset packages that are not installed.
|
|
38
|
+
* The manifest file itself is what a package manager writes, so look for it.
|
|
39
|
+
*/
|
|
40
|
+
/** A package's manifest, found by walking node_modules upward from root, or null. */
|
|
41
|
+
function installedManifest(root, pkg) {
|
|
42
|
+
for (let dir = node_path.default.resolve(root);; dir = node_path.default.dirname(dir)) {
|
|
43
|
+
const file = node_path.default.join(dir, "node_modules", pkg, "package.json");
|
|
44
|
+
if (node_fs.default.existsSync(file)) try {
|
|
45
|
+
return JSON.parse(node_fs.default.readFileSync(file, "utf8"));
|
|
46
|
+
} catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
if (node_path.default.dirname(dir) === dir) return null;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** The installed major version of `pkg`, or null when absent or unversioned. */
|
|
53
|
+
function installedMajor(root, pkg) {
|
|
54
|
+
const version = installedManifest(root, pkg)?.version;
|
|
55
|
+
const major = typeof version === "string" ? Number.parseInt(version, 10) : NaN;
|
|
56
|
+
return Number.isNaN(major) ? null : major;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Whether the installed `pkg` runs its own test mode under Vitest, so no preset
|
|
60
|
+
* replaces it — preset-map's `testsItself`, the rule the plugin applies.
|
|
61
|
+
*/
|
|
62
|
+
function installedTestsItself(root, pkg) {
|
|
63
|
+
return require_preset_map.testsItself(pkg, installedManifest(root, pkg)?.version);
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* The presets a run in this project enables, decided as the plugin decides it: a
|
|
67
|
+
* preset is active when one of its packages is installed and does not test itself,
|
|
68
|
+
* the engine applies it (autoDetectedPresetApplies), and the user has not switched it
|
|
69
|
+
* off.
|
|
70
|
+
*/
|
|
71
|
+
function activePresets(root, disabled = [], engine = "native") {
|
|
72
|
+
const active = /* @__PURE__ */ new Set();
|
|
73
|
+
for (const [pkg, preset] of Object.entries(require_preset_map.AUTO_DETECT_PRESETS)) {
|
|
74
|
+
if (disabled.includes(preset) || !require_preset_map.autoDetectedPresetApplies(preset, engine)) continue;
|
|
75
|
+
if (installedManifest(root, pkg) && !installedTestsItself(root, pkg)) active.add(preset);
|
|
76
|
+
}
|
|
77
|
+
return [...active];
|
|
78
|
+
}
|
|
79
|
+
//#endregion
|
|
80
|
+
//#region src/cli/babel-config.ts
|
|
81
|
+
/**
|
|
82
|
+
* The project's Babel configuration, as `migrate` and `doctor` need to see it.
|
|
83
|
+
*
|
|
84
|
+
* babel-jest applies the project's Babel config to every file; vitest-native never
|
|
85
|
+
* does (website/guide/how-it-works.md). Most plugins in a React Native config exist
|
|
86
|
+
* for Metro, but a macro plugin changes what code means: without it the macro
|
|
87
|
+
* package is imported for real and fails (`Cannot find module
|
|
88
|
+
* 'babel-plugin-macros'`), an error that names nothing about Babel.
|
|
89
|
+
*/
|
|
90
|
+
const PROJECT_FILES = [
|
|
91
|
+
"babel.config.js",
|
|
92
|
+
"babel.config.cjs",
|
|
93
|
+
"babel.config.mjs",
|
|
94
|
+
"babel.config.json",
|
|
95
|
+
"babel.config.cts",
|
|
96
|
+
"babel.config.ts"
|
|
97
|
+
];
|
|
98
|
+
const RELATIVE_FILES = [
|
|
99
|
+
".babelrc",
|
|
100
|
+
".babelrc.js",
|
|
101
|
+
".babelrc.cjs",
|
|
102
|
+
".babelrc.mjs",
|
|
103
|
+
".babelrc.json"
|
|
104
|
+
];
|
|
105
|
+
/**
|
|
106
|
+
* @babel/core's `standardizeName`: `foo` → `babel-plugin-foo`, `@scope/foo` →
|
|
107
|
+
* `@scope/babel-plugin-foo`, `@scope` → `@scope/babel-plugin`, `module:foo` → `foo`.
|
|
108
|
+
*/
|
|
109
|
+
function normalizeBabelName(name, kind = "plugin") {
|
|
110
|
+
const prefix = `babel-${kind}`;
|
|
111
|
+
if (name.startsWith("module:")) return name.slice(7);
|
|
112
|
+
if (name.startsWith(".") || node_path.default.isAbsolute(name)) return name;
|
|
113
|
+
if (/^@[^/]+$/.test(name)) return `${name}/${prefix}`;
|
|
114
|
+
const scoped = /^(@[^/]+)\/(.+)$/.exec(name);
|
|
115
|
+
if (scoped) return scoped[2].startsWith(prefix) ? name : `${scoped[1]}/${prefix}-${scoped[2]}`;
|
|
116
|
+
if (name.includes("/") || name.startsWith(`${prefix}-`)) return name;
|
|
117
|
+
return `${prefix}-${name}`;
|
|
118
|
+
}
|
|
119
|
+
function entryOf(item, kind) {
|
|
120
|
+
const [target, options] = Array.isArray(item) ? item : [item, void 0];
|
|
121
|
+
if (typeof target !== "string") return {
|
|
122
|
+
written: "<inline plugin>",
|
|
123
|
+
name: "<inline plugin>",
|
|
124
|
+
options
|
|
125
|
+
};
|
|
126
|
+
return {
|
|
127
|
+
written: target,
|
|
128
|
+
name: normalizeBabelName(target, kind),
|
|
129
|
+
options
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
/** The `api` babel-jest's Babel passes a function config: env 'test', caller babel-jest. */
|
|
133
|
+
function babelApi() {
|
|
134
|
+
return {
|
|
135
|
+
version: "7.0.0",
|
|
136
|
+
cache: Object.assign(() => {}, {
|
|
137
|
+
forever: () => {},
|
|
138
|
+
never: () => {},
|
|
139
|
+
using: (fn) => fn(),
|
|
140
|
+
invalidate: (fn) => fn()
|
|
141
|
+
}),
|
|
142
|
+
assertVersion: () => {},
|
|
143
|
+
env: (value) => value === void 0 ? "test" : typeof value === "function" ? value("test") : Array.isArray(value) ? value.includes("test") : value === "test",
|
|
144
|
+
caller: (fn) => fn({
|
|
145
|
+
name: "babel-jest",
|
|
146
|
+
supportsDynamicImport: false,
|
|
147
|
+
supportsStaticESM: false
|
|
148
|
+
})
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
/** Evaluate one config file; undefined when it can only be scanned as text. */
|
|
152
|
+
function evaluate(root, file) {
|
|
153
|
+
const text = node_fs.default.readFileSync(file, "utf8");
|
|
154
|
+
if (/(^|\/)\.babelrc$|\.json$/.test(file)) try {
|
|
155
|
+
return JSON.parse(text);
|
|
156
|
+
} catch {
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
if (!/\.c?js$/.test(file)) return void 0;
|
|
160
|
+
const previousEnv = process.env.NODE_ENV;
|
|
161
|
+
process.env.NODE_ENV ??= "test";
|
|
162
|
+
try {
|
|
163
|
+
const loaded = (0, node_module.createRequire)(node_path.default.join(root, "package.json"))(file);
|
|
164
|
+
const exported = loaded && typeof loaded === "object" && "default" in loaded ? loaded.default : loaded;
|
|
165
|
+
const value = typeof exported === "function" ? exported(babelApi()) : exported;
|
|
166
|
+
if (value && typeof value.then === "function") return void 0;
|
|
167
|
+
return value;
|
|
168
|
+
} catch {
|
|
169
|
+
return;
|
|
170
|
+
} finally {
|
|
171
|
+
if (previousEnv === void 0) delete process.env.NODE_ENV;
|
|
172
|
+
else process.env.NODE_ENV = previousEnv;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
const array = (value) => Array.isArray(value) ? value : [];
|
|
176
|
+
function entriesOf(config, key) {
|
|
177
|
+
return [
|
|
178
|
+
config,
|
|
179
|
+
config.env?.test ?? {},
|
|
180
|
+
...array(config.overrides)
|
|
181
|
+
].flatMap((s) => array(s?.[key]));
|
|
182
|
+
}
|
|
183
|
+
function readBabelConfig(root) {
|
|
184
|
+
const found = [];
|
|
185
|
+
for (const group of [PROJECT_FILES, RELATIVE_FILES]) {
|
|
186
|
+
const name = group.find((n) => node_fs.default.existsSync(node_path.default.join(root, n)));
|
|
187
|
+
if (!name) continue;
|
|
188
|
+
const file = node_path.default.join(root, name);
|
|
189
|
+
found.push({
|
|
190
|
+
source: name,
|
|
191
|
+
raw: evaluate(root, file),
|
|
192
|
+
text: node_fs.default.readFileSync(file, "utf8")
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
if (!found.some((f) => f.source.startsWith(".babelrc"))) try {
|
|
196
|
+
const pkg = JSON.parse(node_fs.default.readFileSync(node_path.default.join(root, "package.json"), "utf8"));
|
|
197
|
+
if (pkg.babel && typeof pkg.babel === "object") found.push({
|
|
198
|
+
source: "package.json#babel",
|
|
199
|
+
raw: pkg.babel,
|
|
200
|
+
text: ""
|
|
201
|
+
});
|
|
202
|
+
} catch {}
|
|
203
|
+
if (found.length === 0) return {
|
|
204
|
+
source: null,
|
|
205
|
+
evaluated: false,
|
|
206
|
+
plugins: [],
|
|
207
|
+
presets: []
|
|
208
|
+
};
|
|
209
|
+
const plugins = [];
|
|
210
|
+
const presets = [];
|
|
211
|
+
let evaluated = true;
|
|
212
|
+
for (const { raw, text } of found) {
|
|
213
|
+
if (raw && typeof raw === "object") {
|
|
214
|
+
plugins.push(...entriesOf(raw, "plugins").map((p) => entryOf(p, "plugin")));
|
|
215
|
+
presets.push(...entriesOf(raw, "presets").map((p) => entryOf(p, "preset").name));
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
evaluated = false;
|
|
219
|
+
for (const written of new Set([...text.matchAll(/["'`]([^"'`\s]+)["'`]/g)].map((m) => m[1]))) {
|
|
220
|
+
const name = normalizeBabelName(written);
|
|
221
|
+
if (KNOWN_PLUGINS.some((known) => known.names.includes(name))) plugins.push({
|
|
222
|
+
written,
|
|
223
|
+
name
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return {
|
|
228
|
+
source: found.map((f) => f.source).join(" + "),
|
|
229
|
+
evaluated,
|
|
230
|
+
plugins,
|
|
231
|
+
presets
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
/** Why a worklet plugin is not needed — only when the preset replacing its library is active. */
|
|
235
|
+
function workletReason(pkg, active, root) {
|
|
236
|
+
const preset = require_preset_map.presetShadowing(pkg);
|
|
237
|
+
if (preset && active.includes(preset)) return `transforms worklets for ${pkg}; the active ${preset} preset (auto-detected from ${Object.entries(require_preset_map.AUTO_DETECT_PRESETS).filter(([, name]) => name === preset).map(([detect]) => detect).join(", ")}) replaces ${pkg} with a mock, so no worklet runs.`;
|
|
238
|
+
if (!installedManifest(root, pkg)) return `transforms worklets for ${pkg}, which is not installed.`;
|
|
239
|
+
return null;
|
|
240
|
+
}
|
|
241
|
+
const KNOWN_PLUGINS = [
|
|
242
|
+
{
|
|
243
|
+
names: ["babel-plugin-macros", "@lingui/babel-plugin-lingui-macro"],
|
|
244
|
+
verdict: "required",
|
|
245
|
+
reason: (e) => `${e.written} compiles macro imports away at build time; without it the macro module is imported for real and fails (e.g. "Cannot find module 'babel-plugin-macros'").`
|
|
246
|
+
},
|
|
247
|
+
{
|
|
248
|
+
names: ["babel-plugin-module-resolver"],
|
|
249
|
+
verdict: "alias",
|
|
250
|
+
reason: () => `module-resolver rewrites import paths; its aliases map onto resolve.alias.`
|
|
251
|
+
},
|
|
252
|
+
{
|
|
253
|
+
names: ["react-native-worklets/plugin"],
|
|
254
|
+
verdict: "unneeded",
|
|
255
|
+
reason: () => ""
|
|
256
|
+
},
|
|
257
|
+
{
|
|
258
|
+
names: ["react-native-reanimated/plugin"],
|
|
259
|
+
verdict: "unneeded",
|
|
260
|
+
reason: () => ""
|
|
261
|
+
},
|
|
262
|
+
{
|
|
263
|
+
names: ["babel-plugin-react-compiler"],
|
|
264
|
+
verdict: "unneeded",
|
|
265
|
+
reason: () => "React Compiler only adds memoization to components that follow the Rules of React (react.dev/learn/react-compiler); they render the same without it."
|
|
266
|
+
}
|
|
267
|
+
];
|
|
268
|
+
const unknownReason = (e) => `${e.written} ran on every file under babel-jest and does not run under vitest-native; check whether tests depend on what it does.`;
|
|
269
|
+
function classifyBabelPlugins(report, root, active) {
|
|
270
|
+
return report.plugins.map((entry) => {
|
|
271
|
+
const worklets = /^(react-native-worklets|react-native-reanimated)\/plugin$/.exec(entry.name);
|
|
272
|
+
if (worklets) {
|
|
273
|
+
const reason = workletReason(worklets[1], active, root);
|
|
274
|
+
return reason ? {
|
|
275
|
+
...entry,
|
|
276
|
+
verdict: "unneeded",
|
|
277
|
+
reason
|
|
278
|
+
} : {
|
|
279
|
+
...entry,
|
|
280
|
+
verdict: "unknown",
|
|
281
|
+
reason: unknownReason(entry)
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
const known = KNOWN_PLUGINS.find((k) => k.names.includes(entry.name));
|
|
285
|
+
if (known) return {
|
|
286
|
+
...entry,
|
|
287
|
+
verdict: known.verdict,
|
|
288
|
+
reason: known.reason(entry, active)
|
|
289
|
+
};
|
|
290
|
+
if (/(^|[/-])macros?($|[/-])/.test(entry.name)) return {
|
|
291
|
+
...entry,
|
|
292
|
+
verdict: "required",
|
|
293
|
+
reason: `${entry.written} looks like a macro plugin; macros are compiled away at build time and fail when imported for real.`
|
|
294
|
+
};
|
|
295
|
+
return {
|
|
296
|
+
...entry,
|
|
297
|
+
verdict: "unknown",
|
|
298
|
+
reason: unknownReason(entry)
|
|
299
|
+
};
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
/** The installed major version of `vite`, or null. */
|
|
303
|
+
function viteMajor(root) {
|
|
304
|
+
const major = Number(require_host.installedViteVersion(root)?.replace(/^[^0-9]*/, "").split(".")[0]);
|
|
305
|
+
return Number.isFinite(major) ? major : installedMajor(root, "vite");
|
|
306
|
+
}
|
|
307
|
+
/** Whether `name` is installed where the project resolves it. */
|
|
308
|
+
function installed(root, name) {
|
|
309
|
+
return installedManifest(root, name) !== null;
|
|
310
|
+
}
|
|
311
|
+
/** The plugins array as config source text. */
|
|
312
|
+
function pluginListSource(plugins) {
|
|
313
|
+
return `[${plugins.map((p) => p.options === void 0 ? JSON.stringify(p.written) : `[${JSON.stringify(p.written)}, ${JSON.stringify(p.options)}]`).join(", ")}]`;
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* How to run Babel plugins per Vite major. @vitejs/plugin-react 6 (Vite 8) dropped
|
|
317
|
+
* Babel and points at @rolldown/plugin-babel; on Vite 7 and earlier its `babel`
|
|
318
|
+
* option adds plugins.
|
|
319
|
+
*/
|
|
320
|
+
function babelRecipe(major, plugins) {
|
|
321
|
+
const list = pluginListSource(plugins);
|
|
322
|
+
if (major !== null && major < 8) return `install @vitejs/plugin-react and @babel/core, then add \`react({ babel: { plugins: ${list} } })\` (import react from '@vitejs/plugin-react') to plugins`;
|
|
323
|
+
return `install @rolldown/plugin-babel and @babel/core, then add \`babel({ plugins: ${list} })\` (import babel from '@rolldown/plugin-babel') to plugins`;
|
|
324
|
+
}
|
|
325
|
+
/** Whether a plugin's options are plain data (JSON.stringify drops functions silently). */
|
|
326
|
+
function serializableOptions(entry) {
|
|
327
|
+
const plain = (value) => {
|
|
328
|
+
if (value === null || [
|
|
329
|
+
"string",
|
|
330
|
+
"number",
|
|
331
|
+
"boolean"
|
|
332
|
+
].includes(typeof value)) return true;
|
|
333
|
+
if (Array.isArray(value)) return value.every(plain);
|
|
334
|
+
if (typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) return Object.values(value).every(plain);
|
|
335
|
+
return false;
|
|
336
|
+
};
|
|
337
|
+
return entry.options === void 0 || plain(entry.options);
|
|
338
|
+
}
|
|
339
|
+
//#endregion
|
|
11
340
|
//#region src/cli/doctor.ts
|
|
12
341
|
/**
|
|
13
342
|
* `vitest-native doctor` — diagnose the project's environment: peer versions,
|
|
@@ -22,20 +351,49 @@ function packageVersion(root, name) {
|
|
|
22
351
|
}
|
|
23
352
|
}
|
|
24
353
|
/**
|
|
25
|
-
* The supported Node
|
|
26
|
-
*
|
|
27
|
-
*
|
|
354
|
+
* The supported Node versions, as this package's own `engines.node` states them.
|
|
355
|
+
* Single source: the manifest is what a package manager enforces at install time, so a
|
|
356
|
+
* diagnostic must not carry its own copy of the range.
|
|
28
357
|
*/
|
|
29
|
-
function
|
|
30
|
-
const fallback =
|
|
358
|
+
function nodeRange() {
|
|
359
|
+
const fallback = ">=22.13.0 <23 || >=24.3.0";
|
|
31
360
|
try {
|
|
32
|
-
|
|
33
|
-
const match = /(\d+)\.(\d+)/.exec(manifest.engines?.node ?? "");
|
|
34
|
-
return match ? [Number(match[1]), Number(match[2])] : fallback;
|
|
361
|
+
return JSON.parse(node_fs.default.readFileSync(new URL("../../package.json", require("url").pathToFileURL(__filename).href), "utf8")).engines?.node?.trim() || fallback;
|
|
35
362
|
} catch {
|
|
36
363
|
return fallback;
|
|
37
364
|
}
|
|
38
365
|
}
|
|
366
|
+
const versionParts = (version) => {
|
|
367
|
+
const [major = 0, minor = 0, patch = 0] = version.replace(/^v/, "").split(/[.-]/).map((part) => Number.parseInt(part, 10) || 0);
|
|
368
|
+
return [
|
|
369
|
+
major,
|
|
370
|
+
minor,
|
|
371
|
+
patch
|
|
372
|
+
];
|
|
373
|
+
};
|
|
374
|
+
const compareVersions = (a, b) => {
|
|
375
|
+
const [x, y] = [versionParts(a), versionParts(b)];
|
|
376
|
+
return x[0] - y[0] || x[1] - y[1] || x[2] - y[2];
|
|
377
|
+
};
|
|
378
|
+
/**
|
|
379
|
+
* Whether `version` is in `range`: `||`-separated sets of space-separated comparators
|
|
380
|
+
* (`>=`, `>`, `<=`, `<`, `=`), the forms `engines.node` uses. A version missing parts
|
|
381
|
+
* reads them as 0 (`<23` is `<23.0.0`).
|
|
382
|
+
*/
|
|
383
|
+
function satisfiesNodeRange(version, range) {
|
|
384
|
+
return range.split("||").some((set) => set.trim().split(/\s+/).filter(Boolean).every((comparator) => {
|
|
385
|
+
const match = /^(>=|<=|>|<|=)?\s*v?(\d[\w.-]*)$/.exec(comparator);
|
|
386
|
+
if (!match) return false;
|
|
387
|
+
const order = compareVersions(version, match[2]);
|
|
388
|
+
switch (match[1] ?? "=") {
|
|
389
|
+
case ">=": return order >= 0;
|
|
390
|
+
case ">": return order > 0;
|
|
391
|
+
case "<=": return order <= 0;
|
|
392
|
+
case "<": return order < 0;
|
|
393
|
+
default: return order === 0;
|
|
394
|
+
}
|
|
395
|
+
}));
|
|
396
|
+
}
|
|
39
397
|
/**
|
|
40
398
|
* In Vitest's own precedence order: a `vitest.config.*` wins, and `vite.config.*`
|
|
41
399
|
* is used when there is none.
|
|
@@ -179,52 +537,89 @@ function runDoctor(root, nodeVersion = process.versions.node) {
|
|
|
179
537
|
const rootFor = (name) => resolvesHere(name) || configRoot === root ? root : configRoot;
|
|
180
538
|
lines.push(`vitest-native doctor — ${root}`);
|
|
181
539
|
lines.push("", "Runtime");
|
|
182
|
-
const
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
if (nodeMajorMinor[0] > floorMajor || nodeMajorMinor[0] === floorMajor && nodeMajorMinor[1] >= floorMinor) pass(`Node ${nodeVersion} (floor: ${floorText})`);
|
|
186
|
-
else fail(`Node ${nodeVersion} — vitest-native requires Node >= ${floorText}.`);
|
|
540
|
+
const range = nodeRange();
|
|
541
|
+
if (satisfiesNodeRange(nodeVersion, range)) pass(`Node ${nodeVersion} (supported: ${range})`);
|
|
542
|
+
else fail(`Node ${nodeVersion} — vitest-native supports Node ${range}.`);
|
|
187
543
|
lines.push("", "Peer dependencies");
|
|
188
|
-
for (const { name, minimum, maximumMajor, minimumByMajor, optional } of
|
|
544
|
+
for (const { name, minimum, maximumMajor, minimumByMajor, optional } of require_host.PEER_REQUIREMENTS) {
|
|
189
545
|
if (optional) continue;
|
|
190
546
|
const from = rootFor(name);
|
|
191
|
-
const
|
|
547
|
+
const running = name === "vite" ? require_host.installedViteVersion(from) : name === "vitest" ? packageVersion(from, name) ?? (require_host.usesVitePlus(from) ? require_host.ownVitestPackage()?.version ?? null : null) : null;
|
|
548
|
+
const error = require_host.validatePeerDependency(name, minimum, from, maximumMajor, minimumByMajor, running);
|
|
192
549
|
if (error) fail(error);
|
|
193
550
|
else {
|
|
194
|
-
pass(`${name} ${packageVersion(from, name)}`);
|
|
551
|
+
pass(`${name} ${running ?? packageVersion(from, name)}`);
|
|
195
552
|
if (from !== root) lines.push(` (resolved from ${from}, not from here)`);
|
|
196
553
|
}
|
|
197
554
|
}
|
|
198
555
|
lines.push("", "Engine");
|
|
199
556
|
const rnVersion = packageVersion(rootFor("react-native"), "react-native");
|
|
200
|
-
|
|
201
|
-
|
|
557
|
+
const decision = require_host.detectEngine("auto", rootFor("@react-native/babel-preset"));
|
|
558
|
+
const transformPreset = require_host.resolveTransformPreset(rootFor("@react-native/babel-preset"));
|
|
559
|
+
const presetLabel = transformPreset ? `${transformPreset.name} ${transformPreset.version}` : "a React Native Babel preset";
|
|
560
|
+
if (decision.engine === "native") pass(`engine 'auto' resolves to NATIVE — real React Native${rnVersion ? ` ${rnVersion}` : ""} with ${presetLabel} + @babel/core present.`);
|
|
561
|
+
else if (rnVersion) warn(`engine 'auto' resolves to MOCK: react-native ${rnVersion} is installed but no React Native Babel preset (@react-native/babel-preset, or Expo's from SDK 56) and/or @babel/core resolve. Install both as devDependencies to run the real-RN native engine.`);
|
|
202
562
|
else warn("engine 'auto' resolves to MOCK: react-native is not installed. That is fine for pure-logic suites; install react-native (+ its babel preset) for the native engine.");
|
|
563
|
+
if (decision.engine === "native") {
|
|
564
|
+
const inferredRoot = configRoot;
|
|
565
|
+
const inferredEcosystem = require_host.detectEcosystemPackages([.../* @__PURE__ */ new Set([root, configRoot])], [], root === configRoot ? [] : [root], [], activePresets(root, [], decision.engine));
|
|
566
|
+
const inferredOwnership = require_host.createNativeOwnershipPolicy({
|
|
567
|
+
projectRoot: inferredRoot,
|
|
568
|
+
ecosystemPackages: inferredEcosystem,
|
|
569
|
+
projectDirs: [.../* @__PURE__ */ new Set([root, configRoot])]
|
|
570
|
+
});
|
|
571
|
+
lines.push("", "Ownership model (inferred baseline)");
|
|
572
|
+
for (const line of require_host.formatNativeOwnershipManifest(inferredOwnership.manifest())) lines.push(` · ${line}`);
|
|
573
|
+
lines.push(" · This command does not execute Vitest config. Set diagnostics: true for the resolved static policy and worker-time registration lines.");
|
|
574
|
+
const memoryPlan = require_memory.createHotMemoryPlan();
|
|
575
|
+
lines.push("", "Hot runtime capacity (inferred baseline)");
|
|
576
|
+
for (const line of require_memory.formatHotMemoryPlan(memoryPlan)) lines.push(` · ${line}`);
|
|
577
|
+
if (memoryPlan.maxWorkers < 2) warn("this memory ceiling admits only one hot worker, but current Vitest batches one-worker hot suites into an unrecyclable task. Use the default runtime unless an external scheduler supplies the memory boundary.");
|
|
578
|
+
else lines.push(" · This is capacity, not proof that hotRuntime is enabled; the resolved run reports its actual plan with diagnostics:true.");
|
|
579
|
+
lines.push("", "Hot runtime state restoration");
|
|
580
|
+
lines.push(` · ${HOT_STATE_MANIFEST_ENTRIES.join(", ")}`);
|
|
581
|
+
lines.push(" · Each entry is captured once, restored at the next file boundary and verified after all restore actions complete.");
|
|
582
|
+
}
|
|
203
583
|
lines.push("", "Testing library");
|
|
204
584
|
const rntl = packageVersion(rootFor("@testing-library/react-native"), "@testing-library/react-native");
|
|
205
585
|
if (!rntl) warn("@testing-library/react-native not found — optional, but required for render()/screen queries.");
|
|
206
586
|
else {
|
|
207
587
|
const rntlMajor = Number(rntl.split(".")[0]);
|
|
208
|
-
const rntlReq =
|
|
209
|
-
const rntlError = rntlReq &&
|
|
588
|
+
const rntlReq = require_host.PEER_REQUIREMENTS.find((r) => r.name === "@testing-library/react-native");
|
|
589
|
+
const rntlError = rntlReq && require_host.validatePeerDependency(rntlReq.name, rntlReq.minimum, root, rntlReq.maximumMajor, rntlReq.minimumByMajor);
|
|
210
590
|
if (rntlError) warn(rntlError);
|
|
211
|
-
else if (rntlMajor >= 14 && (
|
|
591
|
+
else if (rntlMajor >= 14 && !satisfiesNodeRange(nodeVersion, ">=22.13.0")) fail(`@testing-library/react-native ${rntl} requires Node >= 22.13, but this is Node ${nodeVersion}. Upgrade Node or pin @testing-library/react-native@13.`);
|
|
212
592
|
else if (rntlMajor >= 14 && !packageVersion(rootFor("test-renderer"), "test-renderer")) fail(`@testing-library/react-native ${rntl} requires the 'test-renderer' package, which is not installed. Every render() will fail with "Cannot find module 'test-renderer'". Install it:\n\n npm install -D test-renderer\n`);
|
|
213
593
|
else pass(`@testing-library/react-native ${rntl}${rntlMajor >= 14 ? " (14 is async: await render/fireEvent)" : ""}`);
|
|
214
594
|
}
|
|
215
595
|
lines.push("", "Auto-detected presets");
|
|
216
|
-
const req = (0, node_module.createRequire)(node_path.default.join(root, "package.json"));
|
|
217
596
|
const detected = [];
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
597
|
+
let installedAny = false;
|
|
598
|
+
for (const [pkg, preset] of Object.entries(require_preset_map.AUTO_DETECT_PRESETS)) {
|
|
599
|
+
if (!installedManifest(root, pkg)) continue;
|
|
600
|
+
installedAny = true;
|
|
601
|
+
if (installedTestsItself(root, pkg)) lines.push(` · ${pkg} ${installedMajor(root, pkg)} runs its own test mode under Vitest, so no preset replaces it`);
|
|
602
|
+
else if (!require_preset_map.autoDetectedPresetApplies(preset, decision.engine)) lines.push(` · ${pkg} runs as itself under the native engine, on its native-module mocks; the ${preset} preset applies under the mock engine or with \`presets: { ${preset}: true }\``);
|
|
603
|
+
else detected.push(`${pkg} → ${preset}`);
|
|
604
|
+
}
|
|
222
605
|
if (detected.length) for (const d of detected) pass(d);
|
|
223
|
-
else lines.push(" (none — no preset-covered packages installed)");
|
|
606
|
+
else if (!installedAny) lines.push(" (none — no preset-covered packages installed)");
|
|
224
607
|
const expo = packageVersion(rootFor("expo"), "expo");
|
|
225
608
|
if (expo) {
|
|
226
609
|
lines.push("", "Expo");
|
|
227
|
-
|
|
610
|
+
pass((decision.engine === "native" ? `expo ${expo} detected. Under the native engine Expo modules run their real JavaScript on native-module mocks, as under jest-expo (unless the config sets \`engine: 'mock'\` or \`presets: { expo: true }\`, where the expo preset shadows ${require_preset_map.PRESET_MODULES.expo.join(", ")}). ` : `expo ${expo} detected. Under the mock engine the expo preset shadows ${require_preset_map.PRESET_MODULES.expo.join(", ")}; other Expo modules load their real JavaScript. `) + `Coming from jest-expo, run \`vitest-native migrate\`. See https://danfry1.github.io/vitest-native/guide/expo`);
|
|
611
|
+
}
|
|
612
|
+
const babel = readBabelConfig(root);
|
|
613
|
+
if (babel.source) {
|
|
614
|
+
lines.push("", "Babel");
|
|
615
|
+
const classified = classifyBabelPlugins(babel, root, activePresets(root, [], decision.engine));
|
|
616
|
+
const required = classified.filter((p) => p.verdict === "required");
|
|
617
|
+
for (const p of classified) if (p.verdict === "required") warn(`${p.reason} Required: ${babelRecipe(viteMajor(rootFor("vite")), required)}.`);
|
|
618
|
+
else if (p.verdict === "alias") warn(`${p.reason} \`vitest-native migrate\` writes them; otherwise add them to resolve.alias.`);
|
|
619
|
+
else if (p.verdict === "unknown") warn(p.reason);
|
|
620
|
+
else lines.push(` · ${p.written}: ${p.reason}`);
|
|
621
|
+
if (!babel.evaluated) lines.push(` · ${babel.source} could not be evaluated; only plugins recognized by name are listed.`);
|
|
622
|
+
else if (classified.length === 0) lines.push(` · ${babel.source} declares no plugins.`);
|
|
228
623
|
}
|
|
229
624
|
lines.push("", "Config");
|
|
230
625
|
const configFile = findConfigFile(configRoot);
|
|
@@ -250,6 +645,15 @@ function runDoctor(root, nodeVersion = process.versions.node) {
|
|
|
250
645
|
* the zero-config default, and the jest-compat variant (the exact block the
|
|
251
646
|
* migration guide documents, so docs and CLI can never drift apart by shape).
|
|
252
647
|
*/
|
|
648
|
+
/**
|
|
649
|
+
* Printed after `init` and `migrate`: the hot runtime is off by default, so a user
|
|
650
|
+
* reading only the CLI output would not otherwise learn it exists or what it costs.
|
|
651
|
+
*/
|
|
652
|
+
const HOT_RUNTIME_NOTE = [
|
|
653
|
+
"Hot runtime: off by default. `hotRuntime: 'auto'` reuses workers between test files, which",
|
|
654
|
+
"usually makes large native-engine suites faster. It has known differences from per-file isolation:",
|
|
655
|
+
" https://danfry1.github.io/vitest-native/guide/troubleshooting#a-test-passes-on-its-own-but-fails-when-run-with-other-files"
|
|
656
|
+
];
|
|
253
657
|
const PLAIN_CONFIG = `import { defineConfig } from 'vitest/config'
|
|
254
658
|
import { reactNative } from 'vitest-native'
|
|
255
659
|
|
|
@@ -283,11 +687,23 @@ export default defineConfig({
|
|
|
283
687
|
},
|
|
284
688
|
})
|
|
285
689
|
`;
|
|
286
|
-
|
|
287
|
-
|
|
690
|
+
/**
|
|
691
|
+
* The config source. Under Vite+ the config is `vite.config.ts` with `defineConfig`
|
|
692
|
+
* from 'vite-plus' (viteplus.dev/guide/test): the project does not install `vitest`
|
|
693
|
+
* itself, so a config importing 'vitest/config' fails to load under pnpm.
|
|
694
|
+
*/
|
|
695
|
+
function renderInitConfig(jestCompat, vitePlus = false) {
|
|
696
|
+
const source = jestCompat ? JEST_COMPAT_CONFIG : PLAIN_CONFIG;
|
|
697
|
+
return vitePlus ? source.replace("import { defineConfig } from 'vitest/config'", "import { defineConfig } from 'vite-plus'") : source;
|
|
288
698
|
}
|
|
289
|
-
function existingConfig(root) {
|
|
699
|
+
function existingConfig(root, vitePlus) {
|
|
290
700
|
for (const name of [
|
|
701
|
+
...vitePlus ? [
|
|
702
|
+
"vite.config.ts",
|
|
703
|
+
"vite.config.mts",
|
|
704
|
+
"vite.config.js",
|
|
705
|
+
"vite.config.mjs"
|
|
706
|
+
] : [],
|
|
291
707
|
"vitest.config.ts",
|
|
292
708
|
"vitest.config.mts",
|
|
293
709
|
"vitest.config.js",
|
|
@@ -299,91 +715,736 @@ function existingConfig(root) {
|
|
|
299
715
|
}
|
|
300
716
|
function runInit(root, opts = {}) {
|
|
301
717
|
const lines = [];
|
|
302
|
-
const
|
|
718
|
+
const vitePlus = require_host.usesVitePlus(root);
|
|
719
|
+
const existing = existingConfig(root, vitePlus);
|
|
720
|
+
if (existing && vitePlus && existing.startsWith("vite.config")) return {
|
|
721
|
+
lines: [
|
|
722
|
+
`✗ ${existing} already exists. Vite+ keeps tests in the same config, so add`,
|
|
723
|
+
` vitest-native to it rather than replacing it:`,
|
|
724
|
+
``,
|
|
725
|
+
` import { reactNative } from 'vitest-native'`,
|
|
726
|
+
``,
|
|
727
|
+
` export default defineConfig({`,
|
|
728
|
+
` plugins: [reactNative()],`,
|
|
729
|
+
` test: { environment: 'node' },`,
|
|
730
|
+
` })`,
|
|
731
|
+
``,
|
|
732
|
+
` Then run: vp test`
|
|
733
|
+
],
|
|
734
|
+
ok: false
|
|
735
|
+
};
|
|
303
736
|
if (existing && !opts.force) return {
|
|
304
737
|
lines: [`✗ ${existing} already exists — not overwriting. Re-run with --force to replace it,`, ` or run \`vitest-native migrate\` to analyze an existing Jest setup first.`],
|
|
305
738
|
ok: false
|
|
306
739
|
};
|
|
307
|
-
const file = node_fs.default.existsSync(node_path.default.join(root, "tsconfig.json")) ? "vitest.config.mts" : "vitest.config.mjs";
|
|
740
|
+
const file = vitePlus ? "vite.config.ts" : node_fs.default.existsSync(node_path.default.join(root, "tsconfig.json")) ? "vitest.config.mts" : "vitest.config.mjs";
|
|
308
741
|
const target = node_path.default.join(root, file);
|
|
309
|
-
node_fs.default.writeFileSync(target, renderInitConfig(opts.jestCompat ?? false));
|
|
742
|
+
node_fs.default.writeFileSync(target, renderInitConfig(opts.jestCompat ?? false, vitePlus));
|
|
310
743
|
lines.push(`✓ wrote ${file}${opts.jestCompat ? " (jest-compat variant)" : ""}`);
|
|
311
744
|
if (existing && opts.force) lines.push(` (replaced ${existing === file ? "it" : existing})`);
|
|
312
|
-
lines.push("", "Next steps:", ` 1. add a script: "test": "vitest"`, ` 2. run: npx vitest`, ` 3. check the environment: npx vitest-native doctor`);
|
|
745
|
+
lines.push("", "Next steps:", vitePlus ? ` 1. add a script: "test": "vp test"` : ` 1. add a script: "test": "vitest"`, vitePlus ? ` 2. run: vp test` : ` 2. run: npx vitest`, ` 3. check the environment: npx vitest-native doctor`);
|
|
313
746
|
if (opts.jestCompat) lines.push(` 4. migrating a Jest suite? \`vitest-native migrate\` maps your jest.config onto this file.`);
|
|
747
|
+
lines.push("", ...HOT_RUNTIME_NOTE);
|
|
314
748
|
return {
|
|
315
749
|
lines,
|
|
316
750
|
ok: true,
|
|
317
751
|
wrote: file
|
|
318
752
|
};
|
|
319
753
|
}
|
|
320
|
-
|
|
321
|
-
|
|
754
|
+
const MAX_EXPANSIONS = 256;
|
|
755
|
+
var Unparseable = class extends Error {};
|
|
322
756
|
/**
|
|
323
|
-
*
|
|
324
|
-
*
|
|
325
|
-
*
|
|
326
|
-
* Vitest config. It never edits test files: `jestMockTransform()` handles
|
|
327
|
-
* top-level `jest.mock` at runtime, so file codemods aren't required to start.
|
|
757
|
+
* @param literalDot read an unescaped `.` as a literal dot. Right for package names
|
|
758
|
+
* and module specifiers, where it never means "any character"; wrong for path
|
|
759
|
+
* patterns, where it throws instead.
|
|
328
760
|
*/
|
|
761
|
+
function expandRegex(source, literalDot) {
|
|
762
|
+
let i = 0;
|
|
763
|
+
const alternation = () => {
|
|
764
|
+
const out = [...sequence()];
|
|
765
|
+
while (source[i] === "|") {
|
|
766
|
+
i++;
|
|
767
|
+
out.push(...sequence());
|
|
768
|
+
}
|
|
769
|
+
return out;
|
|
770
|
+
};
|
|
771
|
+
const sequence = () => {
|
|
772
|
+
let acc = [""];
|
|
773
|
+
while (i < source.length && source[i] !== "|" && source[i] !== ")") {
|
|
774
|
+
let atom;
|
|
775
|
+
const c = source[i];
|
|
776
|
+
if (c === "(") {
|
|
777
|
+
i++;
|
|
778
|
+
if (source.startsWith("?:", i)) i += 2;
|
|
779
|
+
else if (source[i] === "?") throw new Unparseable();
|
|
780
|
+
atom = alternation();
|
|
781
|
+
if (source[i] !== ")") throw new Unparseable();
|
|
782
|
+
i++;
|
|
783
|
+
} else if (c === "\\") {
|
|
784
|
+
const next = source[i + 1];
|
|
785
|
+
if (next === void 0 || /[A-Za-z0-9]/.test(next)) throw new Unparseable();
|
|
786
|
+
atom = [next];
|
|
787
|
+
i += 2;
|
|
788
|
+
} else if (c === ".") {
|
|
789
|
+
i++;
|
|
790
|
+
if (source[i] === "*") {
|
|
791
|
+
i++;
|
|
792
|
+
atom = ["\0"];
|
|
793
|
+
} else if (literalDot) atom = ["."];
|
|
794
|
+
else throw new Unparseable();
|
|
795
|
+
} else if ("[]{}+*^$".includes(c)) throw new Unparseable();
|
|
796
|
+
else {
|
|
797
|
+
atom = [c];
|
|
798
|
+
i++;
|
|
799
|
+
}
|
|
800
|
+
if (source[i] === "?") {
|
|
801
|
+
i++;
|
|
802
|
+
atom = ["", ...atom];
|
|
803
|
+
}
|
|
804
|
+
const next = [];
|
|
805
|
+
for (const a of acc) for (const b of atom) next.push(a + b);
|
|
806
|
+
if (next.length > MAX_EXPANSIONS) throw new Unparseable();
|
|
807
|
+
acc = next;
|
|
808
|
+
}
|
|
809
|
+
return acc;
|
|
810
|
+
};
|
|
811
|
+
const result = alternation();
|
|
812
|
+
if (i !== source.length) throw new Unparseable();
|
|
813
|
+
return result;
|
|
814
|
+
}
|
|
815
|
+
/** expandRegex, or null when the source is outside the language. */
|
|
816
|
+
function tryExpand(source, literalDot) {
|
|
817
|
+
try {
|
|
818
|
+
return expandRegex(source, literalDot);
|
|
819
|
+
} catch (error) {
|
|
820
|
+
if (error instanceof Unparseable) return null;
|
|
821
|
+
throw error;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
//#endregion
|
|
825
|
+
//#region src/cli/allowlist.ts
|
|
329
826
|
/**
|
|
330
|
-
*
|
|
331
|
-
*
|
|
332
|
-
*
|
|
333
|
-
*
|
|
334
|
-
*
|
|
335
|
-
*
|
|
827
|
+
* Reading Jest's `transformIgnorePatterns` allowlist,
|
|
828
|
+
* `node_modules/(?!(a|b|@scope/c)/)`. Real ones nest — React Native's own preset
|
|
829
|
+
* ships `node_modules/(?!((jest-)?react-native|@react-native(-community)?)/)` — so
|
|
830
|
+
* the lookahead is found by counting parentheses and expanded with the shared
|
|
831
|
+
* regex-subset expander. An alternative WITHOUT a trailing `/` is a name PREFIX:
|
|
832
|
+
* `(?!expo)` lets through expo-router and exponent too.
|
|
336
833
|
*/
|
|
834
|
+
/** The body of the first `(?!…)`, or null. */
|
|
835
|
+
function lookaheadBody(pattern) {
|
|
836
|
+
const start = pattern.indexOf("(?!");
|
|
837
|
+
if (start === -1) return null;
|
|
838
|
+
let depth = 0;
|
|
839
|
+
for (let i = start; i < pattern.length; i++) {
|
|
840
|
+
const c = pattern[i];
|
|
841
|
+
if (c === "\\") i++;
|
|
842
|
+
else if (c === "(") depth++;
|
|
843
|
+
else if (c === ")") {
|
|
844
|
+
depth--;
|
|
845
|
+
if (depth === 0) return pattern.slice(start + 3, i);
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
return null;
|
|
849
|
+
}
|
|
850
|
+
/** Split on `|` at depth zero. */
|
|
851
|
+
function topLevelAlternatives(body) {
|
|
852
|
+
const out = [];
|
|
853
|
+
let depth = 0;
|
|
854
|
+
let current = "";
|
|
855
|
+
for (let i = 0; i < body.length; i++) {
|
|
856
|
+
const c = body[i];
|
|
857
|
+
if (c === "\\") {
|
|
858
|
+
current += c + (body[i + 1] ?? "");
|
|
859
|
+
i++;
|
|
860
|
+
continue;
|
|
861
|
+
}
|
|
862
|
+
if (c === "(") depth++;
|
|
863
|
+
if (c === ")") depth--;
|
|
864
|
+
if (c === "|" && depth === 0) {
|
|
865
|
+
out.push(current);
|
|
866
|
+
current = "";
|
|
867
|
+
} else current += c;
|
|
868
|
+
}
|
|
869
|
+
out.push(current);
|
|
870
|
+
return out.map((s) => s.trim()).filter(Boolean);
|
|
871
|
+
}
|
|
872
|
+
const NAME = /^(@[a-z0-9~-][a-z0-9._~-]*\/)?[a-z0-9~-][a-z0-9._~-]*$/i;
|
|
873
|
+
const SCOPE = /^@[a-z0-9~-][a-z0-9._~-]*$/i;
|
|
874
|
+
const PREFIX = /^(@[a-z0-9~-][a-z0-9._~-]*(\/[a-z0-9._~-]*)?|[a-z0-9~-][a-z0-9._~-]*)$/i;
|
|
875
|
+
function classify(expansion) {
|
|
876
|
+
const trimmed = expansion.replace(new RegExp(`/$`), "/");
|
|
877
|
+
if (trimmed.includes("\0")) return null;
|
|
878
|
+
if (trimmed.endsWith("/")) {
|
|
879
|
+
const name = trimmed.slice(0, -1);
|
|
880
|
+
if (SCOPE.test(name)) return {
|
|
881
|
+
name,
|
|
882
|
+
kind: "scope"
|
|
883
|
+
};
|
|
884
|
+
return NAME.test(name) ? {
|
|
885
|
+
name,
|
|
886
|
+
kind: "exact"
|
|
887
|
+
} : null;
|
|
888
|
+
}
|
|
889
|
+
return PREFIX.test(trimmed) ? {
|
|
890
|
+
name: trimmed,
|
|
891
|
+
kind: "prefix"
|
|
892
|
+
} : null;
|
|
893
|
+
}
|
|
894
|
+
/** The names an allowlist pattern lets through, and the alternatives it could not read. */
|
|
337
895
|
function extractAllowlistPackages(pattern) {
|
|
338
|
-
const
|
|
339
|
-
if (
|
|
340
|
-
|
|
896
|
+
const body = lookaheadBody(pattern);
|
|
897
|
+
if (body === null) return {
|
|
898
|
+
entries: [],
|
|
341
899
|
unparseable: []
|
|
342
900
|
};
|
|
343
|
-
const
|
|
901
|
+
const entries = [];
|
|
344
902
|
const unparseable = [];
|
|
345
|
-
for (const
|
|
346
|
-
const
|
|
347
|
-
if (!
|
|
348
|
-
|
|
349
|
-
unparseable.push(entry);
|
|
903
|
+
for (const alternative of topLevelAlternatives(body)) {
|
|
904
|
+
const classified = tryExpand(alternative, true)?.filter((e) => !e.startsWith(".")).map(classify);
|
|
905
|
+
if (!classified || classified.some((c) => c === null)) {
|
|
906
|
+
unparseable.push(alternative);
|
|
350
907
|
continue;
|
|
351
908
|
}
|
|
352
|
-
const
|
|
353
|
-
if (cleaned.length > 0 && !cleaned.includes("\\")) packages.push(cleaned);
|
|
354
|
-
else if (entry.length > 0) unparseable.push(entry);
|
|
909
|
+
for (const entry of classified) if (!entries.some((e) => e.name === entry.name && e.kind === entry.kind)) entries.push(entry);
|
|
355
910
|
}
|
|
356
911
|
return {
|
|
357
|
-
|
|
912
|
+
entries,
|
|
358
913
|
unparseable
|
|
359
914
|
};
|
|
360
915
|
}
|
|
361
|
-
|
|
916
|
+
/** Whether a dependency name falls under an allowlist entry. */
|
|
917
|
+
function allows(entry, pkg) {
|
|
918
|
+
if (entry.kind === "exact") return pkg === entry.name;
|
|
919
|
+
if (entry.kind === "scope") return pkg.startsWith(`${entry.name}/`);
|
|
920
|
+
return pkg.startsWith(entry.name);
|
|
921
|
+
}
|
|
922
|
+
//#endregion
|
|
923
|
+
//#region src/cli/jest-discovery.ts
|
|
924
|
+
/**
|
|
925
|
+
* Which files Jest treats as tests, said to Vitest.
|
|
926
|
+
*
|
|
927
|
+
* Jest's test set is its EFFECTIVE config — the preset's keys under the user's, Jest's
|
|
928
|
+
* defaults under both — narrowed by testPathIgnorePatterns, modulePathIgnorePatterns
|
|
929
|
+
* and moduleFileExtensions. Translating only an explicit testMatch left a jest-expo
|
|
930
|
+
* app on Vitest's default include: about twice Jest's files, some of Jest's missed.
|
|
931
|
+
* Sources: jest-config 30 (`setupPreset`, `normalize`, `Defaults`), jest-util
|
|
932
|
+
* `globsToMatcher`, @jest/core `SearchSource`, jest-runtime's haste map; Vitest
|
|
933
|
+
* collects with tinyglobby (`dot: true`, `ignore: exclude`).
|
|
934
|
+
*/
|
|
935
|
+
/** jest-config `Defaults` for the discovery keys, per major (https://jestjs.io/docs/configuration). */
|
|
936
|
+
const JEST_DEFAULTS = {
|
|
937
|
+
29: {
|
|
938
|
+
testMatch: ["**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[tj]s?(x)"],
|
|
939
|
+
testPathIgnorePatterns: ["/node_modules/"],
|
|
940
|
+
modulePathIgnorePatterns: [],
|
|
941
|
+
moduleFileExtensions: [
|
|
942
|
+
"js",
|
|
943
|
+
"mjs",
|
|
944
|
+
"cjs",
|
|
945
|
+
"jsx",
|
|
946
|
+
"ts",
|
|
947
|
+
"tsx",
|
|
948
|
+
"json",
|
|
949
|
+
"node"
|
|
950
|
+
],
|
|
951
|
+
roots: ["<rootDir>"]
|
|
952
|
+
},
|
|
953
|
+
30: {
|
|
954
|
+
testMatch: ["**/__tests__/**/*.?([mc])[jt]s?(x)", "**/?(*.)+(spec|test).?([mc])[jt]s?(x)"],
|
|
955
|
+
testPathIgnorePatterns: ["/node_modules/"],
|
|
956
|
+
modulePathIgnorePatterns: [],
|
|
957
|
+
moduleFileExtensions: [
|
|
958
|
+
"js",
|
|
959
|
+
"mjs",
|
|
960
|
+
"cjs",
|
|
961
|
+
"jsx",
|
|
962
|
+
"ts",
|
|
963
|
+
"mts",
|
|
964
|
+
"cts",
|
|
965
|
+
"tsx",
|
|
966
|
+
"json",
|
|
967
|
+
"node"
|
|
968
|
+
],
|
|
969
|
+
roots: ["<rootDir>"]
|
|
970
|
+
}
|
|
971
|
+
};
|
|
972
|
+
/** The installed Jest's major (29 or 30), or null when Jest is not installed. */
|
|
973
|
+
function jestMajor(root) {
|
|
974
|
+
const major = installedMajor(root, "jest") ?? installedMajor(root, "jest-config");
|
|
975
|
+
return major === null ? null : major <= 29 ? 29 : 30;
|
|
976
|
+
}
|
|
977
|
+
/**
|
|
978
|
+
* Load a preset as jest-config's `setupPreset` does: a relative or absolute path is
|
|
979
|
+
* resolved as written, anything else as `<name>/jest-preset`, trying the extensions
|
|
980
|
+
* .json, .js, .cjs in that order (.mjs cannot be loaded synchronously). Loading
|
|
981
|
+
* executes the preset, as Jest does.
|
|
982
|
+
*/
|
|
983
|
+
function loadJestPreset(root, preset) {
|
|
362
984
|
const req = (0, node_module.createRequire)(node_path.default.join(root, "package.json"));
|
|
985
|
+
const presetPath = preset.replace(/^<rootDir>/, root);
|
|
986
|
+
const base = presetPath.startsWith(".") || node_path.default.isAbsolute(presetPath) ? node_path.default.resolve(root, presetPath) : `${presetPath}/jest-preset`;
|
|
987
|
+
const candidates = [
|
|
988
|
+
".json",
|
|
989
|
+
".js",
|
|
990
|
+
".cjs"
|
|
991
|
+
].includes(node_path.default.extname(base)) ? [base] : [
|
|
992
|
+
`${base}.json`,
|
|
993
|
+
`${base}.js`,
|
|
994
|
+
`${base}.cjs`,
|
|
995
|
+
base
|
|
996
|
+
];
|
|
997
|
+
let file;
|
|
998
|
+
for (const candidate of candidates) try {
|
|
999
|
+
file = req.resolve(candidate);
|
|
1000
|
+
break;
|
|
1001
|
+
} catch {}
|
|
1002
|
+
if (!file) return { error: `cannot resolve '${base}' from ${root}` };
|
|
1003
|
+
const previousEnv = process.env.NODE_ENV;
|
|
1004
|
+
process.env.NODE_ENV ??= "test";
|
|
1005
|
+
try {
|
|
1006
|
+
const loaded = file.endsWith(".json") ? JSON.parse(node_fs.default.readFileSync(file, "utf8")) : req(file);
|
|
1007
|
+
const config = loaded && typeof loaded === "object" && "default" in loaded ? loaded.default : loaded;
|
|
1008
|
+
if (!config || typeof config !== "object") return { error: `${file} exports no object` };
|
|
1009
|
+
return {
|
|
1010
|
+
config,
|
|
1011
|
+
file
|
|
1012
|
+
};
|
|
1013
|
+
} catch (error) {
|
|
1014
|
+
return { error: `${file} failed to load: ${error.message.split("\n")[0]}` };
|
|
1015
|
+
} finally {
|
|
1016
|
+
if (previousEnv === void 0) delete process.env.NODE_ENV;
|
|
1017
|
+
else process.env.NODE_ENV = previousEnv;
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
/**
|
|
1021
|
+
* Convert a Jest `testPathIgnorePatterns` / `modulePathIgnorePatterns` regex into
|
|
1022
|
+
* `exclude` globs selecting the same files, or null when that cannot be done exactly.
|
|
1023
|
+
*
|
|
1024
|
+
* Jest tests each pattern unanchored against the ABSOLUTE path (@jest/core
|
|
1025
|
+
* SearchSource; jest-runtime's haste-map `ignorePattern`); Vitest matches `exclude`
|
|
1026
|
+
* against root-relative paths. So `<rootDir>/x` anchors at the root, anything else may
|
|
1027
|
+
* start mid-segment (`bskylink/.*` also ignores `notbskylink/`, hence `**\/*`), `/.*\/`
|
|
1028
|
+
* spans whole segments (`*\/**`), a trailing `/`, `/.*` or `.*` leaves the rest free,
|
|
1029
|
+
* a pattern ending mid-segment covers a file and a directory, and `$` is left for a human.
|
|
1030
|
+
* Jest substitutes `<rootDir>` unescaped; it is read here as the directory it names.
|
|
1031
|
+
* A match starting above the root has no relative form and is not attempted.
|
|
1032
|
+
*/
|
|
1033
|
+
function ignorePatternToGlobs(pattern) {
|
|
1034
|
+
let rest = pattern;
|
|
1035
|
+
let anchored = false;
|
|
1036
|
+
if (rest.startsWith("<rootDir>")) {
|
|
1037
|
+
anchored = true;
|
|
1038
|
+
rest = rest.slice(9);
|
|
1039
|
+
if (!rest.startsWith("/") || rest === "/") return null;
|
|
1040
|
+
}
|
|
1041
|
+
const endAnchored = /(^|[^\\])(\\\\)*\$$/.test(rest);
|
|
1042
|
+
if (endAnchored) rest = rest.slice(0, -1);
|
|
1043
|
+
const expansions = tryExpand(rest, false);
|
|
1044
|
+
if (!expansions) return null;
|
|
1045
|
+
const globs = [];
|
|
1046
|
+
for (const expansion of expansions) {
|
|
1047
|
+
const converted = expansionToGlobs(expansion, anchored, endAnchored);
|
|
1048
|
+
if (!converted) return null;
|
|
1049
|
+
globs.push(...converted);
|
|
1050
|
+
}
|
|
1051
|
+
return [...new Set(globs)];
|
|
1052
|
+
}
|
|
1053
|
+
function expansionToGlobs(expansion, anchored, endAnchored) {
|
|
1054
|
+
let s = expansion;
|
|
1055
|
+
if (/[*?[\]{}()!\\]/.test(s.replaceAll("\0", ""))) return null;
|
|
1056
|
+
if (s.endsWith("\0")) {
|
|
1057
|
+
s = s.slice(0, -1);
|
|
1058
|
+
endAnchored = false;
|
|
1059
|
+
}
|
|
1060
|
+
if (!anchored) s = s.replace(new RegExp(`^+`), "");
|
|
1061
|
+
if (s === "" || anchored && s.startsWith(`/`)) return null;
|
|
1062
|
+
if (endAnchored) return s.endsWith("/") ? [] : null;
|
|
1063
|
+
const parts = s.split(`//`);
|
|
1064
|
+
if (parts.some((part) => part.includes("\0") || part === "")) return null;
|
|
1065
|
+
let glob = parts.join("/*/**/");
|
|
1066
|
+
if (anchored) glob = glob.slice(1);
|
|
1067
|
+
else glob = glob.startsWith("/") ? `**/${glob.slice(1)}` : `**/*${glob}`;
|
|
1068
|
+
if (glob.endsWith("/")) return [`${glob}**`];
|
|
1069
|
+
return [`${glob}*`, `${glob}*/**`];
|
|
1070
|
+
}
|
|
1071
|
+
const TEST_FILE_EXTENSIONS = [
|
|
1072
|
+
"js",
|
|
1073
|
+
"mjs",
|
|
1074
|
+
"cjs",
|
|
1075
|
+
"jsx",
|
|
1076
|
+
"ts",
|
|
1077
|
+
"mts",
|
|
1078
|
+
"cts",
|
|
1079
|
+
"tsx"
|
|
1080
|
+
];
|
|
1081
|
+
/** The last-segment extensions Jest's haste map crawls (`ios.ts` adds nothing beyond `ts`). */
|
|
1082
|
+
function visibleExtensions(moduleFileExtensions) {
|
|
1083
|
+
return moduleFileExtensions.filter((ext) => !ext.includes("."));
|
|
1084
|
+
}
|
|
1085
|
+
/**
|
|
1086
|
+
* An exclude glob for the script extensions Jest cannot see: its haste map crawls
|
|
1087
|
+
* only `moduleFileExtensions` (jest-runtime passes them as `extensions`).
|
|
1088
|
+
*/
|
|
1089
|
+
function extensionExclude(moduleFileExtensions) {
|
|
1090
|
+
const visible = new Set(visibleExtensions(moduleFileExtensions));
|
|
1091
|
+
const hidden = TEST_FILE_EXTENSIONS.filter((ext) => !visible.has(ext));
|
|
1092
|
+
if (hidden.length === 0) return null;
|
|
1093
|
+
return hidden.length === 1 ? `**/*.${hidden[0]}` : `**/*.{${hidden.join(",")}}`;
|
|
1094
|
+
}
|
|
1095
|
+
/**
|
|
1096
|
+
* Jest's effective discovery settings, translated. `preset` is the loaded preset's
|
|
1097
|
+
* config (null when none). Merged as `setupPreset` does — the user's keys win,
|
|
1098
|
+
* `modulePathIgnorePatterns` concatenates — and defaulted as `normalize` does.
|
|
1099
|
+
*/
|
|
1100
|
+
function translateDiscovery(options, preset, major) {
|
|
1101
|
+
const defaults = JEST_DEFAULTS[major ?? 30];
|
|
1102
|
+
const automatic = [];
|
|
1103
|
+
const attention = [];
|
|
1104
|
+
const pick = (key) => {
|
|
1105
|
+
if (options[key] !== void 0) return {
|
|
1106
|
+
value: options[key],
|
|
1107
|
+
from: "from the config"
|
|
1108
|
+
};
|
|
1109
|
+
if (preset?.[key] !== void 0) return {
|
|
1110
|
+
value: preset[key],
|
|
1111
|
+
from: "from the preset"
|
|
1112
|
+
};
|
|
1113
|
+
return {
|
|
1114
|
+
value: void 0,
|
|
1115
|
+
from: `Jest ${major ?? 30}'s default`
|
|
1116
|
+
};
|
|
1117
|
+
};
|
|
1118
|
+
const defaultsNote = major === null ? "; Jest is not installed, so Jest 30's" : "";
|
|
1119
|
+
const extensions = pick("moduleFileExtensions");
|
|
1120
|
+
const moduleFileExtensions = extensions.value ?? defaults.moduleFileExtensions;
|
|
1121
|
+
const regexes = [pick("testRegex").value ?? []].flat().filter(Boolean);
|
|
1122
|
+
const exclude = [];
|
|
1123
|
+
let include = null;
|
|
1124
|
+
if (regexes.length > 0) attention.push(`testRegex ${JSON.stringify(regexes)} — Vitest selects test files by glob only; rewrite it as test.include globs (the suggested config keeps Vitest's default include until then).`);
|
|
1125
|
+
else {
|
|
1126
|
+
const match = pick("testMatch");
|
|
1127
|
+
const positive = [];
|
|
1128
|
+
const negated = [];
|
|
1129
|
+
let positiveAfterNegation = false;
|
|
1130
|
+
for (const raw of match.value ?? defaults.testMatch) {
|
|
1131
|
+
const isNegated = raw.startsWith("!");
|
|
1132
|
+
const glob = (isNegated ? raw.slice(1) : raw).replace(/^<rootDir>\//, "");
|
|
1133
|
+
if (node_path.default.isAbsolute(glob)) {
|
|
1134
|
+
attention.push(`testMatch '${raw}' — an absolute glob; map it to test.include by hand.`);
|
|
1135
|
+
continue;
|
|
1136
|
+
}
|
|
1137
|
+
if (!glob.startsWith("**") && raw.replace(/^!/, "") === glob) {
|
|
1138
|
+
attention.push(`testMatch '${raw}' — Jest compares testMatch with absolute paths, so this glob matched nothing; not carried over (prefix it with **/ if it was meant to match).`);
|
|
1139
|
+
continue;
|
|
1140
|
+
}
|
|
1141
|
+
if (isNegated) negated.push(glob);
|
|
1142
|
+
else {
|
|
1143
|
+
if (negated.length) positiveAfterNegation = true;
|
|
1144
|
+
positive.push(glob);
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
if (positiveAfterNegation) attention.push(`testMatch ${JSON.stringify(match.value)} — a positive glob after a negation re-includes what the negation removed; the negations are applied to all files here, so review the result.`);
|
|
1148
|
+
exclude.push(...negated);
|
|
1149
|
+
if (positive.length === 0 && negated.length > 0) {
|
|
1150
|
+
const exts = visibleExtensions(moduleFileExtensions);
|
|
1151
|
+
positive.push(exts.length === 1 ? `**/*.${exts[0]}` : `**/*.{${exts.join(",")}}`);
|
|
1152
|
+
attention.push(`testMatch has only negated globs, so Jest treated every file it crawls (${exts.join(", ")}) that they do not remove as a test; mapped the same way — review it.`);
|
|
1153
|
+
}
|
|
1154
|
+
const roots = (pick("roots").value ?? defaults.roots).map((r) => r.replace(/^<rootDir>\/?/, "").replace(/\/$/, ""));
|
|
1155
|
+
if (roots.every((r) => r === "")) include = positive;
|
|
1156
|
+
else {
|
|
1157
|
+
include = [...new Set(roots.flatMap((r) => positive.map((g) => r === "" ? g : g.startsWith("**/") ? `${r}/${g}` : g)))];
|
|
1158
|
+
automatic.push(`roots ${JSON.stringify(roots)} → test.include scoped to those directories.`);
|
|
1159
|
+
}
|
|
1160
|
+
automatic.push(`testMatch (${match.from}${match.value ? "" : defaultsNote}) → test.include ${JSON.stringify(include)}, so Jest's patterns, not Vitest's default include, decide which files are tests.`);
|
|
1161
|
+
}
|
|
1162
|
+
for (const key of ["testPathIgnorePatterns", "modulePathIgnorePatterns"]) {
|
|
1163
|
+
const fromOptions = options[key];
|
|
1164
|
+
const fromPreset = preset?.[key];
|
|
1165
|
+
const patterns = key === "modulePathIgnorePatterns" && fromOptions && fromPreset ? [...fromPreset, ...fromOptions] : fromOptions ?? fromPreset ?? defaults[key];
|
|
1166
|
+
const extra = key === "modulePathIgnorePatterns" ? " Jest also hid these paths from module resolution; Vite has no equivalent, which only matters if a test imported a module from one." : "";
|
|
1167
|
+
for (const pattern of patterns) {
|
|
1168
|
+
if (pattern === "/node_modules/") continue;
|
|
1169
|
+
const globs = ignorePatternToGlobs(pattern);
|
|
1170
|
+
if (globs) {
|
|
1171
|
+
exclude.push(...globs);
|
|
1172
|
+
automatic.push(`${key} '${pattern}' → test.exclude ${JSON.stringify(globs)}.${extra}`);
|
|
1173
|
+
} else attention.push(`${key} '${pattern}' — a regex with no exact glob form; add the equivalent test.exclude glob by hand (Jest skipped every test whose path matched it).${extra}`);
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
const hidden = extensionExclude(moduleFileExtensions);
|
|
1177
|
+
if (hidden) {
|
|
1178
|
+
exclude.push(hidden);
|
|
1179
|
+
automatic.push(`moduleFileExtensions (${extensions.from}) → test.exclude '${hidden}': Jest never sees files with other extensions, so they are not tests there.`);
|
|
1180
|
+
}
|
|
1181
|
+
return {
|
|
1182
|
+
include,
|
|
1183
|
+
exclude: [...new Set(exclude)],
|
|
1184
|
+
automatic,
|
|
1185
|
+
attention
|
|
1186
|
+
};
|
|
1187
|
+
}
|
|
1188
|
+
/** Jest CLI flags that take a value (https://jestjs.io/docs/cli). */
|
|
1189
|
+
const VALUED_FLAGS = /* @__PURE__ */ new Set([
|
|
1190
|
+
"testTimeout",
|
|
1191
|
+
"maxWorkers",
|
|
1192
|
+
"w",
|
|
1193
|
+
"config",
|
|
1194
|
+
"c",
|
|
1195
|
+
"testNamePattern",
|
|
1196
|
+
"t",
|
|
1197
|
+
"testPathPatterns",
|
|
1198
|
+
"testPathPattern",
|
|
1199
|
+
"testPathIgnorePatterns",
|
|
1200
|
+
"shard",
|
|
1201
|
+
"seed",
|
|
1202
|
+
"reporters",
|
|
1203
|
+
"outputFile",
|
|
1204
|
+
"rootDir",
|
|
1205
|
+
"roots",
|
|
1206
|
+
"selectProjects",
|
|
1207
|
+
"maxConcurrency",
|
|
1208
|
+
"testEnvironment",
|
|
1209
|
+
"env",
|
|
1210
|
+
"coverageDirectory",
|
|
1211
|
+
"collectCoverageFrom",
|
|
1212
|
+
"changedSince"
|
|
1213
|
+
]);
|
|
1214
|
+
/**
|
|
1215
|
+
* Split a shell command into commands of words. Quotes group and are removed
|
|
1216
|
+
* (`--flag="a b"` is the word `--flag=a b`), a backslash escapes outside single
|
|
1217
|
+
* quotes, and `&&`, `||`, `;` and `|` separate commands only outside quotes.
|
|
1218
|
+
*/
|
|
1219
|
+
function shellCommands(command) {
|
|
1220
|
+
const commands = [[]];
|
|
1221
|
+
let word = null;
|
|
1222
|
+
const end = () => {
|
|
1223
|
+
if (word !== null) commands[commands.length - 1].push(word);
|
|
1224
|
+
word = null;
|
|
1225
|
+
};
|
|
1226
|
+
for (let i = 0; i < command.length; i++) {
|
|
1227
|
+
const c = command[i];
|
|
1228
|
+
if (c === "'" || c === "\"") {
|
|
1229
|
+
const close = command.indexOf(c, i + 1);
|
|
1230
|
+
const stop = close === -1 ? command.length : close;
|
|
1231
|
+
let quoted = command.slice(i + 1, stop);
|
|
1232
|
+
if (c === "\"") quoted = quoted.replace(/\\(["\\$`])/g, "$1");
|
|
1233
|
+
word = (word ?? "") + quoted;
|
|
1234
|
+
i = stop;
|
|
1235
|
+
} else if (c === "\\") {
|
|
1236
|
+
word = (word ?? "") + (command[i + 1] ?? "");
|
|
1237
|
+
i++;
|
|
1238
|
+
} else if (/\s/.test(c)) end();
|
|
1239
|
+
else if (c === ";" || c === "|" || c === "&" && command[i + 1] === "&") {
|
|
1240
|
+
end();
|
|
1241
|
+
if (command[i + 1] === c) i++;
|
|
1242
|
+
commands.push([]);
|
|
1243
|
+
} else word = (word ?? "") + c;
|
|
1244
|
+
}
|
|
1245
|
+
end();
|
|
1246
|
+
return commands.filter((words) => words.length > 0);
|
|
1247
|
+
}
|
|
1248
|
+
/**
|
|
1249
|
+
* The Jest flags a package.json script passes, or null when it does not run Jest.
|
|
1250
|
+
* Only the command invoking `jest` (or its bin script) is read. Jest accepts
|
|
1251
|
+
* `--test-timeout` as well as `--testTimeout` (yargs), so names are camel-cased.
|
|
1252
|
+
*/
|
|
1253
|
+
function parseJestScript(script, command) {
|
|
1254
|
+
for (const tokens of shellCommands(command)) {
|
|
1255
|
+
const at = tokens.findIndex((t) => /(^|\/)jest(\.js)?$/.test(t));
|
|
1256
|
+
if (at === -1) continue;
|
|
1257
|
+
const flags = /* @__PURE__ */ new Map();
|
|
1258
|
+
const positional = [];
|
|
1259
|
+
const args = tokens.slice(at + 1);
|
|
1260
|
+
for (let i = 0; i < args.length; i++) {
|
|
1261
|
+
const token = args[i];
|
|
1262
|
+
if (!token.startsWith("-")) {
|
|
1263
|
+
positional.push(token);
|
|
1264
|
+
continue;
|
|
1265
|
+
}
|
|
1266
|
+
const [rawName, inline] = token.replace(/^--?/, "").split(/=(.*)/s, 2);
|
|
1267
|
+
const name = rawName.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
1268
|
+
if (inline !== void 0) flags.set(name, inline);
|
|
1269
|
+
else if (VALUED_FLAGS.has(name) && args[i + 1] !== void 0) flags.set(name, args[++i]);
|
|
1270
|
+
else if (name === "bail" && /^\d+$/.test(args[i + 1] ?? "")) flags.set(name, args[++i]);
|
|
1271
|
+
else flags.set(name, true);
|
|
1272
|
+
}
|
|
1273
|
+
return {
|
|
1274
|
+
script,
|
|
1275
|
+
flags,
|
|
1276
|
+
positional
|
|
1277
|
+
};
|
|
1278
|
+
}
|
|
1279
|
+
return null;
|
|
1280
|
+
}
|
|
1281
|
+
/** A boolean flag's value: bare or `=true` is true, `=false` false, else undefined. */
|
|
1282
|
+
function booleanFlag(value) {
|
|
1283
|
+
if (value === true || value === "true") return true;
|
|
1284
|
+
if (value === "false") return false;
|
|
1285
|
+
}
|
|
1286
|
+
//#endregion
|
|
1287
|
+
//#region src/cli/untranspiled.ts
|
|
1288
|
+
/**
|
|
1289
|
+
* Evidence that a package needs `transform`: a `.js` file under one of its entry
|
|
1290
|
+
* points that is not standard JavaScript (JSX or Flow), which neither Node nor Vite
|
|
1291
|
+
* loads from a `.js` file. Not evidence: ES-module syntax in `.js` and TypeScript
|
|
1292
|
+
* entries — Vitest inlines files that are not valid Node imports, and Vite compiles
|
|
1293
|
+
* both. Parsed with the project's @babel/parser and no syntax plugins; without the
|
|
1294
|
+
* parser there is no evidence and nothing is claimed.
|
|
1295
|
+
*/
|
|
1296
|
+
function babelParser(root) {
|
|
1297
|
+
const req = (0, node_module.createRequire)(node_path.default.join(root, "package.json"));
|
|
1298
|
+
for (const from of [() => req, () => (0, node_module.createRequire)(req.resolve("@babel/core"))]) try {
|
|
1299
|
+
return from()("@babel/parser").parse;
|
|
1300
|
+
} catch {}
|
|
1301
|
+
return null;
|
|
1302
|
+
}
|
|
1303
|
+
/** Directories in a package that are not part of what it runs. */
|
|
1304
|
+
const SKIP_DIRS = /* @__PURE__ */ new Set([
|
|
1305
|
+
"node_modules",
|
|
1306
|
+
"__tests__",
|
|
1307
|
+
"__mocks__",
|
|
1308
|
+
"test",
|
|
1309
|
+
"tests",
|
|
1310
|
+
"example",
|
|
1311
|
+
"examples",
|
|
1312
|
+
"docs"
|
|
1313
|
+
]);
|
|
1314
|
+
const MAX_FILES = 400;
|
|
1315
|
+
function packageDir(root, pkg) {
|
|
1316
|
+
for (let dir = node_path.default.resolve(root);; dir = node_path.default.dirname(dir)) {
|
|
1317
|
+
const candidate = node_path.default.join(dir, "node_modules", pkg);
|
|
1318
|
+
if (node_fs.default.existsSync(node_path.default.join(candidate, "package.json"))) return candidate;
|
|
1319
|
+
if (node_path.default.dirname(dir) === dir) return null;
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
/** Entry files a resolver may pick: `react-native`, `main`, `module` and `exports` strings. */
|
|
1323
|
+
function entryFiles(dir, manifest) {
|
|
1324
|
+
const targets = [];
|
|
1325
|
+
for (const field of [
|
|
1326
|
+
"react-native",
|
|
1327
|
+
"main",
|
|
1328
|
+
"module"
|
|
1329
|
+
]) if (typeof manifest[field] === "string") targets.push(manifest[field]);
|
|
1330
|
+
const walk = (node) => {
|
|
1331
|
+
if (typeof node === "string") targets.push(node);
|
|
1332
|
+
else if (node && typeof node === "object") Object.values(node).forEach(walk);
|
|
1333
|
+
};
|
|
1334
|
+
const exportsField = manifest.exports;
|
|
1335
|
+
walk(exportsField && typeof exportsField === "object" && "." in exportsField ? exportsField["."] : exportsField);
|
|
1336
|
+
if (targets.length === 0) targets.push("index.js");
|
|
1337
|
+
const files = /* @__PURE__ */ new Set();
|
|
1338
|
+
for (const target of targets) {
|
|
1339
|
+
const base = node_path.default.join(dir, target);
|
|
1340
|
+
for (const file of [
|
|
1341
|
+
base,
|
|
1342
|
+
`${base}.js`,
|
|
1343
|
+
node_path.default.join(base, "index.js")
|
|
1344
|
+
]) if (node_fs.default.existsSync(file) && node_fs.default.statSync(file).isFile()) {
|
|
1345
|
+
files.add(file);
|
|
1346
|
+
break;
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
return [...files];
|
|
1350
|
+
}
|
|
1351
|
+
/**
|
|
1352
|
+
* The first file under `pkg`'s entry points that Node cannot run as published, as a
|
|
1353
|
+
* path relative to the package, or null when none was found.
|
|
1354
|
+
*/
|
|
1355
|
+
function untranspiledFile(root, pkg) {
|
|
1356
|
+
const dir = packageDir(root, pkg);
|
|
1357
|
+
const manifest = installedManifest(root, pkg);
|
|
1358
|
+
if (!dir || !manifest) return null;
|
|
1359
|
+
const entries = entryFiles(dir, manifest);
|
|
1360
|
+
const parse = babelParser(root);
|
|
1361
|
+
if (!parse) return null;
|
|
1362
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1363
|
+
const queue = [...new Set(entries.map((e) => node_path.default.dirname(e)))];
|
|
1364
|
+
let budget = MAX_FILES;
|
|
1365
|
+
while (queue.length && budget > 0) {
|
|
1366
|
+
const current = queue.shift();
|
|
1367
|
+
let names;
|
|
1368
|
+
try {
|
|
1369
|
+
names = node_fs.default.readdirSync(current);
|
|
1370
|
+
} catch {
|
|
1371
|
+
continue;
|
|
1372
|
+
}
|
|
1373
|
+
for (const name of names.sort()) {
|
|
1374
|
+
const file = node_path.default.join(current, name);
|
|
1375
|
+
if (seen.has(file)) continue;
|
|
1376
|
+
seen.add(file);
|
|
1377
|
+
if (node_fs.default.statSync(file).isDirectory()) {
|
|
1378
|
+
if (!SKIP_DIRS.has(name)) queue.push(file);
|
|
1379
|
+
continue;
|
|
1380
|
+
}
|
|
1381
|
+
if (!/\.(js|cjs|mjs)$/.test(name) || budget-- <= 0) continue;
|
|
1382
|
+
try {
|
|
1383
|
+
parse(node_fs.default.readFileSync(file, "utf8"), {
|
|
1384
|
+
sourceType: "unambiguous",
|
|
1385
|
+
allowReturnOutsideFunction: true,
|
|
1386
|
+
allowAwaitOutsideFunction: true
|
|
1387
|
+
});
|
|
1388
|
+
} catch {
|
|
1389
|
+
return node_path.default.relative(dir, file).split(node_path.default.sep).join("/");
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
return null;
|
|
1394
|
+
}
|
|
1395
|
+
//#endregion
|
|
1396
|
+
//#region src/cli/migrate.ts
|
|
1397
|
+
/**
|
|
1398
|
+
* `vitest-native migrate` — analyze a project's Jest configuration and report,
|
|
1399
|
+
* key by key, what maps automatically, what the presets already cover (delete
|
|
1400
|
+
* it), and what needs a human. Dry-run by default; --write emits the suggested
|
|
1401
|
+
* Vitest config. It never edits test files: `jestMockTransform()` handles
|
|
1402
|
+
* top-level `jest.mock` at runtime, so file codemods aren't required to start.
|
|
1403
|
+
*
|
|
1404
|
+
* The target is Jest's EFFECTIVE configuration — the config file, the preset under
|
|
1405
|
+
* it, Jest's defaults under that, and the flags the `test` script passes on top —
|
|
1406
|
+
* so that a migrated project collects the same test files with the same settings
|
|
1407
|
+
* without hand edits.
|
|
1408
|
+
*/
|
|
1409
|
+
function loadConfigFile(root, file) {
|
|
1410
|
+
const abs = node_path.default.resolve(root, file);
|
|
1411
|
+
const name = node_path.default.relative(root, abs).split(node_path.default.sep).join("/") || file;
|
|
1412
|
+
if (!node_fs.default.existsSync(abs)) return null;
|
|
1413
|
+
if (!/\.(c?js|json)$/.test(abs)) return {
|
|
1414
|
+
source: name,
|
|
1415
|
+
config: null
|
|
1416
|
+
};
|
|
1417
|
+
try {
|
|
1418
|
+
const req = (0, node_module.createRequire)(node_path.default.join(root, "package.json"));
|
|
1419
|
+
const loaded = abs.endsWith(".json") ? JSON.parse(node_fs.default.readFileSync(abs, "utf8")) : req(abs);
|
|
1420
|
+
const config = loaded && typeof loaded === "object" && "default" in loaded ? loaded.default : loaded;
|
|
1421
|
+
if (typeof config === "function") return {
|
|
1422
|
+
source: name,
|
|
1423
|
+
config: null
|
|
1424
|
+
};
|
|
1425
|
+
return {
|
|
1426
|
+
source: name,
|
|
1427
|
+
config
|
|
1428
|
+
};
|
|
1429
|
+
} catch {
|
|
1430
|
+
return {
|
|
1431
|
+
source: name,
|
|
1432
|
+
config: null
|
|
1433
|
+
};
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
function loadJestConfig(root, explicit) {
|
|
1437
|
+
if (explicit) {
|
|
1438
|
+
const loaded = loadConfigFile(root, explicit);
|
|
1439
|
+
if (loaded) return loaded;
|
|
1440
|
+
}
|
|
363
1441
|
for (const name of [
|
|
364
1442
|
"jest.config.js",
|
|
365
1443
|
"jest.config.cjs",
|
|
366
1444
|
"jest.config.json"
|
|
367
1445
|
]) {
|
|
368
|
-
const
|
|
369
|
-
if (
|
|
370
|
-
try {
|
|
371
|
-
const loaded = name.endsWith(".json") ? JSON.parse(node_fs.default.readFileSync(file, "utf8")) : req(file);
|
|
372
|
-
const config = loaded && typeof loaded === "object" && "default" in loaded ? loaded.default : loaded;
|
|
373
|
-
if (typeof config === "function") return {
|
|
374
|
-
source: name,
|
|
375
|
-
config: null
|
|
376
|
-
};
|
|
377
|
-
return {
|
|
378
|
-
source: name,
|
|
379
|
-
config
|
|
380
|
-
};
|
|
381
|
-
} catch {
|
|
382
|
-
return {
|
|
383
|
-
source: name,
|
|
384
|
-
config: null
|
|
385
|
-
};
|
|
386
|
-
}
|
|
1446
|
+
const loaded = loadConfigFile(root, name);
|
|
1447
|
+
if (loaded) return loaded;
|
|
387
1448
|
}
|
|
388
1449
|
for (const name of [
|
|
389
1450
|
"jest.config.mjs",
|
|
@@ -405,19 +1466,122 @@ function loadJestConfig(root) {
|
|
|
405
1466
|
config: null
|
|
406
1467
|
};
|
|
407
1468
|
}
|
|
1469
|
+
function declaredDependencies(root) {
|
|
1470
|
+
try {
|
|
1471
|
+
const pkg = JSON.parse(node_fs.default.readFileSync(node_path.default.join(root, "package.json"), "utf8"));
|
|
1472
|
+
return [...new Set([
|
|
1473
|
+
"dependencies",
|
|
1474
|
+
"devDependencies",
|
|
1475
|
+
"optionalDependencies"
|
|
1476
|
+
].flatMap((field) => pkg[field] && typeof pkg[field] === "object" ? Object.keys(pkg[field]) : []))];
|
|
1477
|
+
} catch {
|
|
1478
|
+
return [];
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
/** `a, b and c` — for the lists the report prints. */
|
|
1482
|
+
function list(items) {
|
|
1483
|
+
return items.length <= 1 ? items[0] ?? "" : `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
|
|
1484
|
+
}
|
|
1485
|
+
/**
|
|
1486
|
+
* How Expo modules run after migrating. The generated config uses the native engine,
|
|
1487
|
+
* where Expo modules run their own JavaScript on native-module mocks, as jest-expo
|
|
1488
|
+
* runs them; the expo preset applies to the mock engine only (preset-map's
|
|
1489
|
+
* NATIVE_ENGINE_RUNS_PACKAGES).
|
|
1490
|
+
*/
|
|
1491
|
+
function expoPresetCoverage() {
|
|
1492
|
+
return "under the native engine, which the suggested config resolves to wherever React Native's Babel toolchain is installed, Expo modules run their own JavaScript on native-module mocks, as jest-expo runs them: each package's own mocks/ where it ships one, else jest-expo's table of the native modules; check tests that mock an Expo module's native side by hand";
|
|
1493
|
+
}
|
|
1494
|
+
/** Escape a literal for a JavaScript regex literal (including `/`). */
|
|
1495
|
+
function regexLiteral(literal) {
|
|
1496
|
+
return `/^${literal.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}$/`;
|
|
1497
|
+
}
|
|
1498
|
+
/**
|
|
1499
|
+
* The literal a `^literal$` moduleNameMapper key matches exactly, or null. An
|
|
1500
|
+
* unescaped `.` reads as a literal dot: the regex's extra matches (`lodashXdebounce`)
|
|
1501
|
+
* are not specifiers anyone imports.
|
|
1502
|
+
*/
|
|
1503
|
+
function exactMapperKey(pattern) {
|
|
1504
|
+
const m = /^\^(.+)\$$/.exec(pattern);
|
|
1505
|
+
const expansions = m ? tryExpand(m[1], true) : null;
|
|
1506
|
+
return expansions?.length === 1 && !expansions[0].includes("\0") ? expansions[0] : null;
|
|
1507
|
+
}
|
|
1508
|
+
/** `pkg` and `/sub` of a bare specifier (scope-aware). */
|
|
1509
|
+
function splitSpecifier(specifier) {
|
|
1510
|
+
const parts = specifier.split("/");
|
|
1511
|
+
const pkg = specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
|
|
1512
|
+
return {
|
|
1513
|
+
pkg,
|
|
1514
|
+
subpath: specifier.slice(pkg.length)
|
|
1515
|
+
};
|
|
1516
|
+
}
|
|
1517
|
+
/** The package a node_modules path belongs to (after the LAST node_modules/), or null. */
|
|
1518
|
+
function packageOfPath(target) {
|
|
1519
|
+
const at = target.lastIndexOf("node_modules/");
|
|
1520
|
+
return at === -1 ? null : splitSpecifier(target.slice(at + 13)).pkg;
|
|
1521
|
+
}
|
|
1522
|
+
/**
|
|
1523
|
+
* Whether a package's own `exports` (or main entry, for a bare name) serves
|
|
1524
|
+
* `specifier`, so Vite and Node resolve it without help (with the `import` condition
|
|
1525
|
+
* Jest's CommonJS resolver lacked).
|
|
1526
|
+
*/
|
|
1527
|
+
function packageServes(root, specifier) {
|
|
1528
|
+
const { pkg, subpath } = splitSpecifier(specifier);
|
|
1529
|
+
const manifest = installedManifest(root, pkg);
|
|
1530
|
+
if (!manifest) return false;
|
|
1531
|
+
const exportsField = manifest.exports;
|
|
1532
|
+
if (exportsField === void 0) return subpath === "" && (manifest.main !== void 0 || manifest.module !== void 0);
|
|
1533
|
+
const key = `.${subpath}`;
|
|
1534
|
+
if (typeof exportsField === "string" || Array.isArray(exportsField)) return key === ".";
|
|
1535
|
+
if (exportsField && typeof exportsField === "object") {
|
|
1536
|
+
if (Object.keys(exportsField).every((k) => !k.startsWith("."))) return key === ".";
|
|
1537
|
+
return key in exportsField;
|
|
1538
|
+
}
|
|
1539
|
+
return false;
|
|
1540
|
+
}
|
|
408
1541
|
function analyzeJestConfig(root) {
|
|
409
|
-
|
|
1542
|
+
let scriptFlags = null;
|
|
1543
|
+
const otherJestScripts = [];
|
|
1544
|
+
try {
|
|
1545
|
+
const scripts = JSON.parse(node_fs.default.readFileSync(node_path.default.join(root, "package.json"), "utf8")).scripts ?? {};
|
|
1546
|
+
for (const [name, command] of Object.entries(scripts)) {
|
|
1547
|
+
if (typeof command !== "string") continue;
|
|
1548
|
+
const parsed = parseJestScript(name, command);
|
|
1549
|
+
if (!parsed) continue;
|
|
1550
|
+
if (name === "test") scriptFlags = parsed;
|
|
1551
|
+
else otherJestScripts.push(name);
|
|
1552
|
+
}
|
|
1553
|
+
} catch {}
|
|
1554
|
+
const explicitConfig = scriptFlags?.flags.get("config") ?? scriptFlags?.flags.get("c");
|
|
1555
|
+
const { source, config } = loadJestConfig(root, typeof explicitConfig === "string" ? explicitConfig : void 0);
|
|
410
1556
|
const automatic = [];
|
|
411
1557
|
const attention = [];
|
|
412
1558
|
const presetCovered = [];
|
|
413
1559
|
const dropped = [];
|
|
414
1560
|
const testEntries = [`globals: true`, `environment: 'node'`];
|
|
415
1561
|
const setupFiles = ["jestCompatSetup"];
|
|
416
|
-
const aliasEntries = [
|
|
1562
|
+
const aliasEntries = [];
|
|
1563
|
+
const aliasKeys = /* @__PURE__ */ new Set();
|
|
1564
|
+
const regexAliases = [];
|
|
417
1565
|
const transformPkgs = [];
|
|
418
|
-
const
|
|
1566
|
+
const extraImports = [];
|
|
1567
|
+
const extraPlugins = [];
|
|
1568
|
+
let excludeGlobs = [];
|
|
419
1569
|
let needsUrlImport = false;
|
|
420
|
-
const
|
|
1570
|
+
const pluginOptions = [];
|
|
1571
|
+
const jestPreset = typeof config?.preset === "string" ? config.preset : void 0;
|
|
1572
|
+
const navigationOff = /^jest-expo(\/(ios|android|universal))?$/.test(jestPreset ?? "") && activePresets(root).includes("navigation") && !node_fs.default.existsSync(node_path.default.join(root, "__mocks__", "@react-navigation"));
|
|
1573
|
+
const active = activePresets(root, navigationOff ? ["navigation"] : []);
|
|
1574
|
+
const autoInlined = new Set(require_host.detectEcosystemPackages(root, [], [], [], active));
|
|
1575
|
+
const addAlias = (key, value) => {
|
|
1576
|
+
if (aliasKeys.has(key)) return false;
|
|
1577
|
+
aliasKeys.add(key);
|
|
1578
|
+
aliasEntries.push(`${JSON.stringify(key)}: ${value}`);
|
|
1579
|
+
return true;
|
|
1580
|
+
};
|
|
1581
|
+
const absolutePath = (relative) => {
|
|
1582
|
+
needsUrlImport = true;
|
|
1583
|
+
return `fileURLToPath(new URL(${JSON.stringify(relative)}, import.meta.url))`;
|
|
1584
|
+
};
|
|
421
1585
|
if (config) {
|
|
422
1586
|
const handled = /* @__PURE__ */ new Set();
|
|
423
1587
|
const take = (key) => {
|
|
@@ -426,65 +1590,153 @@ function analyzeJestConfig(root) {
|
|
|
426
1590
|
};
|
|
427
1591
|
const preset = take("preset");
|
|
428
1592
|
if (preset === "react-native" || preset === "@react-native/jest-preset") automatic.push(`preset: '${preset}' → replaced by the reactNative() plugin.`);
|
|
429
|
-
else if (preset === "jest-expo"
|
|
1593
|
+
else if (preset === "jest-expo" || preset === "jest-expo/ios" || preset === "jest-expo/android") {
|
|
1594
|
+
const android = preset === "jest-expo/android";
|
|
1595
|
+
if (android) pluginOptions.push(`platform: 'android'`);
|
|
1596
|
+
automatic.push(`preset: '${preset}' → replaced by the reactNative() plugin${android ? " with platform: 'android'" : ""}.`);
|
|
1597
|
+
attention.push(`preset: '${preset}' — ${expoPresetCoverage()}.`);
|
|
1598
|
+
} else if (preset === "jest-expo/universal") attention.push("preset: 'jest-expo/universal' runs one Jest project per platform. Define a Vitest project for each native platform (reactNative({ platform: 'ios' }) and reactNative({ platform: 'android' })); its web and node projects are not React Native renders and stay outside vitest-native.");
|
|
1599
|
+
else if (preset === "jest-expo/web" || preset === "jest-expo/node") attention.push(`preset: '${preset}' targets ${preset.slice(10)}, not a React Native render; run these suites without vitest-native.`);
|
|
430
1600
|
else if (preset) attention.push(`preset: '${preset}' — unknown preset; review what it configured.`);
|
|
1601
|
+
let presetConfig = null;
|
|
1602
|
+
if (preset) {
|
|
1603
|
+
const loaded = loadJestPreset(root, preset);
|
|
1604
|
+
if ("config" in loaded) presetConfig = loaded.config;
|
|
1605
|
+
else attention.push(`preset: '${preset}' could not be loaded (${loaded.error}), so its testMatch/testPathIgnorePatterns could not be read; test.include falls back to Jest's defaults — compare with the preset.`);
|
|
1606
|
+
}
|
|
431
1607
|
for (const key of ["setupFiles", "setupFilesAfterEnv"]) {
|
|
432
1608
|
const files = take(key);
|
|
433
1609
|
if (!files?.length) continue;
|
|
434
|
-
for (const f of files)
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
1610
|
+
for (const f of files) {
|
|
1611
|
+
const setupPackage = /^(@[^/]+\/[^/]+|[^@./][^/]*)\//.exec(f)?.[1];
|
|
1612
|
+
const setupPreset = setupPackage ? require_preset_map.presetShadowing(setupPackage) : void 0;
|
|
1613
|
+
if (/react-native\/jest\/setup/.test(f)) presetCovered.push(`${key}: '${f}' — the plugin injects its own setup; delete.`);
|
|
1614
|
+
else if (setupPreset && active.includes(setupPreset)) presetCovered.push(`${key}: '${f}' — ${setupPackage}'s own test setup; the auto-detected ${setupPreset} preset shadows ${setupPackage}, and this file's jest.mock() calls would replace it; delete.`);
|
|
1615
|
+
else if (/jest-expo/.test(f)) attention.push(`${key}: '${f}' — ${expoPresetCoverage()}.`);
|
|
1616
|
+
else if (f.startsWith("<rootDir>")) {
|
|
1617
|
+
setupFiles.push(absolutePath(f.replace(/^<rootDir>\/?/, "./")));
|
|
1618
|
+
automatic.push(`${key}: '${f}' → test.setupFiles (its jest.* calls run under the jest-compat shim).`);
|
|
1619
|
+
} else {
|
|
1620
|
+
setupFiles.push(JSON.stringify(f));
|
|
1621
|
+
automatic.push(`${key}: '${f}' → test.setupFiles (its jest.* calls run under the jest-compat shim).`);
|
|
1622
|
+
}
|
|
442
1623
|
}
|
|
443
1624
|
}
|
|
444
1625
|
const mapper = take("moduleNameMapper");
|
|
445
|
-
if (mapper) for (const [pattern, target] of Object.entries(mapper))
|
|
446
|
-
|
|
447
|
-
const
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
1626
|
+
if (mapper) for (const [pattern, target] of Object.entries(mapper)) {
|
|
1627
|
+
const assetGroup = /\\\.\(\??:?([a-z0-9|]+)\)\$?$/i.exec(pattern);
|
|
1628
|
+
const literal = exactMapperKey(pattern);
|
|
1629
|
+
if (assetGroup) {
|
|
1630
|
+
const exts = assetGroup[1].toLowerCase().split("|");
|
|
1631
|
+
const missing = exts.filter((e) => !require_preset_map.DEFAULT_ASSET_EXTS.includes(e));
|
|
1632
|
+
if (missing.length === 0) presetCovered.push(`moduleNameMapper '${pattern}' — the plugin handles ${list(exts)} imports itself; delete.`);
|
|
1633
|
+
else {
|
|
1634
|
+
pluginOptions.push(`assetExts: ${JSON.stringify(missing)}`);
|
|
1635
|
+
automatic.push(`moduleNameMapper '${pattern}' — ${list(missing)} ${missing.length === 1 ? "is" : "are"} not among the extensions the plugin handles by default → reactNative({ assetExts: ${JSON.stringify(missing)} }).`);
|
|
1636
|
+
}
|
|
1637
|
+
} else if (/^\^?@\/|\^~\/|\^src\//.test(pattern)) {
|
|
1638
|
+
const aliasKey = pattern.replace(/[\^$]/g, "").replace(/\((\.\*|\.\+)\)\$?$/, "").replace(/\/$/, "");
|
|
1639
|
+
const aliasTarget = String(target).replace(/^<rootDir>\/?/, "./").replace(/\/\$1$/, "").replace(/\/$/, "");
|
|
1640
|
+
if (/[(){}?+*\\[\]]/.test(aliasKey) || /[(){}?+*\\[\]$]/.test(aliasTarget)) attention.push(`moduleNameMapper '${pattern}' → '${String(target)}' — map manually to resolve.alias (regex mappers need rewriting).`);
|
|
1641
|
+
else {
|
|
1642
|
+
addAlias(aliasKey, absolutePath(aliasTarget));
|
|
1643
|
+
automatic.push(`moduleNameMapper '${pattern}' → resolve.alias (absolute path).`);
|
|
1644
|
+
}
|
|
1645
|
+
} else if (literal !== null && typeof target === "string" && !target.includes("$")) {
|
|
1646
|
+
if (packageOfPath(target) === splitSpecifier(literal).pkg && packageServes(root, literal)) dropped.push(`moduleNameMapper '${pattern}' → '${target}' — '${literal}' is served by its package's exports, which Vite and Node resolve (Jest's CommonJS resolver could not); dropped.`);
|
|
1647
|
+
else {
|
|
1648
|
+
const replacement = target.startsWith("<rootDir>") ? absolutePath(target.replace(/^<rootDir>\/?/, "./")) : target.startsWith(".") ? absolutePath(target) : JSON.stringify(target);
|
|
1649
|
+
regexAliases.push(`{ find: ${regexLiteral(literal)}, replacement: ${replacement} }`);
|
|
1650
|
+
automatic.push(`moduleNameMapper '${pattern}' → resolve.alias { find: ${regexLiteral(literal)} } (anchored: a string find would also catch '${literal}/…').`);
|
|
1651
|
+
}
|
|
1652
|
+
} else attention.push(`moduleNameMapper '${pattern}' → '${String(target)}' — map manually to resolve.alias (regex mappers need rewriting).`);
|
|
1653
|
+
}
|
|
456
1654
|
const tip = take("transformIgnorePatterns");
|
|
457
1655
|
if (tip?.length) {
|
|
458
1656
|
const results = tip.map(extractAllowlistPackages);
|
|
459
|
-
const
|
|
1657
|
+
const entries = results.flatMap((r) => r.entries);
|
|
460
1658
|
const unparseable = results.flatMap((r) => r.unparseable);
|
|
461
1659
|
automatic.push(`transformIgnorePatterns (raw): ${JSON.stringify(tip)}`);
|
|
462
1660
|
for (const entry of unparseable) attention.push(`transformIgnorePatterns entry '${entry}' — could not extract package names confidently; expand it by hand into reactNative({ transform: [...] }) if those packages ship untranspiled source.`);
|
|
463
|
-
if (
|
|
464
|
-
else
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
automatic.push(`transformIgnorePatterns allows '${pkg}' → reactNative({ transform: [...] }).`);
|
|
470
|
-
}
|
|
1661
|
+
if (entries.length === 0 && unparseable.length === 0) attention.push(`transformIgnorePatterns: ${JSON.stringify(tip)} — could not extract an allowlist automatically; packages shipping untranspiled source go in reactNative({ transform: [...] }).`);
|
|
1662
|
+
else classifyAllowlist(root, entries, active, autoInlined, {
|
|
1663
|
+
automatic,
|
|
1664
|
+
presetCovered,
|
|
1665
|
+
transformPkgs
|
|
1666
|
+
});
|
|
471
1667
|
}
|
|
472
|
-
const
|
|
1668
|
+
const flag = (...names) => {
|
|
1669
|
+
for (const n of names) {
|
|
1670
|
+
const v = scriptFlags?.flags.get(n);
|
|
1671
|
+
if (v !== void 0) return v;
|
|
1672
|
+
}
|
|
1673
|
+
};
|
|
1674
|
+
const configTimeout = take("testTimeout");
|
|
1675
|
+
const flagTimeout = flag("testTimeout");
|
|
1676
|
+
const timeout = typeof flagTimeout === "string" && /^\d+$/.test(flagTimeout) ? Number(flagTimeout) : configTimeout;
|
|
473
1677
|
if (typeof timeout === "number") {
|
|
474
1678
|
testEntries.push(`testTimeout: ${timeout}`);
|
|
475
|
-
automatic.push(`testTimeout: ${timeout} → test.testTimeout.`);
|
|
1679
|
+
automatic.push(flagTimeout !== void 0 ? `scripts.test --testTimeout=${timeout} → test.testTimeout (Jest's CLI flag overrides the config).` : `testTimeout: ${timeout} → test.testTimeout.`);
|
|
1680
|
+
}
|
|
1681
|
+
const workers = flag("maxWorkers", "w") ?? take("maxWorkers");
|
|
1682
|
+
handled.add("maxWorkers");
|
|
1683
|
+
if (workers !== void 0 && workers !== true) {
|
|
1684
|
+
const value = /^\d+$/.test(String(workers)) ? Number(workers) : JSON.stringify(String(workers));
|
|
1685
|
+
testEntries.push(`maxWorkers: ${value}`);
|
|
1686
|
+
automatic.push(`maxWorkers ${workers} → test.maxWorkers (a count or a percentage, as in Jest).`);
|
|
1687
|
+
}
|
|
1688
|
+
if (booleanFlag(flag("runInBand", "i")) === true) {
|
|
1689
|
+
testEntries.push(`fileParallelism: false`);
|
|
1690
|
+
automatic.push(`scripts.test --runInBand → test.fileParallelism: false (one file at a time).`);
|
|
1691
|
+
}
|
|
1692
|
+
const bail = flag("bail") ?? take("bail");
|
|
1693
|
+
if (bail !== void 0 && bail !== false) attention.push("bail — Jest stops after N failed test SUITES; Vitest's test.bail counts failed TESTS, so it is not mapped. Add test.bail yourself if early exit matters.");
|
|
1694
|
+
for (const [name, value] of scriptFlags?.flags ?? []) {
|
|
1695
|
+
if ([
|
|
1696
|
+
"testTimeout",
|
|
1697
|
+
"maxWorkers",
|
|
1698
|
+
"w",
|
|
1699
|
+
"runInBand",
|
|
1700
|
+
"i",
|
|
1701
|
+
"bail",
|
|
1702
|
+
"config",
|
|
1703
|
+
"c"
|
|
1704
|
+
].includes(name)) continue;
|
|
1705
|
+
if (name === "forceExit") dropped.push("scripts.test --forceExit — `vitest run` exits by itself: if something keeps the process alive after the run it waits test.teardownTimeout, warns, and exits.");
|
|
1706
|
+
else if (name === "ci") dropped.push("scripts.test --ci — Vitest writes no new snapshots when it detects CI, as Jest's --ci defaults to; set CI=true to get that elsewhere.");
|
|
1707
|
+
else if ((name === "silent" || name === "passWithNoTests") && booleanFlag(value) !== void 0) {
|
|
1708
|
+
const on = booleanFlag(value);
|
|
1709
|
+
testEntries.push(`${name}: ${on}`);
|
|
1710
|
+
automatic.push(`scripts.test --${name}=${on} → test.${name}: ${on} (same meaning in Vitest).`);
|
|
1711
|
+
} else attention.push(`scripts.test passes --${name}${value === true ? "" : `=${value}`} to Jest — no automatic mapping; pass the Vitest equivalent on the vitest command line if it still matters.`);
|
|
476
1712
|
}
|
|
1713
|
+
if (scriptFlags?.positional.length) attention.push(`scripts.test passes test path patterns ${JSON.stringify(scriptFlags.positional)} — pass them to \`vitest run\` as filters.`);
|
|
1714
|
+
if (scriptFlags) {
|
|
1715
|
+
const mapped = scriptFlags.flags.size > 0 ? " (its flags are mapped above)" : "";
|
|
1716
|
+
attention.push(`scripts.test runs Jest — point it at \`vitest run\` once the suite passes${mapped}.`);
|
|
1717
|
+
}
|
|
1718
|
+
if (otherJestScripts.length) attention.push(`${otherJestScripts.length === 1 ? "script" : "scripts"} ${list(otherJestScripts)} also ${otherJestScripts.length === 1 ? "runs" : "run"} Jest; only scripts.test was read for flags.`);
|
|
477
1719
|
const env = take("testEnvironment");
|
|
478
1720
|
if (env && env !== "node") attention.push(`testEnvironment: '${env}' — vitest-native suites run under 'node'; review.`);
|
|
479
1721
|
else handled.add("testEnvironment");
|
|
480
|
-
if (take("fakeTimers") !== void 0) attention.push(`fakeTimers —
|
|
481
|
-
const
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
1722
|
+
if (take("fakeTimers") !== void 0) attention.push(`fakeTimers — not carried over: call jest.useFakeTimers(options) in a beforeEach, which the jest-compat shim translates, or set Vitest's test.fakeTimers. Not at a setup file's top level: RNTL's import drops options set there.`);
|
|
1723
|
+
const discoveryOptions = {};
|
|
1724
|
+
for (const key of [
|
|
1725
|
+
"testMatch",
|
|
1726
|
+
"testRegex",
|
|
1727
|
+
"testPathIgnorePatterns",
|
|
1728
|
+
"modulePathIgnorePatterns",
|
|
1729
|
+
"moduleFileExtensions",
|
|
1730
|
+
"roots"
|
|
1731
|
+
]) {
|
|
1732
|
+
const value = take(key);
|
|
1733
|
+
if (value !== void 0) discoveryOptions[key] = value;
|
|
1734
|
+
}
|
|
1735
|
+
const discovery = translateDiscovery(discoveryOptions, presetConfig, jestMajor(root));
|
|
1736
|
+
if (discovery.include) testEntries.push(`include: [${discovery.include.map((g) => JSON.stringify(g)).join(", ")}]`);
|
|
1737
|
+
excludeGlobs = discovery.exclude;
|
|
1738
|
+
automatic.push(...discovery.automatic);
|
|
1739
|
+
attention.push(...discovery.attention);
|
|
488
1740
|
const coverageFrom = take("collectCoverageFrom");
|
|
489
1741
|
if (coverageFrom?.length) {
|
|
490
1742
|
testEntries.push(`coverage: { include: [${coverageFrom.map((g) => JSON.stringify(g.replace(/^<rootDir>\//, ""))).join(", ")}] }`);
|
|
@@ -494,8 +1746,6 @@ function analyzeJestConfig(root) {
|
|
|
494
1746
|
take("coverageThreshold");
|
|
495
1747
|
if (config.coveragePathIgnorePatterns || config.coverageThreshold) attention.push(`coverage settings — map onto test.coverage.{exclude,thresholds}.`);
|
|
496
1748
|
for (const key of [
|
|
497
|
-
"moduleFileExtensions",
|
|
498
|
-
"maxWorkers",
|
|
499
1749
|
"verbose",
|
|
500
1750
|
"clearMocks",
|
|
501
1751
|
"resetMocks",
|
|
@@ -508,47 +1758,91 @@ function analyzeJestConfig(root) {
|
|
|
508
1758
|
"watchPlugins",
|
|
509
1759
|
"transform",
|
|
510
1760
|
"globals",
|
|
511
|
-
"roots",
|
|
512
|
-
"testRegex",
|
|
513
1761
|
"snapshotSerializers",
|
|
514
|
-
"reporters"
|
|
515
|
-
"modulePathIgnorePatterns"
|
|
1762
|
+
"reporters"
|
|
516
1763
|
]) if (config[key] !== void 0) {
|
|
517
1764
|
handled.add(key);
|
|
518
1765
|
if (key === "transform") dropped.push(`transform — Babel/esbuild transforms are the plugin's job; dropped.`);
|
|
519
1766
|
else if (key === "clearMocks" || key === "resetMocks" || key === "restoreMocks") {
|
|
520
|
-
|
|
521
|
-
|
|
1767
|
+
const vitestKey = key === "resetMocks" ? "mockReset" : key;
|
|
1768
|
+
automatic.push(key === vitestKey ? `${key} → test.${key} (same name in Vitest).` : `${key} → test.${vitestKey} (Vitest's name for it).`);
|
|
1769
|
+
testEntries.push(`${vitestKey}: ${JSON.stringify(config[key])}`);
|
|
522
1770
|
} else if (key === "snapshotSerializers") attention.push(`snapshotSerializers — Vitest uses expect.addSnapshotSerializer; vitest-native ships one for RN trees.`);
|
|
523
1771
|
else dropped.push(`${key} — no vitest-native equivalent needed; dropped.`);
|
|
524
1772
|
}
|
|
1773
|
+
if (config.clearMocks === void 0) {
|
|
1774
|
+
testEntries.push(`clearMocks: false`);
|
|
1775
|
+
automatic.push("Jest keeps mock calls between tests unless clearMocks is set → test.clearMocks: false (Vitest 5 clears them before each test by default).");
|
|
1776
|
+
}
|
|
525
1777
|
for (const key of Object.keys(config)) if (!handled.has(key)) attention.push(`'${key}' — unrecognized Jest key; review manually.`);
|
|
526
1778
|
}
|
|
527
1779
|
const mocksDir = node_path.default.join(root, "__mocks__");
|
|
528
1780
|
if (node_fs.default.existsSync(mocksDir)) for (const entry of node_fs.default.readdirSync(mocksDir)) {
|
|
529
1781
|
const name = entry.replace(/\.(js|cjs|mjs|ts|tsx)$/, "");
|
|
530
1782
|
const candidates = node_fs.default.statSync(node_path.default.join(mocksDir, entry)).isDirectory() ? node_fs.default.readdirSync(node_path.default.join(mocksDir, entry)).map((f) => `${name}/${f.replace(/\.(js|cjs|mjs|ts|tsx)$/, "")}`) : [name];
|
|
531
|
-
for (const candidate of candidates)
|
|
532
|
-
const preset = require_preset_map.
|
|
533
|
-
presetCovered.push(`__mocks__/${candidate} — the ${preset} preset
|
|
1783
|
+
for (const candidate of candidates) {
|
|
1784
|
+
const preset = require_preset_map.presetShadowing(candidate);
|
|
1785
|
+
if (preset && active.includes(preset)) presetCovered.push(`__mocks__/${candidate} — the auto-detected ${preset} preset shadows ${candidate}; delete the manual mock.`);
|
|
1786
|
+
else if (installedManifest(root, candidate) && installedTestsItself(root, candidate)) attention.push(`__mocks__/${candidate} — ${candidate} ${installedMajor(root, candidate)} runs its own test mode under Vitest, so no preset replaces it, and Vitest applies a root __mocks__ file only through vi.mock; the library's test mode stands in for this mock.`);
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
if (navigationOff) {
|
|
1790
|
+
pluginOptions.push(`presets: { navigation: false }`);
|
|
1791
|
+
automatic.push("jest-expo renders the real React Navigation → presets: { navigation: false }, so screens keep running in real navigators.");
|
|
1792
|
+
}
|
|
1793
|
+
const babel = readBabelConfig(root);
|
|
1794
|
+
if (babel.source) {
|
|
1795
|
+
const classified = classifyBabelPlugins(babel, root, active);
|
|
1796
|
+
const required = classified.filter((p) => p.verdict === "required");
|
|
1797
|
+
const vite = viteMajor(root);
|
|
1798
|
+
if (required.length) {
|
|
1799
|
+
if (vite !== null && vite >= 8 && installed(root, "@rolldown/plugin-babel") && installed(root, "@babel/core") && required.every(serializableOptions)) {
|
|
1800
|
+
extraImports.push(`import babel from '@rolldown/plugin-babel'`);
|
|
1801
|
+
extraPlugins.push(`babel({ plugins: ${pluginListSource(required)} })`);
|
|
1802
|
+
for (const p of required) automatic.push(`${babel.source}: ${p.reason} → babel() from @rolldown/plugin-babel.`);
|
|
1803
|
+
} else for (const p of required) attention.push(`${babel.source}: ${p.reason} Required: ${babelRecipe(vite, required)}.`);
|
|
1804
|
+
}
|
|
1805
|
+
for (const p of classified.filter((c) => c.verdict === "alias")) {
|
|
1806
|
+
const options = p.options ?? {};
|
|
1807
|
+
for (const [key, value] of Object.entries(options.alias ?? {})) {
|
|
1808
|
+
if (key.startsWith("^") || typeof value !== "string" || options.cwd !== void 0) {
|
|
1809
|
+
attention.push(`${babel.source}: module-resolver alias '${key}' → ${JSON.stringify(value)} — not a plain path alias; map it to resolve.alias by hand.`);
|
|
1810
|
+
continue;
|
|
1811
|
+
}
|
|
1812
|
+
if (addAlias(key, value.startsWith(".") ? absolutePath(value) : JSON.stringify(value))) automatic.push(`${babel.source}: module-resolver alias '${key}' → resolve.alias.`);
|
|
1813
|
+
}
|
|
1814
|
+
if (options.root !== void 0) attention.push(`${babel.source}: module-resolver root ${JSON.stringify(options.root)} — bare imports resolved from those directories need resolve.alias entries by hand.`);
|
|
534
1815
|
}
|
|
1816
|
+
for (const p of classified.filter((c) => c.verdict === "unneeded")) dropped.push(`${babel.source}: ${p.written} — ${p.reason}`);
|
|
1817
|
+
for (const p of classified.filter((c) => c.verdict === "unknown")) attention.push(`${babel.source}: ${p.reason}`);
|
|
1818
|
+
if (!babel.evaluated) attention.push(`${babel.source} could not be evaluated, so only plugins recognized by name are listed; review it for others.`);
|
|
535
1819
|
}
|
|
536
|
-
|
|
1820
|
+
if (transformPkgs.length) pluginOptions.unshift(`transform: [${transformPkgs.map((p) => JSON.stringify(p)).join(", ")}]`);
|
|
1821
|
+
const transformLine = pluginOptions.length ? `reactNative({ ${pluginOptions.join(", ")} })` : `reactNative()`;
|
|
1822
|
+
if (excludeGlobs.length) testEntries.push(`exclude: [...configDefaults.exclude, ${excludeGlobs.map((g) => JSON.stringify(g)).join(", ")}]`);
|
|
1823
|
+
const aliasSource = regexAliases.length ? `[\n ...Object.entries(jestCompatAliases()).map(([find, replacement]) => ({ find, replacement })),\n` + aliasEntries.map((e) => {
|
|
1824
|
+
const at = e.indexOf(": ");
|
|
1825
|
+
return ` { find: ${e.slice(0, at)}, replacement: ${e.slice(at + 2)} },\n`;
|
|
1826
|
+
}).join("") + regexAliases.map((e) => ` ${e},\n`).join("") + ` ]` : `{ ${["...jestCompatAliases()", ...aliasEntries].join(", ")} }`;
|
|
1827
|
+
const vitePlus = require_host.usesVitePlus(root);
|
|
537
1828
|
return {
|
|
538
1829
|
source,
|
|
539
1830
|
automatic,
|
|
540
1831
|
attention,
|
|
541
1832
|
presetCovered,
|
|
542
1833
|
dropped,
|
|
543
|
-
suggestedConfig: `import { defineConfig } from 'vitest/config'
|
|
544
|
-
import { reactNative } from 'vitest-native'
|
|
1834
|
+
suggestedConfig: `${vitePlus ? `import { defineConfig } from 'vite-plus'\n${excludeGlobs.length ? "import { configDefaults } from 'vite-plus/test/config'\n" : ""}` : `import { ${excludeGlobs.length ? "configDefaults, " : ""}defineConfig } from 'vitest/config'\n`}import { reactNative } from 'vitest-native'
|
|
545
1835
|
import { jestCompatAliases, jestCompatSetup, jestMockTransform } from 'vitest-native/jest-compat'
|
|
546
|
-
${needsUrlImport ? "import { fileURLToPath } from 'node:url'\n" : ""}
|
|
1836
|
+
${needsUrlImport ? "import { fileURLToPath } from 'node:url'\n" : ""}${extraImports.map((i) => `${i}\n`).join("")}
|
|
547
1837
|
export default defineConfig({
|
|
548
|
-
plugins: [${
|
|
1838
|
+
plugins: [${[
|
|
1839
|
+
transformLine,
|
|
1840
|
+
...extraPlugins,
|
|
1841
|
+
"jestMockTransform()"
|
|
1842
|
+
].join(", ")}],
|
|
549
1843
|
resolve: {
|
|
550
1844
|
dedupe: ['react', 'react-test-renderer', 'react-is'],
|
|
551
|
-
alias:
|
|
1845
|
+
alias: ${aliasSource},
|
|
552
1846
|
},
|
|
553
1847
|
test: {
|
|
554
1848
|
${testEntries.join(",\n ")},
|
|
@@ -556,9 +1850,48 @@ export default defineConfig({
|
|
|
556
1850
|
},
|
|
557
1851
|
})
|
|
558
1852
|
`,
|
|
1853
|
+
vitePlus,
|
|
559
1854
|
ok: source !== null
|
|
560
1855
|
};
|
|
561
1856
|
}
|
|
1857
|
+
/**
|
|
1858
|
+
* What each package a transformIgnorePatterns allowlist lets through needs here.
|
|
1859
|
+
* Jest compiles nothing in node_modules unless allowed, so its allowlists mix React
|
|
1860
|
+
* Native source every runner must compile with ES-module packages only Jest's
|
|
1861
|
+
* CommonJS runtime cannot load. React Native, active presets and the engine's own
|
|
1862
|
+
* detection (native/ecosystem.ts) cover the first kind; Node loads the second. A
|
|
1863
|
+
* package goes into `transform: [...]` — which overrides detection — only with
|
|
1864
|
+
* evidence: a file under its entry point that Node cannot parse (see untranspiled.ts).
|
|
1865
|
+
* Prefix and scope entries are matched against the project's declared dependencies.
|
|
1866
|
+
*/
|
|
1867
|
+
function classifyAllowlist(root, entries, active, autoInlined, out) {
|
|
1868
|
+
const candidates = /* @__PURE__ */ new Set([...declaredDependencies(root), ...entries.filter((e) => e.kind === "exact").map((e) => e.name)]);
|
|
1869
|
+
const groups = {
|
|
1870
|
+
rn: [],
|
|
1871
|
+
detected: [],
|
|
1872
|
+
absent: []
|
|
1873
|
+
};
|
|
1874
|
+
const shadowed = /* @__PURE__ */ new Map();
|
|
1875
|
+
for (const pkg of [...candidates].sort()) {
|
|
1876
|
+
if (!entries.some((e) => allows(e, pkg))) continue;
|
|
1877
|
+
const preset = require_preset_map.presetShadowing(pkg);
|
|
1878
|
+
if (pkg === "react-native" || pkg.startsWith("@react-native/")) groups.rn.push(pkg);
|
|
1879
|
+
else if (preset && active.includes(preset)) shadowed.set(preset, [...shadowed.get(preset) ?? [], pkg]);
|
|
1880
|
+
else if (autoInlined.has(pkg)) groups.detected.push(pkg);
|
|
1881
|
+
else if (!installedManifest(root, pkg)) groups.absent.push(pkg);
|
|
1882
|
+
else {
|
|
1883
|
+
const evidence = untranspiledFile(root, pkg);
|
|
1884
|
+
if (evidence) {
|
|
1885
|
+
out.transformPkgs.push(pkg);
|
|
1886
|
+
out.automatic.push(`transformIgnorePatterns allows '${pkg}', which ships ${evidence} that Node cannot parse → reactNative({ transform: [...] }).`);
|
|
1887
|
+
}
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
if (groups.rn.length) out.automatic.push(`transformIgnorePatterns allows ${list(groups.rn)} — the native engine transforms React Native itself; nothing to do.`);
|
|
1891
|
+
for (const [preset, pkgs] of shadowed) out.presetCovered.push(`transformIgnorePatterns allows ${list(pkgs)} — shadowed by the auto-detected ${preset} preset; nothing to do.`);
|
|
1892
|
+
if (groups.detected.length) out.automatic.push(`transformIgnorePatterns allows ${list(groups.detected)} — detected by the engine (React Native ecosystem), which compiles what Node cannot run; nothing to do.`);
|
|
1893
|
+
if (groups.absent.length) out.automatic.push(`transformIgnorePatterns allows ${list(groups.absent)} — not installed; nothing to do.`);
|
|
1894
|
+
}
|
|
562
1895
|
function renderMigrationReport(report) {
|
|
563
1896
|
const lines = [];
|
|
564
1897
|
if (!report.source) {
|
|
@@ -576,9 +1909,9 @@ function renderMigrationReport(report) {
|
|
|
576
1909
|
section("Covered by presets — delete", report.presetCovered);
|
|
577
1910
|
section("Needs your attention", report.attention);
|
|
578
1911
|
section("Dropped (no equivalent needed)", report.dropped);
|
|
579
|
-
lines.push("Suggested vitest.config:", "");
|
|
1912
|
+
lines.push(report.vitePlus ? "Suggested vite.config:" : "Suggested vitest.config:", "");
|
|
580
1913
|
lines.push(...report.suggestedConfig.split("\n").map((l) => ` ${l}`));
|
|
581
|
-
lines.push("Re-run with --write to save this config, then: npx vitest-native doctor && npx vitest");
|
|
1914
|
+
lines.push(report.vitePlus ? "Re-run with --write to save this config, then: npx vitest-native doctor && vp test" : "Re-run with --write to save this config, then: npx vitest-native doctor && npx vitest", "", ...HOT_RUNTIME_NOTE);
|
|
582
1915
|
return lines;
|
|
583
1916
|
}
|
|
584
1917
|
//#endregion
|