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/native/registry.mjs
CHANGED
|
@@ -25,19 +25,36 @@
|
|
|
25
25
|
// The registry is an optimization, never a semantic: anything it cannot serve falls
|
|
26
26
|
// through to the per-file hooks in hooks.mjs / loader.mjs, and a failed build leaves
|
|
27
27
|
// the engine running exactly as it did before.
|
|
28
|
-
import Module from "node:module";
|
|
29
|
-
import { createRequire } from "node:module";
|
|
28
|
+
import Module, { createRequire } from "node:module";
|
|
30
29
|
import path from "node:path";
|
|
31
30
|
import fs from "node:fs";
|
|
32
31
|
import crypto from "node:crypto";
|
|
33
32
|
import { projectContext } from "../context.mjs";
|
|
34
|
-
import {
|
|
33
|
+
import { VitestNativeError } from "../errors.mjs";
|
|
34
|
+
import {
|
|
35
|
+
transformRN,
|
|
36
|
+
isFlow,
|
|
37
|
+
needsTransform,
|
|
38
|
+
cacheRootFor,
|
|
39
|
+
TRANSFORM_CACHE_VERSION,
|
|
40
|
+
} from "./transform.mjs";
|
|
35
41
|
|
|
36
42
|
import { boundarySourceFor, BOUNDARY_SOURCES } from "./boundary.mjs";
|
|
37
43
|
import { resolveTransformPreset } from "./babel-preset.mjs";
|
|
38
44
|
import { assetRegistryPathFor, nativeAssetModuleSource } from "./assets.mjs";
|
|
39
|
-
import {
|
|
45
|
+
import {
|
|
46
|
+
extensionsFor,
|
|
47
|
+
resolveRelativePlatformFile,
|
|
48
|
+
resolveRelativeWithExtensions,
|
|
49
|
+
resolveDeepPackageFile,
|
|
50
|
+
resolvePackageMainField,
|
|
51
|
+
isWholePackageRequest,
|
|
52
|
+
} from "./resolve.mjs";
|
|
40
53
|
import { createNativeOwnershipPolicy } from "./ownership.mjs";
|
|
54
|
+
import { owningPackageOfFile, packageNameOf } from "./match.mjs";
|
|
55
|
+
import { libraryExtensionsFor, libraryResolverFiles } from "./jest-resolvers.mjs";
|
|
56
|
+
import { nodeDispatch } from "../node-dispatch.mjs";
|
|
57
|
+
import { createSharedResolver, resolverInputsHash } from "./shared-resolver.mjs";
|
|
41
58
|
|
|
42
59
|
/**
|
|
43
60
|
* Losing the registry is a silent performance cliff, not a correctness problem:
|
|
@@ -69,12 +86,21 @@ export function _warnRegistryUnavailable(rawReason) {
|
|
|
69
86
|
warnRegistryUnavailable(rawReason);
|
|
70
87
|
}
|
|
71
88
|
|
|
89
|
+
const LIBRARY_PREFIX = "library registry: ";
|
|
72
90
|
function warnRegistryUnavailable(rawReason) {
|
|
73
91
|
// Node appends a "Require stack:" block to resolution failures; one line is
|
|
74
92
|
// enough to identify the cause without turning a warning into a wall of text.
|
|
75
93
|
const reason = String(rawReason).split("\n")[0].trim();
|
|
76
94
|
if (reportedRegistryFailures.has(reason)) return;
|
|
77
95
|
reportedRegistryFailures.add(reason);
|
|
96
|
+
if (reason.startsWith(LIBRARY_PREFIX)) {
|
|
97
|
+
console.warn(
|
|
98
|
+
`[vitest-native] (native) could not precompile the library registry ` +
|
|
99
|
+
`(${reason.slice(LIBRARY_PREFIX.length)}); those libraries load file by file, which ` +
|
|
100
|
+
"is slower. React Native's registry is unaffected, and results are unaffected.",
|
|
101
|
+
);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
78
104
|
console.warn(
|
|
79
105
|
`[vitest-native] (native) could not precompile the React Native registry (${reason}); ` +
|
|
80
106
|
"falling back to per-file module loading, which is slower. Tests still run and " +
|
|
@@ -93,7 +119,8 @@ export function _resetRegistryFailureReports() {
|
|
|
93
119
|
// 5: the registry's internal require consults jest-compat's Node-side mocks.
|
|
94
120
|
// 6: each module keeps its own strictness, and runs with `this` = module.exports.
|
|
95
121
|
// 7: modules are stored as source and compiled per module under their own file name.
|
|
96
|
-
|
|
122
|
+
// 10: the React Native registry exposes `ran()`, the modules run since the last reset.
|
|
123
|
+
export const REGISTRY_FORMAT_VERSION = 10;
|
|
97
124
|
|
|
98
125
|
/**
|
|
99
126
|
* Literal `require('…')` / `require("…")` calls. The leading class excludes
|
|
@@ -116,7 +143,10 @@ const PASSTHROUGH_EXT = new Set([".json", ".node", ".wasm"]);
|
|
|
116
143
|
* Source for one file, applying the same precedence the per-file hooks use:
|
|
117
144
|
* asset module → native-boundary mock → Flow-stripped RN → verbatim.
|
|
118
145
|
*/
|
|
119
|
-
function sourceFor(
|
|
146
|
+
function sourceFor(
|
|
147
|
+
file,
|
|
148
|
+
{ projectRoot, platform, reactNativeVersion, assetExtSet, ownership, library = false },
|
|
149
|
+
) {
|
|
120
150
|
const norm = file.replace(/\\/g, "/");
|
|
121
151
|
const ext = path.extname(norm).slice(1).toLowerCase();
|
|
122
152
|
if (ext && assetExtSet.has(ext)) {
|
|
@@ -128,6 +158,12 @@ function sourceFor(file, { projectRoot, platform, reactNativeVersion, assetExtSe
|
|
|
128
158
|
scan: true,
|
|
129
159
|
};
|
|
130
160
|
}
|
|
161
|
+
if (library && ext === "json") {
|
|
162
|
+
// A library's JSON (its package.json, a data file) is a module of its graph, with
|
|
163
|
+
// the value Node's JSON loader gives it.
|
|
164
|
+
const value = JSON.parse(fs.readFileSync(file, "utf8").replace(/^\uFEFF/, ""));
|
|
165
|
+
return { code: `module.exports = ${JSON.stringify(value)};`, scan: false };
|
|
166
|
+
}
|
|
131
167
|
const boundary = boundarySourceFor(
|
|
132
168
|
ownership.reactNativePathFor(file) ?? norm,
|
|
133
169
|
platform,
|
|
@@ -135,22 +171,55 @@ function sourceFor(file, { projectRoot, platform, reactNativeVersion, assetExtSe
|
|
|
135
171
|
);
|
|
136
172
|
if (boundary != null) return { code: boundary, scan: true };
|
|
137
173
|
const src = fs.readFileSync(file, "utf8");
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
174
|
+
// A library file is compiled when Node could not run it as published, the test the
|
|
175
|
+
// per-file hooks apply to a package selected for compiling (hooks.mjs). React
|
|
176
|
+
// Native's own files keep the Flow test the registry has always applied to them.
|
|
177
|
+
const compile = library
|
|
178
|
+
? needsTransform(file, src)
|
|
179
|
+
: /\.(?:ts|tsx|jsx)$/.test(norm) || (norm.endsWith(".js") && isFlow(src));
|
|
180
|
+
if (compile) return { code: transformRN(file, src, projectRoot, platform), scan: true };
|
|
141
181
|
return { code: src, scan: true };
|
|
142
182
|
}
|
|
143
183
|
|
|
144
184
|
/**
|
|
145
185
|
* Resolve one require target from a file, applying the platform-extension
|
|
146
|
-
* resolution the hooks apply inside node_modules (`./Foo` → `Foo.ios.js`)
|
|
147
|
-
*
|
|
186
|
+
* resolution the hooks apply inside node_modules (`./Foo` → `Foo.ios.js`), narrowed
|
|
187
|
+
* by a library's own Jest resolver for that library's files, as the hooks narrow it
|
|
188
|
+
* (jest-resolvers.mjs). Returns an absolute path, or null when the target cannot be
|
|
189
|
+
* resolved.
|
|
148
190
|
*/
|
|
149
|
-
function resolveTarget(
|
|
191
|
+
function resolveTarget(
|
|
192
|
+
request,
|
|
193
|
+
fromFile,
|
|
194
|
+
{ projectRoot, platform, sourceExts, sharedResolver = null },
|
|
195
|
+
) {
|
|
150
196
|
if (request.startsWith(".") && !path.extname(request)) {
|
|
151
|
-
const
|
|
197
|
+
const narrowed = libraryExtensionsFor(
|
|
198
|
+
projectRoot,
|
|
199
|
+
request,
|
|
200
|
+
fromFile,
|
|
201
|
+
extensionsFor(platform, sourceExts),
|
|
202
|
+
);
|
|
203
|
+
const hit = narrowed
|
|
204
|
+
? resolveRelativeWithExtensions(request, fromFile, narrowed)
|
|
205
|
+
: resolveRelativePlatformFile(request, fromFile, platform, sourceExts);
|
|
152
206
|
if (hit) return hit;
|
|
153
207
|
}
|
|
208
|
+
// experimental.ownershipModel: a bare request is answered by the resolver every realm
|
|
209
|
+
// uses, here, once, at build time, so the registry bakes in the file Node's require
|
|
210
|
+
// hook would answer and costs no resolution when a worker runs it.
|
|
211
|
+
if (sharedResolver !== null && !request.startsWith(".") && !path.isAbsolute(request)) {
|
|
212
|
+
const shared = sharedResolver.resolve(request, fromFile, (id) =>
|
|
213
|
+
createRequire(fromFile).resolve(id),
|
|
214
|
+
);
|
|
215
|
+
if (shared) return shared;
|
|
216
|
+
}
|
|
217
|
+
// A whole package through its `react-native` field, as the require hooks resolve it at
|
|
218
|
+
// run time (hooks.mjs), so the registry's module and Node's are one file.
|
|
219
|
+
if (isWholePackageRequest(request)) {
|
|
220
|
+
const entry = resolvePackageMainField(request, path.dirname(fromFile), platform, sourceExts);
|
|
221
|
+
if (entry) return entry;
|
|
222
|
+
}
|
|
154
223
|
try {
|
|
155
224
|
return createRequire(fromFile).resolve(request);
|
|
156
225
|
} catch {
|
|
@@ -222,6 +291,7 @@ export function registryKeyInputs({
|
|
|
222
291
|
assetExts = [],
|
|
223
292
|
sourceExts = ["js", "jsx", "json", "ts", "tsx"],
|
|
224
293
|
additionalEntries = [],
|
|
294
|
+
resolverInputs,
|
|
225
295
|
}) {
|
|
226
296
|
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
227
297
|
const version = (name) => {
|
|
@@ -290,6 +360,16 @@ export function registryKeyInputs({
|
|
|
290
360
|
...sourceExts.map((extension) => `source:${extension}`),
|
|
291
361
|
...canonicalAssetExtensions(assetExts).map((extension) => `asset:${extension}`),
|
|
292
362
|
...canonicalAdditionalEntries(additionalEntries).map((entry) => `entry:${entry}`),
|
|
363
|
+
// experimental.ownershipModel: the walk resolves bare requests with the shared
|
|
364
|
+
// resolver (resolveTarget), so the baked paths depend on every input it resolves
|
|
365
|
+
// from. Absent with the flag off, so the key, and the cache, are unchanged for
|
|
366
|
+
// every other project.
|
|
367
|
+
// The project root is left out: the walk resolves every request from the React
|
|
368
|
+
// Native file that asks, never from the root, so projects that share the other
|
|
369
|
+
// inputs share one registry, as they do with the flag off.
|
|
370
|
+
...(resolverInputs
|
|
371
|
+
? [`resolver:${resolverInputsHash({ ...resolverInputs, projectRoot: "" })}`]
|
|
372
|
+
: []),
|
|
293
373
|
boundaries.digest("hex"),
|
|
294
374
|
];
|
|
295
375
|
}
|
|
@@ -339,15 +419,68 @@ function manifestValid(manifest) {
|
|
|
339
419
|
* +6% per file on a 200-file hot suite; reusing `vm.compileFunction` after a first
|
|
340
420
|
* `_compile` load needs a hand-built copy of Node's `require`.
|
|
341
421
|
*/
|
|
342
|
-
function emit(files, modules) {
|
|
422
|
+
function emit(files, modules, { library = false } = {}) {
|
|
343
423
|
const idOf = new Map(files.map((f, i) => [f, i]));
|
|
344
424
|
const deps = files.map((f) => {
|
|
345
425
|
const out = {};
|
|
426
|
+
const own = library ? owningPackageOfFile(f) : null;
|
|
346
427
|
for (const [request, target] of Object.entries(modules.get(f).deps)) {
|
|
347
|
-
|
|
428
|
+
// In a library registry an edge into another package is linked by path, through
|
|
429
|
+
// __out, so a preset shadowing that package applies to it as to any require.
|
|
430
|
+
const id = target === null ? undefined : idOf.get(target);
|
|
431
|
+
out[request] =
|
|
432
|
+
target === null
|
|
433
|
+
? null
|
|
434
|
+
: id !== undefined && (!library || owningPackageOfFile(target) === own)
|
|
435
|
+
? id
|
|
436
|
+
: target;
|
|
348
437
|
}
|
|
349
438
|
return JSON.stringify(out);
|
|
350
439
|
});
|
|
440
|
+
// A require that leaves this registry. In React Native's registry that is a Node
|
|
441
|
+
// require at a pre-resolved path. In a library registry, a path that is one of React
|
|
442
|
+
// Native's modules is served from React Native's registry instance instead, so a
|
|
443
|
+
// library and the app share one React Native by construction rather than by
|
|
444
|
+
// re-entering Node's loader for it. A request for a package a preset shadows gets
|
|
445
|
+
// what the per-file hooks give it (__vitest_native_preset_require, hooks.mjs). Any
|
|
446
|
+
// other target, another package of this registry included, is required by path
|
|
447
|
+
// through this file's own require, which Node resolves once per path rather than on
|
|
448
|
+
// every call; a target in this registry comes back to it by path
|
|
449
|
+
// (installRegistry's interceptor).
|
|
450
|
+
const outside = library
|
|
451
|
+
? [
|
|
452
|
+
`const __names = new Map();`,
|
|
453
|
+
`function __name(q) {`,
|
|
454
|
+
` let n = __names.get(q);`,
|
|
455
|
+
` if (n === undefined) {`,
|
|
456
|
+
` const c = q.charCodeAt(0);`,
|
|
457
|
+
` const parts = q.split("/");`,
|
|
458
|
+
` n = c === 46 || c === 47 || q.includes(":") ? null : c === 64 ? parts.slice(0, 2).join("/") : parts[0];`,
|
|
459
|
+
` __names.set(q, n);`,
|
|
460
|
+
` }`,
|
|
461
|
+
` return n;`,
|
|
462
|
+
`}`,
|
|
463
|
+
`function __out(t, q, from) {`,
|
|
464
|
+
// A jest.mock of the target wins, then a preset shadowing it, as for a require
|
|
465
|
+
// that goes through Node's loader (jest-compat's hook runs first there).
|
|
466
|
+
` const mock = globalThis.__vitest_native_node_mock_for;`,
|
|
467
|
+
` if (mock !== undefined) {`,
|
|
468
|
+
` const v = mock(t, q, from);`,
|
|
469
|
+
` if (v !== mock.NONE) return v;`,
|
|
470
|
+
` }`,
|
|
471
|
+
` const rn = __rnIdOf.get(t);`,
|
|
472
|
+
` if (rn !== undefined) return __rnLoad(rn);`,
|
|
473
|
+
` const mocks = globalThis.__vitest_native_preset_mocks;`,
|
|
474
|
+
` const preset = globalThis.__vitest_native_preset_require;`,
|
|
475
|
+
` if (mocks !== undefined && preset !== undefined) {`,
|
|
476
|
+
` const name = __name(q);`,
|
|
477
|
+
` const own = Object.prototype.hasOwnProperty;`,
|
|
478
|
+
` if (own.call(mocks, q) || (name !== null && own.call(mocks, name))) return preset(q, t);`,
|
|
479
|
+
` }`,
|
|
480
|
+
` return __ext(t);`,
|
|
481
|
+
`}`,
|
|
482
|
+
]
|
|
483
|
+
: [];
|
|
351
484
|
const prologue = [
|
|
352
485
|
// __ext is this file's own require: the escape hatch for targets outside the
|
|
353
486
|
// registry (react, invariant, JSON, anything computed). Pre-resolved absolute
|
|
@@ -359,18 +492,20 @@ function emit(files, modules) {
|
|
|
359
492
|
`const __ids = ${JSON.stringify(files)};`,
|
|
360
493
|
`const __deps = [${deps.join(",")}];`,
|
|
361
494
|
`const __dirs = __ids.map((f) => f.slice(0, Math.max(f.lastIndexOf("/"), f.lastIndexOf("\\\\"))));`,
|
|
495
|
+
...outside,
|
|
362
496
|
`function __req(i) {`,
|
|
363
497
|
` const map = __deps[i];`,
|
|
364
498
|
` const r = function (q) {`,
|
|
365
499
|
` const t = map[q];`,
|
|
366
500
|
` if (t === undefined || t === null) return __ext(q);`,
|
|
367
|
-
` if (typeof t !== "number") return __ext(t);`,
|
|
501
|
+
` if (typeof t !== "number") return ${library ? "__out(t, q, __ids[i])" : "__ext(t)"};`,
|
|
368
502
|
// A jest.mock of a React Native module (jest-compat's per-file registry, see
|
|
369
503
|
// jest-compat/node-registry.mjs) applies to RN's own requires of it, as under
|
|
370
504
|
// Jest. The global is undefined unless such a mock is registered.
|
|
371
505
|
` const mock = globalThis.__vitest_native_node_mock_for;`,
|
|
372
506
|
` if (mock !== undefined) {`,
|
|
373
|
-
|
|
507
|
+
// With the request and the requiring module, as Node's loader has them.
|
|
508
|
+
` const v = mock(__ids[t], q, __ids[i]);`,
|
|
374
509
|
` if (v !== mock.NONE) return v;`,
|
|
375
510
|
` }`,
|
|
376
511
|
` return __r(t);`,
|
|
@@ -422,6 +557,31 @@ function emit(files, modules) {
|
|
|
422
557
|
` return mod.exports;`,
|
|
423
558
|
`}`,
|
|
424
559
|
];
|
|
560
|
+
const sources = files.map((f, i) => {
|
|
561
|
+
const code = modules.get(f).code;
|
|
562
|
+
return USES_IMPORT.test(code)
|
|
563
|
+
? `__s[${i}] = null; __l[${i}] = ${JSON.stringify(code)};`
|
|
564
|
+
: `__s[${i}] = ${JSON.stringify(code)};`;
|
|
565
|
+
});
|
|
566
|
+
const reset = `reset: () => { __m.length = 0; }, compiles: () => __compiles`;
|
|
567
|
+
// The modules that have run since the last reset: the library registry's per-file
|
|
568
|
+
// cost, which the native suite holds to the modules a file touches.
|
|
569
|
+
const ran = `ran: () => __ids.filter((_, i) => __m[i] !== undefined)`;
|
|
570
|
+
if (library) {
|
|
571
|
+
// A library registry is linked to the worker's React Native registry, whose ids
|
|
572
|
+
// and loader it receives, rather than finding it through a global. Linking runs
|
|
573
|
+
// once per worker; a reset clears instances and keeps compiled functions, as in
|
|
574
|
+
// React Native's registry. Nothing runs until a module is required.
|
|
575
|
+
const packages = [...new Set(files.map(owningPackageOfFile).filter(Boolean))].sort();
|
|
576
|
+
return [
|
|
577
|
+
`module.exports = function link(__rnIds, __rnLoad) {`,
|
|
578
|
+
`const __rnIdOf = new Map(__rnIds.map((f, i) => [f, i]));`,
|
|
579
|
+
...prologue,
|
|
580
|
+
...sources,
|
|
581
|
+
`return { ids: __ids, load: __r, ${reset}, ${ran}, packages: ${JSON.stringify(packages)} };`,
|
|
582
|
+
`};`,
|
|
583
|
+
].join("\n");
|
|
584
|
+
}
|
|
425
585
|
const epilogue = [
|
|
426
586
|
// The entry's exports are the module's value, so `require(registry)` behaves
|
|
427
587
|
// like `require('react-native')`. __registry is the lookup surface the install
|
|
@@ -429,18 +589,224 @@ function emit(files, modules) {
|
|
|
429
589
|
`const __entry = __r(0);`,
|
|
430
590
|
`module.exports = __entry;`,
|
|
431
591
|
`Object.defineProperty(module.exports, "__vitestNativeRegistry", {`,
|
|
432
|
-
`
|
|
592
|
+
// `ran` as in the library registry: what a test file's imports cost in React Native
|
|
593
|
+
// modules, which tests-native/rn-facade-cost.test.ts holds and
|
|
594
|
+
// scripts/measure-rn-evaluations.mjs sums per file.
|
|
595
|
+
` value: { ids: __ids, load: __r, entry: __ids[0], ${reset}, ${ran} },`,
|
|
433
596
|
` enumerable: false, configurable: true,`,
|
|
434
597
|
`});`,
|
|
435
598
|
];
|
|
599
|
+
return [...prologue, ...sources, ...epilogue].join("\n");
|
|
600
|
+
}
|
|
436
601
|
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
602
|
+
/**
|
|
603
|
+
* Where the registry for these options lives: its file, and the metadata file that is
|
|
604
|
+
* published last and so marks a complete registry. Computing it never creates a
|
|
605
|
+
* directory or compiles anything. Throws when the cache key cannot be computed.
|
|
606
|
+
*/
|
|
607
|
+
export function registryLocation({
|
|
608
|
+
projectRoot,
|
|
609
|
+
platform = "ios",
|
|
610
|
+
reactNativeVersion = "0.0.0",
|
|
611
|
+
assetExts = [],
|
|
612
|
+
sourceExts = ["js", "jsx", "json", "ts", "tsx"],
|
|
613
|
+
additionalEntries = [],
|
|
614
|
+
resolverInputs,
|
|
615
|
+
}) {
|
|
616
|
+
const key = registryKey({
|
|
617
|
+
projectRoot,
|
|
618
|
+
platform,
|
|
619
|
+
reactNativeVersion,
|
|
620
|
+
assetExts,
|
|
621
|
+
sourceExts,
|
|
622
|
+
additionalEntries,
|
|
623
|
+
resolverInputs,
|
|
442
624
|
});
|
|
443
|
-
|
|
625
|
+
const dir = path.join(cacheRootFor(projectRoot), "registry");
|
|
626
|
+
const registryFile = path.join(dir, `rn-${platform}-${key}.cjs`);
|
|
627
|
+
return { key, registryFile, metaFile: `${registryFile}.json` };
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* A memoised lookup of the packages a file's package depends on as its own: those in
|
|
632
|
+
* its manifest's `dependencies` and `optionalDependencies` that it does not also name
|
|
633
|
+
* as peers. A peer is shared with the app, so it stays outside the library's graph.
|
|
634
|
+
*/
|
|
635
|
+
function privateDependenciesOf() {
|
|
636
|
+
const byManifest = new Map();
|
|
637
|
+
return (file) => {
|
|
638
|
+
const norm = file.replace(/\\/g, "/");
|
|
639
|
+
const at = norm.lastIndexOf("/node_modules/");
|
|
640
|
+
const pkg = owningPackageOfFile(file);
|
|
641
|
+
if (at === -1 || pkg === null) return EMPTY;
|
|
642
|
+
const manifest = path.join(
|
|
643
|
+
file.slice(0, at + "/node_modules/".length + pkg.length),
|
|
644
|
+
"package.json",
|
|
645
|
+
);
|
|
646
|
+
let names = byManifest.get(manifest);
|
|
647
|
+
if (names === undefined) {
|
|
648
|
+
const json = JSON.parse(fs.readFileSync(manifest, "utf8"));
|
|
649
|
+
const peers = new Set(Object.keys(json.peerDependencies ?? {}));
|
|
650
|
+
names = new Set(
|
|
651
|
+
[
|
|
652
|
+
...Object.keys(json.dependencies ?? {}),
|
|
653
|
+
...Object.keys(json.optionalDependencies ?? {}),
|
|
654
|
+
].filter((name) => !peers.has(name)),
|
|
655
|
+
);
|
|
656
|
+
byManifest.set(manifest, names);
|
|
657
|
+
}
|
|
658
|
+
return names;
|
|
659
|
+
};
|
|
660
|
+
}
|
|
661
|
+
const EMPTY = new Set();
|
|
662
|
+
|
|
663
|
+
/** The registry cache directory, or null (warned, or thrown under failOnError). */
|
|
664
|
+
function registryDir(projectRoot, failOnError) {
|
|
665
|
+
try {
|
|
666
|
+
const dir = path.join(cacheRootFor(projectRoot), "registry");
|
|
667
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
668
|
+
return dir;
|
|
669
|
+
} catch (error) {
|
|
670
|
+
if (failOnError) throw error;
|
|
671
|
+
warnRegistryUnavailable(error?.message ?? "cache directory unavailable");
|
|
672
|
+
return null;
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
/** True when a published registry file and its metadata match `key` and its manifest. */
|
|
677
|
+
function cachedLayer(registryFile, key) {
|
|
678
|
+
try {
|
|
679
|
+
const meta = JSON.parse(fs.readFileSync(`${registryFile}.json`, "utf8"));
|
|
680
|
+
if (meta.key === key && fs.existsSync(registryFile) && manifestValid(meta.manifest)) {
|
|
681
|
+
return meta;
|
|
682
|
+
}
|
|
683
|
+
} catch {
|
|
684
|
+
// No usable cache entry.
|
|
685
|
+
}
|
|
686
|
+
return null;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/**
|
|
690
|
+
* Walk a module graph from `roots` and publish it as one registry file.
|
|
691
|
+
*
|
|
692
|
+
* Shared by React Native's registry and the library registry, so both are built,
|
|
693
|
+
* keyed, validated and published the same way: `inline(target, from)` decides which
|
|
694
|
+
* resolved targets become registry modules; every other resolved target stays a
|
|
695
|
+
* require at a pre-resolved path and is pinned in the manifest.
|
|
696
|
+
*/
|
|
697
|
+
function publishLayer({ registryFile, key, roots, inline, options, library, pinned = [] }) {
|
|
698
|
+
const modules = new Map();
|
|
699
|
+
const manifest = [];
|
|
700
|
+
// Targets the registry does NOT inline but DOES bake in as pre-resolved absolute
|
|
701
|
+
// paths. They belong in the manifest for the same reason the inlined files do: if
|
|
702
|
+
// one moves or changes, the paths compiled into the registry are wrong. See the
|
|
703
|
+
// note above the externals loop below.
|
|
704
|
+
const externals = new Set();
|
|
705
|
+
const queue = [...roots].reverse();
|
|
706
|
+
let file;
|
|
707
|
+
try {
|
|
708
|
+
walk();
|
|
709
|
+
} catch (error) {
|
|
710
|
+
// What the walk had read when it failed, the failing file included: a recorded
|
|
711
|
+
// failure stands until one of them changes (buildLibraryRegistry).
|
|
712
|
+
error.filesRead = [...manifest.map(([read]) => read), file];
|
|
713
|
+
throw error;
|
|
714
|
+
}
|
|
715
|
+
function walk() {
|
|
716
|
+
while (queue.length > 0) {
|
|
717
|
+
file = queue.pop();
|
|
718
|
+
if (modules.has(file)) continue;
|
|
719
|
+
const { code, scan } = sourceFor(file, { ...options, library });
|
|
720
|
+
const deps = {};
|
|
721
|
+
if (scan) {
|
|
722
|
+
for (const match of code.matchAll(REQUIRE_RE)) {
|
|
723
|
+
const request = match[2];
|
|
724
|
+
if (request in deps) continue;
|
|
725
|
+
const target = resolveTarget(request, file, options);
|
|
726
|
+
deps[request] = target;
|
|
727
|
+
if (target === null) continue;
|
|
728
|
+
const ext = path.extname(target).toLowerCase();
|
|
729
|
+
if (inline(target, file) && (!PASSTHROUGH_EXT.has(ext) || (library && ext === ".json"))) {
|
|
730
|
+
queue.push(target);
|
|
731
|
+
} else {
|
|
732
|
+
externals.add(target);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
modules.set(file, { code, deps });
|
|
737
|
+
const st = fs.statSync(file);
|
|
738
|
+
manifest.push([file, st.mtimeMs, st.size]);
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
// Externals are require()d through pre-resolved absolute paths baked into the
|
|
743
|
+
// emitted registry, so the registry is only valid while those paths still point
|
|
744
|
+
// at what they pointed at when it was built. Nothing noticed when they did not:
|
|
745
|
+
// upgrading React served a registry whose baked path was a react directory that
|
|
746
|
+
// no longer existed, and the fallback produced a second React — a null dispatcher
|
|
747
|
+
// and React Native singletons that stopped comparing equal.
|
|
748
|
+
//
|
|
749
|
+
// Naming the packages in the cache key instead would work only for the ones
|
|
750
|
+
// somebody remembered to name. Statting the resolved targets covers every
|
|
751
|
+
// external there is, and covers both node_modules layouts: under bun and pnpm a
|
|
752
|
+
// version change moves the path, so the stat fails; under a flat npm or yarn tree
|
|
753
|
+
// the path survives but the file's size and mtime change.
|
|
754
|
+
for (const target of [...externals, ...pinned]) {
|
|
755
|
+
try {
|
|
756
|
+
const st = fs.statSync(target);
|
|
757
|
+
manifest.push([target, st.mtimeMs, st.size]);
|
|
758
|
+
} catch {
|
|
759
|
+
// Not a real file on disk (a native addon resolved elsewhere, a virtual
|
|
760
|
+
// target). Nothing to pin; the runtime require still decides.
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
const files = [...modules.keys()];
|
|
765
|
+
const code = emit(files, modules, { library });
|
|
766
|
+
publishAtomically(registryFile, `${code}\n`);
|
|
767
|
+
publishAtomically(`${registryFile}.json`, JSON.stringify({ key, count: files.length, manifest }));
|
|
768
|
+
return files.length;
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
// Write via a unique temp file then rename: several workers may race here on a
|
|
772
|
+
// cold cache, and a reader must never observe a partially written registry.
|
|
773
|
+
function publishAtomically(destination, contents) {
|
|
774
|
+
const temporaryFile = `${destination}.${process.pid}.tmp`;
|
|
775
|
+
try {
|
|
776
|
+
fs.writeFileSync(temporaryFile, contents);
|
|
777
|
+
try {
|
|
778
|
+
fs.renameSync(temporaryFile, destination);
|
|
779
|
+
} catch (error) {
|
|
780
|
+
// POSIX rename replaces an existing file atomically. Windows rejects that
|
|
781
|
+
// shape, which two cold compiler processes can hit together. Remove only
|
|
782
|
+
// the already-published destination and retry; metadata is committed last,
|
|
783
|
+
// so readers never accept a half-published new registry as valid.
|
|
784
|
+
if (
|
|
785
|
+
process.platform !== "win32" ||
|
|
786
|
+
!["EEXIST", "EPERM", "EACCES"].includes(error?.code) ||
|
|
787
|
+
!fs.existsSync(destination)
|
|
788
|
+
) {
|
|
789
|
+
throw error;
|
|
790
|
+
}
|
|
791
|
+
fs.rmSync(destination, { force: true });
|
|
792
|
+
fs.renameSync(temporaryFile, destination);
|
|
793
|
+
}
|
|
794
|
+
} finally {
|
|
795
|
+
// A failed write or publication must not leave a growing trail of PID
|
|
796
|
+
// temp files. A fatal process kill is recovered by the next cache miss.
|
|
797
|
+
fs.rmSync(temporaryFile, { force: true });
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
function layerOptions({ projectRoot, platform, reactNativeVersion, assetExts, sourceExts }) {
|
|
802
|
+
return {
|
|
803
|
+
projectRoot,
|
|
804
|
+
platform,
|
|
805
|
+
reactNativeVersion,
|
|
806
|
+
assetExtSet: new Set(assetExts.map((e) => String(e).replace(/^\./, "").toLowerCase())),
|
|
807
|
+
sourceExts,
|
|
808
|
+
ownership: createNativeOwnershipPolicy({ projectRoot }),
|
|
809
|
+
};
|
|
444
810
|
}
|
|
445
811
|
|
|
446
812
|
/**
|
|
@@ -456,12 +822,17 @@ export function buildRegistry({
|
|
|
456
822
|
sourceExts = ["js", "jsx", "json", "ts", "tsx"],
|
|
457
823
|
diagnostics = false,
|
|
458
824
|
additionalEntries = [],
|
|
825
|
+
// experimental.ownershipModel: the project context's resolver inputs, or undefined.
|
|
826
|
+
resolverInputs,
|
|
459
827
|
// Internal orchestration controls. `cacheOnly` lets the long-lived Vite process
|
|
460
828
|
// perform the cheap key/manifest check without ever loading Babel or compiling
|
|
461
829
|
// RN. `failOnError` lets the bounded compiler child return a structured failure;
|
|
462
830
|
// ordinary callers keep the warning + correctness-preserving fallback contract.
|
|
463
831
|
cacheOnly = false,
|
|
464
832
|
failOnError = false,
|
|
833
|
+
// registryLocation's result for these options, when the caller already has it, so a
|
|
834
|
+
// run computes the key (which hashes the boundary mocks' source) once.
|
|
835
|
+
location,
|
|
465
836
|
}) {
|
|
466
837
|
// See warnRegistryUnavailable: this is the one path that stays quiet, because
|
|
467
838
|
// the user asked for it.
|
|
@@ -478,70 +849,59 @@ export function buildRegistry({
|
|
|
478
849
|
}
|
|
479
850
|
return null;
|
|
480
851
|
}
|
|
481
|
-
let dir;
|
|
482
852
|
let key;
|
|
853
|
+
let registryFile;
|
|
483
854
|
try {
|
|
484
|
-
key =
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
855
|
+
({ key, registryFile } =
|
|
856
|
+
location ??
|
|
857
|
+
registryLocation({
|
|
858
|
+
projectRoot,
|
|
859
|
+
platform,
|
|
860
|
+
reactNativeVersion,
|
|
861
|
+
assetExts,
|
|
862
|
+
sourceExts,
|
|
863
|
+
additionalEntries,
|
|
864
|
+
resolverInputs,
|
|
865
|
+
}));
|
|
494
866
|
} catch (error) {
|
|
495
867
|
if (failOnError) throw error;
|
|
496
868
|
warnRegistryUnavailable(error?.message ?? "cache directory unavailable");
|
|
497
869
|
return null;
|
|
498
870
|
}
|
|
871
|
+
if (registryDir(projectRoot, failOnError) === null) return null;
|
|
499
872
|
|
|
500
|
-
const
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
console.log(
|
|
507
|
-
`[vitest-native] (native) reusing precompiled RN registry (${meta.count} modules)`,
|
|
508
|
-
);
|
|
509
|
-
}
|
|
510
|
-
return registryFile;
|
|
873
|
+
const meta = cachedLayer(registryFile, key);
|
|
874
|
+
if (meta !== null) {
|
|
875
|
+
if (diagnostics) {
|
|
876
|
+
console.log(
|
|
877
|
+
`[vitest-native] (native) reusing precompiled RN registry (${meta.count} modules)`,
|
|
878
|
+
);
|
|
511
879
|
}
|
|
512
|
-
|
|
513
|
-
// No usable cache entry — build one below.
|
|
880
|
+
return registryFile;
|
|
514
881
|
}
|
|
515
882
|
|
|
516
883
|
if (cacheOnly) return null;
|
|
517
884
|
|
|
518
885
|
const started = Date.now();
|
|
519
|
-
const
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
assetExtSet,
|
|
526
|
-
sourceExts,
|
|
527
|
-
ownership,
|
|
528
|
-
};
|
|
529
|
-
const modules = new Map();
|
|
530
|
-
const manifest = [];
|
|
531
|
-
// Targets the registry does NOT inline but DOES bake in as pre-resolved absolute
|
|
532
|
-
// paths. They belong in the manifest for the same reason React Native's own files
|
|
533
|
-
// do: if one moves or changes, the paths compiled into the registry are wrong.
|
|
534
|
-
// See the note above the manifest write below.
|
|
535
|
-
const externals = new Set();
|
|
886
|
+
const sharedResolver = resolverInputs
|
|
887
|
+
? // Node's CommonJS resolution, NODE_PATH included: the registry answers require.
|
|
888
|
+
createSharedResolver(resolverInputs, { realm: "registry", globalFolders: true })
|
|
889
|
+
: null;
|
|
890
|
+
// The counters are per realm and process; this build's errors are those counted after.
|
|
891
|
+
const errorsBeforeWalk = sharedResolver?.counters.fallbacks.error ?? 0;
|
|
536
892
|
try {
|
|
893
|
+
const options = {
|
|
894
|
+
...layerOptions({ projectRoot, platform, reactNativeVersion, assetExts, sourceExts }),
|
|
895
|
+
sharedResolver,
|
|
896
|
+
};
|
|
537
897
|
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
538
|
-
const entry = req.resolve("react-native");
|
|
539
898
|
// Keep the public React Native entry first in insertion order: emit() treats
|
|
540
899
|
// module zero as the capsule's default export. Additional ecosystem-owned deep
|
|
541
900
|
// imports are seed roots only; their factories remain lazy like the root graph.
|
|
542
|
-
const
|
|
543
|
-
req.resolve(
|
|
544
|
-
|
|
901
|
+
const roots = [
|
|
902
|
+
req.resolve("react-native"),
|
|
903
|
+
...canonicalAdditionalEntries(additionalEntries).map((request) => req.resolve(request)),
|
|
904
|
+
];
|
|
545
905
|
// Asset modules require Metro's assetRegistryPath by absolute path (assets.mjs),
|
|
546
906
|
// and that entry must be a registry module: loaded outside it, its relative
|
|
547
907
|
// require of the registry module (0.87+) would create a second asset array whose
|
|
@@ -549,104 +909,200 @@ export function buildRegistry({
|
|
|
549
909
|
// already pull the entry in through their asset modules; seeding it keeps that
|
|
550
910
|
// true without depending on which of React Native's assets the walk reaches.
|
|
551
911
|
const assetRegistry = assetRegistryPathFor(projectRoot);
|
|
552
|
-
if (assetRegistry !== null)
|
|
553
|
-
const
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
912
|
+
if (assetRegistry !== null) roots.push(assetRegistry);
|
|
913
|
+
const count = publishLayer({
|
|
914
|
+
registryFile,
|
|
915
|
+
key,
|
|
916
|
+
roots,
|
|
917
|
+
// Only React Native's own graph is inlined. Everything else — react,
|
|
918
|
+
// invariant, JSON manifests, native addons — stays a normal Node require at a
|
|
919
|
+
// pre-resolved absolute path, so those modules keep their usual identity and
|
|
920
|
+
// are shared with the rest of the worker.
|
|
921
|
+
inline: (target) => options.ownership.isReactNativeFile(target),
|
|
922
|
+
options,
|
|
923
|
+
library: false,
|
|
924
|
+
});
|
|
925
|
+
// A resolver error during the walk would bake Node's answer in silently, where the
|
|
926
|
+
// workers' resolver would answer otherwise: fail the build by name instead (the
|
|
927
|
+
// caller reports it and falls back to per-file loading).
|
|
928
|
+
const walkErrors = sharedResolver?.counters.fallbacks.error ?? 0;
|
|
929
|
+
if (walkErrors > errorsBeforeWalk) {
|
|
930
|
+
throw new VitestNativeError(
|
|
931
|
+
"RESOLVER_ERROR",
|
|
932
|
+
`experimental.ownershipModel: the shared resolver failed while the registry was ` +
|
|
933
|
+
`built: ${sharedResolver.counters.errors.join("; ")}`,
|
|
934
|
+
);
|
|
935
|
+
}
|
|
936
|
+
if (diagnostics) {
|
|
937
|
+
console.log(
|
|
938
|
+
`[vitest-native] (native) precompiled RN registry: ${count} modules in ${Date.now() - started}ms`,
|
|
939
|
+
);
|
|
580
940
|
}
|
|
941
|
+
return registryFile;
|
|
942
|
+
} catch (error) {
|
|
943
|
+
if (failOnError) throw error;
|
|
944
|
+
warnRegistryUnavailable(error?.message ?? "unknown error");
|
|
945
|
+
return null;
|
|
946
|
+
}
|
|
947
|
+
}
|
|
581
948
|
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
949
|
+
/**
|
|
950
|
+
* Build (or reuse) the library registry layered on a React Native registry: the
|
|
951
|
+
* module graphs of the packages `libraryEntries` name, compiled the way the per-file
|
|
952
|
+
* hooks compile a package selected for compiling, in one file of lazy factories.
|
|
953
|
+
*
|
|
954
|
+
* Without it, a library that runs as itself in tests — Reanimated as its own mock is
|
|
955
|
+
* about 300 modules — goes through Node's loader module by module in every test file:
|
|
956
|
+
* a resolution, a read and a module object each, the cost React Native's registry
|
|
957
|
+
* removed for React Native. Built here, the walk and its transforms run once per
|
|
958
|
+
* install, like React Native's.
|
|
959
|
+
*
|
|
960
|
+
* Its key extends React Native's key, so anything that rebuilds React Native's
|
|
961
|
+
* registry rebuilds this one, while React Native's key and file never depend on the
|
|
962
|
+
* libraries. A require of a React Native module from a library file is linked to
|
|
963
|
+
* React Native's registry instance when the worker loads it (emit). Only files of
|
|
964
|
+
* the entries' own packages are inlined; their other dependencies stay requires at
|
|
965
|
+
* pre-resolved paths, pinned in the manifest, as React Native's are.
|
|
966
|
+
*
|
|
967
|
+
* Returns the file, or null when there is nothing to build or it cannot be built, in
|
|
968
|
+
* which case those packages keep loading through the per-file hooks.
|
|
969
|
+
*/
|
|
970
|
+
export function buildLibraryRegistry({
|
|
971
|
+
projectRoot,
|
|
972
|
+
platform = "ios",
|
|
973
|
+
reactNativeVersion = "0.0.0",
|
|
974
|
+
assetExts = [],
|
|
975
|
+
sourceExts = ["js", "jsx", "json", "ts", "tsx"],
|
|
976
|
+
diagnostics = false,
|
|
977
|
+
additionalEntries = [],
|
|
978
|
+
libraryEntries = [],
|
|
979
|
+
cacheOnly = false,
|
|
980
|
+
failOnError = false,
|
|
981
|
+
}) {
|
|
982
|
+
const entries = canonicalAdditionalEntries(libraryEntries);
|
|
983
|
+
if (entries.length === 0 || process.env.VITEST_NATIVE_NO_REGISTRY === "1") return null;
|
|
984
|
+
let key;
|
|
985
|
+
let roots;
|
|
986
|
+
try {
|
|
987
|
+
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
988
|
+
roots = entries.map(
|
|
989
|
+
(request) =>
|
|
990
|
+
(isWholePackageRequest(request) &&
|
|
991
|
+
resolvePackageMainField(request, projectRoot, platform, sourceExts)) ||
|
|
992
|
+
req.resolve(request),
|
|
993
|
+
);
|
|
994
|
+
key = crypto
|
|
995
|
+
.createHash("sha1")
|
|
996
|
+
.update(
|
|
997
|
+
[
|
|
998
|
+
registryKey({
|
|
999
|
+
projectRoot,
|
|
1000
|
+
platform,
|
|
1001
|
+
reactNativeVersion,
|
|
1002
|
+
assetExts,
|
|
1003
|
+
sourceExts,
|
|
1004
|
+
additionalEntries,
|
|
1005
|
+
}),
|
|
1006
|
+
...entries.map((entry, i) => `library:${entry}\0${roots[i]}`),
|
|
1007
|
+
].join("\0"),
|
|
1008
|
+
)
|
|
1009
|
+
.digest("hex")
|
|
1010
|
+
.slice(0, 16);
|
|
1011
|
+
} catch (error) {
|
|
1012
|
+
if (failOnError) throw error;
|
|
1013
|
+
warnRegistryUnavailable(error?.message ?? "library entries unavailable");
|
|
1014
|
+
return null;
|
|
1015
|
+
}
|
|
1016
|
+
const dir = registryDir(projectRoot, failOnError);
|
|
1017
|
+
if (dir === null) return null;
|
|
1018
|
+
|
|
1019
|
+
const registryFile = path.join(dir, `lib-${platform}-${key}.cjs`);
|
|
1020
|
+
const failureFile = `${registryFile}.failed.json`;
|
|
1021
|
+
const meta = cachedLayer(registryFile, key);
|
|
1022
|
+
if (meta !== null) {
|
|
1023
|
+
if (diagnostics) {
|
|
1024
|
+
console.log(
|
|
1025
|
+
`[vitest-native] (native) reusing precompiled library registry (${meta.count} modules)`,
|
|
1026
|
+
);
|
|
602
1027
|
}
|
|
1028
|
+
return registryFile;
|
|
1029
|
+
}
|
|
1030
|
+
// A build of these inputs that failed is not attempted again until one of the
|
|
1031
|
+
// files it read changes: a library registry is an optimisation, and relaunching
|
|
1032
|
+
// the compiler on every run to fail the same way would cost each run its build.
|
|
1033
|
+
const failed = recordedFailure(failureFile, key);
|
|
1034
|
+
if (failed !== null) {
|
|
1035
|
+
if (failOnError) throw new VitestNativeError("LIBRARY_REGISTRY_FAILED", failed);
|
|
1036
|
+
warnRegistryUnavailable(`library registry: ${failed}`);
|
|
1037
|
+
return null;
|
|
1038
|
+
}
|
|
1039
|
+
if (cacheOnly) return null;
|
|
603
1040
|
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
1041
|
+
const started = Date.now();
|
|
1042
|
+
try {
|
|
1043
|
+
const options = layerOptions({
|
|
1044
|
+
projectRoot,
|
|
1045
|
+
platform,
|
|
1046
|
+
reactNativeVersion,
|
|
1047
|
+
assetExts,
|
|
1048
|
+
sourceExts,
|
|
1049
|
+
});
|
|
1050
|
+
const packages = new Set(roots.map(owningPackageOfFile));
|
|
1051
|
+
const privateDependencies = privateDependenciesOf();
|
|
1052
|
+
const count = publishLayer({
|
|
1053
|
+
registryFile,
|
|
1054
|
+
key,
|
|
1055
|
+
roots,
|
|
1056
|
+
// The entries' packages, and the packages each inlined package depends on as its
|
|
1057
|
+
// own (`dependencies`, not peers, which it shares with the app). React Native's
|
|
1058
|
+
// files belong to React Native's registry.
|
|
1059
|
+
inline: (target, from) => {
|
|
1060
|
+
if (options.ownership.isReactNativeFile(target)) return false;
|
|
1061
|
+
const pkg = owningPackageOfFile(target);
|
|
1062
|
+
return (
|
|
1063
|
+
pkg !== null &&
|
|
1064
|
+
(packages.has(pkg) ||
|
|
1065
|
+
pkg === owningPackageOfFile(from) ||
|
|
1066
|
+
privateDependencies(from).has(pkg))
|
|
1067
|
+
);
|
|
1068
|
+
},
|
|
1069
|
+
options,
|
|
1070
|
+
library: true,
|
|
1071
|
+
// The libraries' own Jest resolvers chose the files this graph holds.
|
|
1072
|
+
pinned: libraryResolverFiles(projectRoot),
|
|
1073
|
+
});
|
|
637
1074
|
if (diagnostics) {
|
|
638
1075
|
console.log(
|
|
639
|
-
`[vitest-native] (native) precompiled
|
|
1076
|
+
`[vitest-native] (native) precompiled library registry: ${count} modules in ${Date.now() - started}ms`,
|
|
640
1077
|
);
|
|
641
1078
|
}
|
|
642
1079
|
return registryFile;
|
|
643
1080
|
} catch (error) {
|
|
1081
|
+
recordFailure(failureFile, key, error, [...roots, ...libraryResolverFiles(projectRoot)]);
|
|
644
1082
|
if (failOnError) throw error;
|
|
645
|
-
warnRegistryUnavailable(error?.message ?? "unknown error");
|
|
1083
|
+
warnRegistryUnavailable(`library registry: ${error?.message ?? "unknown error"}`);
|
|
646
1084
|
return null;
|
|
647
1085
|
}
|
|
648
1086
|
}
|
|
649
1087
|
|
|
1088
|
+
/** The reason a library registry build of `key` failed, while its inputs are unchanged. */
|
|
1089
|
+
function recordedFailure(failureFile, key) {
|
|
1090
|
+
if (!fs.existsSync(failureFile)) return null;
|
|
1091
|
+
const record = JSON.parse(fs.readFileSync(failureFile, "utf8"));
|
|
1092
|
+
return record.key === key && manifestValid(record.manifest) ? String(record.reason) : null;
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
/** Record a failed library registry build, against the files it read. */
|
|
1096
|
+
function recordFailure(failureFile, key, error, alwaysRead) {
|
|
1097
|
+
const manifest = [];
|
|
1098
|
+
for (const file of new Set([...(error?.filesRead ?? []), ...alwaysRead])) {
|
|
1099
|
+
const st = typeof file === "string" ? fs.statSync(file, { throwIfNoEntry: false }) : undefined;
|
|
1100
|
+
if (st) manifest.push([file, st.mtimeMs, st.size]);
|
|
1101
|
+
}
|
|
1102
|
+
const reason = String(error?.message ?? error).split("\n")[0];
|
|
1103
|
+
publishAtomically(failureFile, JSON.stringify({ key, reason, manifest }));
|
|
1104
|
+
}
|
|
1105
|
+
|
|
650
1106
|
/**
|
|
651
1107
|
* Serve React Native from the precompiled registry in this worker.
|
|
652
1108
|
*
|
|
@@ -658,6 +1114,7 @@ export function installRegistry(
|
|
|
658
1114
|
registryFile,
|
|
659
1115
|
projectRoot,
|
|
660
1116
|
sourceExts = ["js", "jsx", "json", "ts", "tsx"],
|
|
1117
|
+
libraryRegistryFile = undefined,
|
|
661
1118
|
) {
|
|
662
1119
|
if (globalThis.__vitest_native_registry_installed) return true;
|
|
663
1120
|
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
@@ -668,66 +1125,161 @@ export function installRegistry(
|
|
|
668
1125
|
} catch {
|
|
669
1126
|
return false;
|
|
670
1127
|
}
|
|
1128
|
+
const library = linkLibraryRegistry(req, libraryRegistryFile, registry);
|
|
1129
|
+
// The linked library registry, beside React Native's on the registry's own surface,
|
|
1130
|
+
// for the per-file accounting the native suite holds it to.
|
|
1131
|
+
registry.library = library?.registry ?? null;
|
|
1132
|
+
// Which files the library registry holds, for a preset that requires one by path to
|
|
1133
|
+
// get the registry's module (presets/reanimated.ts, ownHelpers).
|
|
1134
|
+
nodeDispatch().channel("registry").libraryHolds = (file) => library?.holds(file) === true;
|
|
671
1135
|
globalThis.__vitest_native_registry_installed = true;
|
|
672
|
-
|
|
1136
|
+
// One reset for both layers: a library module holds React Native instances, so it
|
|
1137
|
+
// must never outlive the React Native registry instances it was linked to.
|
|
1138
|
+
globalThis.__vitest_native_registry_reset = () => {
|
|
1139
|
+
registry.reset();
|
|
1140
|
+
library?.registry.reset();
|
|
1141
|
+
};
|
|
673
1142
|
|
|
674
1143
|
// Node records the loaded file under its real path (`/private/var/…` for macOS's
|
|
675
1144
|
// `/var/…` tmpdir), so match the registry file by both spellings.
|
|
676
1145
|
let registryRealFile = registryFile;
|
|
677
1146
|
try {
|
|
1147
|
+
// Node's spelling (fs.realpathSync): the file name Node records for the loaded registry.
|
|
678
1148
|
registryRealFile = fs.realpathSync(registryFile);
|
|
679
1149
|
} catch {
|
|
680
1150
|
// Just loaded, so it exists; an unresolvable path keeps the given spelling.
|
|
681
1151
|
}
|
|
682
1152
|
const idOf = new Map(registry.ids.map((f, i) => [f, i]));
|
|
683
1153
|
const entryId = idOf.get(registry.entry);
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
1154
|
+
// Beneath a per-file mock and a preset, above Node (LOAD_STEPS).
|
|
1155
|
+
nodeDispatch().load.add(
|
|
1156
|
+
"registry",
|
|
1157
|
+
(next) =>
|
|
1158
|
+
function (request, parent, ...rest) {
|
|
1159
|
+
if (request === "react-native") return registry.load(entryId);
|
|
1160
|
+
// An absolute path lands here when something re-enters through Node's loader
|
|
1161
|
+
// with an already-resolved file — most importantly the ESM loader's
|
|
1162
|
+
// `react-native/index.js` facade, which requires the real index by path.
|
|
1163
|
+
const direct = idOf.get(request);
|
|
1164
|
+
if (direct !== undefined) return registry.load(direct);
|
|
1165
|
+
if (library !== null) {
|
|
1166
|
+
const served = library.serve(request, parent);
|
|
1167
|
+
if (served !== NOT_SERVED) return served.value;
|
|
1168
|
+
}
|
|
1169
|
+
// Deep imports of RN internals (`react-native/Libraries/…`) and of the
|
|
1170
|
+
// @react-native/* packages inlined alongside it must resolve to the SAME
|
|
1171
|
+
// instances the entry graph uses, or RN's singletons would exist twice.
|
|
1172
|
+
if (request.startsWith("react-native/") || request.startsWith("@react-native/")) {
|
|
1173
|
+
// The registry's own code requires with the registry FILE as parent, and that
|
|
1174
|
+
// file lives in a cache directory that may be outside the project (tmpdir when
|
|
1175
|
+
// the project has no writable node_modules). Resolve those from the project.
|
|
1176
|
+
const fromProject =
|
|
1177
|
+
!parent?.filename ||
|
|
1178
|
+
parent.filename === registryFile ||
|
|
1179
|
+
parent.filename === registryRealFile ||
|
|
1180
|
+
(library !== null && library.isRegistryFile(parent.filename));
|
|
1181
|
+
const resolver = fromProject ? req : createRequire(parent.filename);
|
|
1182
|
+
const platform = projectContext()?.platform === "android" ? "android" : "ios";
|
|
1183
|
+
let resolved;
|
|
1184
|
+
try {
|
|
1185
|
+
resolved = resolver.resolve(request);
|
|
1186
|
+
} catch {
|
|
1187
|
+
// RN 0.87's exports map refuses the deep self-references its preset
|
|
1188
|
+
// emits; resolve by path (Metro's behavior) so the file still lands on
|
|
1189
|
+
// the registry's instance instead of loading a twin outside it.
|
|
1190
|
+
resolved =
|
|
1191
|
+
(fromProject
|
|
1192
|
+
? null
|
|
1193
|
+
: resolveDeepPackageFile(
|
|
1194
|
+
request,
|
|
1195
|
+
path.dirname(parent.filename),
|
|
1196
|
+
platform,
|
|
1197
|
+
sourceExts,
|
|
1198
|
+
)) ?? resolveDeepPackageFile(request, projectRoot, platform, sourceExts);
|
|
1199
|
+
}
|
|
1200
|
+
const id = resolved === null ? undefined : idOf.get(resolved);
|
|
1201
|
+
if (id !== undefined) return registry.load(id);
|
|
1202
|
+
// Resolved by path but not in the registry: forward the PATH — reloading
|
|
1203
|
+
// the bare specifier would just hit the exports map again.
|
|
1204
|
+
if (resolved !== null && path.isAbsolute(resolved)) {
|
|
1205
|
+
return next(resolved, parent, ...rest);
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
return next(request, parent, ...rest);
|
|
1209
|
+
},
|
|
1210
|
+
);
|
|
1211
|
+
return true;
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
const NOT_SERVED = Symbol("not served");
|
|
1215
|
+
|
|
1216
|
+
/**
|
|
1217
|
+
* Load and link the library registry, or null when there is none or it cannot be
|
|
1218
|
+
* loaded (those packages then keep loading through the per-file hooks).
|
|
1219
|
+
*
|
|
1220
|
+
* `serve` answers a request the library registry owns: an absolute path that is one
|
|
1221
|
+
* of its modules (the ESM loader's facades require by path), a bare request for one of
|
|
1222
|
+
* its packages, or a relative request from a file of those packages that Node loaded,
|
|
1223
|
+
* resolved from its parent by Node's resolution as the per-file hooks see it. Any
|
|
1224
|
+
* other request costs a Set lookup.
|
|
1225
|
+
*/
|
|
1226
|
+
function linkLibraryRegistry(req, file, rnRegistry) {
|
|
1227
|
+
if (!file) return null;
|
|
1228
|
+
let registry;
|
|
1229
|
+
// Node records a loaded file under its real path; match the registry's own
|
|
1230
|
+
// requires (their parent) by both spellings, as for React Native's registry.
|
|
1231
|
+
let spellings;
|
|
1232
|
+
try {
|
|
1233
|
+
registry = req(file)(rnRegistry.ids, rnRegistry.load);
|
|
1234
|
+
// The given and Node's spelling (fs.realpathSync), as Node records a loaded file.
|
|
1235
|
+
spellings = new Set([file, fs.realpathSync(file)]);
|
|
1236
|
+
} catch (error) {
|
|
1237
|
+
warnRegistryUnavailable(`library registry: ${error?.message ?? error}`);
|
|
1238
|
+
return null;
|
|
1239
|
+
}
|
|
1240
|
+
const idOf = new Map(registry.ids.map((f, i) => [f, i]));
|
|
1241
|
+
const packages = new Set(registry.packages);
|
|
1242
|
+
const isRegistryFile = (filename) => spellings.has(filename);
|
|
1243
|
+
// A request by name, from one directory, is one of the registry's modules for the
|
|
1244
|
+
// worker's lifetime: the registry was built from those files and serves them as
|
|
1245
|
+
// built, so it is resolved once rather than on every file the worker runs.
|
|
1246
|
+
const byName = new Map();
|
|
1247
|
+
return {
|
|
1248
|
+
registry,
|
|
1249
|
+
isRegistryFile,
|
|
1250
|
+
/** Whether `file` (its path as Node spells it) is one of the library registry's modules. */
|
|
1251
|
+
holds: (filename) => idOf.has(filename),
|
|
1252
|
+
serve(request, parent) {
|
|
1253
|
+
let id = idOf.get(request);
|
|
1254
|
+
if (id === undefined) {
|
|
1255
|
+
// A request the registry's own modules could not resolve at build time
|
|
1256
|
+
// has nothing to resolve against here either: the per-file hooks decide.
|
|
1257
|
+
if (!parent?.filename || isRegistryFile(parent.filename)) return NOT_SERVED;
|
|
1258
|
+
// A request for one of its packages by name, or a relative one from a file of
|
|
1259
|
+
// those packages that Node loaded (an entry the library never reached, such as
|
|
1260
|
+
// semver's index.js): either way the target, when it is one of the registry's
|
|
1261
|
+
// modules, is that module, so a package is one set of instances whichever way
|
|
1262
|
+
// it is reached.
|
|
1263
|
+
const owner =
|
|
1264
|
+
request.charCodeAt(0) === 46 /* . */
|
|
1265
|
+
? owningPackageOfFile(parent.filename)
|
|
1266
|
+
: packageNameOf(request);
|
|
1267
|
+
if (!packages.has(owner)) return NOT_SERVED;
|
|
1268
|
+
const key = `${path.dirname(parent.filename)}\0${request}`;
|
|
1269
|
+
id = byName.get(key);
|
|
1270
|
+
if (id === undefined) {
|
|
1271
|
+
let resolved;
|
|
1272
|
+
try {
|
|
1273
|
+
resolved = Module._resolveFilename(request, parent);
|
|
1274
|
+
} catch {
|
|
1275
|
+
return NOT_SERVED;
|
|
1276
|
+
}
|
|
1277
|
+
id = idOf.get(resolved);
|
|
1278
|
+
if (id === undefined) return NOT_SERVED;
|
|
1279
|
+
byName.set(key, id);
|
|
1280
|
+
}
|
|
728
1281
|
}
|
|
729
|
-
|
|
730
|
-
|
|
1282
|
+
return { value: registry.load(id) };
|
|
1283
|
+
},
|
|
731
1284
|
};
|
|
732
|
-
return true;
|
|
733
1285
|
}
|