vitest-native 0.9.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +921 -0
- package/README.md +33 -1
- package/dist/cli.cjs +185 -31
- package/dist/cli.mjs +182 -28
- package/dist/ecosystem-BJzJU3Cf.cjs +568 -0
- package/dist/ecosystem-C4qT_vl3.mjs +506 -0
- package/dist/errors-B3lJK46O.cjs +75 -0
- package/dist/errors-CxoBUfVJ.mjs +64 -0
- package/dist/errors.d.mts +46 -0
- package/dist/errors.mjs +78 -0
- package/dist/helpers.cjs +6 -23
- package/dist/helpers.d.cts +0 -6
- package/dist/helpers.d.mts +0 -6
- package/dist/helpers.mjs +6 -23
- package/dist/{index-CEgRDdhd.d.cts → index-CrMeE8rd.d.mts} +14 -9
- package/dist/{index-j-0tueBr.d.mts → index-DIMbjH8R.d.cts} +15 -7
- package/dist/index.d.mts +8 -7
- package/dist/index.mjs +307 -91
- package/dist/jest-compat/interop.mjs +15 -0
- package/dist/jest-compat/setup.mjs +102 -7
- package/dist/jest-compat.cjs +4 -4
- package/dist/jest-compat.d.cts +0 -1
- package/dist/jest-compat.d.mts +0 -1
- package/dist/jest-compat.mjs +2 -2
- package/dist/matchers.cjs +16 -7
- package/dist/matchers.mjs +16 -7
- package/dist/native/hooks.mjs +152 -13
- package/dist/native/loader.mjs +36 -11
- package/dist/native/match.d.mts +33 -0
- package/dist/native/match.mjs +94 -22
- package/dist/native/module-reset.mjs +63 -0
- package/dist/native/registry.mjs +110 -13
- package/dist/native/resolve.d.mts +22 -0
- package/dist/native/resolve.mjs +21 -13
- package/dist/native/runner.mjs +21 -0
- package/dist/native/setup.mjs +4 -2
- package/dist/native/transform.mjs +108 -3
- package/dist/native/worker.mjs +59 -16
- package/dist/{pool-DzsEo9vv.cjs → pool-BU-1ecIF.cjs} +7 -6
- package/dist/{pool-CJmjRgsB.mjs → pool-Bcxn9a3I.mjs} +4 -3
- package/dist/{preset-map-CG4FMtsl.cjs → preset-map-BoG19dLa.cjs} +1 -1
- package/dist/{preset-map-CNsZKfvu.mjs → preset-map-DuX0ocdn.mjs} +1 -1
- package/dist/{presets-C4faM3ds.cjs → presets-CwO_c4aL.cjs} +224 -55
- package/dist/{presets-CuDrNA_W.mjs → presets-IStcJEOa.mjs} +216 -53
- package/dist/presets.d.mts +2 -2
- package/dist/presets.mjs +2 -2
- package/dist/rntl-matchers.d.ts +35 -0
- package/dist/{chunk-CjcI7cDX.mjs → rolldown-runtime-BhDjJH2R.mjs} +1 -1
- package/dist/{chunk-CZWwpsFl.cjs → rolldown-runtime-C0BPl7ul.cjs} +1 -1
- package/dist/serializer.cjs +34 -4
- package/dist/serializer.mjs +34 -4
- package/dist/setup.d.mts +1 -1
- package/dist/setup.mjs +237 -74
- package/docs/release-readiness.md +22 -5
- package/docs/versioning.md +133 -0
- package/package.json +38 -46
- package/dist/ecosystem-BIWaVwYL.cjs +0 -294
- package/dist/ecosystem-EFtHnKS9.mjs +0 -256
- package/dist/index.cjs +0 -788
- package/dist/index.d.cts +0 -14
- package/dist/presets.cjs +0 -18
- package/dist/presets.d.cts +0 -2
- package/dist/setup.cjs +0 -2702
- package/dist/setup.d.cts +0 -1
|
@@ -13,8 +13,10 @@
|
|
|
13
13
|
// `jest.useFakeTimers` work at runtime via the `jest` global installed here.
|
|
14
14
|
import { vi } from "vitest";
|
|
15
15
|
import { createRequire } from "node:module";
|
|
16
|
+
import { fileURLToPath } from "node:url";
|
|
16
17
|
import path from "node:path";
|
|
17
18
|
import { jestMockInterop } from "./interop.mjs";
|
|
19
|
+
import { VitestNativeError } from "../errors.mjs";
|
|
18
20
|
|
|
19
21
|
// Resolve modules from the consumer project root, not this file's location, so
|
|
20
22
|
// `jest.requireActual('some-project-dep')` resolves the same module the suite sees.
|
|
@@ -43,12 +45,68 @@ function writableModuleFacade(mod) {
|
|
|
43
45
|
});
|
|
44
46
|
}
|
|
45
47
|
|
|
48
|
+
/**
|
|
49
|
+
* The file that called into here, taken from the stack.
|
|
50
|
+
*
|
|
51
|
+
* Jest resolves a relative `requireActual('../x')` against the CALLING module. This
|
|
52
|
+
* shim had a single require anchored at the project root, so bare specifiers worked
|
|
53
|
+
* and relative ones escaped the source tree: `jest.requireActual('../thing')` threw
|
|
54
|
+
* MODULE_NOT_FOUND with a requireStack pointing at <projectRoot>/package.json, which
|
|
55
|
+
* is a confusing place to be sent when the file sits next to the test.
|
|
56
|
+
*
|
|
57
|
+
* The stack is the only thing that knows the caller. These are plain runtime calls
|
|
58
|
+
* on the `jest` global, not rewritten at transform time, so there is no import.meta
|
|
59
|
+
* to consult.
|
|
60
|
+
*/
|
|
61
|
+
function callerFile() {
|
|
62
|
+
const original = Error.prepareStackTrace;
|
|
63
|
+
try {
|
|
64
|
+
Error.prepareStackTrace = (_, frames) => frames;
|
|
65
|
+
const frames = new Error().stack;
|
|
66
|
+
for (const frame of frames) {
|
|
67
|
+
const file = typeof frame.getFileName === "function" ? frame.getFileName() : null;
|
|
68
|
+
if (!file || file.startsWith("node:") || file.includes("/jest-compat/")) continue;
|
|
69
|
+
return file.startsWith("file://") ? fileURLToPath(file) : file;
|
|
70
|
+
}
|
|
71
|
+
} catch {
|
|
72
|
+
// Fall through to the project-root require below.
|
|
73
|
+
} finally {
|
|
74
|
+
Error.prepareStackTrace = original;
|
|
75
|
+
}
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Resolve as Jest does: relative against the caller, bare from the project root. */
|
|
80
|
+
function requireFrom(specifier) {
|
|
81
|
+
if (typeof specifier === "string" && specifier.startsWith(".")) {
|
|
82
|
+
const caller = callerFile();
|
|
83
|
+
// A caller-relative miss is the honest answer. Falling back to the project root
|
|
84
|
+
// could resolve some other file that happens to sit at the same relative path.
|
|
85
|
+
if (caller) return createRequire(caller)(specifier);
|
|
86
|
+
}
|
|
87
|
+
return require(specifier);
|
|
88
|
+
}
|
|
89
|
+
|
|
46
90
|
if (typeof vi.requireActual !== "function")
|
|
47
|
-
vi.requireActual = (m) =>
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
//
|
|
51
|
-
|
|
91
|
+
vi.requireActual = (m) =>
|
|
92
|
+
m === "react-native" ? writableModuleFacade(require(m)) : requireFrom(m);
|
|
93
|
+
if (typeof vi.requireMock !== "function") vi.requireMock = (m) => requireFrom(m);
|
|
94
|
+
// `jest.setTimeout(ms)` maps onto `vi.setConfig({ testTimeout })`, which applies for
|
|
95
|
+
// the rest of the file — the same scope Jest gives it, since Vitest resets the config
|
|
96
|
+
// after each test file.
|
|
97
|
+
//
|
|
98
|
+
// This used to be a silent no-op, on the grounds that there was no `vi` equivalent.
|
|
99
|
+
// There is. The cost of the no-op was not a crash but silence: a suite opening with
|
|
100
|
+
// `jest.setTimeout(30000)`, which is routine for slower React Native suites, kept
|
|
101
|
+
// Vitest's 5s default and its slow tests failed on time while the line that was
|
|
102
|
+
// supposed to prevent that sat there looking effective.
|
|
103
|
+
if (typeof vi.setTimeout !== "function") {
|
|
104
|
+
vi.setTimeout = (ms) => {
|
|
105
|
+
if (typeof vi.setConfig === "function" && typeof ms === "number") {
|
|
106
|
+
vi.setConfig({ testTimeout: ms });
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
}
|
|
52
110
|
|
|
53
111
|
// `jest.advanceTimersByTime(Async)` is lenient in Jest: when fake timers are NOT
|
|
54
112
|
// active it's effectively a no-op. Vitest's `vi.advanceTimersByTimeAsync` instead
|
|
@@ -65,6 +123,20 @@ vi.advanceTimersByTime = (...args) =>
|
|
|
65
123
|
vi.advanceTimersByTimeAsync = async (...args) =>
|
|
66
124
|
vi.isFakeTimers() ? advanceTimersByTimeAsync(...args) : undefined;
|
|
67
125
|
|
|
126
|
+
// Jest APIs that DO have a Vitest equivalent, under a different name. Each of these
|
|
127
|
+
// was missing, so a suite calling it hit `jest.X is not a function` — the bare
|
|
128
|
+
// TypeError the signposting below exists to avoid — even though the behaviour was
|
|
129
|
+
// available all along. `dontMock` is the sibling of the already-signposted
|
|
130
|
+
// `deepUnmock`, which is what marks these as omissions rather than decisions.
|
|
131
|
+
if (typeof vi.dontMock !== "function") vi.dontMock = (m) => vi.doUnmock(m);
|
|
132
|
+
if (typeof vi.setMock !== "function") vi.setMock = (m, exports) => vi.doMock(m, () => exports);
|
|
133
|
+
// `Date.now()` alone is right for both clocks: Vitest's fake timers replace Date, so
|
|
134
|
+
// this returns the faked time when they are active and the real time otherwise —
|
|
135
|
+
// which is what jest.now() reports. An earlier version consulted
|
|
136
|
+
// vi.getMockedSystemTime() first; removing that branch changed no observable
|
|
137
|
+
// behaviour, so it was complexity no test could distinguish.
|
|
138
|
+
if (typeof vi.now !== "function") vi.now = () => Date.now();
|
|
139
|
+
|
|
68
140
|
// Jest APIs with NO Vitest equivalent would otherwise surface as bare
|
|
69
141
|
// "jest.isolateModules is not a function" TypeErrors deep in a migrated suite.
|
|
70
142
|
// Give each one an error that names the API and states the closest migration,
|
|
@@ -74,8 +146,10 @@ const MIGRATION_GUIDE =
|
|
|
74
146
|
function unsupported(name, guidance) {
|
|
75
147
|
if (typeof vi[name] === "function") return;
|
|
76
148
|
vi[name] = () => {
|
|
77
|
-
throw new
|
|
78
|
-
|
|
149
|
+
throw new VitestNativeError(
|
|
150
|
+
"JEST_API_UNSUPPORTED",
|
|
151
|
+
`jest.${name}() has no Vitest equivalent. ${guidance}`,
|
|
152
|
+
{ docs: MIGRATION_GUIDE },
|
|
79
153
|
);
|
|
80
154
|
};
|
|
81
155
|
}
|
|
@@ -92,6 +166,27 @@ unsupported(
|
|
|
92
166
|
"Build the mock explicitly with vi.fn()/vi.mock(), or import the real module and override members.",
|
|
93
167
|
);
|
|
94
168
|
unsupported("deepUnmock", "Use vi.unmock()/vi.doUnmock() per module.");
|
|
169
|
+
unsupported(
|
|
170
|
+
"isolateModulesAsync",
|
|
171
|
+
"Use vi.resetModules() plus a dynamic import() to get a fresh module copy.",
|
|
172
|
+
);
|
|
173
|
+
unsupported("unstable_mockModule", "Use vi.doMock(path, factory), which mocks ESM too.");
|
|
174
|
+
unsupported(
|
|
175
|
+
"replaceProperty",
|
|
176
|
+
"Assign the property and restore it yourself, or use vi.spyOn(obj, key, 'get') for an accessor.",
|
|
177
|
+
);
|
|
178
|
+
// Vitest has no automocking at all, so these cannot be approximated — the whole
|
|
179
|
+
// premise (every module auto-replaced with mocks) does not exist. Naming that is more
|
|
180
|
+
// useful than a TypeError.
|
|
181
|
+
for (const name of [
|
|
182
|
+
"enableAutomock",
|
|
183
|
+
"disableAutomock",
|
|
184
|
+
"autoMockOff",
|
|
185
|
+
"autoMockOn",
|
|
186
|
+
"onGenerateMock",
|
|
187
|
+
]) {
|
|
188
|
+
unsupported(name, "Vitest has no automocking; mock each module explicitly with vi.mock().");
|
|
189
|
+
}
|
|
95
190
|
// jest.retryTimes configures retries at runtime; Vitest configures them statically.
|
|
96
191
|
// Warn once and continue — crashing a suite over retry policy helps nobody.
|
|
97
192
|
if (typeof vi.retryTimes !== "function") {
|
package/dist/jest-compat.cjs
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const
|
|
2
|
+
const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
|
|
3
3
|
let magic_string = require("magic-string");
|
|
4
|
-
magic_string =
|
|
4
|
+
magic_string = require_rolldown_runtime.__toESM(magic_string, 1);
|
|
5
5
|
//#region src/jest-compat/transform.ts
|
|
6
|
-
const HOISTABLE = new Set([
|
|
6
|
+
const HOISTABLE = /* @__PURE__ */ new Set([
|
|
7
7
|
"mock",
|
|
8
8
|
"unmock",
|
|
9
9
|
"doMock",
|
|
10
10
|
"doUnmock"
|
|
11
11
|
]);
|
|
12
|
-
const WITH_FACTORY = new Set(["mock", "doMock"]);
|
|
12
|
+
const WITH_FACTORY = /* @__PURE__ */ new Set(["mock", "doMock"]);
|
|
13
13
|
const TRANSFORMABLE = /\.(?:[cm]?[jt]sx?)$/;
|
|
14
14
|
const HAS_JEST_MOCK = /\bjest\s*\.\s*(?:mock|unmock|doMock|doUnmock)\s*\(/;
|
|
15
15
|
/** Visit every node in an ESTree AST (depth-first), calling `fn` on each. */
|
package/dist/jest-compat.d.cts
CHANGED
package/dist/jest-compat.d.mts
CHANGED
package/dist/jest-compat.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import MagicString from "magic-string";
|
|
2
2
|
//#region src/jest-compat/transform.ts
|
|
3
|
-
const HOISTABLE = new Set([
|
|
3
|
+
const HOISTABLE = /* @__PURE__ */ new Set([
|
|
4
4
|
"mock",
|
|
5
5
|
"unmock",
|
|
6
6
|
"doMock",
|
|
7
7
|
"doUnmock"
|
|
8
8
|
]);
|
|
9
|
-
const WITH_FACTORY = new Set(["mock", "doMock"]);
|
|
9
|
+
const WITH_FACTORY = /* @__PURE__ */ new Set(["mock", "doMock"]);
|
|
10
10
|
const TRANSFORMABLE = /\.(?:[cm]?[jt]sx?)$/;
|
|
11
11
|
const HAS_JEST_MOCK = /\bjest\s*\.\s*(?:mock|unmock|doMock|doUnmock)\s*\(/;
|
|
12
12
|
/** Visit every node in an ESTree AST (depth-first), calling `fn` on each. */
|
package/dist/matchers.cjs
CHANGED
|
@@ -15,11 +15,20 @@ function getProps(received) {
|
|
|
15
15
|
}
|
|
16
16
|
return null;
|
|
17
17
|
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
18
|
+
/**
|
|
19
|
+
* THROWS for a value that is not a rendered element — it does not return
|
|
20
|
+
* `{ pass: false }`.
|
|
21
|
+
*
|
|
22
|
+
* Returning a failing result reads as the safe option and is not: under `.not` the
|
|
23
|
+
* result is inverted, so `expect(null).not.toHaveAnimatedStyle({ opacity: 1 })`
|
|
24
|
+
* SILENTLY PASSED. A query that matched nothing, or a value of the wrong shape, then
|
|
25
|
+
* produced a green assertion — the failure mode a matcher must never have.
|
|
26
|
+
*
|
|
27
|
+
* Throwing also matches React Native Testing Library, whose `checkHostElement` raises
|
|
28
|
+
* a HostElementTypeError for the same case rather than failing softly.
|
|
29
|
+
*/
|
|
30
|
+
function throwNotAnElement(ctx, matcherName, received) {
|
|
31
|
+
throw new Error(`${ctx.utils.matcherHint(`${ctx.isNot ? ".not." : ""}${matcherName}`, "element", "expected")}\n\nExpected a rendered element with a \`props\` object, but received:\n ${ctx.utils.printReceived(received)}`);
|
|
23
32
|
}
|
|
24
33
|
/** Pick only the keys present in `expected` from `actual`, for readable diffs. */
|
|
25
34
|
function subset(actual, expected) {
|
|
@@ -29,7 +38,7 @@ function subset(actual, expected) {
|
|
|
29
38
|
}
|
|
30
39
|
function toHaveAnimatedStyle(received, expectedStyle, config = {}) {
|
|
31
40
|
const props = getProps(received);
|
|
32
|
-
if (!props)
|
|
41
|
+
if (!props) throwNotAnElement(this, "toHaveAnimatedStyle", received);
|
|
33
42
|
const currentStyle = flattenStyle(props.style);
|
|
34
43
|
const compared = config.shouldMatchAllProps ? currentStyle : subset(currentStyle, expectedStyle);
|
|
35
44
|
const pass = this.equals(compared, expectedStyle);
|
|
@@ -45,7 +54,7 @@ function toHaveAnimatedStyle(received, expectedStyle, config = {}) {
|
|
|
45
54
|
}
|
|
46
55
|
function toHaveAnimatedProps(received, expectedProps) {
|
|
47
56
|
const props = getProps(received);
|
|
48
|
-
if (!props)
|
|
57
|
+
if (!props) throwNotAnElement(this, "toHaveAnimatedProps", received);
|
|
49
58
|
const compared = subset(props.animatedProps && typeof props.animatedProps === "object" ? props.animatedProps : props, expectedProps);
|
|
50
59
|
const pass = this.equals(compared, expectedProps);
|
|
51
60
|
return {
|
package/dist/matchers.mjs
CHANGED
|
@@ -14,11 +14,20 @@ function getProps(received) {
|
|
|
14
14
|
}
|
|
15
15
|
return null;
|
|
16
16
|
}
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
17
|
+
/**
|
|
18
|
+
* THROWS for a value that is not a rendered element — it does not return
|
|
19
|
+
* `{ pass: false }`.
|
|
20
|
+
*
|
|
21
|
+
* Returning a failing result reads as the safe option and is not: under `.not` the
|
|
22
|
+
* result is inverted, so `expect(null).not.toHaveAnimatedStyle({ opacity: 1 })`
|
|
23
|
+
* SILENTLY PASSED. A query that matched nothing, or a value of the wrong shape, then
|
|
24
|
+
* produced a green assertion — the failure mode a matcher must never have.
|
|
25
|
+
*
|
|
26
|
+
* Throwing also matches React Native Testing Library, whose `checkHostElement` raises
|
|
27
|
+
* a HostElementTypeError for the same case rather than failing softly.
|
|
28
|
+
*/
|
|
29
|
+
function throwNotAnElement(ctx, matcherName, received) {
|
|
30
|
+
throw new Error(`${ctx.utils.matcherHint(`${ctx.isNot ? ".not." : ""}${matcherName}`, "element", "expected")}\n\nExpected a rendered element with a \`props\` object, but received:\n ${ctx.utils.printReceived(received)}`);
|
|
22
31
|
}
|
|
23
32
|
/** Pick only the keys present in `expected` from `actual`, for readable diffs. */
|
|
24
33
|
function subset(actual, expected) {
|
|
@@ -28,7 +37,7 @@ function subset(actual, expected) {
|
|
|
28
37
|
}
|
|
29
38
|
function toHaveAnimatedStyle(received, expectedStyle, config = {}) {
|
|
30
39
|
const props = getProps(received);
|
|
31
|
-
if (!props)
|
|
40
|
+
if (!props) throwNotAnElement(this, "toHaveAnimatedStyle", received);
|
|
32
41
|
const currentStyle = flattenStyle(props.style);
|
|
33
42
|
const compared = config.shouldMatchAllProps ? currentStyle : subset(currentStyle, expectedStyle);
|
|
34
43
|
const pass = this.equals(compared, expectedStyle);
|
|
@@ -44,7 +53,7 @@ function toHaveAnimatedStyle(received, expectedStyle, config = {}) {
|
|
|
44
53
|
}
|
|
45
54
|
function toHaveAnimatedProps(received, expectedProps) {
|
|
46
55
|
const props = getProps(received);
|
|
47
|
-
if (!props)
|
|
56
|
+
if (!props) throwNotAnElement(this, "toHaveAnimatedProps", received);
|
|
48
57
|
const compared = subset(props.animatedProps && typeof props.animatedProps === "object" ? props.animatedProps : props, expectedProps);
|
|
49
58
|
const pass = this.equals(compared, expectedProps);
|
|
50
59
|
return {
|
package/dist/native/hooks.mjs
CHANGED
|
@@ -6,20 +6,156 @@ import fs from "node:fs";
|
|
|
6
6
|
import { transformRN, isFlow } from "./transform.mjs";
|
|
7
7
|
import { boundarySourceFor } from "./boundary.mjs";
|
|
8
8
|
import { resolvePlatformFile } from "./resolve.mjs";
|
|
9
|
-
import {
|
|
9
|
+
import {
|
|
10
|
+
NODE_MODULES_PATH,
|
|
11
|
+
REACT_NATIVE_PATH,
|
|
12
|
+
buildPkgMatcher,
|
|
13
|
+
isUtilitySubpath,
|
|
14
|
+
packageNameOf,
|
|
15
|
+
subpathLeafOf,
|
|
16
|
+
} from "./match.mjs";
|
|
10
17
|
import { explainUntransformedSyntaxError } from "./explain.mjs";
|
|
11
18
|
|
|
12
|
-
const RN_PATH = /[\\/]node_modules[\\/](react-native|@react-native)[\\/]/;
|
|
13
|
-
// Any file under a node_modules directory. Platform-extension resolution
|
|
14
|
-
// (`.native.js` etc.) applies to every node_modules package, not just RN — matching
|
|
15
|
-
// Metro, which resolves platform variants project-wide. See loader.mjs for the
|
|
16
|
-
// ESM-path counterpart and the @react-navigation silent-failure this prevents.
|
|
17
|
-
const NODE_MODULES = /[\\/]node_modules[\\/]/;
|
|
18
|
-
|
|
19
19
|
// Guarded via globalThis, not module scope: under the hot runtime this module
|
|
20
20
|
// can be evaluated twice in one worker (once by the worker entry through Node's
|
|
21
21
|
// loader, once through Vitest's module runner when the setup file is inlined),
|
|
22
22
|
// and the hooks must still install exactly once per worker.
|
|
23
|
+
/**
|
|
24
|
+
* Packages Vite executes itself (see ecosystem.ts). If Node also resolves one of
|
|
25
|
+
* these, the module exists TWICE in the process — once in Vite's graph, once in
|
|
26
|
+
* Node's — and module-level state does not cross between them.
|
|
27
|
+
*
|
|
28
|
+
* This is silent by construction: nothing fails, nothing is logged, the second
|
|
29
|
+
* copy simply starts empty. A store configured through one copy reads back
|
|
30
|
+
* unset through the other, so a translated label renders as "" and the test
|
|
31
|
+
* compares empty output against expected output with nothing pointing at the
|
|
32
|
+
* cause. Reported once per package, with both files, because the two paths are
|
|
33
|
+
* what makes it recognisable.
|
|
34
|
+
*/
|
|
35
|
+
// The fields Vite is configured with for React Native (see plugin.ts), in order.
|
|
36
|
+
// Node's CJS resolver uses `main`, which is not in this list at all.
|
|
37
|
+
const VITE_MAIN_FIELDS = ["react-native", "module", "jsnext:main", "jsnext"];
|
|
38
|
+
|
|
39
|
+
const reportedDuplicates = new Set();
|
|
40
|
+
const reportedProjectLoads = new Set();
|
|
41
|
+
|
|
42
|
+
/** Test seam: the warning is once per package for the life of the worker. */
|
|
43
|
+
export function _resetDuplicateReports() {
|
|
44
|
+
reportedDuplicates.clear();
|
|
45
|
+
reportedProjectLoads.clear();
|
|
46
|
+
cachedProjectDirs = undefined;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Directories Vite owns outright: the package the run lives in, and any package a
|
|
51
|
+
* `test.include` pattern points into (see plugin.ts). Read from the environment
|
|
52
|
+
* because it has to cross into the worker.
|
|
53
|
+
*
|
|
54
|
+
* Parsed once. This is consulted on every module resolution in the worker, so
|
|
55
|
+
* re-reading and re-parsing the variable per call put a JSON.parse in the hot path.
|
|
56
|
+
*/
|
|
57
|
+
let cachedProjectDirs;
|
|
58
|
+
function projectDirs() {
|
|
59
|
+
if (cachedProjectDirs) return cachedProjectDirs;
|
|
60
|
+
try {
|
|
61
|
+
cachedProjectDirs = JSON.parse(process.env.VITEST_NATIVE_PROJECT_DIRS || "[]").map(
|
|
62
|
+
(dir) => dir.replace(/\\/g, "/").replace(/\/+$/, "") + "/",
|
|
63
|
+
);
|
|
64
|
+
} catch {
|
|
65
|
+
cachedProjectDirs = [];
|
|
66
|
+
}
|
|
67
|
+
return cachedProjectDirs;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Say so when Node loads the project's own source.
|
|
72
|
+
*
|
|
73
|
+
* The package under test is Vite's (see the ownership rule in apply.ts). If an
|
|
74
|
+
* installed package requires it as well, it exists twice — once in each graph — and
|
|
75
|
+
* the symptom is silence: a store configured through the test's copy reads back unset
|
|
76
|
+
* through the copy the library sees, so an assertion compares "" against the expected
|
|
77
|
+
* text with nothing pointing at the cause. It is the same failure the
|
|
78
|
+
* duplicate-instance warning above covers, arrived at from the other direction: there
|
|
79
|
+
* the two graphs disagree about which FILE the package is, here they agree on the file
|
|
80
|
+
* and still hold separate instances of it.
|
|
81
|
+
*
|
|
82
|
+
* Only reported when the requirer is an installed package. A test reaching into its
|
|
83
|
+
* own source deliberately — `jest.requireActual('./src/thing')` — is Node loading
|
|
84
|
+
* project files on purpose, and is not this.
|
|
85
|
+
*/
|
|
86
|
+
export function checkProjectSourceLoadedByNode(resolved, parent, dirs = projectDirs()) {
|
|
87
|
+
if (dirs.length === 0 || typeof resolved !== "string") return;
|
|
88
|
+
const file = resolved.replace(/\\/g, "/");
|
|
89
|
+
// Project source never lives under node_modules, and the project directory
|
|
90
|
+
// contains its own node_modules — so this has to be excluded explicitly.
|
|
91
|
+
if (file.includes("/node_modules/")) return;
|
|
92
|
+
if (!dirs.some((dir) => file.startsWith(dir))) return;
|
|
93
|
+
const from = parent && parent.filename ? parent.filename.replace(/\\/g, "/") : "";
|
|
94
|
+
if (!NODE_MODULES_PATH.test(from) || from.includes("/vitest-native/dist/")) return;
|
|
95
|
+
if (reportedProjectLoads.has(file)) return;
|
|
96
|
+
reportedProjectLoads.add(file);
|
|
97
|
+
console.warn(
|
|
98
|
+
`[vitest-native] Node loaded a file from the package under test.\n` +
|
|
99
|
+
` file -> ${resolved}\n` +
|
|
100
|
+
` required by -> ${parent.filename}\n` +
|
|
101
|
+
" The package under test belongs to Vite's graph, so it now exists twice — once\n" +
|
|
102
|
+
" in each module system — and module-level state is not shared between the copies.\n" +
|
|
103
|
+
" Nothing throws: writes through one are invisible to the other, so values read back\n" +
|
|
104
|
+
" unset. This happens when an installed React Native package depends on the very\n" +
|
|
105
|
+
" package whose tests are running. Import it from one side only, or test it from a\n" +
|
|
106
|
+
" package that does not sit underneath the dependency.",
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
function reportDuplicateInstance(pkg, nodeFile, viteFile, field) {
|
|
110
|
+
reportedDuplicates.add(pkg);
|
|
111
|
+
console.warn(
|
|
112
|
+
`[vitest-native] '${pkg}' resolves to two different files.\n` +
|
|
113
|
+
` Node (require) -> ${nodeFile}\n` +
|
|
114
|
+
` Vite ("${field}") -> ${viteFile}\n` +
|
|
115
|
+
" If both module systems load it, the package exists twice and module-level state —\n" +
|
|
116
|
+
" stores, React contexts, event emitters, registries — is not shared between the copies.\n" +
|
|
117
|
+
" Nothing throws: writes through one are simply invisible to the other, so values read\n" +
|
|
118
|
+
" back unset. Set `resolve.mainFields` so both resolvers agree, or import the package\n" +
|
|
119
|
+
" from one side only.",
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Compare what Node just resolved against what Vite's field order would pick for
|
|
125
|
+
* the same package. A difference means the two module systems have different
|
|
126
|
+
* files for one package id, so anything importing it from both sides gets two
|
|
127
|
+
* copies with separate state.
|
|
128
|
+
*/
|
|
129
|
+
export function checkResolverAgreement(request, resolved) {
|
|
130
|
+
const pkg = packageOf(request);
|
|
131
|
+
if (!pkg || typeof resolved !== "string") return;
|
|
132
|
+
if (reportedDuplicates.has(pkg)) return;
|
|
133
|
+
const marker = `${path.sep}node_modules${path.sep}`;
|
|
134
|
+
const at = resolved.lastIndexOf(marker + pkg.split("/").join(path.sep) + path.sep);
|
|
135
|
+
if (at === -1) return;
|
|
136
|
+
const dir = resolved.slice(0, at + marker.length + pkg.length);
|
|
137
|
+
let manifest;
|
|
138
|
+
try {
|
|
139
|
+
manifest = JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"));
|
|
140
|
+
} catch {
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
const field = VITE_MAIN_FIELDS.find((f) => typeof manifest[f] === "string");
|
|
144
|
+
if (!field) return;
|
|
145
|
+
const viteFile = path.resolve(dir, manifest[field]);
|
|
146
|
+
if (viteFile === resolved) return;
|
|
147
|
+
reportDuplicateInstance(pkg, resolved, viteFile, field);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The npm package a bare specifier belongs to, or null for relative/absolute ones. */
|
|
151
|
+
function packageOf(request) {
|
|
152
|
+
if (!request || request.startsWith(".") || request.startsWith("/") || request.startsWith("\\")) {
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
const parts = request.split("/");
|
|
156
|
+
return request.startsWith("@") ? (parts[1] ? `${parts[0]}/${parts[1]}` : null) : parts[0];
|
|
157
|
+
}
|
|
158
|
+
|
|
23
159
|
export function installRequireHooks(
|
|
24
160
|
projectRoot,
|
|
25
161
|
transformPkgs = [],
|
|
@@ -125,8 +261,8 @@ export function installRequireHooks(
|
|
|
125
261
|
if (
|
|
126
262
|
parent &&
|
|
127
263
|
parent.filename &&
|
|
128
|
-
(
|
|
129
|
-
|
|
264
|
+
(NODE_MODULES_PATH.test(parent.filename) ||
|
|
265
|
+
REACT_NATIVE_PATH.test(parent.filename) ||
|
|
130
266
|
isExtra(parent.filename)) &&
|
|
131
267
|
request.startsWith(".") &&
|
|
132
268
|
!path.extname(request)
|
|
@@ -137,7 +273,10 @@ export function installRequireHooks(
|
|
|
137
273
|
);
|
|
138
274
|
if (hit) return hit;
|
|
139
275
|
}
|
|
140
|
-
|
|
276
|
+
const resolved = origResolve.call(this, request, parent, ...rest);
|
|
277
|
+
checkResolverAgreement(request, resolved);
|
|
278
|
+
checkProjectSourceLoadedByNode(resolved, parent);
|
|
279
|
+
return resolved;
|
|
141
280
|
};
|
|
142
281
|
|
|
143
282
|
const origJs = Module._extensions[".js"];
|
|
@@ -145,7 +284,7 @@ export function installRequireHooks(
|
|
|
145
284
|
const norm = filename.replace(/\\/g, "/");
|
|
146
285
|
const boundary = boundarySourceFor(norm, platform, reactNativeVersion);
|
|
147
286
|
if (boundary != null) return mod._compile(boundary, filename);
|
|
148
|
-
if (
|
|
287
|
+
if (REACT_NATIVE_PATH.test(norm)) {
|
|
149
288
|
const src = fs.readFileSync(filename, "utf8");
|
|
150
289
|
if (isFlow(src))
|
|
151
290
|
return mod._compile(transformRN(filename, src, projectRoot, platform), filename);
|
|
@@ -155,7 +294,7 @@ export function installRequireHooks(
|
|
|
155
294
|
const src = fs.readFileSync(filename, "utf8");
|
|
156
295
|
return mod._compile(transformRN(filename, src, projectRoot, platform), filename);
|
|
157
296
|
}
|
|
158
|
-
if (
|
|
297
|
+
if (NODE_MODULES_PATH.test(norm)) {
|
|
159
298
|
// A node_modules package we did NOT transform: when Node's compile throws a
|
|
160
299
|
// SyntaxError that fingerprints as untranspiled JSX/Flow/TS, explain the
|
|
161
300
|
// real fix (add the package to `transform: [...]`) instead of leaving a
|
package/dist/native/loader.mjs
CHANGED
|
@@ -3,18 +3,23 @@
|
|
|
3
3
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import fs from "node:fs";
|
|
6
|
-
import { transformRN, isFlow } from "./transform.mjs";
|
|
6
|
+
import { transformRN, isFlow, cjsExportNames } from "./transform.mjs";
|
|
7
7
|
import { boundarySourceFor } from "./boundary.mjs";
|
|
8
8
|
import { resolvePlatformFile } from "./resolve.mjs";
|
|
9
|
-
import {
|
|
9
|
+
import {
|
|
10
|
+
NODE_MODULES_PATH,
|
|
11
|
+
REACT_NATIVE_PATH,
|
|
12
|
+
buildPkgMatcher,
|
|
13
|
+
isUtilitySubpath,
|
|
14
|
+
packageNameOf,
|
|
15
|
+
subpathLeafOf,
|
|
16
|
+
} from "./match.mjs";
|
|
10
17
|
|
|
11
|
-
const RN_PATH = /[\\/]node_modules[\\/](react-native|@react-native)[\\/]/;
|
|
12
18
|
// Any file living under a node_modules directory. Platform-extension resolution
|
|
13
19
|
// (`.native.js` etc.) applies to every node_modules package, not just RN, matching
|
|
14
20
|
// Metro — which resolves platform variants project-wide. (Without this, e.g.
|
|
15
21
|
// `@react-navigation/native` silently loads its `.js`/web variant instead of
|
|
16
22
|
// `.native.js`, breaking the navigation lifecycle with no error.)
|
|
17
|
-
const NODE_MODULES = /[\\/]node_modules[\\/]/;
|
|
18
23
|
// React Native's main entry (`react-native/index.js`).
|
|
19
24
|
const RN_INDEX = /[\\/]react-native[\\/]index\.js$/;
|
|
20
25
|
const TRANSFORMABLE = /\.(jsx?|tsx?|mjs|cjs)$/;
|
|
@@ -87,19 +92,21 @@ export async function resolve(specifier, context, nextResolve) {
|
|
|
87
92
|
context.parentURL && context.parentURL.startsWith("file:")
|
|
88
93
|
? fileURLToPath(context.parentURL)
|
|
89
94
|
: null;
|
|
95
|
+
let resolved;
|
|
90
96
|
if (
|
|
91
97
|
parent &&
|
|
92
|
-
(
|
|
98
|
+
(NODE_MODULES_PATH.test(parent) || REACT_NATIVE_PATH.test(parent) || isExtra(parent)) &&
|
|
93
99
|
specifier.startsWith(".") &&
|
|
94
100
|
!path.extname(specifier)
|
|
95
101
|
) {
|
|
96
102
|
const hit = resolvePlatformFile(path.resolve(path.dirname(parent), specifier), PLATFORM);
|
|
97
|
-
|
|
103
|
+
// Not returned directly: `json` is a Metro source extension, so this can now
|
|
104
|
+
// land on a .json file, which still needs the import attribute injected below.
|
|
105
|
+
if (hit) resolved = { url: pathToFileURL(hit).href, shortCircuit: true };
|
|
98
106
|
}
|
|
99
107
|
|
|
100
|
-
let resolved;
|
|
101
108
|
try {
|
|
102
|
-
resolved
|
|
109
|
+
resolved ??= await nextResolve(specifier, context);
|
|
103
110
|
} catch (err) {
|
|
104
111
|
// Fallback: an extensionless relative import that Node's ESM resolver rejected
|
|
105
112
|
// but a bundler (Metro) would accept. Common in externalized RN libs shipping
|
|
@@ -181,7 +188,7 @@ export async function load(url, context, nextLoad) {
|
|
|
181
188
|
};
|
|
182
189
|
}
|
|
183
190
|
|
|
184
|
-
const isRN =
|
|
191
|
+
const isRN = REACT_NATIVE_PATH.test(norm);
|
|
185
192
|
if (!isRN && !isExtra(norm)) return nextLoad(url, context);
|
|
186
193
|
|
|
187
194
|
if (isRN) {
|
|
@@ -222,12 +229,30 @@ export async function load(url, context, nextLoad) {
|
|
|
222
229
|
return nextLoad(url, context);
|
|
223
230
|
}
|
|
224
231
|
|
|
225
|
-
// Configured third-party package: transform any JS/TS/JSX source to CJS
|
|
232
|
+
// Configured third-party package: transform any JS/TS/JSX source to CJS, and tell
|
|
233
|
+
// Node what it exports.
|
|
234
|
+
//
|
|
235
|
+
// When Node imports a CommonJS module from ESM it decides the named exports with
|
|
236
|
+
// cjs-module-lexer, which reads the source statically and gives up partway through
|
|
237
|
+
// shapes it cannot follow. `module.exports = { A() {}, b: () => 1 }` — ordinary
|
|
238
|
+
// hand-written CommonJS, and common in this ecosystem — yields
|
|
239
|
+
// ["A", "default", "module.exports"]: `b` is missing and a name that is not an
|
|
240
|
+
// export appears. Plain Node behaviour, reproducible with no plugin involved; it
|
|
241
|
+
// became reachable when these packages moved from Vite's graph (whose interop
|
|
242
|
+
// enumerates the real object at run time) to Node's.
|
|
243
|
+
//
|
|
244
|
+
// The dead `0 && (module.exports = { … })` hint is the form the lexer does
|
|
245
|
+
// understand — the same trick react-native's index facade uses below. Names are
|
|
246
|
+
// read from the transform's own output rather than by requiring the module: this
|
|
247
|
+
// hook runs on the module-loader thread, where the CJS require hooks that compile
|
|
248
|
+
// JSX are not installed, so a require here fails with "Unexpected token '<'".
|
|
226
249
|
if (TRANSFORMABLE.test(norm)) {
|
|
227
250
|
const src = fs.readFileSync(file, "utf8");
|
|
251
|
+
const code = transformRN(file, src, PROJECT_ROOT, PLATFORM);
|
|
252
|
+
const names = cjsExportNames(code);
|
|
228
253
|
return {
|
|
229
254
|
format: "commonjs",
|
|
230
|
-
source:
|
|
255
|
+
source: names.length > 0 ? `${code}\n0 && (module.exports = { ${names.join(", ")} });` : code,
|
|
231
256
|
shortCircuit: true,
|
|
232
257
|
};
|
|
233
258
|
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** Any file under a node_modules directory. */
|
|
2
|
+
export declare const NODE_MODULES_PATH: RegExp;
|
|
3
|
+
|
|
4
|
+
/** React Native's own source, including the `@react-native/*` packages. */
|
|
5
|
+
export declare const REACT_NATIVE_PATH: RegExp;
|
|
6
|
+
|
|
7
|
+
/** Does `dir` contain `target` (or equal it)? Case-insensitive on Windows. */
|
|
8
|
+
export declare function containsPath(dir: string, target: string): boolean;
|
|
9
|
+
|
|
10
|
+
/** The on-disk directory a package resolves to from `projectRoot`, or null. */
|
|
11
|
+
export declare function packageDirOf(name: string, projectRoot: string): string | null;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The patterns identifying one package's files: under `node_modules/<name>/`, and
|
|
15
|
+
* inside the directory it resolves to. The second is omitted when that directory
|
|
16
|
+
* contains `projectRoot` — the project is not one of its own dependencies.
|
|
17
|
+
*/
|
|
18
|
+
export declare function packagePatterns(name: string, projectRoot?: string): RegExp[];
|
|
19
|
+
|
|
20
|
+
/** A predicate over `packagePatterns` for every named package. */
|
|
21
|
+
export declare function buildPkgMatcher(
|
|
22
|
+
pkgs: string[] | undefined,
|
|
23
|
+
projectRoot?: string,
|
|
24
|
+
): (file: string) => boolean;
|
|
25
|
+
|
|
26
|
+
/** The bare package name of an import specifier. */
|
|
27
|
+
export declare function packageNameOf(specifier: string): string;
|
|
28
|
+
|
|
29
|
+
/** The leaf module name a subpath import points at, or null. */
|
|
30
|
+
export declare function subpathLeafOf(specifier: string): string | null;
|
|
31
|
+
|
|
32
|
+
/** Deep entries of preset packages that must not be shadowed by the preset mock. */
|
|
33
|
+
export declare function isUtilitySubpath(specifier: string): boolean;
|