vitest-native 0.14.1 → 0.15.0-rc.2
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/README.md +11 -10
- package/dist/cli.d.mts +9 -1
- package/dist/cli.mjs +2609 -361
- package/dist/context.d.mts +19 -0
- package/dist/context.mjs +47 -1
- package/dist/docs-url.d.mts +4 -0
- package/dist/docs-url.mjs +9 -0
- package/dist/errors.d.mts +21 -1
- package/dist/hang-watch-setup.mjs +55 -0
- package/dist/hang-watch.d.mts +56 -0
- package/dist/hang-watch.mjs +343 -0
- package/dist/helpers.cjs +24 -53
- package/dist/helpers.mjs +22 -1
- package/dist/host-D0r3P_T1.mjs +1985 -0
- package/dist/{index-aNBCTfA5.d.mts → index-JOR602XU.d.mts} +105 -2
- package/dist/index.d.mts +2 -1
- package/dist/index.mjs +723 -149
- package/dist/jest-compat/aliases.d.mts +1 -0
- package/dist/jest-compat/aliases.mjs +11 -0
- package/dist/jest-compat/interop.mjs +1 -1
- package/dist/jest-compat/jest-object.mjs +23 -5
- package/dist/jest-compat/node-registry.mjs +836 -68
- package/dist/jest-compat/setup.mjs +205 -12
- package/dist/jest-compat.cjs +383 -47
- package/dist/jest-compat.d.cts +19 -2
- package/dist/jest-compat.d.mts +19 -2
- package/dist/jest-compat.mjs +232 -47
- package/dist/matchers.d.cts +0 -1
- package/dist/matchers.d.mts +0 -1
- package/dist/native/assets.mjs +3 -1
- package/dist/native/babel-caller.d.mts +13 -0
- package/dist/native/babel-caller.mjs +24 -0
- package/dist/native/babel-toolchain.mjs +27 -3
- package/dist/native/boundary.mjs +45 -8
- package/dist/native/bounded-process.mjs +63 -5
- package/dist/native/bridge-client.mjs +133 -0
- package/dist/native/bridge-server.mjs +215 -0
- package/dist/native/bridge-thread.mjs +79 -0
- package/dist/native/bridge.mjs +512 -0
- package/dist/native/compile-error.mjs +120 -0
- package/dist/native/explain.mjs +3 -2
- package/dist/native/expo-module-mocks.mjs +2 -0
- package/dist/native/export-condition-recovery.mjs +20 -99
- package/dist/native/hooks.mjs +256 -133
- package/dist/native/jest-resolvers.mjs +94 -0
- package/dist/native/library-jest.mjs +352 -0
- package/dist/native/loader.mjs +167 -73
- package/dist/native/match.mjs +67 -7
- package/dist/native/module-reset.mjs +44 -49
- package/dist/native/ownership-ledger.d.mts +87 -0
- package/dist/native/ownership-ledger.mjs +524 -0
- package/dist/native/ownership.d.mts +20 -0
- package/dist/native/ownership.mjs +114 -0
- package/dist/native/registry-compiler.mjs +39 -5
- package/dist/native/registry-process.mjs +327 -28
- package/dist/native/registry.mjs +752 -200
- package/dist/native/resident-health.mjs +1 -0
- package/dist/native/resolve.d.mts +7 -0
- package/dist/native/resolve.mjs +119 -4
- package/dist/native/rntl-hooks.mjs +9 -5
- package/dist/native/rntl-text-host.mjs +5 -15
- package/dist/native/root-spelling.d.mts +6 -0
- package/dist/native/root-spelling.mjs +77 -0
- package/dist/native/runner.mjs +2 -19
- package/dist/native/setup.mjs +119 -38
- package/dist/native/shared-resolver.d.mts +141 -0
- package/dist/native/shared-resolver.mjs +719 -0
- package/dist/native/test-runner.mjs +26 -0
- package/dist/native/transform.mjs +18 -22
- package/dist/native/worker.mjs +9 -4
- package/dist/node-dispatch.mjs +293 -0
- package/dist/{preset-map-CogjYmSw.mjs → preset-map-DdAexIwz.mjs} +113 -2
- package/dist/{presets-CXDyg51l.mjs → presets-_EaSw29m.mjs} +710 -130
- package/dist/presets.d.mts +1 -1
- package/dist/presets.mjs +1 -1
- package/dist/rntl-matchers.d.ts +11 -15
- package/dist/rntl-support.mjs +28 -13
- package/dist/root-mocks-BNXeosbR.mjs +155 -0
- package/dist/serializer.cjs +7 -5
- package/dist/serializer.d.cts +7 -5
- package/dist/serializer.d.mts +7 -5
- package/dist/serializer.mjs +7 -5
- package/dist/setup.mjs +26 -27
- package/docs/migrating-from-jest.md +9 -232
- package/docs/migrating-from-vitest-react-native.md +4 -4
- package/docs/release-readiness.md +9 -11
- package/docs/versioning.md +38 -9
- package/package.json +59 -33
- package/dist/host-BAAAlSkO.mjs +0 -1028
package/dist/index.mjs
CHANGED
|
@@ -1,23 +1,30 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { a as presetForInstalled, i as
|
|
1
|
+
import { A as unsupportedExpoSdkMessage, C as assertSupportedNode, D as SUPPORTED_EXPO_SDKS, E as PEER_REQUIREMENTS, M as validateOptions, N as validatePeerDependency, O as installedExpoVersion, P as warnUnknownOptions, a as runningVite, b as fsModuleCacheKey, c as detectEcosystemPackages, d as createProjectBabel, f as isProjectSourceFile, j as unsupportedReactNativeMessage, k as isBelowSupportedReactNative, n as assertHotWorkerLoadsRunningVitest, p as missingBabelCoreNotice, s as aliasReachedPaths, t as assertHostResolvesRunningVitest, v as installedManifest, x as shouldDefaultFsModuleCache, y as detectEngine } from "./host-D0r3P_T1.mjs";
|
|
2
|
+
import { N as BUILT_IN_PRESET, t as presets_exports } from "./presets-_EaSw29m.mjs";
|
|
3
|
+
import { a as PRESET_MODULES, d as presetForInstalled, i as LIBRARY_SETUP_FILES, r as DEFAULT_ASSET_EXTS, s as autoDetectedPresetApplies, t as AUTO_DETECT_PRESETS, u as libraryRegistryEntries } from "./preset-map-DdAexIwz.mjs";
|
|
4
4
|
import { t as workerVitestMismatch } from "./worker-vitest-CILPFeRX.mjs";
|
|
5
5
|
import { createRequire } from "node:module";
|
|
6
|
-
import { extensionsFor, firstExact } from "./native/resolve.mjs";
|
|
6
|
+
import { extensionsFor, firstExact, platformSubpathFile } from "./native/resolve.mjs";
|
|
7
7
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
8
8
|
import path from "node:path";
|
|
9
9
|
import fs from "node:fs";
|
|
10
10
|
import os from "node:os";
|
|
11
11
|
import flowRemoveTypes from "flow-remove-types";
|
|
12
12
|
import { VitestNativeError, VitestNativeTypeError } from "./errors.mjs";
|
|
13
|
+
import { docsUrl } from "./docs-url.mjs";
|
|
13
14
|
import { presetFromModule } from "./preset-modules.mjs";
|
|
14
15
|
import { serializableAliases } from "./jest-compat/aliases.mjs";
|
|
15
16
|
import { tsconfigPathAliases } from "./native/tsconfig-paths.mjs";
|
|
17
|
+
import { aliasList, checkResolverInputs, conditionsIn, createSharedResolver, identityKey, nodeDefaultConditions, nodeOptionsList, ownershipShadowFile, resolverInputsHash, serializeResolutionAliases } from "./native/shared-resolver.mjs";
|
|
16
18
|
import { knownNativeModulesFor, nativeModuleSpecsFor } from "./native/native-modules.mjs";
|
|
17
19
|
import { createNativeOwnershipPolicy, findNativeInlineConflicts, findNativeOwnershipConflict, formatNativeOwnershipManifest } from "./native/ownership.mjs";
|
|
20
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
21
|
+
import { transformWithOxc } from "vite";
|
|
18
22
|
import { containsPath, dependencyDirOf, isPackageEntryFile, memoizePackageDirOf, packageDirOf } from "./native/match.mjs";
|
|
23
|
+
import { OWNERSHIP_META_KEY, OWNERSHIP_ROUTES, viteMarkerFor } from "./native/ownership-ledger.mjs";
|
|
19
24
|
import { CONTEXT_ENV, ensureProjectContext, projectContext, writeProjectContext } from "./context.mjs";
|
|
20
25
|
import { cacheRootFor } from "./native/transform.mjs";
|
|
26
|
+
import { HangWatch, debugging, hangTimeoutFor } from "./hang-watch.mjs";
|
|
27
|
+
import inspector from "node:inspector";
|
|
21
28
|
// src/resolve.ts
|
|
22
29
|
/**
|
|
23
30
|
* Extension search order for the Vite graph, taken from the same definition the
|
|
@@ -36,7 +43,49 @@ function getConfiguredPlatformExtensions(platform, sourceExts) {
|
|
|
36
43
|
return extensionsFor(platform, sourceExts);
|
|
37
44
|
}
|
|
38
45
|
// src/native/apply.ts
|
|
39
|
-
|
|
46
|
+
/**
|
|
47
|
+
* Vite/Vitest config fragment for the native engine.
|
|
48
|
+
*
|
|
49
|
+
* # Module ownership
|
|
50
|
+
*
|
|
51
|
+
* The native engine runs two module systems at once, and every rule in this file
|
|
52
|
+
* exists to serve one invariant:
|
|
53
|
+
*
|
|
54
|
+
* **Exactly one of them owns any given package, for the duration of a run.**
|
|
55
|
+
*
|
|
56
|
+
* Two graphs is fine. Two *copies* is the bug, and it is silent: nothing throws,
|
|
57
|
+
* module-level state simply stops being shared, so a store written through one copy
|
|
58
|
+
* reads back unset through the other and a translated label renders as "". Note the
|
|
59
|
+
* invariant is one OWNER, not one path — two graphs resolving to the same file still
|
|
60
|
+
* produce two instances (see the duplicate-instance warning in hooks.mjs).
|
|
61
|
+
*
|
|
62
|
+
* Who owns what, and why:
|
|
63
|
+
*
|
|
64
|
+
* - **Node owns React Native and `@react-native/*`.** Not a preference: the Flow
|
|
65
|
+
* strip, the Babel transform, the boundary mocks and the precompiled registry are
|
|
66
|
+
* all implemented as Node loader hooks. This is the engine.
|
|
67
|
+
* - **Node owns installed React Native packages** — those declaring `react-native` in
|
|
68
|
+
* their own manifest — and their dependency closures. They ship source Node cannot
|
|
69
|
+
* run unaided (untranspiled JSX, Flow, TypeScript), they are reachable from React
|
|
70
|
+
* Native's own require graph, and the same hooks compile them.
|
|
71
|
+
* - **Vite owns all first-party source**: the application, and the whole of the
|
|
72
|
+
* package under test. Its `react-native` imports cross into Node's single React
|
|
73
|
+
* Native instance exactly as application code's always have.
|
|
74
|
+
* - **Vite owns every test entry**, unconditionally. A test file is something Vitest
|
|
75
|
+
* runs, never something a module imports. Handing one to Node compiles it to
|
|
76
|
+
* CommonJS, and its own `import { it } from 'vitest'` becomes `require('vitest')`,
|
|
77
|
+
* which throws.
|
|
78
|
+
* - **Never claimed by either rule above**: the test library, the renderers, and
|
|
79
|
+
* React itself (see NEVER_INLINE in ecosystem.ts). The engine wires these up; a
|
|
80
|
+
* second copy of any of them corrupts rendering.
|
|
81
|
+
*
|
|
82
|
+
* The consequence worth knowing: a workspace library is Vite-owned when it is the
|
|
83
|
+
* package under test and Node-owned when the run merely depends on it. Ownership
|
|
84
|
+
* follows what is under test. The invariant still holds — one owner per run — but the
|
|
85
|
+
* same library is not hosted identically by both kinds of run.
|
|
86
|
+
*/
|
|
87
|
+
const JSX_TRANSFORM = { oxc: { jsx: { runtime: "automatic" } } };
|
|
88
|
+
function nativeEngineConfig(setupFilePath, fields, extensions, transformPkgs = [], hot, jsxTransform = JSX_TRANSFORM, userPool, inlinePkgs = [], projectRoot = process.cwd(), userInlinesEverything = false, projectDirs = [], ownershipPolicy) {
|
|
40
89
|
const ownership = ownershipPolicy ?? createNativeOwnershipPolicy({
|
|
41
90
|
projectRoot,
|
|
42
91
|
explicitTransforms: transformPkgs,
|
|
@@ -47,6 +96,10 @@ function nativeEngineConfig(setupFilePath, fields, extensions, transformPkgs = [
|
|
|
47
96
|
const nodeTransformed = ownership.nodeTransformPackages;
|
|
48
97
|
const ownershipManifest = ownership.manifest();
|
|
49
98
|
fields.ownership = ownershipManifest;
|
|
99
|
+
fields.packageDirs = {
|
|
100
|
+
root: ownership.projectRoot,
|
|
101
|
+
dirs: Object.fromEntries(nodeTransformed.map((name) => [name, ownership.packageDirOf(name)]).filter(([, dir]) => dir === null || path.isAbsolute(dir)))
|
|
102
|
+
};
|
|
50
103
|
if (fields.diagnostics) for (const line of formatNativeOwnershipManifest(ownershipManifest)) {
|
|
51
104
|
const report = `[vitest-native] ownership: ${line}`;
|
|
52
105
|
if (line.startsWith("WARNING:")) console.warn(report);
|
|
@@ -96,6 +149,81 @@ function nativeEngineConfig(setupFilePath, fields, extensions, transformPkgs = [
|
|
|
96
149
|
}
|
|
97
150
|
};
|
|
98
151
|
}
|
|
152
|
+
// src/project-jsx.ts
|
|
153
|
+
/**
|
|
154
|
+
* JSX in a project's own `.js` files.
|
|
155
|
+
*
|
|
156
|
+
* Metro and babel-jest parse every `.js` file with JSX enabled, so React Native projects
|
|
157
|
+
* keep JSX in `.js` sources, tests and setup files (a `jest.setup.js` that renders a
|
|
158
|
+
* provider, say). Vite's Oxc transform chooses the language by extension and skips `.js`
|
|
159
|
+
* entirely, so the same file reaches Vite's parser with its JSX intact and fails to
|
|
160
|
+
* compile. This compiles a project `.js` file as JSX, with the same Oxc options Vite
|
|
161
|
+
* applies to `.jsx` and `.tsx` (the automatic runtime this plugin configures, plus any
|
|
162
|
+
* the user set), and returns its sourcemap so Vite chains it.
|
|
163
|
+
*
|
|
164
|
+
* It runs when the file is loaded, before every transform: under the native engine the
|
|
165
|
+
* plugin's own transform hook runs after Vite's (see plugin.ts), too late for a file
|
|
166
|
+
* Vite's import analysis cannot parse.
|
|
167
|
+
*
|
|
168
|
+
* Only files outside `node_modules`: packages are compiled by their own path (the native
|
|
169
|
+
* engine's Babel transform, or the mock engine's Flow strip and Vite's pipeline).
|
|
170
|
+
*/
|
|
171
|
+
/** The Oxc options for a project `.js` file, or undefined when Oxc is turned off. */
|
|
172
|
+
function projectJsxOptions(oxc) {
|
|
173
|
+
if (oxc === false || oxc === void 0) return void 0;
|
|
174
|
+
const { include: _include, exclude: _exclude, jsxInject: _jsxInject, jsxRefreshInclude: _jsxRefreshInclude, jsxRefreshExclude: _jsxRefreshExclude, ...transform } = oxc;
|
|
175
|
+
const jsx = typeof transform.jsx === "object" ? {
|
|
176
|
+
...transform.jsx,
|
|
177
|
+
refresh: false
|
|
178
|
+
} : transform.jsx;
|
|
179
|
+
return {
|
|
180
|
+
...transform,
|
|
181
|
+
jsx,
|
|
182
|
+
lang: "jsx"
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
const NODE_MODULES = /[\\/]node_modules[\\/]/;
|
|
186
|
+
const MAY_HAVE_JSX = /<[A-Za-z_$>]/;
|
|
187
|
+
/**
|
|
188
|
+
* Whether `id` is a project `.js` file this compiles: the plain file, outside
|
|
189
|
+
* `node_modules`. An id with a query is a different module made from the file (`?raw` is
|
|
190
|
+
* its text, `?url` its URL), so it is left to the plugin that serves that query.
|
|
191
|
+
*/
|
|
192
|
+
function isProjectJsFile(id) {
|
|
193
|
+
return id.endsWith(".js") && !id.includes("?") && path.isAbsolute(id) && !NODE_MODULES.test(id);
|
|
194
|
+
}
|
|
195
|
+
const asking = new AsyncLocalStorage();
|
|
196
|
+
/**
|
|
197
|
+
* A project `.js` file compiled as JSX, or undefined to leave it to Vite: not a project
|
|
198
|
+
* `.js` file, no possible JSX, Oxc turned off, or a file Oxc cannot parse as JSX (Flow,
|
|
199
|
+
* say, which a project's own transform plugin may strip later).
|
|
200
|
+
*
|
|
201
|
+
* Another plugin that loads the file keeps it: the chain is asked first (this hook
|
|
202
|
+
* answers nothing to its own question), and what a plugin returns is served as it
|
|
203
|
+
* returned it. The plugin's load hook runs early because the plugin is `enforce: "pre"`
|
|
204
|
+
* (it also serves assets and virtual modules ahead of Vite's own plugins); asking first
|
|
205
|
+
* keeps that from taking a file away from a project's own plugin.
|
|
206
|
+
*/
|
|
207
|
+
async function loadProjectJsx(id, options, config, chain, log) {
|
|
208
|
+
if (!options || !isProjectJsFile(id) || asking.getStore() === id) return void 0;
|
|
209
|
+
const code = await fs.promises.readFile(id, "utf8");
|
|
210
|
+
if (!MAY_HAVE_JSX.test(code)) return void 0;
|
|
211
|
+
if (chain) {
|
|
212
|
+
const other = await asking.run(id, () => chain.load(id));
|
|
213
|
+
if (other != null) return other;
|
|
214
|
+
}
|
|
215
|
+
let result;
|
|
216
|
+
try {
|
|
217
|
+
result = await transformWithOxc(code, id, options, void 0, config);
|
|
218
|
+
} catch (error) {
|
|
219
|
+
log?.(`[vitest-native] ${id} is not JSX Oxc can parse (${error.message.split("\n")[0]}); serving it unchanged.`);
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
return {
|
|
223
|
+
code: result.code,
|
|
224
|
+
map: result.map
|
|
225
|
+
};
|
|
226
|
+
}
|
|
99
227
|
// src/plugin.ts
|
|
100
228
|
function uniqueExtensions(values) {
|
|
101
229
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -249,15 +377,14 @@ function resolvePackageVersion(packageName, projectRoot) {
|
|
|
249
377
|
* tsconfig path aliases by default (`experiments.tsconfigPaths`, docs.expo.dev/guides/
|
|
250
378
|
* typescript), and the SDK 57 template imports its own components through `@/…`, so
|
|
251
379
|
* without this a new Expo project's first component test fails to resolve. Bare React
|
|
252
|
-
* Native's Metro does not, so neither does this. Vite
|
|
253
|
-
* when `resolve.tsconfigPaths` is on
|
|
380
|
+
* Native's Metro does not, so neither does this. Vite resolves tsconfig paths itself
|
|
381
|
+
* when `resolve.tsconfigPaths` is on.
|
|
254
382
|
*
|
|
255
|
-
*
|
|
256
|
-
*
|
|
257
|
-
* `resolve.tsconfigPaths` themselves).
|
|
383
|
+
* False when it is not an Expo project, has no tsconfig, opted out, or the user set
|
|
384
|
+
* `resolve.tsconfigPaths` themselves.
|
|
258
385
|
*/
|
|
259
|
-
function expoTsconfigPaths(projectRoot, userTsconfigPaths
|
|
260
|
-
if (userTsconfigPaths !== void 0) return
|
|
386
|
+
function expoTsconfigPaths(projectRoot, userTsconfigPaths) {
|
|
387
|
+
if (userTsconfigPaths !== void 0) return false;
|
|
261
388
|
const read = (file) => {
|
|
262
389
|
try {
|
|
263
390
|
return fs.readFileSync(path.join(projectRoot, file), "utf8");
|
|
@@ -269,19 +396,17 @@ function expoTsconfigPaths(projectRoot, userTsconfigPaths, viteMajor) {
|
|
|
269
396
|
try {
|
|
270
397
|
manifest = JSON.parse(read("package.json") ?? "{}");
|
|
271
398
|
} catch {
|
|
272
|
-
return
|
|
399
|
+
return false;
|
|
273
400
|
}
|
|
274
401
|
if (!("expo" in {
|
|
275
402
|
...manifest.dependencies,
|
|
276
403
|
...manifest.devDependencies
|
|
277
|
-
})) return
|
|
278
|
-
|
|
279
|
-
if (tsconfig === null) return null;
|
|
404
|
+
})) return false;
|
|
405
|
+
if (read("tsconfig.json") === null) return false;
|
|
280
406
|
try {
|
|
281
|
-
if (JSON.parse(read("app.json") ?? "{}").expo?.experiments?.tsconfigPaths === false) return
|
|
407
|
+
if (JSON.parse(read("app.json") ?? "{}").expo?.experiments?.tsconfigPaths === false) return false;
|
|
282
408
|
} catch {}
|
|
283
|
-
|
|
284
|
-
return /"paths"\s*:/.test(tsconfig) ? "unsupported" : null;
|
|
409
|
+
return true;
|
|
285
410
|
}
|
|
286
411
|
/**
|
|
287
412
|
* One line, once per process, stating which engine this run actually uses.
|
|
@@ -293,7 +418,7 @@ function expoTsconfigPaths(projectRoot, userTsconfigPaths, viteMajor) {
|
|
|
293
418
|
* Written to stderr: this is the plugin's only unconditional output, and stdout
|
|
294
419
|
* must stay parseable for pipelines like `vitest --reporter=json > results.json`.
|
|
295
420
|
*/
|
|
296
|
-
function printEngineBanner(engine, platform, projectRoot, presetNames, hotRuntime = false) {
|
|
421
|
+
function printEngineBanner(engine, platform, projectRoot, presetNames, hotRuntime = false, ownershipModel, nodeMocks = false) {
|
|
297
422
|
const g = globalThis;
|
|
298
423
|
if (g.__vitest_native_banner_printed) return;
|
|
299
424
|
g.__vitest_native_banner_printed = true;
|
|
@@ -301,7 +426,9 @@ function printEngineBanner(engine, platform, projectRoot, presetNames, hotRuntim
|
|
|
301
426
|
if (engine === "native") {
|
|
302
427
|
const rn = resolvePackageVersion("react-native", projectRoot);
|
|
303
428
|
const runtime = hotRuntime ? ", hot runtime" : "";
|
|
304
|
-
|
|
429
|
+
const model = ownershipModel ? `, experimental.ownershipModel: ${ownershipModel}` : "";
|
|
430
|
+
const mocks = nodeMocks ? `, experimental.nodeMocks${ownershipModel === "resolution" && model ? " (implied)" : ""}` : "";
|
|
431
|
+
console.error(`[vitest-native] engine: native — real react-native${rn ? `@${rn}` : ""}${mocked} (platform ${platform}${runtime}${model}${mocks})`);
|
|
305
432
|
} else console.error(`[vitest-native] engine: mock — React Native reimplementation, cross-checked against real RN${mocked} (platform ${platform})`);
|
|
306
433
|
}
|
|
307
434
|
/**
|
|
@@ -319,14 +446,11 @@ function mockEnginePresetNames(listed, presetsOption, projectRoot) {
|
|
|
319
446
|
return autoDetectPresetNames(projectRoot, false).filter((n) => !disabled.has(n));
|
|
320
447
|
}
|
|
321
448
|
/** The major of a version string, or NaN. */
|
|
322
|
-
/** The unsupported
|
|
449
|
+
/** The unsupported React Native and Expo SDK warnings already printed in this process. */
|
|
323
450
|
const warnedExpoProblems = /* @__PURE__ */ new Set();
|
|
324
451
|
function majorOf(version) {
|
|
325
452
|
return Number(version?.replace(/^[^0-9]*/, "").split(".")[0]);
|
|
326
453
|
}
|
|
327
|
-
function getJsxTransformConfig(viteMajor) {
|
|
328
|
-
return viteMajor >= 8 ? { oxc: { jsx: { runtime: "automatic" } } } : { esbuild: { jsx: "automatic" } };
|
|
329
|
-
}
|
|
330
454
|
/**
|
|
331
455
|
* The names React Native's index exports.
|
|
332
456
|
*
|
|
@@ -344,37 +468,16 @@ function getJsxTransformConfig(viteMajor) {
|
|
|
344
468
|
* real module in the native suite, across every React Native version in CI.
|
|
345
469
|
*/
|
|
346
470
|
function parseReactNativeExports(indexSource) {
|
|
347
|
-
return parseReactNativeMembers(indexSource).map((member) => member.name);
|
|
348
|
-
}
|
|
349
|
-
/**
|
|
350
|
-
* The members of React Native's index that announce their own deprecation.
|
|
351
|
-
*
|
|
352
|
-
* React Native marks a deprecated or extracted export by calling `warnOnce` inside
|
|
353
|
-
* its getter, so reading the member is what prints the notice. The facade must not
|
|
354
|
-
* read these while it initialises, or every file that imports `Pressable` prints
|
|
355
|
-
* notices for `SafeAreaView`, `Clipboard` and the rest; it exposes them as getters
|
|
356
|
-
* instead, and the notice appears only where a test really uses one.
|
|
357
|
-
*/
|
|
358
|
-
function parseDeprecatedReactNativeExports(indexSource) {
|
|
359
|
-
return parseReactNativeMembers(indexSource).filter((member) => member.deprecated).map((member) => member.name);
|
|
360
|
-
}
|
|
361
|
-
function parseReactNativeMembers(indexSource) {
|
|
362
471
|
const start = indexSource.indexOf("module.exports = {");
|
|
363
472
|
if (start === -1) return [];
|
|
364
473
|
const end = indexSource.slice(start).search(/^\}/m);
|
|
365
|
-
const
|
|
366
|
-
const
|
|
367
|
-
const
|
|
368
|
-
matches.forEach((match, i) => {
|
|
474
|
+
const matches = [...(end === -1 ? indexSource.slice(start) : indexSource.slice(start, start + end)).matchAll(/^ {2}(?:get\s+)?([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*[(:,]/gm)];
|
|
475
|
+
const members = /* @__PURE__ */ new Set();
|
|
476
|
+
for (const match of matches) {
|
|
369
477
|
const name = match[1];
|
|
370
|
-
if (name
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
});
|
|
374
|
-
return [...members].map(([name, deprecated]) => ({
|
|
375
|
-
name,
|
|
376
|
-
deprecated
|
|
377
|
-
}));
|
|
478
|
+
if (name !== "default" && name !== "__esModule" && name !== "get") members.add(name);
|
|
479
|
+
}
|
|
480
|
+
return [...members];
|
|
378
481
|
}
|
|
379
482
|
/**
|
|
380
483
|
* Coverage of the files Node compiles (native/coverage-v8.mjs): `@vitest/coverage-v8`,
|
|
@@ -417,18 +520,46 @@ async function loadAssetModules() {
|
|
|
417
520
|
return await import(pathToFileURL(path.resolve(dir, "native/assets.mjs")).href);
|
|
418
521
|
}
|
|
419
522
|
/**
|
|
420
|
-
*
|
|
421
|
-
*
|
|
422
|
-
*
|
|
423
|
-
*
|
|
424
|
-
* dynamic import rather than a static one — a static specifier would bundle a second
|
|
425
|
-
* copy into the plugin entry. Returns the registry path, or null when one could not
|
|
426
|
-
* be produced, in which case the engine keeps loading RN file by file.
|
|
523
|
+
* The main-process half of the require bridge (native/bridge-server.mjs) for one project:
|
|
524
|
+
* it answers a worker's synchronous fetch with Vitest's own fetch (the one the worker's
|
|
525
|
+
* module runner makes, externalization included), for files the project's ownership
|
|
526
|
+
* policy gives to Vite only.
|
|
427
527
|
*/
|
|
528
|
+
async function startRequireBridge(project, vitest) {
|
|
529
|
+
const { startBridgeServer, BRIDGE_PROVIDE_KEY } = await import(pathToFileURL(path.resolve(path.dirname(fileURLToPath(import.meta.url)), "native/bridge-server.mjs")).href);
|
|
530
|
+
const allow = project.vite.config.server?.fs?.allow ?? [];
|
|
531
|
+
const roots = allow.length > 0 ? [...allow] : [project.vite.config.root];
|
|
532
|
+
const realRoots = roots.map((root) => fs.existsSync(root) ? fs.realpathSync.native(root) : root);
|
|
533
|
+
const inRoots = (file) => realRoots.some((root) => {
|
|
534
|
+
const relative = path.relative(root, file);
|
|
535
|
+
return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
536
|
+
});
|
|
537
|
+
const { isFileLoadingAllowed } = await import("vite");
|
|
538
|
+
if (typeof isFileLoadingAllowed !== "function") throw new VitestNativeError("BRIDGE_CONTRACT_CHANGED", `experimental.ownershipModel 'resolution' needs Vite's isFileLoadingAllowed, which this Vite does not export.`);
|
|
539
|
+
const server = await startBridgeServer({
|
|
540
|
+
root: project.vite.config.root,
|
|
541
|
+
fetch: async (url, importer, environmentName) => {
|
|
542
|
+
const transform = project._transformService;
|
|
543
|
+
const environment = project.vite.environments[environmentName];
|
|
544
|
+
if (typeof transform?.fetch !== "function" || environment === void 0) throw new VitestNativeError("BRIDGE_CONTRACT_CHANGED", `Vitest's per-project fetch (${environment === void 0 ? `environment ${environmentName}` : "_transformService"}) is not where this version of vitest-native expects it`);
|
|
545
|
+
return transform.fetch(url, importer, environment, false);
|
|
546
|
+
},
|
|
547
|
+
mayServe: (file) => {
|
|
548
|
+
if (/[\\/]node_modules[\\/]/.test(file)) return true;
|
|
549
|
+
const real = (fs.existsSync(file) ? fs.realpathSync.native(file) : file).replace(/\\/g, "/");
|
|
550
|
+
return inRoots(real) && isFileLoadingAllowed(project.vite.config, real);
|
|
551
|
+
}
|
|
552
|
+
});
|
|
553
|
+
project.provide(BRIDGE_PROVIDE_KEY, {
|
|
554
|
+
endpoint: server.endpoint,
|
|
555
|
+
token: server.token,
|
|
556
|
+
roots
|
|
557
|
+
});
|
|
558
|
+
vitest.onClose?.(() => server.close());
|
|
559
|
+
}
|
|
428
560
|
async function buildRegistryFor(options) {
|
|
429
561
|
try {
|
|
430
|
-
|
|
431
|
-
return (await import(pathToFileURL(path.resolve(dir, "native/registry-process.mjs")).href)).buildRegistryFor(options);
|
|
562
|
+
return (await loadRegistryProcess()).buildRegistryFor(options);
|
|
432
563
|
} catch (error) {
|
|
433
564
|
try {
|
|
434
565
|
const dir = path.dirname(fileURLToPath(import.meta.url));
|
|
@@ -439,21 +570,67 @@ async function buildRegistryFor(options) {
|
|
|
439
570
|
return null;
|
|
440
571
|
}
|
|
441
572
|
}
|
|
573
|
+
/** The registry-process module, reached as buildRegistryFor explains. */
|
|
574
|
+
async function loadRegistryProcess() {
|
|
575
|
+
const dir = path.dirname(fileURLToPath(import.meta.url));
|
|
576
|
+
return import(pathToFileURL(path.resolve(dir, "native/registry-process.mjs")).href);
|
|
577
|
+
}
|
|
578
|
+
/**
|
|
579
|
+
* The warm registries, or the registry this cache miss is compiling in the background
|
|
580
|
+
* (startRegistryBuild in native/registry-process.mjs), or `wait` when only the library
|
|
581
|
+
* registry is missing and is built first. None of them when none is available.
|
|
582
|
+
*/
|
|
583
|
+
async function startRegistryFor(options) {
|
|
584
|
+
try {
|
|
585
|
+
return (await loadRegistryProcess()).startRegistryBuild(options);
|
|
586
|
+
} catch (error) {
|
|
587
|
+
console.warn(`[vitest-native] (native) could not precompile the React Native registry (${error?.message ?? error}); using slower per-file module loading.`);
|
|
588
|
+
return {};
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
/** Vitest instances whose close already settles the background registry builds. */
|
|
592
|
+
const registrySettlers = /* @__PURE__ */ new WeakSet();
|
|
442
593
|
/** Load declarative Metro data without retaining Metro/Expo in Vite's process. */
|
|
443
594
|
async function loadProjectMetroProfile(options) {
|
|
444
595
|
const dir = path.dirname(fileURLToPath(import.meta.url));
|
|
445
596
|
return (await import(pathToFileURL(path.resolve(dir, "native/metro-profile.mjs")).href)).loadMetroProfile(options);
|
|
446
597
|
}
|
|
447
598
|
/**
|
|
448
|
-
*
|
|
449
|
-
*
|
|
450
|
-
*
|
|
451
|
-
* but a build against any single Vite major cannot type the other major's
|
|
452
|
-
* valid config. Keep that unavoidable assertion at this compatibility edge.
|
|
599
|
+
* The config this plugin returns, typed as Vite's: nativeEngineConfig builds it from
|
|
600
|
+
* plain objects (its `test` section is Vitest's), which TypeScript cannot match to
|
|
601
|
+
* Vite's `UserConfig` structurally.
|
|
453
602
|
*/
|
|
454
603
|
function asCompatibleViteConfig(config) {
|
|
455
604
|
return config;
|
|
456
605
|
}
|
|
606
|
+
/**
|
|
607
|
+
* The CommonJS conditions Node applies in this project's workers, computed the way
|
|
608
|
+
* Vitest builds a worker's arguments (`resolveConditions` in its pool, Vite 6+): the
|
|
609
|
+
* SSR conditions Vite resolved, as `--conditions` flags, then the project's
|
|
610
|
+
* `test.execArgv`. Only profiling flags of this process's own `execArgv` reach a
|
|
611
|
+
* worker, never its conditions. A worker, thread or fork, also applies the
|
|
612
|
+
* `NODE_OPTIONS` of the environment it is given: the project's `test.env`, else this
|
|
613
|
+
* process's. Node's defaults complete the set; `react-native` is the resolver's own.
|
|
614
|
+
*/
|
|
615
|
+
function finishResolverInputs(pending, project) {
|
|
616
|
+
const viteConfig = project.vite?.config;
|
|
617
|
+
const production = viteConfig?.isProduction === true;
|
|
618
|
+
const vite = [...new Set(viteConfig?.ssr?.resolve?.conditions ?? [])].filter((c) => c === "production" ? production : c === "development" ? !production : true).map((c) => c === "development|production" ? production ? "production" : "development" : c);
|
|
619
|
+
const execArgv = Array.isArray(project.config.execArgv) ? project.config.execArgv.filter((a) => typeof a === "string") : [];
|
|
620
|
+
const env = project.config.env ?? {};
|
|
621
|
+
const nodeOptions = Object.hasOwn(env, "NODE_OPTIONS") ? env.NODE_OPTIONS : process.env.NODE_OPTIONS;
|
|
622
|
+
const conditions = new Set(nodeDefaultConditions(process.features));
|
|
623
|
+
for (const c of [
|
|
624
|
+
...vite,
|
|
625
|
+
...conditionsIn(execArgv),
|
|
626
|
+
...conditionsIn(nodeOptionsList(nodeOptions))
|
|
627
|
+
]) if (c !== "react-native") conditions.add(c);
|
|
628
|
+
return {
|
|
629
|
+
...pending,
|
|
630
|
+
preserveSymlinks: execArgv.includes("--preserve-symlinks") || nodeOptionsList(nodeOptions).includes("--preserve-symlinks"),
|
|
631
|
+
conditions: [...conditions].sort()
|
|
632
|
+
};
|
|
633
|
+
}
|
|
457
634
|
/** Fields of every context this process wrote, by reference. */
|
|
458
635
|
const writtenContexts = /* @__PURE__ */ new Map();
|
|
459
636
|
/**
|
|
@@ -469,6 +646,18 @@ function withProjectContext(fields, env, projectRoot) {
|
|
|
469
646
|
[CONTEXT_ENV]: ref
|
|
470
647
|
};
|
|
471
648
|
}
|
|
649
|
+
/**
|
|
650
|
+
* A written context's fields minus the registries', for Vitest's module-cache key.
|
|
651
|
+
* Whether the registries are warm, compiling or absent changes how workers load React
|
|
652
|
+
* Native and libraries through Node, never what Vite transforms, so a run that found
|
|
653
|
+
* the cache cold must not key every module differently from the warm run after it.
|
|
654
|
+
*/
|
|
655
|
+
function registryNeutralContext(ref) {
|
|
656
|
+
const fields = writtenContexts.get(ref);
|
|
657
|
+
if (!fields) return void 0;
|
|
658
|
+
const { registry: _registry, registryPending: _pending, libraryRegistry: _library, ...rest } = fields;
|
|
659
|
+
return rest;
|
|
660
|
+
}
|
|
472
661
|
/** The same context with `changes` applied, written as its own file. */
|
|
473
662
|
function amendProjectContext(ref, changes, projectRoot) {
|
|
474
663
|
const current = writtenContexts.get(ref) ?? projectContext(ref);
|
|
@@ -704,7 +893,9 @@ const UTILITY_SUBPATH_LEAVES = /* @__PURE__ */ new Set([
|
|
|
704
893
|
]);
|
|
705
894
|
function isUtilitySubpath(specifier) {
|
|
706
895
|
const leaf = subpathLeafOf(specifier);
|
|
707
|
-
|
|
896
|
+
if (leaf !== null && UTILITY_SUBPATH_LEAVES.has(leaf)) return true;
|
|
897
|
+
const pkg = packageNameOf(specifier);
|
|
898
|
+
return pkg !== specifier && specifier.slice(pkg.length + 1).split("/")[0] === "jest";
|
|
708
899
|
}
|
|
709
900
|
/** Check if a value (or any nested value) contains functions. */
|
|
710
901
|
function containsFunctions(value, visited = /* @__PURE__ */ new WeakSet()) {
|
|
@@ -879,8 +1070,7 @@ async function loadPresetModules(files, root) {
|
|
|
879
1070
|
configFile: false,
|
|
880
1071
|
logLevel: "error",
|
|
881
1072
|
plugins: [presetModuleReactNative],
|
|
882
|
-
resolve: { noExternal: [REACT_NATIVE_IMPORT] }
|
|
883
|
-
ssr: { noExternal: [REACT_NATIVE_IMPORT] }
|
|
1073
|
+
resolve: { noExternal: [REACT_NATIVE_IMPORT] }
|
|
884
1074
|
}));
|
|
885
1075
|
} catch (cause) {
|
|
886
1076
|
throw new VitestNativeError("INVALID_OPTION", `The preset module ${file} could not be imported while the plugin read its preset: ${cause instanceof Error ? cause.message : String(cause)}\nThe plugin imports it in Node, with only react-native stood in, before any test runs. It must be an ES module (export default), and anything else React Native needs (another React Native library, the app's code) belongs inside its factories, which run in the test workers.`, { cause });
|
|
@@ -920,7 +1110,7 @@ function hotAutoConfigDeclineReason(userPool, userIsolate) {
|
|
|
920
1110
|
}
|
|
921
1111
|
/**
|
|
922
1112
|
* Why the resolved Vitest config overrides a hot runtime chosen at config time, or
|
|
923
|
-
* null. Vitest
|
|
1113
|
+
* null. Vitest applies CLI flags after plugins' config hooks, so `--maxWorkers=1`,
|
|
924
1114
|
* `--no-file-parallelism`, `--pool` and `--isolate`/`--no-isolate` arrive only in the
|
|
925
1115
|
* resolved config. `--no-isolate` sets the same `isolate: false` the hot runtime uses,
|
|
926
1116
|
* so it is read from the CLI options themselves.
|
|
@@ -935,7 +1125,7 @@ function hotOverrideReason(resolved, cli, hotPool, singleWorkerAccepted = false)
|
|
|
935
1125
|
return null;
|
|
936
1126
|
}
|
|
937
1127
|
/**
|
|
938
|
-
* The root Vitest gives a project: `test.root` over Vite's `root` (Vitest
|
|
1128
|
+
* The root Vitest gives a project: `test.root` over Vite's `root` (Vitest 5's
|
|
939
1129
|
* resolveConfig). `vitest --root` arrives as `test.root`. Per-project state is keyed
|
|
940
1130
|
* by it, since that is the root configureVitest sees.
|
|
941
1131
|
*/
|
|
@@ -953,8 +1143,8 @@ function vitestRootOf(config) {
|
|
|
953
1143
|
* ownership, env, the hot pool. Vitest shares a server only when an entry sets no
|
|
954
1144
|
* Vite-level option; `root` is one, and pinning it to the inherited value changes
|
|
955
1145
|
* nothing else. Unlike `sharedViteServer: false`, which Vitest reads from the
|
|
956
|
-
* top-level config alone, this works in a nested config too.
|
|
957
|
-
*
|
|
1146
|
+
* top-level config alone, this works in a nested config too. Returns how many were
|
|
1147
|
+
* pinned.
|
|
958
1148
|
*/
|
|
959
1149
|
function pinInlineProjectRoots(test, declaringRoot) {
|
|
960
1150
|
const projects = test?.projects;
|
|
@@ -992,16 +1182,9 @@ function prependSetupFile(userConfig, contributed) {
|
|
|
992
1182
|
contributed.setupFiles = [];
|
|
993
1183
|
}
|
|
994
1184
|
function sameDirectory(a, b) {
|
|
995
|
-
|
|
996
|
-
const real = (p) => {
|
|
997
|
-
try {
|
|
998
|
-
return fs.realpathSync.native(p);
|
|
999
|
-
} catch {
|
|
1000
|
-
return path.resolve(p);
|
|
1001
|
-
}
|
|
1002
|
-
};
|
|
1003
|
-
return real(a) === real(b);
|
|
1185
|
+
return a === b || directoryKey(a) === directoryKey(b);
|
|
1004
1186
|
}
|
|
1187
|
+
const directoryKey = identityKey;
|
|
1005
1188
|
function hasSetupFile(setupFiles, file) {
|
|
1006
1189
|
const real = (f) => {
|
|
1007
1190
|
try {
|
|
@@ -1017,7 +1200,7 @@ function hasSetupFile(setupFiles, file) {
|
|
|
1017
1200
|
* Why this project's worker count cannot coexist with another project's, or null.
|
|
1018
1201
|
* Vitest schedules projects that share a `sequence.groupOrder` (0 unless set) as one
|
|
1019
1202
|
* group, and throws when they resolve to different `maxWorkers` ("Projects … have
|
|
1020
|
-
* different 'maxWorkers' but same 'sequence.groupOrder'", groupSpecs in Vitest
|
|
1203
|
+
* different 'maxWorkers' but same 'sequence.groupOrder'", groupSpecs in Vitest
|
|
1021
1204
|
* 5). The hot runtime's memory plan caps workers (at most four unless the user set the
|
|
1022
1205
|
* count), while a project beside it gets Vitest's default of one fewer than the CPUs,
|
|
1023
1206
|
* so a native project next to a mock or non-React-Native project failed on any machine
|
|
@@ -1046,7 +1229,7 @@ function hotRuntimeOverridden(reason) {
|
|
|
1046
1229
|
/**
|
|
1047
1230
|
* The worker count Vitest would have used had the hot runtime not capped it: the
|
|
1048
1231
|
* user's own value (a count or a percentage of the CPUs), else Vitest's default.
|
|
1049
|
-
* Mirrors Vitest
|
|
1232
|
+
* Mirrors Vitest 5's resolveMaxWorkers and getWorkersCountByPercentage.
|
|
1050
1233
|
*/
|
|
1051
1234
|
function vitestMaxWorkers(userValue, watch, cpus = os.availableParallelism?.() ?? os.cpus().length) {
|
|
1052
1235
|
if (typeof userValue === "number" && userValue > 0) return userValue;
|
|
@@ -1083,7 +1266,7 @@ function printHotMemoryPlan(lines) {
|
|
|
1083
1266
|
/**
|
|
1084
1267
|
* Rebuild the hot memory plan for the worker count Vitest resolved, when it is not the
|
|
1085
1268
|
* count config() planned for. Vitest applies `--maxWorkers` and `VITEST_MAX_WORKERS`
|
|
1086
|
-
* over the `maxWorkers` every config hook returned (resolveConfig in Vitest
|
|
1269
|
+
* over the `maxWorkers` every config hook returned (resolveConfig in Vitest 5;
|
|
1087
1270
|
* Vitest 5 also copies `--maxWorkers` into each project), and config() never sees the
|
|
1088
1271
|
* environment variable: `VITEST_MAX_WORKERS=10` ran ten workers on a heap threshold
|
|
1089
1272
|
* and plan sized for four. The count is the user's explicit choice, so memory
|
|
@@ -1120,15 +1303,168 @@ function applyHotMemoryPlan(memory, plan, projectConfig, diagnostics) {
|
|
|
1120
1303
|
printHotMemoryPlan(memory.formatPlan(plan));
|
|
1121
1304
|
}
|
|
1122
1305
|
}
|
|
1306
|
+
/**
|
|
1307
|
+
* The ownership guard's worker config (native/ownership-ledger.mjs). The mode comes from
|
|
1308
|
+
* the `ownership` option alone, the guard's one switch. Exemptions are real paths, as both
|
|
1309
|
+
* sides of the ledger key files by real path.
|
|
1310
|
+
*
|
|
1311
|
+
* An exemption covering the project root (`path: '.'`) is refused: it would exempt
|
|
1312
|
+
* every file the guard watches, which is turning the guard off, and the guard has no
|
|
1313
|
+
* off switch by design. Name the files or directories that are deliberate.
|
|
1314
|
+
*/
|
|
1315
|
+
function ownershipGuardConfig(options, root) {
|
|
1316
|
+
const option = options?.ownership;
|
|
1317
|
+
const mode = (typeof option === "string" ? option : option?.mode) ?? "warn";
|
|
1318
|
+
const realpathOr = (file) => {
|
|
1319
|
+
try {
|
|
1320
|
+
return fs.realpathSync(file);
|
|
1321
|
+
} catch {
|
|
1322
|
+
return file;
|
|
1323
|
+
}
|
|
1324
|
+
};
|
|
1325
|
+
const realRoot = realpathOr(root);
|
|
1326
|
+
return {
|
|
1327
|
+
mode,
|
|
1328
|
+
allow: (typeof option === "object" && option?.allow ? option.allow : []).map((entry) => {
|
|
1329
|
+
const target = realpathOr(path.resolve(root, entry.path));
|
|
1330
|
+
if (containsPath(target, realRoot)) throw new VitestNativeTypeError("INVALID_OPTION", `"ownership.allow" entry '${entry.path}' covers the whole project (${realRoot}), which would turn the ownership guard off. Name the files or directories whose dual evaluation is deliberate.`);
|
|
1331
|
+
return {
|
|
1332
|
+
path: target,
|
|
1333
|
+
reason: entry.reason
|
|
1334
|
+
};
|
|
1335
|
+
})
|
|
1336
|
+
};
|
|
1337
|
+
}
|
|
1338
|
+
/**
|
|
1339
|
+
* Prints the ownership guard's findings at the end of the run, whatever the reporter:
|
|
1340
|
+
* worker console output is dropped by `silent`, by reporters that print only failures,
|
|
1341
|
+
* and by Vitest 5's agent reporter, and a warning nobody sees is no warning. Each test
|
|
1342
|
+
* file's dual evaluations arrive in its task meta (native/setup.mjs). Also names the
|
|
1343
|
+
* `ownership.allow` entries that exempted nothing during the run.
|
|
1344
|
+
*/
|
|
1345
|
+
var OwnershipSummaryReporter = class {
|
|
1346
|
+
allow;
|
|
1347
|
+
write;
|
|
1348
|
+
found = /* @__PURE__ */ new Map();
|
|
1349
|
+
used = /* @__PURE__ */ new Set();
|
|
1350
|
+
mode = "warn";
|
|
1351
|
+
constructor(allow, write = (text) => process.stderr.write(text)) {
|
|
1352
|
+
this.allow = allow;
|
|
1353
|
+
this.write = write;
|
|
1354
|
+
}
|
|
1355
|
+
onTestRunStart() {
|
|
1356
|
+
this.found.clear();
|
|
1357
|
+
this.used.clear();
|
|
1358
|
+
this.mode = "warn";
|
|
1359
|
+
}
|
|
1360
|
+
add(route, origin, file, test) {
|
|
1361
|
+
const key = `${route}\0${origin}`;
|
|
1362
|
+
let cause = this.found.get(key);
|
|
1363
|
+
if (cause === void 0) {
|
|
1364
|
+
cause = {
|
|
1365
|
+
route,
|
|
1366
|
+
origin,
|
|
1367
|
+
files: /* @__PURE__ */ new Set(),
|
|
1368
|
+
tests: /* @__PURE__ */ new Set()
|
|
1369
|
+
};
|
|
1370
|
+
this.found.set(key, cause);
|
|
1371
|
+
}
|
|
1372
|
+
cause.files.add(file);
|
|
1373
|
+
cause.tests.add(test);
|
|
1374
|
+
}
|
|
1375
|
+
onTestModuleEnd(testModule) {
|
|
1376
|
+
const test = path.relative(process.cwd(), testModule.moduleId).split(path.sep).join("/");
|
|
1377
|
+
const data = testModule.meta()?.[OWNERSHIP_META_KEY];
|
|
1378
|
+
if (!data) {
|
|
1379
|
+
for (const error of testModule.errors?.() ?? []) {
|
|
1380
|
+
const match = /\[vitest-native\] (.+?) was evaluated by both Node and Vite/.exec(error.message ?? "");
|
|
1381
|
+
if (!match) continue;
|
|
1382
|
+
const origin = /origin\s+-> (.+?), which Node loaded through (.+?), and which loaded/.exec(error.message ?? "");
|
|
1383
|
+
const label = origin?.[2] ?? /route\s+-> (.+)/.exec(error.message ?? "")?.[1] ?? "while collecting";
|
|
1384
|
+
const route = Object.entries(OWNERSHIP_ROUTES).find(([, r]) => r.label === label)?.[0] ?? label;
|
|
1385
|
+
this.mode = "error";
|
|
1386
|
+
this.add(route, origin?.[1] ?? match[1], match[1], test);
|
|
1387
|
+
}
|
|
1388
|
+
return;
|
|
1389
|
+
}
|
|
1390
|
+
if (data.mode === "error") this.mode = "error";
|
|
1391
|
+
for (const used of data.allowUsed) this.used.add(used);
|
|
1392
|
+
for (const conflict of data.conflicts) {
|
|
1393
|
+
const cause = conflict.cause ?? {
|
|
1394
|
+
route: conflict.route,
|
|
1395
|
+
file: conflict.file
|
|
1396
|
+
};
|
|
1397
|
+
this.add(cause.route, cause.file, conflict.file, test);
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
onTestRunEnd() {
|
|
1401
|
+
const lines = [];
|
|
1402
|
+
if (this.found.size > 0) {
|
|
1403
|
+
const files = new Set([...this.found.values()].flatMap((cause) => [...cause.files]));
|
|
1404
|
+
const rel = (file) => (path.relative(process.cwd(), file) || file).split(path.sep).join("/");
|
|
1405
|
+
const some = (items) => [...items].slice(0, 3).join(", ") + (items.size > 3 ? `, +${items.size - 3} more` : "");
|
|
1406
|
+
lines.push(`[vitest-native] ownership: ${files.size} file(s) were evaluated by both Node and Vite (${this.mode === "error" ? "failed: ownership 'error'" : "warning; reactNative({ ownership: 'error' }) fails on it"}), from ${this.found.size} cause(s):`);
|
|
1407
|
+
for (const cause of this.found.values()) {
|
|
1408
|
+
const known = OWNERSHIP_ROUTES[cause.route];
|
|
1409
|
+
const first = [...cause.files][0];
|
|
1410
|
+
lines.push(` ${rel(cause.origin)}, loaded by Node through ${known?.label ?? cause.route}: ${cause.files.size} file(s), in ${some(cause.tests)}`, ...cause.files.has(cause.origin) ? [] : [` first: ${rel(first)}`], ...known ? [` fix: ${known.fix}`] : []);
|
|
1411
|
+
}
|
|
1412
|
+
lines.push(` See ${docsUrl("/guide/errors#SOURCE_EVALUATED_TWICE")}.`);
|
|
1413
|
+
}
|
|
1414
|
+
const unused = this.allow().filter((entry) => !this.used.has(entry.path));
|
|
1415
|
+
if (unused.length > 0) lines.push(`[vitest-native] ownership.allow: ${unused.length} entr${unused.length === 1 ? "y" : "ies"} exempted nothing in this run:`, ...unused.map((entry) => ` ${entry.path} (${entry.reason})`), " If the files that needed an entry ran, its dual evaluation is gone: remove it, so it cannot hide a new one. A run of only some files leaves others unexercised.");
|
|
1416
|
+
if (lines.length > 0) this.write(`${lines.join("\n")}\n`);
|
|
1417
|
+
}
|
|
1418
|
+
};
|
|
1419
|
+
/**
|
|
1420
|
+
* The cache-key state without the ownership guard's run-time settings. Workers get the
|
|
1421
|
+
* guard's config in the project context (`ownershipGuard`), whose reference is a hash of
|
|
1422
|
+
* every field: the key takes the context's other fields in place of the reference.
|
|
1423
|
+
*/
|
|
1424
|
+
function withoutOwnershipGuard(options, env, contextOf = (ref) => writtenContexts.get(ref)) {
|
|
1425
|
+
const { ownership: _ownership, ...rest } = options ?? {};
|
|
1426
|
+
const ref = env?.[CONTEXT_ENV];
|
|
1427
|
+
const fields = typeof ref === "string" ? contextOf(ref) : void 0;
|
|
1428
|
+
if (!env || !fields) return {
|
|
1429
|
+
options: options ? rest : options,
|
|
1430
|
+
env
|
|
1431
|
+
};
|
|
1432
|
+
const { ownershipGuard: _guard, ...otherFields } = fields;
|
|
1433
|
+
return {
|
|
1434
|
+
options: options ? rest : options,
|
|
1435
|
+
env: {
|
|
1436
|
+
...env,
|
|
1437
|
+
[CONTEXT_ENV]: otherFields
|
|
1438
|
+
}
|
|
1439
|
+
};
|
|
1440
|
+
}
|
|
1441
|
+
/**
|
|
1442
|
+
* The ownership guard's Vite half (native/ownership-ledger.mjs): a call appended at the
|
|
1443
|
+
* end of the module, run as it finishes evaluating. Appended on lines of its own after
|
|
1444
|
+
* esbuild/oxc (`order: 'post'`), so no code moves and the map is the previous one
|
|
1445
|
+
* (`map: null`). A marker at the top had to be mapped, and it cost both a phantom
|
|
1446
|
+
* covered line 1 in coverage and a high-resolution map per module: +30-40% transform
|
|
1447
|
+
* time on react-native-paper (docs/ownership-guard.md).
|
|
1448
|
+
*/
|
|
1449
|
+
function withOwnershipMarker(code, id) {
|
|
1450
|
+
const marker = viteMarkerFor(id);
|
|
1451
|
+
return marker === null ? void 0 : {
|
|
1452
|
+
code: `${code}\n;${marker}\n`,
|
|
1453
|
+
map: null
|
|
1454
|
+
};
|
|
1455
|
+
}
|
|
1456
|
+
/** The ownership summary of each running Vitest, and the exemption lists it reports on. */
|
|
1457
|
+
const ownershipSummaries = /* @__PURE__ */ new WeakMap();
|
|
1123
1458
|
function reactNative(options) {
|
|
1459
|
+
assertSupportedNode();
|
|
1124
1460
|
let jestMockTransformPresent = true;
|
|
1125
1461
|
const hotSelections = /* @__PURE__ */ new Map();
|
|
1126
1462
|
const nativeRoots = /* @__PURE__ */ new Set();
|
|
1127
1463
|
const contributedSetup = /* @__PURE__ */ new Map();
|
|
1128
1464
|
const presetExportsByRoot = /* @__PURE__ */ new Map();
|
|
1129
1465
|
const cacheKeys = /* @__PURE__ */ new Map();
|
|
1466
|
+
const ownershipAllow = /* @__PURE__ */ new Map();
|
|
1130
1467
|
let warnedMissingJestMockTransform = false;
|
|
1131
|
-
let warnedTsconfigPaths = false;
|
|
1132
1468
|
let hostViteVersion = null;
|
|
1133
1469
|
let hostViteSource = "";
|
|
1134
1470
|
const warnIfJestMockUnhoisted = (code, id) => {
|
|
@@ -1144,12 +1480,17 @@ function reactNative(options) {
|
|
|
1144
1480
|
}
|
|
1145
1481
|
if (options?.mocks && containsFunctions(options.mocks)) throw new VitestNativeError("INVALID_OPTION", "The \"mocks\" option contains function values, which cannot be transferred to Vitest worker processes. Only JSON-serializable values (strings, numbers, booleans, plain objects, arrays) are supported.\n\nFor function-based mock overrides, use vi.mock() in a setup file:\n\n // vitest.setup.ts\n import { vi } from 'vitest';\n vi.mock('react-native', async (importOriginal) => {\n const actual = await importOriginal();\n return { ...actual, Alert: { alert: vi.fn() } };\n });");
|
|
1146
1482
|
let resolved;
|
|
1483
|
+
let viteConfig;
|
|
1484
|
+
let projectJsx;
|
|
1485
|
+
const projectBabels = /* @__PURE__ */ new Map();
|
|
1486
|
+
const projectBabelFor = (root) => root === void 0 ? void 0 : projectBabels.get(path.resolve(root));
|
|
1147
1487
|
const presetModules = /* @__PURE__ */ new Map();
|
|
1488
|
+
const presetNameByModule = /* @__PURE__ */ new Map();
|
|
1489
|
+
let ownJestSetupFiles = [];
|
|
1148
1490
|
const presetExportNames = /* @__PURE__ */ new Map();
|
|
1149
1491
|
let assetPattern;
|
|
1150
1492
|
let realRnPackageJson;
|
|
1151
1493
|
let rnFacadeExports = null;
|
|
1152
|
-
let rnFacadeDeprecated = /* @__PURE__ */ new Set();
|
|
1153
1494
|
let rnFacadeRoot = "";
|
|
1154
1495
|
let nativeOwnership = null;
|
|
1155
1496
|
const assertInlineOwnership = (inline) => {
|
|
@@ -1160,7 +1501,16 @@ function reactNative(options) {
|
|
|
1160
1501
|
throw new VitestNativeError("INLINE_BREAKS_OWNERSHIP", `engine:'native' cannot run because ${selection}. Vitest gives inlining precedence over the engine's Node-ownership rules, so the same React Native package can load once through Vite and again through Node with separate module state. Remove the overlapping inline rule; use reactNative({ transform: [...] }) for Metro-source packages that need compiling.`);
|
|
1161
1502
|
};
|
|
1162
1503
|
let alignRoot = "";
|
|
1504
|
+
const requestedModel = options?.experimental?.ownershipModel;
|
|
1505
|
+
const ownershipModel = requestedModel === "resolver" || requestedModel === "resolution" ? requestedModel : void 0;
|
|
1506
|
+
const pendingResolverInputs = /* @__PURE__ */ new Map();
|
|
1507
|
+
const viteResolvers = /* @__PURE__ */ new Map();
|
|
1508
|
+
const pendingRegistries = /* @__PURE__ */ new Map();
|
|
1509
|
+
const backgroundRegistryRoots = /* @__PURE__ */ new Set();
|
|
1510
|
+
let ownershipReady;
|
|
1511
|
+
const resolverKeys = /* @__PURE__ */ new Map();
|
|
1163
1512
|
const alignedCache = /* @__PURE__ */ new Map();
|
|
1513
|
+
const mayHavePlatformSubpath = (source) => source.startsWith("react-native/") && !source.includes("?") && path.extname(source) === "";
|
|
1164
1514
|
const resolveExtensionless = (source, importer) => {
|
|
1165
1515
|
if (importer && path.isAbsolute(importer) && source.startsWith(".") && !path.extname(source)) {
|
|
1166
1516
|
const cacheKey = `${importer}\0${source}`;
|
|
@@ -1176,6 +1526,24 @@ function reactNative(options) {
|
|
|
1176
1526
|
resolveCache.set(cacheKey, void 0);
|
|
1177
1527
|
}
|
|
1178
1528
|
};
|
|
1529
|
+
const sharedResolution = (source, importer, environmentRoot) => {
|
|
1530
|
+
if (viteResolvers.size === 0) return void 0;
|
|
1531
|
+
const root = environmentRoot ?? alignRoot;
|
|
1532
|
+
let rootKey = resolverKeys.get(root);
|
|
1533
|
+
if (rootKey === void 0) resolverKeys.set(root, rootKey = directoryKey(root));
|
|
1534
|
+
const resolver = viteResolvers.get(rootKey);
|
|
1535
|
+
if (!resolver) throw new VitestNativeError("RESOLVER_INPUTS_MISSING", `experimental.ownershipModel: Vite resolves for the project at ${root}, but the plugin recorded resolver inputs only for ${[...viteResolvers.keys()].join(", ")}. Give each Vitest project its own reactNative() and \`root\`, or report this, with the Vitest config, as a vitest-native bug.`);
|
|
1536
|
+
const from = importer && path.isAbsolute(importer) && !importer.startsWith("\0") ? importer : void 0;
|
|
1537
|
+
const next = resolver.resolve(source, from, (id) => createRequire(from ?? path.join(alignRoot || process.cwd(), "package.json")).resolve(id));
|
|
1538
|
+
if (next === null) return void 0;
|
|
1539
|
+
const key = `${from ?? ""}\0${source}`;
|
|
1540
|
+
if (diagnostics && !shadowed.has(key)) {
|
|
1541
|
+
shadowed.add(key);
|
|
1542
|
+
resolver.shadow(source, from, next, alignedResolution(source, importer) ?? null);
|
|
1543
|
+
}
|
|
1544
|
+
return next;
|
|
1545
|
+
};
|
|
1546
|
+
const shadowed = /* @__PURE__ */ new Set();
|
|
1179
1547
|
const alignedResolution = (source, importer) => {
|
|
1180
1548
|
if (engine !== "native") return void 0;
|
|
1181
1549
|
const from = importer && path.isAbsolute(importer) && !importer.startsWith("\0") ? importer : path.join(alignRoot || process.cwd(), "package.json");
|
|
@@ -1215,9 +1583,12 @@ function reactNative(options) {
|
|
|
1215
1583
|
}
|
|
1216
1584
|
const presetReadyPath = path.resolve(thisDir, "preset-ready.mjs");
|
|
1217
1585
|
const nativeSetupPath = path.resolve(thisDir, "native/setup.mjs");
|
|
1586
|
+
const HANG_SETUP = path.resolve(thisDir, "hang-watch-setup.mjs");
|
|
1218
1587
|
const EXPORT_RECOVERY_ARGV = ["--import", pathToFileURL(path.resolve(thisDir, "native/export-condition-recovery-preload.mjs")).href];
|
|
1219
1588
|
const nativeWorkerPath = path.resolve(thisDir, "native/worker.mjs");
|
|
1220
1589
|
const nativeRunnerPath = path.resolve(thisDir, "native/runner.mjs");
|
|
1590
|
+
const testRunnerPath = path.resolve(thisDir, "native/test-runner.mjs");
|
|
1591
|
+
const userRunnerOf = (config) => config.test?.runner;
|
|
1221
1592
|
const platform = options?.platform ?? "ios";
|
|
1222
1593
|
const diagnostics = options?.diagnostics ?? false;
|
|
1223
1594
|
const requestedEngine = options?.engine ?? "auto";
|
|
@@ -1265,6 +1636,12 @@ function reactNative(options) {
|
|
|
1265
1636
|
root: alignRoot,
|
|
1266
1637
|
platform
|
|
1267
1638
|
};
|
|
1639
|
+
},
|
|
1640
|
+
packageCoveredBy: (spec) => {
|
|
1641
|
+
const preset = presetNameByModule.get(spec);
|
|
1642
|
+
if (preset) return `the ${preset} preset`;
|
|
1643
|
+
const setup = ownJestSetupFiles.find((file) => packageNameOf(file) === spec);
|
|
1644
|
+
return setup ? `its own Jest setup (${setup})` : null;
|
|
1268
1645
|
}
|
|
1269
1646
|
},
|
|
1270
1647
|
async config(userConfig, _env) {
|
|
@@ -1298,7 +1675,7 @@ function reactNative(options) {
|
|
|
1298
1675
|
console.log(`[vitest-native] Metro resolverMainFields=${metro.profile.resolverMainFields.join(",")} and conditions=${metro.profile.conditionNames.join(",")} are observational; module ownership keeps the package-format policy authoritative.`);
|
|
1299
1676
|
}
|
|
1300
1677
|
}
|
|
1301
|
-
const jsxTransform =
|
|
1678
|
+
const jsxTransform = JSX_TRANSFORM;
|
|
1302
1679
|
const decision = detectEngine(requestedEngine, resolvedRoot);
|
|
1303
1680
|
engine = decision.engine;
|
|
1304
1681
|
if (engine === "native" && !decision.nativeAvailable) throw new VitestNativeError("ENGINE_REQUIRES_BABEL", `engine:'native' requires react-native, a React Native Babel preset ('@react-native/babel-preset', or Expo's from SDK 56), and '@babel/core' to resolve from ${resolvedRoot} — missing: ${decision.missing.join(", ")}. React Native and Expo projects ship all three by default. Install what's missing (react-native as a dependency, the toolchain as devDependencies), or set engine:'mock' to run without a React Native install.`);
|
|
@@ -1309,25 +1686,42 @@ function reactNative(options) {
|
|
|
1309
1686
|
diagnostics,
|
|
1310
1687
|
projectRoot: resolvedRoot
|
|
1311
1688
|
};
|
|
1689
|
+
if (userConfig.test?.restoreMocks === true) fields.restoreMocks = true;
|
|
1312
1690
|
const env = {};
|
|
1313
1691
|
const userAlias = userConfig.resolve?.alias;
|
|
1314
1692
|
const requireAliases = serializableAliases(userAlias, resolvedRoot);
|
|
1315
1693
|
const aliasTargets = aliasReachedPaths(userAlias, resolvedRoot);
|
|
1316
1694
|
const userTsconfigPaths = userConfig.resolve?.tsconfigPaths;
|
|
1317
|
-
|
|
1318
|
-
if (userTsconfigPaths === true || expoTsconfigPaths(resolvedRoot, userTsconfigPaths, viteMajorForPaths) === "enable") {
|
|
1695
|
+
if (userTsconfigPaths === true || expoTsconfigPaths(resolvedRoot, userTsconfigPaths)) {
|
|
1319
1696
|
const pathAliases = tsconfigPathAliases(resolvedRoot).entries;
|
|
1320
1697
|
requireAliases.entries.push(...pathAliases);
|
|
1321
1698
|
aliasTargets.push(...pathAliases.map(([, target]) => target).filter((target) => path.isAbsolute(target)));
|
|
1322
1699
|
}
|
|
1323
|
-
if (
|
|
1324
|
-
|
|
1700
|
+
if (!(ownershipModel && engine === "native")) {
|
|
1701
|
+
if (requireAliases.entries.length > 0) fields.requireAliases = requireAliases.entries;
|
|
1702
|
+
if (requireAliases.skipped.length > 0) fields.requireAliasesSkipped = requireAliases.skipped;
|
|
1703
|
+
}
|
|
1704
|
+
if (ownershipModel && engine === "native") {
|
|
1705
|
+
fields.ownershipModel = ownershipModel;
|
|
1706
|
+
const shared = serializeResolutionAliases([...aliasList(userConfig.test?.alias), ...aliasList(userConfig.resolve?.alias)], resolvedRoot);
|
|
1707
|
+
if (shared.skipped.length > 0) throw new VitestNativeTypeError("INVALID_OPTION", `experimental.ownershipModel cannot apply the alias ${shared.skipped.map((find) => `"${find}"`).join(", ")} in Node's loaders (a custom resolver, or a replacement that is not a string). Rewrite it as a string or RegExp alias, or leave the flag off.`);
|
|
1708
|
+
if (userTsconfigPaths === true || expoTsconfigPaths(resolvedRoot, userTsconfigPaths)) shared.entries.push(...tsconfigPathAliases(resolvedRoot).entries.sort((a, b) => b[0].length - a[0].length).map(([find, replacement]) => [find.endsWith("/") ? { prefix: find } : { exact: find }, replacement]));
|
|
1709
|
+
pendingResolverInputs.set(directoryKey(resolvedRoot), {
|
|
1710
|
+
projectRoot: resolvedRoot,
|
|
1711
|
+
platform,
|
|
1712
|
+
...metroOption === true || typeof metroOption === "object" ? { sourceExts } : {},
|
|
1713
|
+
aliases: shared.entries
|
|
1714
|
+
});
|
|
1715
|
+
}
|
|
1325
1716
|
const reactNativeVersion = resolvePackageVersion("react-native", resolvedRoot);
|
|
1326
1717
|
if (reactNativeVersion) fields.reactNativeVersion = reactNativeVersion;
|
|
1327
1718
|
if (engine === "native") {
|
|
1328
1719
|
fields.knownNativeModules = knownNativeModulesFor(resolvedRoot);
|
|
1329
1720
|
fields.nativeModuleSpecs = nativeModuleSpecsFor(resolvedRoot);
|
|
1330
1721
|
if (options?.nativeModules === "permissive") fields.nativeModules = "permissive";
|
|
1722
|
+
const guard = ownershipGuardConfig(options, resolvedRoot);
|
|
1723
|
+
ownershipAllow.set(resolvedRoot, guard.allow);
|
|
1724
|
+
fields.ownershipGuard = guard;
|
|
1331
1725
|
fields.expoSdks = [SUPPORTED_EXPO_SDKS.minimum, SUPPORTED_EXPO_SDKS.maximum];
|
|
1332
1726
|
}
|
|
1333
1727
|
fields.assetExts = assetExtList;
|
|
@@ -1336,12 +1730,23 @@ function reactNative(options) {
|
|
|
1336
1730
|
if (hotRuntimeRequested && hotRecycle.esmGeneration === false) fields.hotEsmGeneration = false;
|
|
1337
1731
|
const userDeps = userConfig.test?.deps;
|
|
1338
1732
|
if (hotRuntimeRequested && userDeps?.interopDefault === false) fields.hotReleaseGenerations = false;
|
|
1733
|
+
if (engine !== "native" && options?.experimental?.nodeMocks === true) console.warn("[vitest-native] experimental.nodeMocks applies to engine:'native' only; the mock engine has no Node-loaded packages for a vi.mock to reach, so it is ignored.");
|
|
1339
1734
|
if (engine === "native") {
|
|
1340
1735
|
if (options?.mocks && Object.keys(options.mocks).length > 0) throw new VitestNativeError("MOCKS_REQUIRE_MOCK_ENGINE", "The \"mocks\" option is only supported by engine:'mock'. The native engine runs the real react-native module and cannot safely merge arbitrary exports into it. Use vi.mock() in a setup file, mockNativeModule() for native modules, or set engine:'mock'.");
|
|
1341
1736
|
const disabledNative = disabledPresetNames(options?.presets);
|
|
1342
1737
|
const selection = selectPresets(options?.presets, resolvedRoot);
|
|
1343
1738
|
const nativePresetNames = selection.listed ? selection.listed.map((p) => p.name) : autoDetectPresetNames(resolvedRoot, diagnostics).filter((n) => !disabledNative.has(n) && autoDetectedPresetApplies(n, "native", options?.presets));
|
|
1344
1739
|
if (nativePresetNames.length > 0) fields.presetNames = nativePresetNames;
|
|
1740
|
+
if (options?.experimental?.nodeMocks === true || ownershipModel === "resolution") fields.nodeMocks = true;
|
|
1741
|
+
let ownJestSupport = [];
|
|
1742
|
+
if (!selection.listed) {
|
|
1743
|
+
const librarySetupFiles = autoDetectPresetNames(resolvedRoot, diagnostics).filter((n) => !disabledNative.has(n) && !nativePresetNames.includes(n)).map((n) => LIBRARY_SETUP_FILES[n]).filter((file) => typeof file === "string");
|
|
1744
|
+
if (librarySetupFiles.length > 0) fields.librarySetupFiles = librarySetupFiles;
|
|
1745
|
+
ownJestSupport = librarySetupFiles.map((request) => packageNameOf(request));
|
|
1746
|
+
ownJestSetupFiles = librarySetupFiles;
|
|
1747
|
+
const pending = pendingResolverInputs.get(directoryKey(resolvedRoot));
|
|
1748
|
+
if (pending && ownJestSupport.length > 0) pending.ownJestSupport = ownJestSupport;
|
|
1749
|
+
}
|
|
1345
1750
|
if (selection.modulePaths.length > 0) fields.presetModules = selection.modulePaths;
|
|
1346
1751
|
if (selection.listed) {
|
|
1347
1752
|
const presetConfig = {};
|
|
@@ -1353,6 +1758,11 @@ function reactNative(options) {
|
|
|
1353
1758
|
const userInlinesEverything = userInline === true;
|
|
1354
1759
|
const dirOf = memoizePackageDirOf();
|
|
1355
1760
|
const ecosystem = detectEcosystemPackages([resolvedRoot, ...includeRoots], transformPkgs, includeRoots, neverTransform, nativePresetNames, memoizePackageDirOf(dependencyDirOf), {
|
|
1761
|
+
compileReactNativeFieldSource: ownershipModel && engine === "native" ? {
|
|
1762
|
+
platform,
|
|
1763
|
+
sourceExts,
|
|
1764
|
+
resolvedToMain: ownJestSupport
|
|
1765
|
+
} : void 0,
|
|
1356
1766
|
reachedPaths: aliasTargets,
|
|
1357
1767
|
onReachedUndeclared: (name, dir) => {
|
|
1358
1768
|
if (diagnostics) console.log(`[vitest-native] ${name} (${dir}) is reached through an alias (resolve.alias or tsconfig paths) but is not a dependency of this package. Its installed React Native dependencies are compiled as if it were declared; declaring it makes the dependency explicit.`);
|
|
@@ -1369,6 +1779,7 @@ function reactNative(options) {
|
|
|
1369
1779
|
projectDirs,
|
|
1370
1780
|
entryFiles: setupEntryFiles(userConfig.test?.setupFiles, resolvedRoot),
|
|
1371
1781
|
serverDepsInlineAll: userInlinesEverything,
|
|
1782
|
+
installedTypeScriptToNode: fields.nodeMocks === true,
|
|
1372
1783
|
packageDirOf: dirOf
|
|
1373
1784
|
});
|
|
1374
1785
|
assertInlineOwnership(userInline);
|
|
@@ -1415,15 +1826,29 @@ function reactNative(options) {
|
|
|
1415
1826
|
};
|
|
1416
1827
|
}
|
|
1417
1828
|
}
|
|
1418
|
-
const
|
|
1829
|
+
const registryOptions = {
|
|
1419
1830
|
projectRoot: resolvedRoot,
|
|
1420
1831
|
platform,
|
|
1421
1832
|
reactNativeVersion: reactNativeVersion ?? "0.0.0",
|
|
1422
1833
|
assetExts: assetExtList,
|
|
1423
1834
|
sourceExts,
|
|
1424
|
-
diagnostics
|
|
1425
|
-
|
|
1426
|
-
|
|
1835
|
+
diagnostics,
|
|
1836
|
+
libraryEntries: libraryRegistryEntries(resolvedRoot, fields.presetNames ?? [])
|
|
1837
|
+
};
|
|
1838
|
+
const useRegistries = (registries) => {
|
|
1839
|
+
if (registries?.registry) fields.registry = registries.registry;
|
|
1840
|
+
if (registries?.libraryRegistry) fields.libraryRegistry = registries.libraryRegistry;
|
|
1841
|
+
};
|
|
1842
|
+
if (fields.ownershipModel) pendingRegistries.set(directoryKey(resolvedRoot), registryOptions);
|
|
1843
|
+
else if (hotMemory !== void 0 || options?.registryBuild === "wait" || await loadRegistryProcess().then((rp) => rp.registryWaitForced() || rp.isCI())) useRegistries(await buildRegistryFor(registryOptions));
|
|
1844
|
+
else {
|
|
1845
|
+
const started = await startRegistryFor(registryOptions);
|
|
1846
|
+
if (started.wait) useRegistries(await buildRegistryFor(registryOptions));
|
|
1847
|
+
else if (started.pending) {
|
|
1848
|
+
fields.registryPending = started.pending;
|
|
1849
|
+
backgroundRegistryRoots.add(directoryKey(resolvedRoot));
|
|
1850
|
+
} else useRegistries(started);
|
|
1851
|
+
}
|
|
1427
1852
|
let hot;
|
|
1428
1853
|
let hotPoolOptions;
|
|
1429
1854
|
if (hotMemory) {
|
|
@@ -1443,10 +1868,11 @@ function reactNative(options) {
|
|
|
1443
1868
|
maxWorkers: hotMemory.allowUnboundedMemory ? void 0 : hotMemory.plan.maxWorkers
|
|
1444
1869
|
};
|
|
1445
1870
|
}
|
|
1446
|
-
printEngineBanner(engine, platform, resolvedRoot, [...nativePresetNames, ...selection.moduleSpecs], hot !== void 0);
|
|
1871
|
+
printEngineBanner(engine, platform, resolvedRoot, [...nativePresetNames, ...selection.moduleSpecs], hot !== void 0, ownershipModel, fields.nodeMocks === true);
|
|
1447
1872
|
if (hot) hotSelections.set(vitestRootOf(userConfig), {
|
|
1448
1873
|
pool: hot.pool,
|
|
1449
1874
|
userPool,
|
|
1875
|
+
userRunner: userRunnerOf(userConfig),
|
|
1450
1876
|
userMaxWorkers: userTest?.maxWorkers,
|
|
1451
1877
|
singleWorkerAccepted: hotMemory?.allowUnboundedMemory === true,
|
|
1452
1878
|
memory: hotMemory && hotPoolOptions && !hotMemory.allowUnboundedMemory ? {
|
|
@@ -1462,8 +1888,10 @@ function reactNative(options) {
|
|
|
1462
1888
|
else hotSelections.delete(vitestRootOf(userConfig));
|
|
1463
1889
|
const nativeConfig = nativeEngineConfig(nativeSetupPath, fields, extensions, transformPkgs, hot, jsxTransform, userPool, ecosystem, resolvedRoot, userInlinesEverything, projectDirs, nativeOwnership);
|
|
1464
1890
|
nativeConfig.test.env = withProjectContext(fields, env, resolvedRoot);
|
|
1891
|
+
if (!hot && userRunnerOf(userConfig) == null) nativeConfig.test.runner = testRunnerPath;
|
|
1465
1892
|
return asCompatibleViteConfig(nativeConfig);
|
|
1466
1893
|
}
|
|
1894
|
+
if (options?.ownership !== void 0) console.warn(`[vitest-native] 'ownership' only applies to engine:'native' (resolved engine: '${engine}'); ignoring. The mock engine has one module system.`);
|
|
1467
1895
|
if (hotRuntimeRequested && hotRuntimeExplicit) console.warn(`[vitest-native] 'hotRuntime' only applies to engine:'native' (resolved engine: '${engine}'); ignoring.`);
|
|
1468
1896
|
if (options?.mocks && Object.keys(options.mocks).length > 0) fields.mocks = options.mocks;
|
|
1469
1897
|
const selection = selectPresets(options?.presets, resolvedRoot);
|
|
@@ -1503,11 +1931,14 @@ function reactNative(options) {
|
|
|
1503
1931
|
},
|
|
1504
1932
|
test: {
|
|
1505
1933
|
setupFiles: [setupFilePath, presetReadyPath],
|
|
1506
|
-
env: withProjectContext(fields, env, resolvedRoot)
|
|
1934
|
+
env: withProjectContext(fields, env, resolvedRoot),
|
|
1935
|
+
...userRunnerOf(userConfig) == null ? { runner: testRunnerPath } : {}
|
|
1507
1936
|
}
|
|
1508
1937
|
});
|
|
1509
1938
|
},
|
|
1510
1939
|
async configResolved(config) {
|
|
1940
|
+
viteConfig = config;
|
|
1941
|
+
projectJsx = projectJsxOptions(config.oxc);
|
|
1511
1942
|
assetModules ??= await loadAssetModules();
|
|
1512
1943
|
jestMockTransformPresent = (config.plugins ?? []).some((plugin) => plugin?.name === "vitest-native:jest-mock-hoist");
|
|
1513
1944
|
const finalInline = config.test?.server?.deps?.inline;
|
|
@@ -1525,26 +1956,27 @@ function reactNative(options) {
|
|
|
1525
1956
|
]);
|
|
1526
1957
|
if (duplicateReact) console.warn(`[vitest-native] Two copies of React are resolvable: your project loads one, and '${duplicateReact.consumer}' loads another.\n project: ${duplicateReact.projectCopy}\n ${duplicateReact.consumer}: ${duplicateReact.otherCopy}\nReact throws "Cannot read properties of null (reading 'use')" when hooks run through a second copy, which React Native Testing Library reports as a failure to detect host component names. Install a single React version at the project root (npm dedupe, or match the version '${duplicateReact.consumer}' expects).`);
|
|
1527
1958
|
const peerErrors = [];
|
|
1528
|
-
for (const { name, minimum, maximumMajor,
|
|
1959
|
+
for (const { name, minimum, maximumMajor, optional } of PEER_REQUIREMENTS) {
|
|
1529
1960
|
if (optional) continue;
|
|
1530
1961
|
if (name === "vitest") {
|
|
1531
1962
|
const found = resolvePackageVersion("vitest", config.root);
|
|
1532
|
-
if (found === null || !(majorOf(found) <
|
|
1963
|
+
if (found === null || !(majorOf(found) < 5)) continue;
|
|
1533
1964
|
}
|
|
1534
|
-
const error = validatePeerDependency(name, minimum, config.root, maximumMajor,
|
|
1965
|
+
const error = validatePeerDependency(name, minimum, config.root, maximumMajor, name === "vite" ? hostViteVersion : void 0, name === "vite" ? hostViteSource : void 0);
|
|
1535
1966
|
if (error) peerErrors.push(error);
|
|
1536
1967
|
}
|
|
1968
|
+
const reactNativeVersion = engine === "native" ? resolvePackageVersion("react-native", config.root) : null;
|
|
1969
|
+
if (reactNativeVersion && isBelowSupportedReactNative(reactNativeVersion)) peerErrors.push(unsupportedReactNativeMessage(reactNativeVersion));
|
|
1537
1970
|
if (peerErrors.length > 0) throw new VitestNativeError("UNSUPPORTED_PEER", `Unsupported peer dependencies:\n- ${peerErrors.join("\n- ")}`);
|
|
1538
|
-
for (const { name, minimum, maximumMajor,
|
|
1971
|
+
for (const { name, minimum, maximumMajor, optional } of PEER_REQUIREMENTS) {
|
|
1539
1972
|
if (!optional) continue;
|
|
1540
|
-
const error = validatePeerDependency(name, minimum, config.root, maximumMajor
|
|
1973
|
+
const error = validatePeerDependency(name, minimum, config.root, maximumMajor);
|
|
1541
1974
|
if (error && !error.includes("not found")) console.warn(`[vitest-native] ${error}`);
|
|
1542
1975
|
}
|
|
1543
1976
|
const expoVersion = installedExpoVersion(config.root);
|
|
1544
|
-
const
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
console.warn(`[vitest-native] ${expoProblem}`);
|
|
1977
|
+
for (const problem of [reactNativeVersion && unsupportedReactNativeMessage(reactNativeVersion), expoVersion && unsupportedExpoSdkMessage(expoVersion)]) if (problem && !warnedExpoProblems.has(problem)) {
|
|
1978
|
+
warnedExpoProblems.add(problem);
|
|
1979
|
+
console.warn(`[vitest-native] ${problem}`);
|
|
1548
1980
|
}
|
|
1549
1981
|
resolved = await resolveOptions({
|
|
1550
1982
|
...options,
|
|
@@ -1563,26 +1995,39 @@ function reactNative(options) {
|
|
|
1563
1995
|
for (const [moduleName, presetModule] of Object.entries(preset.modules)) {
|
|
1564
1996
|
const names = presetModule.exportsFor ? presetModule.exportsFor({
|
|
1565
1997
|
projectRoot: config.root,
|
|
1566
|
-
platform: resolved.platform
|
|
1998
|
+
platform: resolved.platform,
|
|
1999
|
+
engine
|
|
1567
2000
|
}) : presetModule.exports;
|
|
1568
2001
|
exportsByModule[moduleName] = names;
|
|
1569
2002
|
if (names === null) continue;
|
|
1570
2003
|
shadows = true;
|
|
1571
2004
|
presetModules.set(moduleName, presetModule.factory);
|
|
2005
|
+
presetNameByModule.set(moduleName, preset.name);
|
|
1572
2006
|
presetExportNames.set(moduleName, names);
|
|
1573
2007
|
}
|
|
1574
2008
|
const readsInstalled = Object.values(preset.modules).some((m) => m.exportsFor);
|
|
1575
2009
|
if (!shadows && readsInstalled && Array.isArray(options?.presets)) throw new VitestNativeError("PRESET_UNAVAILABLE", `The ${preset.name} preset is listed in \`presets\`, and none of its packages (${Object.keys(preset.modules).join(", ")}) resolves from the project root, ${config.root}. Set the Vitest project's \`root\` to the package that depends on them.`);
|
|
1576
2010
|
}
|
|
1577
2011
|
presetExportsByRoot.set(vitestRootOf(config), exportsByModule);
|
|
2012
|
+
const babelRoute = createProjectBabel(config.root, options?.projectBabel ?? "auto", {
|
|
2013
|
+
active: resolved.presets.map((preset) => preset.name),
|
|
2014
|
+
hasExpo: installedManifest(config.root, "expo") !== null,
|
|
2015
|
+
platform: resolved.platform,
|
|
2016
|
+
onCompile: diagnostics ? (file, reasons) => console.log(`[vitest-native] projectBabel: ${file} (${reasons.join(", ")})`) : void 0
|
|
2017
|
+
}, (reasons) => console.log(`[vitest-native] projectBabel: project source that needs it compiles with the project's Babel config, for ${reasons.join(", ")}. Set projectBabel: 'never' to compile it with Oxc only.`));
|
|
2018
|
+
if (babelRoute) projectBabels.set(path.resolve(config.root), babelRoute);
|
|
2019
|
+
else projectBabels.delete(path.resolve(config.root));
|
|
2020
|
+
if (!babelRoute) {
|
|
2021
|
+
const notice = missingBabelCoreNotice(config.root, options?.projectBabel ?? "auto");
|
|
2022
|
+
if (notice) console.warn(notice);
|
|
2023
|
+
}
|
|
2024
|
+
babelRoute?.announceRoot();
|
|
1578
2025
|
if (engine === "native") {
|
|
1579
2026
|
rnFacadeRoot = config.root;
|
|
1580
2027
|
try {
|
|
1581
2028
|
const indexPath = createRequire(path.join(config.root, "package.json")).resolve("react-native");
|
|
1582
|
-
const
|
|
1583
|
-
const names = parseReactNativeExports(indexSource);
|
|
2029
|
+
const names = parseReactNativeExports(fs.readFileSync(indexPath, "utf8"));
|
|
1584
2030
|
rnFacadeExports = names.length > 0 ? names : null;
|
|
1585
|
-
rnFacadeDeprecated = new Set(parseDeprecatedReactNativeExports(indexSource));
|
|
1586
2031
|
} catch {
|
|
1587
2032
|
rnFacadeExports = null;
|
|
1588
2033
|
}
|
|
@@ -1590,14 +2035,36 @@ function reactNative(options) {
|
|
|
1590
2035
|
const escaped = resolved.assetExts.map((e) => e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
|
1591
2036
|
assetPattern = new RegExp(`\\.(${escaped.join("|")})$`, "i");
|
|
1592
2037
|
},
|
|
2038
|
+
configureServer(server) {
|
|
2039
|
+
if (!ownershipModel) return;
|
|
2040
|
+
const forget = () => {
|
|
2041
|
+
for (const resolver of viteResolvers.values()) resolver.clear();
|
|
2042
|
+
};
|
|
2043
|
+
server.watcher.on("add", forget);
|
|
2044
|
+
server.watcher.on("unlink", forget);
|
|
2045
|
+
server.watcher.on("addDir", forget);
|
|
2046
|
+
server.watcher.on("unlinkDir", forget);
|
|
2047
|
+
},
|
|
1593
2048
|
resolveId(source, importer) {
|
|
1594
2049
|
if (engine === "native") {
|
|
1595
2050
|
if (source === "react-native" && rnFacadeExports !== null) return "\0virtual:rn-facade";
|
|
1596
2051
|
const presetHit = resolvePresetId(source);
|
|
1597
2052
|
if (presetHit) return presetHit;
|
|
1598
|
-
const resolveReal = () => resolveExtensionless(source, importer) ?? alignedResolution(source, importer);
|
|
2053
|
+
const resolveReal = () => resolveExtensionless(source, importer) ?? sharedResolution(source, importer, this.environment?.config?.root) ?? alignedResolution(source, importer);
|
|
1599
2054
|
const entryOf = assetPattern ? unexportedPresetSubpath(source) : null;
|
|
1600
|
-
if (entryOf === null)
|
|
2055
|
+
if (entryOf === null) {
|
|
2056
|
+
const real = resolveReal();
|
|
2057
|
+
if (real !== void 0 || !mayHavePlatformSubpath(source)) return real;
|
|
2058
|
+
return this.resolve(source, importer, { skipSelf: true }).then((hit) => {
|
|
2059
|
+
if (!hit || hit.external) return hit;
|
|
2060
|
+
const file = stripFsPrefix(hit.id.split("?")[0]);
|
|
2061
|
+
const variant = platformSubpathFile(source, file, platform, sourceExts);
|
|
2062
|
+
return variant === null ? hit : {
|
|
2063
|
+
...hit,
|
|
2064
|
+
id: variant
|
|
2065
|
+
};
|
|
2066
|
+
});
|
|
2067
|
+
}
|
|
1601
2068
|
return this.resolve(source, importer, { skipSelf: true }).then((hit) => hit && isPackageEntryFile(entryOf, stripFsPrefix(hit.id.split("?")[0]), importer?.split("?")[0]) ? `\0virtual:preset:${entryOf}` : resolveReal());
|
|
1602
2069
|
}
|
|
1603
2070
|
if (source === "react-native") return "\0virtual:react-native";
|
|
@@ -1611,23 +2078,25 @@ function reactNative(options) {
|
|
|
1611
2078
|
if (extensionless !== void 0) return extensionless;
|
|
1612
2079
|
},
|
|
1613
2080
|
load(id) {
|
|
2081
|
+
const chain = this.environment?.pluginContainer;
|
|
2082
|
+
const jsx = () => loadProjectJsx(id, projectJsx, viteConfig, chain, diagnostics ? console.log : void 0);
|
|
2083
|
+
const projectBabel = projectBabelFor(this.environment?.config?.root);
|
|
2084
|
+
if (projectBabel && isProjectSourceFile(id)) return projectBabel.load(id, chain).then((compiled) => compiled == null && projectJsx && isProjectJsFile(id) ? jsx() : compiled);
|
|
2085
|
+
if (projectJsx && isProjectJsFile(id)) return jsx();
|
|
1614
2086
|
if (id === "\0virtual:rn-facade" && rnFacadeExports !== null) {
|
|
1615
2087
|
const cached = virtualCodeCache.get(id);
|
|
1616
2088
|
if (cached) return cached;
|
|
1617
2089
|
const code = [
|
|
1618
2090
|
`import { createRequire } from "node:module";`,
|
|
1619
2091
|
`const _rn = createRequire(${JSON.stringify(path.join(rnFacadeRoot, "package.json"))})("react-native");`,
|
|
1620
|
-
...rnFacadeExports.filter((n) => !rnFacadeDeprecated.has(n)).map((n) => `export const ${n} = _rn[${JSON.stringify(n)}];`),
|
|
1621
2092
|
`export default _rn;`,
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
`}`
|
|
1630
|
-
] : []
|
|
2093
|
+
`for (const name of ${JSON.stringify(rnFacadeExports)}) {`,
|
|
2094
|
+
` Object.defineProperty(__vite_ssr_exports__, name, {`,
|
|
2095
|
+
` enumerable: true,`,
|
|
2096
|
+
` configurable: true,`,
|
|
2097
|
+
` get: () => _rn[name],`,
|
|
2098
|
+
` });`,
|
|
2099
|
+
`}`
|
|
1631
2100
|
].join("\n");
|
|
1632
2101
|
virtualCodeCache.set(id, code);
|
|
1633
2102
|
return code;
|
|
@@ -1699,7 +2168,7 @@ function reactNative(options) {
|
|
|
1699
2168
|
if (engine === "native") {
|
|
1700
2169
|
if (!nativeOwnership) return void 0;
|
|
1701
2170
|
const conflict = findNativeOwnershipConflict(nativeOwnership, id, "vite");
|
|
1702
|
-
if (!conflict) return
|
|
2171
|
+
if (!conflict) return withOwnershipMarker(code, id);
|
|
1703
2172
|
throw new VitestNativeError("MODULE_OWNER_CONFLICT", `Vite attempted to transform '${id}', but the native ownership policy assigns that file to Node (${conflict.decision.reason}). Evaluating it in Vite would create a second module instance with separate state. Remove the inline/noExternal rule that claimed it; Metro-source packages belong in reactNative({ transform: [...] }).`);
|
|
1704
2173
|
}
|
|
1705
2174
|
if (!RN_ECOSYSTEM_PATH.test(id) || !id.endsWith(".js")) return void 0;
|
|
@@ -1716,17 +2185,41 @@ function reactNative(options) {
|
|
|
1716
2185
|
}
|
|
1717
2186
|
}
|
|
1718
2187
|
};
|
|
1719
|
-
function configureProject({ vitest, project, defineCacheKeyGenerator
|
|
2188
|
+
function configureProject({ vitest, project, defineCacheKeyGenerator }) {
|
|
1720
2189
|
const projectConfig = project.config;
|
|
1721
2190
|
const root = projectConfig.root ? path.resolve(projectConfig.root) : process.cwd();
|
|
1722
2191
|
const coverage = engine === "native" && useNativeCoverageProvider(vitest.config?.coverage);
|
|
2192
|
+
if (ownershipAllow.size > 0) {
|
|
2193
|
+
let summary = ownershipSummaries.get(vitest);
|
|
2194
|
+
if (!summary) {
|
|
2195
|
+
const sources = /* @__PURE__ */ new Set();
|
|
2196
|
+
const reporter = new OwnershipSummaryReporter(() => [...sources].flatMap((source) => [...source.values()].flat()));
|
|
2197
|
+
summary = { sources };
|
|
2198
|
+
ownershipSummaries.set(vitest, summary);
|
|
2199
|
+
if (Array.isArray(vitest.reporters) && vitest.reporters.length > 0) vitest.reporters.push(reporter);
|
|
2200
|
+
else if (Array.isArray(vitest.config?.reporters)) vitest.config.reporters.push(reporter);
|
|
2201
|
+
}
|
|
2202
|
+
summary.sources.add(ownershipAllow);
|
|
2203
|
+
}
|
|
1723
2204
|
if (typeof vitest.version === "string") {
|
|
1724
2205
|
const vitestPeer = PEER_REQUIREMENTS.find((peer) => peer.name === "vitest");
|
|
1725
|
-
const error = vitestPeer && validatePeerDependency("vitest", vitestPeer.minimum, root, vitestPeer.maximumMajor,
|
|
2206
|
+
const error = vitestPeer && validatePeerDependency("vitest", vitestPeer.minimum, root, vitestPeer.maximumMajor, vitest.version);
|
|
1726
2207
|
if (error) throw new VitestNativeError("UNSUPPORTED_PEER", `Unsupported peer dependencies:\n- ${error}`);
|
|
1727
2208
|
}
|
|
2209
|
+
if (backgroundRegistryRoots.has(directoryKey(root)) && !registrySettlers.has(vitest)) {
|
|
2210
|
+
registrySettlers.add(vitest);
|
|
2211
|
+
const closable = vitest;
|
|
2212
|
+
let lastRunReason;
|
|
2213
|
+
closable.config?.reporters?.push({ onTestRunEnd(_modules, _errors, reason) {
|
|
2214
|
+
lastRunReason = reason;
|
|
2215
|
+
} });
|
|
2216
|
+
const budgetMs = (closable.config?.teardownTimeout ?? 1e4) / 2;
|
|
2217
|
+
closable.onClose?.(async () => {
|
|
2218
|
+
await (await loadRegistryProcess()).settleRegistryBuilds(budgetMs, { cancelled: lastRunReason === "interrupted" });
|
|
2219
|
+
});
|
|
2220
|
+
}
|
|
1728
2221
|
const cacheKey = cacheKeys.get(root);
|
|
1729
|
-
if (cacheKey)
|
|
2222
|
+
if (cacheKey) defineCacheKeyGenerator?.((context) => cacheKey + (context?.id ? projectBabelFor(root)?.cacheKey(context.id, context.sourceCode) ?? "" : ""));
|
|
1730
2223
|
const setupFile = contributedSetup.get(root);
|
|
1731
2224
|
if (setupFile && !hasSetupFile(projectConfig.setupFiles, setupFile)) throw new VitestNativeError("SHARED_VITE_SERVER", `A Vitest project under ${root} shares a Vite server without vitest-native's test config, so React Native's setup would not run. Give the project a \`root\`, or set \`test.sharedViteServer: false\` in the top-level Vitest config.`);
|
|
1732
2225
|
const presetExports = presetExportsByRoot.get(root);
|
|
@@ -1738,14 +2231,52 @@ function reactNative(options) {
|
|
|
1738
2231
|
...presetExports ? { presetExports } : {},
|
|
1739
2232
|
...coverage ? { sourceMaps: true } : {}
|
|
1740
2233
|
};
|
|
1741
|
-
const
|
|
1742
|
-
|
|
1743
|
-
const
|
|
1744
|
-
if (
|
|
1745
|
-
|
|
1746
|
-
|
|
2234
|
+
const pending = pendingResolverInputs.get(directoryKey(root));
|
|
2235
|
+
if (!pending && pendingResolverInputs.size > 0) throw new VitestNativeError("RESOLVER_INPUTS_MISSING", `experimental.ownershipModel: the Vitest project at ${root} has no resolver inputs; this reactNative() recorded them for ${[...pendingResolverInputs.keys()].join(", ")}. Give each Vitest project its own reactNative() and \`root\`, or report this, with the Vitest config, as a vitest-native bug.`);
|
|
2236
|
+
const resolverInputs = pending ? finishResolverInputs(pending, project) : void 0;
|
|
2237
|
+
if (resolverInputs) {
|
|
2238
|
+
changes.resolverInputs = resolverInputs;
|
|
2239
|
+
changes.resolverInputsHash = resolverInputsHash(resolverInputs);
|
|
2240
|
+
checkResolverInputs(resolverInputs, changes.resolverInputsHash, "Vite");
|
|
2241
|
+
}
|
|
2242
|
+
if (resolverInputs) {
|
|
2243
|
+
let shadowFile = null;
|
|
2244
|
+
if (diagnostics) {
|
|
2245
|
+
shadowFile = ownershipShadowFile(contextRef, changes.resolverInputsHash);
|
|
2246
|
+
fs.mkdirSync(path.dirname(shadowFile), { recursive: true });
|
|
2247
|
+
fs.writeFileSync(shadowFile, "");
|
|
2248
|
+
console.error(`[vitest-native] experimental.ownershipModel shadow: ${shadowFile}`);
|
|
2249
|
+
}
|
|
2250
|
+
viteResolvers.set(directoryKey(root), createSharedResolver(resolverInputs, {
|
|
2251
|
+
realm: "vite",
|
|
2252
|
+
shadowFile,
|
|
2253
|
+
viteAliasesApplied: true
|
|
2254
|
+
}));
|
|
2255
|
+
}
|
|
2256
|
+
const publish = (amended) => {
|
|
2257
|
+
const ref = Object.keys(amended).length > 0 ? amendProjectContext(contextRef, amended, root) : contextRef;
|
|
2258
|
+
projectConfig.env[CONTEXT_ENV] = ref;
|
|
2259
|
+
const fields = writtenContexts.get(ref);
|
|
2260
|
+
if (fields) vitest.onTestsRerun?.(() => {
|
|
2261
|
+
projectConfig.env[CONTEXT_ENV] = ensureProjectContext(projectConfig.env[CONTEXT_ENV] ?? ref, fields);
|
|
2262
|
+
});
|
|
2263
|
+
};
|
|
2264
|
+
const registryOptions = resolverInputs ? pendingRegistries.get(directoryKey(root)) : void 0;
|
|
2265
|
+
if (registryOptions) ownershipReady = buildRegistryFor({
|
|
2266
|
+
...registryOptions,
|
|
2267
|
+
resolverInputs
|
|
2268
|
+
}).then((registries) => publish(registries ? {
|
|
2269
|
+
...changes,
|
|
2270
|
+
registry: registries.registry,
|
|
2271
|
+
...registries.libraryRegistry ? { libraryRegistry: registries.libraryRegistry } : {}
|
|
2272
|
+
} : changes));
|
|
2273
|
+
else publish(changes);
|
|
2274
|
+
if (ownershipModel === "resolution" && resolverInputs) {
|
|
2275
|
+
const bridge = startRequireBridge(project, vitest);
|
|
2276
|
+
ownershipReady = Promise.all([ownershipReady, bridge]).then(() => void 0);
|
|
2277
|
+
}
|
|
1747
2278
|
}
|
|
1748
|
-
const cli = vitest.
|
|
2279
|
+
const cli = vitest.config?.cliOptions ?? {};
|
|
1749
2280
|
if (nativeRoots.has(root) && isVmPool(cli.pool)) throw vmPoolUnsupported(cli.pool);
|
|
1750
2281
|
const pool = cli.pool ?? projectConfig.pool;
|
|
1751
2282
|
if (isVmPool(pool) && PRESET_MODULES.skia.some((name) => presetExports?.[name])) throw new VitestNativeError("UNSUPPORTED_POOL", `The skia preset cannot run on the '${pool}' pool: Skia's test mock loads react-native through Node's require, which a VM pool's context does not route to the React Native mock. Use 'threads' (the default) or 'forks', or turn the preset off: reactNative({ presets: { skia: false } }).`);
|
|
@@ -1769,12 +2300,54 @@ function reactNative(options) {
|
|
|
1769
2300
|
if (!hotRuntimeAuto) throw hotRuntimeOverridden(reason);
|
|
1770
2301
|
projectConfig.pool = cli.pool ?? selection.userPool ?? "threads";
|
|
1771
2302
|
projectConfig.isolate = cli.isolate ?? true;
|
|
1772
|
-
projectConfig.runner =
|
|
2303
|
+
projectConfig.runner = selection.userRunner ?? testRunnerPath;
|
|
1773
2304
|
if (cli.maxWorkers === void 0 && !process.env.VITEST_MAX_WORKERS) projectConfig.maxWorkers = projectConfig.fileParallelism === false ? 1 : selection.userMaxWorkers === void 0 && vitest.config !== projectConfig && typeof vitest.config?.maxWorkers === "number" && vitestRootOf(vitest.config) !== root ? vitest.config.maxWorkers : vitestMaxWorkers(selection.userMaxWorkers, vitest.config?.watch === true);
|
|
1774
2305
|
if (projectConfig.env) delete projectConfig.env.VITEST_NATIVE_MEMORY_PLAN;
|
|
1775
2306
|
hotSelections.delete(root);
|
|
1776
2307
|
console.error(`[vitest-native] hot runtime off: ${reason}; Vitest's settings apply.`);
|
|
1777
2308
|
}
|
|
2309
|
+
function watchForHangs(context, hotActive) {
|
|
2310
|
+
const config = context.vitest.config;
|
|
2311
|
+
if (!config?.reporters) return;
|
|
2312
|
+
const projectConfig = context.project?.config;
|
|
2313
|
+
const configs = [
|
|
2314
|
+
config,
|
|
2315
|
+
projectConfig,
|
|
2316
|
+
...(context.vitest.projects ?? []).map((p) => p.config)
|
|
2317
|
+
];
|
|
2318
|
+
const option = options?.hangTimeout;
|
|
2319
|
+
const limit = hangTimeoutFor(typeof option === "number" ? option : void 0, {
|
|
2320
|
+
testTimeout: Math.max(...configs.map((c) => c?.testTimeout ?? 0)),
|
|
2321
|
+
hookTimeout: Math.max(...configs.map((c) => c?.hookTimeout ?? 0))
|
|
2322
|
+
});
|
|
2323
|
+
const off = option === false || debugging(configs, process.execArgv, inspector.url());
|
|
2324
|
+
const active = typeof option === "number" || hotActive;
|
|
2325
|
+
let watch = config.reporters.find((r) => r instanceof HangWatch);
|
|
2326
|
+
if (!watch) {
|
|
2327
|
+
const recordsDir = fs.mkdtempSync(path.join(os.tmpdir(), "vitest-native-hang-"));
|
|
2328
|
+
process.once("exit", () => fs.rmSync(recordsDir, {
|
|
2329
|
+
recursive: true,
|
|
2330
|
+
force: true
|
|
2331
|
+
}));
|
|
2332
|
+
watch = new HangWatch({
|
|
2333
|
+
timeoutMs: null,
|
|
2334
|
+
recordsDir
|
|
2335
|
+
});
|
|
2336
|
+
config.reporters.push(watch);
|
|
2337
|
+
}
|
|
2338
|
+
watch.contribute({
|
|
2339
|
+
off,
|
|
2340
|
+
active,
|
|
2341
|
+
limit
|
|
2342
|
+
});
|
|
2343
|
+
if (active && !off && projectConfig?.setupFiles && !projectConfig.setupFiles.includes(HANG_SETUP)) {
|
|
2344
|
+
context.project.provide?.("vitestNativeHangWatch", {
|
|
2345
|
+
dir: watch.recordsDir,
|
|
2346
|
+
hookTimeout: projectConfig.hookTimeout ?? 1e4
|
|
2347
|
+
});
|
|
2348
|
+
projectConfig.setupFiles.unshift(HANG_SETUP);
|
|
2349
|
+
}
|
|
2350
|
+
}
|
|
1778
2351
|
/**
|
|
1779
2352
|
* Refuse a run in which vitest-native's own `import 'vitest'` would reach a different
|
|
1780
2353
|
* physical Vitest from the one running (host.ts): through the project's Vite resolver
|
|
@@ -1795,8 +2368,15 @@ function reactNative(options) {
|
|
|
1795
2368
|
await assertHostResolvesRunningVitest(running, resolveId, setupFile);
|
|
1796
2369
|
}
|
|
1797
2370
|
const configHandler = pluginDefinition.config;
|
|
2371
|
+
const transformHandler = pluginDefinition.transform;
|
|
1798
2372
|
return {
|
|
1799
2373
|
...pluginDefinition,
|
|
2374
|
+
transform: {
|
|
2375
|
+
get order() {
|
|
2376
|
+
return engine === "native" ? "post" : "pre";
|
|
2377
|
+
},
|
|
2378
|
+
handler: transformHandler
|
|
2379
|
+
},
|
|
1800
2380
|
config: {
|
|
1801
2381
|
order: "post",
|
|
1802
2382
|
async handler(userConfig, env) {
|
|
@@ -1810,34 +2390,28 @@ function reactNative(options) {
|
|
|
1810
2390
|
if (test) test.execArgv = [...test.execArgv ?? [], ...EXPORT_RECOVERY_ARGV];
|
|
1811
2391
|
if (test) {
|
|
1812
2392
|
const viteRoot = userConfig.root ? path.resolve(userConfig.root) : process.cwd();
|
|
1813
|
-
const vitestMajor = majorOf(resolvePackageVersion("vitest", viteRoot) ?? ownVitestPackage()?.version);
|
|
1814
2393
|
const userTest = userConfig.test;
|
|
1815
|
-
if (shouldDefaultFsModuleCache(
|
|
1816
|
-
cacheKeys.set(vitestRootOf(userConfig), fsModuleCacheKey(path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."), viteRoot,
|
|
1817
|
-
options,
|
|
1818
|
-
env: test.env
|
|
1819
|
-
}));
|
|
2394
|
+
if (shouldDefaultFsModuleCache(userTest)) test.fsModuleCache = true;
|
|
2395
|
+
cacheKeys.set(vitestRootOf(userConfig), fsModuleCacheKey(path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."), viteRoot, withoutOwnershipGuard(options, test.env, registryNeutralContext)));
|
|
1820
2396
|
}
|
|
1821
2397
|
if (test) {
|
|
1822
2398
|
const viteRoot = userConfig.root ? path.resolve(userConfig.root) : process.cwd();
|
|
1823
|
-
const viteMajor = majorOf(hostViteVersion);
|
|
1824
|
-
const tsconfigPaths = expoTsconfigPaths(viteRoot, userConfig.resolve?.tsconfigPaths, viteMajor);
|
|
1825
2399
|
const config = result;
|
|
1826
|
-
if (tsconfigPaths
|
|
2400
|
+
if (expoTsconfigPaths(viteRoot, userConfig.resolve?.tsconfigPaths)) config.resolve = {
|
|
1827
2401
|
...config.resolve,
|
|
1828
2402
|
tsconfigPaths: true
|
|
1829
2403
|
};
|
|
1830
|
-
else if (tsconfigPaths === "unsupported" && !warnedTsconfigPaths) {
|
|
1831
|
-
warnedTsconfigPaths = true;
|
|
1832
|
-
console.warn(`[vitest-native] This Expo project's tsconfig declares \`paths\`, which Expo's Metro resolves by default, but Vite ${viteMajor} cannot (Vite 8 adds \`resolve.tsconfigPaths\`). Upgrade to Vite 8, or add the vite-tsconfig-paths plugin, so imports such as \`@/…\` resolve in tests.`);
|
|
1833
|
-
}
|
|
1834
2404
|
}
|
|
1835
2405
|
return result;
|
|
1836
2406
|
}
|
|
1837
2407
|
},
|
|
1838
2408
|
configureVitest(context) {
|
|
2409
|
+
ownershipReady = void 0;
|
|
1839
2410
|
configureProject(context);
|
|
1840
|
-
|
|
2411
|
+
const projectRoot = context.project?.config?.root ? path.resolve(context.project.config.root) : process.cwd();
|
|
2412
|
+
watchForHangs(context, hotSelections.has(projectRoot));
|
|
2413
|
+
const ready = ownershipReady;
|
|
2414
|
+
return ready ? ready.then(() => verifyRunningVitest(context)) : verifyRunningVitest(context);
|
|
1841
2415
|
}
|
|
1842
2416
|
};
|
|
1843
2417
|
}
|