@provino/loader 0.0.0-stage → 0.1.0-rc.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/dist/index.js ADDED
@@ -0,0 +1,3272 @@
1
+ import { a as esmSyntaxOf, c as conditionsOf, i as inGraph, n as packageDirOf, o as initLexer, r as buildThirdPartyGraph, s as scanSource } from "./graph.js";
2
+ import Module, { SourceMap, createRequire } from "node:module";
3
+ import { existsSync, readFileSync, statSync } from "node:fs";
4
+ import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
5
+ import { createBehaviourLoader } from "@provino/policy";
6
+ import { createNameMapper, createResolver } from "@provino/resolver";
7
+ import { LATE_IMPORT, createJestHost, createPipeline, ignoreRegExp, lockfileHash, toModuleRunner, usesModuleRunnerForm } from "@provino/transform";
8
+ import { cacheModeFor, openV8Pack } from "@provino/transform/v8cache";
9
+ import { fileURLToPath, pathToFileURL } from "node:url";
10
+ import * as vm from "node:vm";
11
+ import { Script, compileFunction } from "node:vm";
12
+ import { AsyncLocalStorage } from "node:async_hooks";
13
+ import { open, readFile } from "node:fs/promises";
14
+
15
+ // src/errors.ts
16
+ /**
17
+ * A specifier that doesn't resolve, thrown when its import or `require` runs. Its `name` stays
18
+ * `Error`, as Node's own not-found errors and jest-resolve's `ModuleNotFoundError` have it, since
19
+ * tests print and compare it; the text is the dialect's (`module-not-found`).
20
+ * @public
21
+ */
22
+ var ModuleNotFoundError = class extends Error {
23
+ code;
24
+ constructor(code, message) {
25
+ super(message);
26
+ this.code = code;
27
+ }
28
+ };
29
+ /**
30
+ * A `node_modules` file with ES module syntax that no transform takes and Node could not load,
31
+ * in the dialect's words (`require-esm`, Jest's `Must use import to load ES Module`). Its `name`
32
+ * stays `Error` and its code is Node's, as Jest's own error has them; its `cause` is Node's error.
33
+ * @public
34
+ */
35
+ var RequireEsmError = class extends Error {
36
+ code = "ERR_REQUIRE_ESM";
37
+ };
38
+ /**
39
+ * A loader error with a stable code.
40
+ * @public
41
+ */
42
+ var LoaderError = class extends Error {
43
+ code;
44
+ constructor(code, message, options) {
45
+ super(message, options);
46
+ this.name = "LoaderError";
47
+ this.code = code;
48
+ }
49
+ };
50
+
51
+ // src/internal/edge-kind.ts
52
+ /** Whether `path` is a file, without throwing for a missing one (an ENOENT costs a `NodeError`). */
53
+ function isFileOnDisk(path) {
54
+ return statSync(path, { throwIfNoEntry: false })?.isFile() === true;
55
+ }
56
+ /** A member of `node:vm` this Node may lack, read without its type (the flags decide). */
57
+ function vmMember(name) {
58
+ return Reflect.get(vm, name);
59
+ }
60
+ /**
61
+ * This process's answers. `vm.SyntheticModule` and `vm.SourceTextModule` exist only under
62
+ * `--experimental-vm-modules`, and `hasAsyncGraph` from Node 24.9, as jest-runtime's
63
+ * `nodeCapabilities.ts` reads them.
64
+ */
65
+ function probeRuntime() {
66
+ const sourceTextModule = vmMember("SourceTextModule");
67
+ return {
68
+ vmModules: typeof vmMember("SyntheticModule") === "function",
69
+ syncEvaluate: typeof sourceTextModule === "function" && typeof Reflect.get(sourceTextModule.prototype, "hasAsyncGraph") === "function"
70
+ };
71
+ }
72
+ /** `runtime` is this process's answers, probed when first asked for; a test passes its own. */
73
+ function createEdgeKindState(options, runtime, isFile = isFileOnDisk) {
74
+ const conditions = conditionsOf(options);
75
+ let capabilities = runtime;
76
+ return {
77
+ options,
78
+ runtime: () => capabilities ??= probeRuntime(),
79
+ conditions,
80
+ withModuleSync: conditions.includes("module-sync") ? conditions : [...conditions, "module-sync"],
81
+ esmByPath: /* @__PURE__ */ new Map(),
82
+ typeByManifest: /* @__PURE__ */ new Map(),
83
+ manifestByDir: /* @__PURE__ */ new Map(),
84
+ isFile
85
+ };
86
+ }
87
+ /** The `type` the `package.json` at `manifest` gives; an unreadable or broken one gives none. */
88
+ function packageTypeOf(manifest) {
89
+ try {
90
+ const parsed = JSON.parse(readFileSync(manifest, "utf8"));
91
+ if (typeof parsed !== "object" || parsed === null) return void 0;
92
+ const type = parsed.type;
93
+ return typeof type === "string" ? type : void 0;
94
+ } catch {
95
+ return;
96
+ }
97
+ }
98
+ /**
99
+ * The nearest `package.json` at or above `dir`, or `undefined` for none. The search stops at a
100
+ * `node_modules` directory, as Node's own (`module.findPackageJSON`) does. The answer is kept per
101
+ * directory, and every directory the walk passed gets it, so a directory's files cost one lookup
102
+ * and a walk ends at the first directory already known.
103
+ */
104
+ function nearestManifest(state, dir) {
105
+ const passed = [];
106
+ let found = null;
107
+ let current = dir;
108
+ for (;;) {
109
+ const known = state.manifestByDir.get(current);
110
+ if (known !== void 0) {
111
+ found = known;
112
+ break;
113
+ }
114
+ passed.push(current);
115
+ if (basename(current) === "node_modules") break;
116
+ const candidate = join(current, "package.json");
117
+ if (state.isFile(candidate)) {
118
+ found = candidate;
119
+ break;
120
+ }
121
+ const parent = dirname(current);
122
+ if (parent === current) break;
123
+ current = parent;
124
+ }
125
+ for (const directory of passed) state.manifestByDir.set(directory, found);
126
+ return found ?? void 0;
127
+ }
128
+ /**
129
+ * The `type` of the nearest `package.json` at or above the file at `path` (`"module"`,
130
+ * `"commonjs"`), or `undefined` for none, or one that does not parse: CommonJS, as Jest
131
+ * has it. Each manifest is read once.
132
+ */
133
+ function packageTypeAt(state, path) {
134
+ const manifest = nearestManifest(state, dirname(path));
135
+ if (manifest === void 0) return void 0;
136
+ if (state.typeByManifest.has(manifest)) return state.typeByManifest.get(manifest);
137
+ const type = packageTypeOf(manifest);
138
+ state.typeByManifest.set(manifest, type);
139
+ return type;
140
+ }
141
+ /**
142
+ * Whether the file at `path` is CommonJS by its name or its package, whatever its source holds:
143
+ * `.cjs`, or a `.js` whose nearest `package.json` says `"type": "commonjs"` (jest-runtime's
144
+ * `Resolution.isExplicitlyCommonjs`, jest-resolve's `isExplicitlyCommonjsPackage`).
145
+ */
146
+ function isExplicitlyCommonjs(state, path) {
147
+ const extension = extname(path);
148
+ if (extension === ".cjs") return true;
149
+ return extension === ".js" && packageTypeAt(state, path) === "commonjs";
150
+ }
151
+ /** Whether the module at `path` runs as an ES module under `importer-format`. */
152
+ function runsAsEsm(state, path) {
153
+ if (!state.runtime().vmModules) return false;
154
+ const known = state.esmByPath.get(path);
155
+ if (known !== void 0) return known;
156
+ const extension = extname(path);
157
+ let answer;
158
+ if (extension === ".mjs" || extension === ".wasm") answer = true;
159
+ else if (extension === ".cjs") answer = false;
160
+ else if (extension === ".js") answer = packageTypeAt(state, path) === "module";
161
+ else answer = (state.options.esmExtensions ?? []).includes(extension);
162
+ state.esmByPath.set(path, answer);
163
+ return answer;
164
+ }
165
+ /** The kind a `kind` edge from `importer` resolves as, under the policy's `edgeResolveKind`. */
166
+ function edgeKind(state, importer, kind) {
167
+ if (state.options.policy.edgeResolveKind === "as-written" || kind === "import-meta-resolve") return kind;
168
+ return runsAsEsm(state, importer) ? "import" : "require";
169
+ }
170
+ /**
171
+ * The conditions a lookup of `kind` (the kind the edge resolves as) runs with, under the policy's
172
+ * `moduleSyncCondition`; the resolver adds the kind's own `import` or `require`.
173
+ */
174
+ function edgeConditions(state, kind) {
175
+ if (state.options.policy.moduleSyncCondition === "never") return state.conditions;
176
+ return kind !== "require" || state.runtime().syncEvaluate ? state.withModuleSync : state.conditions;
177
+ }
178
+
179
+ // src/internal/reevaluate.ts
180
+ function createPerFileGraph() {
181
+ return {
182
+ edges: /* @__PURE__ */ new Map(),
183
+ importers: /* @__PURE__ */ new Map(),
184
+ members: /* @__PURE__ */ new Set(),
185
+ pending: /* @__PURE__ */ new Set(),
186
+ region: /* @__PURE__ */ new Set(),
187
+ elsewhere: /* @__PURE__ */ new Set(),
188
+ dynamicByName: /* @__PURE__ */ new Map(),
189
+ dynamic: /* @__PURE__ */ new Map(),
190
+ probes: /* @__PURE__ */ new Set(),
191
+ answered: false,
192
+ primedActive: 0,
193
+ primedClaimed: 0
194
+ };
195
+ }
196
+ const NO_TARGETS = [];
197
+ const NO_REFUSALS = [];
198
+ function importersOf(graph, path) {
199
+ let importers = graph.importers.get(path);
200
+ if (importers === void 0) {
201
+ importers = {
202
+ files: [],
203
+ inSet: 0,
204
+ inRegion: 0
205
+ };
206
+ graph.importers.set(path, importers);
207
+ }
208
+ return importers;
209
+ }
210
+ function inSet(graph, path) {
211
+ return graph.members.has(path) || graph.pending.has(path);
212
+ }
213
+ /** Whether the loader can evaluate `path` itself: a user module, or a `keep` node_modules file. */
214
+ function candidate(path, keep) {
215
+ return !inGraph(path) || keep(path);
216
+ }
217
+ /** The importers of `path` outside the set and the region: files that load it natively. */
218
+ function sharedImporters(graph, path) {
219
+ const importers = graph.importers.get(path);
220
+ return importers === void 0 ? 0 : importers.files.length - importers.inSet - importers.inRegion;
221
+ }
222
+ /** The package a node_modules file belongs to, by name (`@scope/name`), or `null`. */
223
+ function packageNameOf(path) {
224
+ const dir = packageDirOf(path);
225
+ return dir === null ? null : dir.slice(dir.lastIndexOf("/node_modules/") + 14);
226
+ }
227
+ /** Puts `path` and its downward closure outside the set into the region, each to be probed. */
228
+ function enterRegion(graph, path, keep) {
229
+ const stack = [path];
230
+ while (stack.length > 0) {
231
+ const current = stack.pop();
232
+ if (current === void 0 || graph.region.has(current)) continue;
233
+ graph.region.add(current);
234
+ graph.probes.add(current);
235
+ const counted = graph.elsewhere.has(current);
236
+ for (const target of graph.edges.get(current) ?? NO_TARGETS) {
237
+ if (!counted) importersOf(graph, target).inRegion++;
238
+ graph.probes.add(target);
239
+ if (!inSet(graph, target) && candidate(target, keep)) stack.push(target);
240
+ }
241
+ }
242
+ }
243
+ /**
244
+ * Puts `path` in the set, with every file that imports it (the reach rule): in `members` when
245
+ * `effective` (the running file may evaluate it per file now), else in `pending`. A pending file
246
+ * that a member reaches is made a member. What it imports is a candidate from now on.
247
+ */
248
+ function joinSet(graph, path, effective, keep) {
249
+ const stack = [[path, effective]];
250
+ while (stack.length > 0) {
251
+ const next = stack.pop();
252
+ if (next === void 0) break;
253
+ const [current, now] = next;
254
+ if (graph.members.has(current)) continue;
255
+ if (graph.pending.has(current)) {
256
+ if (!now) continue;
257
+ graph.pending.delete(current);
258
+ graph.members.add(current);
259
+ for (const importer of graph.importers.get(current)?.files ?? NO_TARGETS) stack.push([importer, true]);
260
+ continue;
261
+ }
262
+ (now ? graph.members : graph.pending).add(current);
263
+ const fromRegion = graph.region.delete(current);
264
+ const counted = graph.elsewhere.has(current);
265
+ const bound = graph.dynamic.get(current);
266
+ for (const target of graph.edges.get(current) ?? NO_TARGETS) {
267
+ const importers = importersOf(graph, target);
268
+ if (!counted) {
269
+ if (fromRegion) importers.inRegion--;
270
+ importers.inSet++;
271
+ }
272
+ if (inSet(graph, target)) continue;
273
+ if (!candidate(target, keep)) continue;
274
+ if (graph.region.has(target)) graph.probes.add(target);
275
+ else enterRegion(graph, target, keep);
276
+ }
277
+ if (bound !== void 0) for (const file of graph.region) {
278
+ const name = packageNameOf(file);
279
+ if (name !== null && bound.has(name)) graph.probes.add(file);
280
+ }
281
+ for (const importer of graph.importers.get(current)?.files ?? NO_TARGETS) stack.push([importer, now || !graph.answered]);
282
+ }
283
+ }
284
+ /**
285
+ * Puts `path`'s edges in the graph, once per worker. `dynamic` is the package names a file that
286
+ * scans as dynamic could load (`null` for a file the scan reads whole), `elsewhere` whether the
287
+ * file is evaluated in every file for another reason (so it never keeps a dependency shared).
288
+ */
289
+ function indexFile(graph, path, targets, dynamic, elsewhere, keep) {
290
+ if (graph.edges.has(path)) return;
291
+ graph.edges.set(path, targets.length === 0 ? NO_TARGETS : targets);
292
+ if (elsewhere) graph.elsewhere.add(path);
293
+ if (dynamic !== null) {
294
+ graph.dynamic.set(path, dynamic);
295
+ for (const name of dynamic) {
296
+ const files = graph.dynamicByName.get(name);
297
+ if (files === void 0) graph.dynamicByName.set(name, [path]);
298
+ else files.push(path);
299
+ }
300
+ }
301
+ const counted = inSet(graph, path) || elsewhere;
302
+ const below = inSet(graph, path) || graph.region.has(path);
303
+ let reaches = false;
304
+ let reachesMember = false;
305
+ for (const target of targets) {
306
+ const importers = importersOf(graph, target);
307
+ importers.files.push(path);
308
+ if (counted) importers.inSet++;
309
+ else if (graph.region.has(path)) importers.inRegion++;
310
+ if (graph.members.has(target)) reachesMember = true;
311
+ if (inSet(graph, target)) reaches = true;
312
+ else if (below && candidate(target, keep)) {
313
+ if (graph.region.has(target)) graph.probes.add(target);
314
+ else enterRegion(graph, target, keep);
315
+ }
316
+ }
317
+ if (reaches && !inSet(graph, path)) joinSet(graph, path, reachesMember || !graph.answered, keep);
318
+ }
319
+ /** The dynamic files outside the set (and not in `within`) that could load `path` natively. */
320
+ function dynamicLoaders(graph, path, within) {
321
+ const name = packageNameOf(path);
322
+ const files = name === null ? void 0 : graph.dynamicByName.get(name);
323
+ if (files === void 0) return NO_TARGETS;
324
+ return files.filter((file) => file !== path && !inSet(graph, file) && !within.has(file));
325
+ }
326
+ /**
327
+ * Decides the probed region files: the greatest set of them (and of the region files they reach
328
+ * whose every importer is in the set or the region) whose importers are all in the set or in it,
329
+ * and joins it. A region file with an importer outside both (a shared package, or a dynamic file
330
+ * outside the set that could load it, `dynamicLoaders`) is dropped, and so is what only reaches the
331
+ * set through a dropped one. The rest joins: a cycle below a per-file package too, which no
332
+ * least fixed point admits. Each settle touches only the probed files and what they reach, and an
333
+ * edge between two files outside the set and the region probes nothing.
334
+ */
335
+ function joinProbed(graph, keep, refusals) {
336
+ while (graph.probes.size > 0) {
337
+ const area = /* @__PURE__ */ new Set();
338
+ const stack = [];
339
+ for (const probe of graph.probes) if (graph.region.has(probe) && sharedImporters(graph, probe) === 0) stack.push(probe);
340
+ graph.probes.clear();
341
+ while (stack.length > 0) {
342
+ const current = stack.pop();
343
+ if (current === void 0 || area.has(current)) continue;
344
+ area.add(current);
345
+ for (const target of graph.edges.get(current) ?? NO_TARGETS) if (graph.region.has(target) && sharedImporters(graph, target) === 0) stack.push(target);
346
+ }
347
+ if (area.size === 0) return;
348
+ const outside = /* @__PURE__ */ new Map();
349
+ for (const file of area) outside.set(file, importersOf(graph, file).inRegion);
350
+ for (const file of area) for (const target of graph.edges.get(file) ?? NO_TARGETS) {
351
+ const count = outside.get(target);
352
+ if (count !== void 0) outside.set(target, count - 1);
353
+ }
354
+ const dropped = /* @__PURE__ */ new Set();
355
+ const drop = [];
356
+ for (const file of area) {
357
+ const loaders = dynamicLoaders(graph, file, area);
358
+ const first = loaders[0];
359
+ if (first !== void 0) {
360
+ if ((outside.get(file) ?? 0) === 0) refusals.push({
361
+ target: file,
362
+ dynamic: first
363
+ });
364
+ outside.set(file, (outside.get(file) ?? 0) + loaders.length);
365
+ }
366
+ if ((outside.get(file) ?? 0) > 0) drop.push(file);
367
+ }
368
+ while (drop.length > 0) {
369
+ const file = drop.pop();
370
+ if (file === void 0 || dropped.has(file)) continue;
371
+ dropped.add(file);
372
+ for (const target of graph.edges.get(file) ?? NO_TARGETS) {
373
+ if (!area.has(target) || dropped.has(target)) continue;
374
+ outside.set(target, (outside.get(target) ?? 0) + 1);
375
+ drop.push(target);
376
+ }
377
+ const bound = graph.dynamic.get(file);
378
+ if (bound === void 0) continue;
379
+ for (const target of area) {
380
+ const name = packageNameOf(target);
381
+ if (target !== file && !dropped.has(target) && name !== null && bound.has(name)) {
382
+ refusals.push({
383
+ target,
384
+ dynamic: file
385
+ });
386
+ drop.push(target);
387
+ }
388
+ }
389
+ }
390
+ for (const file of area) if (!dropped.has(file)) joinSet(graph, file, !graph.answered, keep);
391
+ }
392
+ }
393
+ /**
394
+ * Settles the set before `evaluatedPerFile` answers for `path`: when the seeds grew, indexes what
395
+ * the worker loaded natively (so a shared importer an earlier file loaded counts) and the new
396
+ * seeds, and puts them in the set; indexes `path`; then decides what the changes probed
397
+ * (`joinProbed`). `index` indexes a file's closure (`indexClosure` in `inline.ts`). Returns the
398
+ * joins a dynamic file refused, for the caller to report.
399
+ */
400
+ function settlePerFile(state, sources, index, path) {
401
+ const graph = state.perFile;
402
+ const { active } = state;
403
+ const { claimed, keep } = sources;
404
+ if (graph.primedActive !== active.size || graph.primedClaimed !== claimed.length) {
405
+ for (const loaded of sources.loaded.keys()) if (inGraph(loaded)) index(loaded);
406
+ let at = 0;
407
+ for (const seed of active) {
408
+ if (at++ < graph.primedActive) continue;
409
+ index(seed);
410
+ joinSet(graph, seed, !graph.answered, keep);
411
+ }
412
+ for (let next = graph.primedClaimed; next < claimed.length; next++) {
413
+ const seed = claimed[next];
414
+ if (seed === void 0) continue;
415
+ index(seed);
416
+ joinSet(graph, seed, !graph.answered, keep);
417
+ }
418
+ graph.primedActive = active.size;
419
+ graph.primedClaimed = claimed.length;
420
+ }
421
+ index(path);
422
+ if (graph.probes.size === 0) return NO_REFUSALS;
423
+ const refusals = [];
424
+ joinProbed(graph, keep, refusals);
425
+ return refusals.length === 0 ? NO_REFUSALS : refusals;
426
+ }
427
+ /** Makes what joined while the last file ran a member: called as a file's registry is created. */
428
+ function promotePerFile(graph) {
429
+ graph.answered = false;
430
+ if (graph.pending.size === 0) return;
431
+ for (const path of graph.pending) graph.members.add(path);
432
+ graph.pending.clear();
433
+ }
434
+ function createReevaluateState() {
435
+ return {
436
+ active: /* @__PURE__ */ new Set(),
437
+ pending: /* @__PURE__ */ new Set(),
438
+ learned: [],
439
+ watchers: /* @__PURE__ */ new Set(),
440
+ perFile: createPerFileGraph(),
441
+ watching: false
442
+ };
443
+ }
444
+ /** Makes `paths` active (an earlier run's set); the per-file set sees them on its next question. */
445
+ function activate(state, paths) {
446
+ for (const path of paths) state.active.add(path);
447
+ }
448
+ /** Learns `file`, unless it is evaluated per file already: pending, and one more for `takeLearned`. */
449
+ function learn(state, file) {
450
+ if (state.active.has(file) || state.pending.has(file)) return;
451
+ state.pending.add(file);
452
+ state.learned.push(file);
453
+ }
454
+ const NOTHING_LEARNED = [];
455
+ /** What was learned since the last call (each file once, not a seeded one); no allocation for none. */
456
+ function takeLearned(state) {
457
+ return state.learned.length === 0 ? NOTHING_LEARNED : state.learned.splice(0);
458
+ }
459
+ /** Node's own module cache: what a native `require` adds an entry to, in load order. */
460
+ const nativeCache = createRequire(import.meta.url).cache;
461
+ /**
462
+ * Runs `load`, the first native load of the external at `path`, as a watched window when anyone
463
+ * watches and no window is open. When a watcher says a per-file global was read, `path`, the files
464
+ * of its own package its static closure reaches (`ownPackage`: an ES module a `require(esm)`
465
+ * evaluated is not in Node's cache) and every file the load added to Node's cache are learned,
466
+ * each that `keep` accepts (a node_modules file the loader could evaluate itself), active from the
467
+ * next file on. A load that throws after such a read is learned too: the next file evaluates it
468
+ * (and meets its error) through its registry, as Jest's would, instead of watching it again.
469
+ *
470
+ * Every window a watcher opened is closed, whatever throws: a watcher that throws as it opens (the
471
+ * load is then not run, and its error is thrown), the load, or another window's end (each end is
472
+ * called; the first end's error is thrown after the load's result is known, unless the load threw).
473
+ */
474
+ function watchedLoad(state, path, load, keep, ownPackage) {
475
+ if (state.watching || state.watchers.size === 0 || state.active.has(path)) return load();
476
+ const ends = [];
477
+ /** Node's cache before the load: read only once a window is open, as only then can it learn. */
478
+ let before;
479
+ let loadFailed = false;
480
+ state.watching = true;
481
+ try {
482
+ for (const watcher of state.watchers) {
483
+ const end = watcher(path);
484
+ if (end !== null) ends.push(end);
485
+ }
486
+ if (ends.length > 0) before = Object.keys(nativeCache);
487
+ try {
488
+ return load();
489
+ } catch (error) {
490
+ loadFailed = true;
491
+ throw error;
492
+ }
493
+ } finally {
494
+ state.watching = false;
495
+ let perFile = false;
496
+ let failure;
497
+ for (const end of ends) try {
498
+ if (end()) perFile = true;
499
+ } catch (error) {
500
+ failure ??= { error };
501
+ }
502
+ if (perFile && before !== void 0) {
503
+ const known = new Set(before);
504
+ learn(state, path);
505
+ for (const file of ownPackage(path)) if (keep(file)) learn(state, file);
506
+ for (const file of Object.keys(nativeCache)) if (!known.has(file) && keep(file)) learn(state, file);
507
+ }
508
+ if (failure !== void 0 && !loadFailed) throw failure.error;
509
+ }
510
+ }
511
+ /**
512
+ * Makes what the last file learned active, and what joined the per-file set while it ran a member:
513
+ * called as a file's registry is created.
514
+ */
515
+ function promoteLearned(state) {
516
+ promotePerFile(state.perFile);
517
+ if (state.pending.size === 0) return;
518
+ activate(state, state.pending);
519
+ state.pending.clear();
520
+ }
521
+
522
+ // src/internal/source.ts
523
+ /** The text of the file at `path`, or `undefined` when it can't be read (Node meets that too). */
524
+ function readSource(path) {
525
+ try {
526
+ return readFileSync(path, "utf8");
527
+ } catch {
528
+ return;
529
+ }
530
+ }
531
+ /**
532
+ * `source` with a hashbang made a line comment of the same length: a hashbang is legal only at the
533
+ * start of a script or module, and a wrapper puts the body inside a function. The length is kept, so
534
+ * columns, source maps and V8 coverage offsets hold.
535
+ */
536
+ function blankHashbang(source) {
537
+ return source.startsWith("#!") ? `//${source.slice(2)}` : source;
538
+ }
539
+ /** The parameters of Node's CommonJS wrapper, in order (`vm.compileFunction` takes a mutable array). */
540
+ const CJS_WRAPPER = [
541
+ "exports",
542
+ "require",
543
+ "module",
544
+ "__filename",
545
+ "__dirname"
546
+ ];
547
+ /** The same as a parameter list. */
548
+ const CJS_PARAMS = CJS_WRAPPER.join(", ");
549
+
550
+ // src/internal/inline.ts
551
+ /** The default for `LoaderOptions.inlineBudget`. */
552
+ const DEFAULT_INLINE_BUDGET = 400;
553
+ function createInlineState() {
554
+ return {
555
+ graph: null,
556
+ warned: /* @__PURE__ */ new Set(),
557
+ verdicts: /* @__PURE__ */ new WeakMap(),
558
+ served: /* @__PURE__ */ new Map(),
559
+ claimed: /* @__PURE__ */ new Map(),
560
+ declared: /* @__PURE__ */ new Map()
561
+ };
562
+ }
563
+ function createLedger() {
564
+ return {
565
+ byMock: /* @__PURE__ */ new Map(),
566
+ modules: /* @__PURE__ */ new Set()
567
+ };
568
+ }
569
+ function warn(options, warning) {
570
+ if (options.onWarning !== void 0) {
571
+ options.onWarning(warning);
572
+ return;
573
+ }
574
+ if (warning.level === "debug") return;
575
+ process.emitWarning(warning.message, { code: warning.code });
576
+ }
577
+ /** Starts the graph on first use. */
578
+ function graphOf(state, options) {
579
+ state.graph ??= buildThirdPartyGraph({
580
+ root: options.root,
581
+ resolver: options.resolver,
582
+ conditions: conditionsOf(options),
583
+ cacheDir: options.graphCache ?? null,
584
+ lockfileHash: options.lockfileHash ?? null
585
+ });
586
+ return state.graph;
587
+ }
588
+ /** Writes what the graph scanned to its cache; the worker does this once, when its loader ends. */
589
+ function saveGraph(state) {
590
+ state.graph?.save();
591
+ }
592
+ const NO_EDGES = [];
593
+ /** Whether an edge's resolved target is a file: not a builtin (`node:`), and resolved. */
594
+ function isFileTarget(target) {
595
+ return target !== null && !target.startsWith("node:");
596
+ }
597
+ function verdictsOf(state, mocks) {
598
+ const generation = mocks.generation();
599
+ let verdicts = state.verdicts.get(mocks);
600
+ if (verdicts === void 0 || verdicts.generation !== generation) {
601
+ verdicts = {
602
+ generation,
603
+ byPath: /* @__PURE__ */ new Map()
604
+ };
605
+ state.verdicts.set(mocks, verdicts);
606
+ }
607
+ return verdicts;
608
+ }
609
+ /**
610
+ * Walks `path`'s closure until `takes` names an edge, node by node, so a walk that finds one early
611
+ * costs the files visited before it, not the whole closure (a component library's file reaches
612
+ * thousands). The node_modules files go depth first through the graph (`ThirdPartyGraph.visitNode`)
613
+ * in the order `ThirdPartyGraph.reachable` lists them: each edge is put to `takes` as the file is
614
+ * visited, and its target pushed as written. A user module an edge leads out to (a workspace package
615
+ * linked into `node_modules`) waits on its own stack, and is walked (`userEdges`) once the graph
616
+ * walk that found it ends, with the node_modules files it leads back to. So the first edge `takes`
617
+ * names is the one a walk over the whole closure's edges names first. `known` (`KnownReach`)
618
+ * shortens the walk with verdicts kept from earlier walks.
619
+ */
620
+ function walkClosure(state, options, path, takes, userEdges, known) {
621
+ const graph = graphOf(state, options);
622
+ const done = /* @__PURE__ */ new Set();
623
+ const users = [path];
624
+ let dynamic = false;
625
+ let found = null;
626
+ while (found === null && users.length > 0) {
627
+ const start = users.pop();
628
+ if (start === void 0 || done.has(start)) continue;
629
+ if (!inGraph(start)) {
630
+ done.add(start);
631
+ const edges = userEdges(start);
632
+ if (edges === null) {
633
+ dynamic = true;
634
+ continue;
635
+ }
636
+ for (const edge of edges) {
637
+ found = takes(edge, start);
638
+ if (found !== null) break;
639
+ if (isFileTarget(edge.target) && !done.has(edge.target)) users.push(edge.target);
640
+ }
641
+ continue;
642
+ }
643
+ const files = [start];
644
+ while (found === null && files.length > 0) {
645
+ const current = files.pop();
646
+ if (current === void 0 || done.has(current)) continue;
647
+ done.add(current);
648
+ const verdict = current === path ? void 0 : known?.(current);
649
+ if (verdict === null) continue;
650
+ if (verdict !== void 0) {
651
+ found = verdict;
652
+ break;
653
+ }
654
+ const node = graph.visitNode(current);
655
+ if (node === void 0) continue;
656
+ if (node.dynamic) dynamic = true;
657
+ for (const edge of node.edges) {
658
+ found = takes(edge, current);
659
+ if (found !== null) break;
660
+ if (!isFileTarget(edge.target) || done.has(edge.target)) continue;
661
+ if (inGraph(edge.target)) files.push(edge.target);
662
+ else users.push(edge.target);
663
+ }
664
+ }
665
+ }
666
+ return {
667
+ found,
668
+ done,
669
+ dynamic
670
+ };
671
+ }
672
+ /**
673
+ * The first id among the edges `path` reaches that `mocks` takes, or `null` when none is. `path` is
674
+ * a real file under `node_modules`; the walk (`walkClosure`) ends at that edge. It goes on
675
+ * through a user module an edge leads to (`userEdges`) and through the node_modules files it leads
676
+ * back to. The verdict is kept until the mocks change, and a negative one holds for every
677
+ * node_modules file the walk covered, since each reaches no more than `path` does.
678
+ */
679
+ function mockedReach(state, options, path, mocks, userEdges) {
680
+ const verdicts = verdictsOf(state, mocks);
681
+ const known = verdicts.byPath.get(path);
682
+ if (known !== void 0) return known;
683
+ const asked = /* @__PURE__ */ new Set();
684
+ /** The mocked id an edge reaches, or `null`. */
685
+ const takes = (edge, importer) => {
686
+ const style = edge.kind === "require" ? "cjs" : "esm";
687
+ const key = `${style}\0${edge.target ?? ""}\0${edge.specifier}`;
688
+ if (asked.has(key)) return null;
689
+ asked.add(key);
690
+ if (edge.target === null) {
691
+ try {
692
+ if (mocks.decideUnresolved(edge.specifier, importer).mocked) return edge.specifier;
693
+ } catch {}
694
+ return null;
695
+ }
696
+ const decision = mocks.decide(edge.target, importer, edge.target.startsWith("node:") ? "builtin" : style, edge.specifier);
697
+ return decision.mocked ? decision.id : null;
698
+ };
699
+ const { found, done, dynamic } = walkClosure(state, options, path, takes, userEdges);
700
+ if (found !== null) {
701
+ verdicts.byPath.set(path, found);
702
+ return found;
703
+ }
704
+ for (const member of done) if (inGraph(member)) verdicts.byPath.set(member, null);
705
+ if (dynamic && !state.warned.has(path)) {
706
+ state.warned.add(path);
707
+ warn(options, {
708
+ code: "PROVINO_INLINE_DYNAMIC",
709
+ level: "debug",
710
+ message: `${path} (or a module it loads) has a require the graph can't follow (a computed or aliased specifier, createRequire, or a file that could not be read or parsed), so a mock may not reach what it loads.`
711
+ });
712
+ }
713
+ return null;
714
+ }
715
+ /**
716
+ * `path`'s verdict in `known`, or a walk's: true when `direct` (a check of the file itself, made
717
+ * before any walk) holds or `takes` names an edge of its closure. A positive verdict is kept for
718
+ * `path`, and a negative one for every node_modules file the walk covered, since each reaches no
719
+ * more than `path` does. The walk (`walkClosure`) stops at the first edge `takes` names, and at a
720
+ * file with a verdict in `known` already: a positive one ends it, a negative one has nothing to add.
721
+ * The verdict is the same as a walk over the whole closure's edges: it is whether any edge of the
722
+ * same reachable set is one `takes` names.
723
+ */
724
+ function cachedReach(known, state, options, path, takes, userEdges, direct) {
725
+ const cached = known.get(path);
726
+ if (cached !== void 0) return cached;
727
+ if (direct?.() === true) {
728
+ known.set(path, true);
729
+ return true;
730
+ }
731
+ const { found, done } = walkClosure(state, options, path, takes, userEdges, (file) => {
732
+ const verdict = known.get(file);
733
+ return verdict === void 0 ? void 0 : verdict ? file : null;
734
+ });
735
+ if (found !== null) {
736
+ known.set(path, true);
737
+ return true;
738
+ }
739
+ for (const member of done) if (inGraph(member)) known.set(member, false);
740
+ return false;
741
+ }
742
+ /**
743
+ * Whether `path`'s closure has an edge to a module the dialect serves (`ModuleScope.modules`, such
744
+ * as `@jest/globals`). Loaded natively, such a package would reach the real module (whose own code
745
+ * may refuse to load outside its runner), so it is inlined, and its edge gets the served module, as
746
+ * a user file's does. Kept per worker; a negative verdict holds for every node_modules file the
747
+ * walk covered.
748
+ *
749
+ * The external's own edges are read first: one that requests a served module itself is inlined
750
+ * without building its closure (`requestsDirectly`). Only otherwise is the closure walked (on a
751
+ * cold graph, about 170 ms for jsdom's 1,107 files, `local`; read from the graph cache on later
752
+ * runs).
753
+ *
754
+ * Limit: a request the scan can't read (a computed `require(name)` or `import(name)`, the closure's
755
+ * `dynamic` flag) is not seen, so a package that reaches a served module only that way stays shared
756
+ * and meets the real module.
757
+ */
758
+ function servedReach(state, options, path, served, userEdges) {
759
+ return cachedReach(state.served, state, options, path, (edge) => served.includes(edge.specifier) ? edge.specifier : null, userEdges, () => requestsDirectly(state, path, served));
760
+ }
761
+ /**
762
+ * Whether `path`'s closure has an edge whose resolved target `reaches` names, with the verdict kept
763
+ * in `known` (`cachedReach`).
764
+ */
765
+ function reachesTarget(known, state, options, path, reaches, userEdges) {
766
+ return cachedReach(known, state, options, path, (edge) => edge.target !== null && reaches(edge.target) ? edge.target : null, userEdges);
767
+ }
768
+ /** The distinct targets of `edges` that are files (no builtin, nothing unresolved). */
769
+ function fileTargets(edges) {
770
+ const targets = [];
771
+ for (const { target } of edges) if (isFileTarget(target) && !targets.includes(target)) targets.push(target);
772
+ return targets;
773
+ }
774
+ /**
775
+ * The package names a file that scans as dynamic could load natively: its own package's, and the
776
+ * ones its `package.json` declares (`dependencies`, `optionalDependencies`, `peerDependencies`).
777
+ * A computed `require(name)` resolves from the file's own directory, and a strict layout (pnpm's)
778
+ * finds only these there; a hoisted one finds more, but a package that loads one it does not
779
+ * declare is broken under pnpm already. The package directories its static closure reaches would be
780
+ * no bound at all: a computed `require` is how a package loads what it does not import statically.
781
+ * Kept per package directory; `null` outside one (a user module, which the registry loads anyway).
782
+ */
783
+ function dynamicBound(state, path) {
784
+ const dir = packageDirOf(path);
785
+ if (dir === null) return null;
786
+ const known = state.declared.get(dir);
787
+ if (known !== void 0) return known;
788
+ const names = /* @__PURE__ */ new Set([dir.slice(dir.lastIndexOf("/node_modules/") + 14)]);
789
+ try {
790
+ const manifest = JSON.parse(readFileSync(`${dir}/package.json`, "utf8"));
791
+ if (typeof manifest === "object" && manifest !== null) for (const key of [
792
+ "dependencies",
793
+ "optionalDependencies",
794
+ "peerDependencies"
795
+ ]) {
796
+ const declared = Reflect.get(manifest, key);
797
+ if (typeof declared === "object" && declared !== null) for (const name of Object.keys(declared)) names.add(name);
798
+ }
799
+ } catch {}
800
+ state.declared.set(dir, names);
801
+ return names;
802
+ }
803
+ /**
804
+ * Puts the edges of `path`'s static closure into the per-file graph (each file once per worker),
805
+ * through the node_modules files the graph holds and the user modules an edge leads to
806
+ * (`userEdges`). A file's own edges are read from its graph node, not from the closure's
807
+ * deduplicated list, which names only the first importer of each request. `elsewhere` says which
808
+ * files are evaluated per file for another reason (a served module), `null` when none can be.
809
+ *
810
+ * The walk goes node by node (`ThirdPartyGraph.visitNode`) and does not descend into a file that is
811
+ * indexed already: every walk indexes a whole closure, so that file's closure is indexed too. A
812
+ * walk from an external whose closure is mostly known (a component beside the ones a file loaded
813
+ * before it) costs the files that are new, not the whole closure each time.
814
+ */
815
+ function indexClosure(state, options, reevaluate, sources, path) {
816
+ const perFile = reevaluate.perFile;
817
+ if (perFile.edges.has(path)) return;
818
+ const graph = graphOf(state, options);
819
+ const { keep, userEdges, elsewhere } = sources;
820
+ const stack = [path];
821
+ while (stack.length > 0) {
822
+ const current = stack.pop();
823
+ if (current === void 0 || perFile.edges.has(current)) continue;
824
+ let targets;
825
+ if (inGraph(current)) {
826
+ const node = graph.visitNode(current);
827
+ if (node === void 0) continue;
828
+ targets = fileTargets(node.edges);
829
+ const bound = node.dynamic ? dynamicBound(state, current) : null;
830
+ indexFile(perFile, current, targets, bound, elsewhere?.(current) ?? false, keep);
831
+ } else {
832
+ targets = fileTargets(userEdges(current) ?? NO_EDGES);
833
+ indexFile(perFile, current, targets, null, elsewhere?.(current) ?? false, keep);
834
+ }
835
+ for (const target of targets) if (!perFile.edges.has(target)) stack.push(target);
836
+ }
837
+ }
838
+ /**
839
+ * Whether the external at `path` is evaluated per file in the running file (D127, D129, D132): it
840
+ * is a seed (`active`, or a claimed user module), it imports a member through any chain of edges
841
+ * (so it shares the file's copy, never Node's cached one: a component library over a learned
842
+ * `react`, an "Invalid hook call"), or it is a dependency of members that only files evaluated per
843
+ * file import (a registry a per-file package writes into as it loads, which would otherwise keep
844
+ * the first file's entries). `settlePerFile` keeps the set; a join this file can't take yet
845
+ * (it asked about an external already) is the next file's. A join a dynamic file refused is
846
+ * reported once as `PROVINO_INLINE_DYNAMIC`. Once the graph is known, a question costs a lookup.
847
+ */
848
+ function evaluatedPerFile(state, options, path, reevaluate, sources) {
849
+ const refusals = settlePerFile(reevaluate, sources, (file) => indexClosure(state, options, reevaluate, sources, file), path);
850
+ for (const { target, dynamic } of refusals) {
851
+ const key = `per-file\0${target}`;
852
+ if (state.warned.has(key)) continue;
853
+ state.warned.add(key);
854
+ warn(options, {
855
+ code: "PROVINO_INLINE_DYNAMIC",
856
+ level: "debug",
857
+ message: `${dynamic} has a require the graph can't follow, and could load ${target} with it, so ${target} stays shared: evaluated per file, it would be a second copy beside the one ${dynamic} loads natively.`
858
+ });
859
+ }
860
+ return reevaluate.perFile.members.has(path);
861
+ }
862
+ /**
863
+ * Whether `path`'s static closure has an edge to a `node_modules` file the project's transforms
864
+ * make a user module (`claimed`, B23e, D115). Loaded natively, such an external would `require`
865
+ * Node's own copy of that file while the file's code gets its per-file one (two instances), or fail
866
+ * on what only the transform resolves (an extensionless import). So it is inlined too. The verdict
867
+ * is kept in `InlineState.claimed`, which is cleared when a claimed file becomes a user module
868
+ * after Node failed to parse it.
869
+ */
870
+ function claimedReach(state, options, path, claimed, userEdges) {
871
+ return reachesTarget(state.claimed, state, options, path, claimed, userEdges);
872
+ }
873
+ /**
874
+ * Whether the file at `path` itself requests one of `served`: its edges when the graph (if one was
875
+ * built) already holds them, else its text (a cheap test first, then the scan).
876
+ */
877
+ function requestsDirectly(state, path, served) {
878
+ const node = state.graph?.nodeOf(path);
879
+ if (node !== void 0) return node.edges.some((edge) => served.includes(edge.specifier));
880
+ const source = readSource(path);
881
+ if (source === void 0) return false;
882
+ if (!served.some((specifier) => source.includes(specifier))) return false;
883
+ return scanSource(source).edges.some((edge) => served.includes(edge.specifier));
884
+ }
885
+ /**
886
+ * Records that `path` was inlined for the mocked module `mockedId`, and warns once per mocked id
887
+ * and worker when more than the budget load for it in one file. It still inlines.
888
+ */
889
+ function noteInlined(state, options, ledger, path, mockedId) {
890
+ ledger.modules.add(path);
891
+ let modules = ledger.byMock.get(mockedId);
892
+ if (modules === void 0) {
893
+ modules = /* @__PURE__ */ new Set();
894
+ ledger.byMock.set(mockedId, modules);
895
+ }
896
+ modules.add(path);
897
+ const budget = options.inlineBudget ?? 400;
898
+ if (modules.size > budget && !state.warned.has(`budget\0${mockedId}`)) {
899
+ state.warned.add(`budget\0${mockedId}`);
900
+ warn(options, {
901
+ code: "PROVINO_INLINE_BUDGET",
902
+ level: "warn",
903
+ message: `Mocking ${mockedId} loads ${modules.size} modules per test file (the budget is ${budget}). They still load per file; mock a module nearer to your code to avoid this cost.`
904
+ });
905
+ }
906
+ }
907
+ /**
908
+ * The files of `path`'s own package that its static closure reaches (`path` among them). An
909
+ * external evaluated per file takes them along (D127): Node's module cache shows what a CommonJS
910
+ * load evaluated, but not the ES modules a `require(esm)` evaluated, and a package split between a
911
+ * per-file entry and shared internals would be two half copies of itself.
912
+ */
913
+ function packageClosure(state, options, path) {
914
+ const own = packageDirOf(path);
915
+ if (own === null) return [];
916
+ const graph = graphOf(state, options);
917
+ graph.add(path);
918
+ const files = [];
919
+ for (const entry of graph.reachable(path)) if (packageDirOf(entry.path) === own) files.push(entry.path);
920
+ return files;
921
+ }
922
+
923
+ // src/internal/messages.ts
924
+ const NEUTRAL = {
925
+ "transform-failed": "{file}{where}: {message}",
926
+ "transformer-failed": "{message}",
927
+ "module-not-found": "Cannot find module '{specifier}' imported from {importer}"
928
+ };
929
+ /** The text for `code`, filled with `values`, or `undefined` when neither the policy nor the neutral set has one. */
930
+ function loaderMessage(policy, code, values) {
931
+ const template = policy.messages[code] ?? NEUTRAL[code];
932
+ if (template === void 0) return void 0;
933
+ return template.replace(/\{(\w+)\}/g, (whole, key) => Object.hasOwn(values, key) ? values[key] ?? "" : whole);
934
+ }
935
+
936
+ // src/internal/third-party.ts
937
+ const NO_RULES = [];
938
+ /** Whether `path` is a `node_modules` file `inline` doesn't name. */
939
+ function isThirdParty(path, rules) {
940
+ if (!inGraph(path)) return false;
941
+ return !rules.some((rule) => typeof rule === "string" ? path.includes(`/node_modules/${rule}/`) : rule.test(path));
942
+ }
943
+ /**
944
+ * Whether a file is a node_modules file the loader could evaluate itself, as a module it inlines:
945
+ * third party, and no addon or WebAssembly.
946
+ */
947
+ function isEvaluableExternal(path, rules) {
948
+ return !/\.(?:node|wasm)$/.test(path) && isThirdParty(path, rules);
949
+ }
950
+
951
+ // src/internal/claims.ts
952
+ /** Gives `path` the verdict `user`, and makes it a seed of the per-file set. */
953
+ function markUser(claims, path) {
954
+ claims.verdicts.set(path, "user");
955
+ claims.users.push(path);
956
+ }
957
+ function compiled(what, make) {
958
+ try {
959
+ return make();
960
+ } catch (cause) {
961
+ throw new LoaderError("LOADER_INVALID_TRANSFORM_CLAIMS", `transformClaims.${what} is not a regular expression: ${cause.message}`, { cause });
962
+ }
963
+ }
964
+ /** The claims of `options`, or `null` for none. A pattern that is no regular expression is refused. */
965
+ function compileClaims(options, shared) {
966
+ const claims = options.transformClaims;
967
+ if (claims === void 0 || claims.patterns.length === 0) return null;
968
+ const patterns = claims.patterns.map((pattern, index) => compiled(`patterns[${index}]`, () => new RegExp(pattern)));
969
+ const ignore = compiled("ignorePatterns (joined with \"|\")", () => ignoreRegExp(claims.ignorePatterns));
970
+ return {
971
+ ...shared,
972
+ patterns,
973
+ ignore,
974
+ verdicts: /* @__PURE__ */ new Map(),
975
+ users: []
976
+ };
977
+ }
978
+ /**
979
+ * The extensions Node loads without a transform (none is a `.js`-like file too). A claimed file
980
+ * with any other extension (`.ts`, `.tsx`, `.jsx`, `.css`, `.svg`, `.md`) is a user module
981
+ * whatever its text holds: Node strips no types under `node_modules`, runs no JSX, and a `.css`
982
+ * file it `require`s is a `SyntaxError`; Jest runs the transform on every claimed file.
983
+ */
984
+ const NODE_EXTENSIONS = /* @__PURE__ */ new Set([
985
+ "",
986
+ ".js",
987
+ ".cjs",
988
+ ".mjs",
989
+ ".json",
990
+ ".node",
991
+ ".wasm"
992
+ ]);
993
+ /** Loaded by Node, and never source text: no syntax to read in an addon, WebAssembly or JSON file. */
994
+ const NEVER_READ = /* @__PURE__ */ new Set([
995
+ ".json",
996
+ ".node",
997
+ ".wasm"
998
+ ]);
999
+ /**
1000
+ * Whether the file at `path` has ES module syntax, as Node decides a format: `.mjs` does, `.cjs`
1001
+ * doesn't, a `.js` under a `"type": "module"` package does, and any other file by its source
1002
+ * (`import`/`export` or `import.meta`, as Node's detection reads an ambiguous `.js`), from the
1003
+ * graph when it has scanned the file, else from the file. A file the lexer rejects counts as ESM:
1004
+ * Node can't run it either. Called once per file a transform takes.
1005
+ */
1006
+ function isEsmFile(claims, path, extension) {
1007
+ if (extension === ".mjs") return true;
1008
+ if (extension === ".cjs") return false;
1009
+ if (extension === ".js" && packageTypeAt(claims.edgeKinds, path) === "module") return true;
1010
+ const node = claims.inline.graph?.nodeOf(path);
1011
+ if (node !== void 0) return node.esm;
1012
+ const source = readSource(path);
1013
+ return source === void 0 ? false : esmSyntaxOf(source) ?? true;
1014
+ }
1015
+ /**
1016
+ * What the claims make of a `node_modules` file (B23e, D115): a transform takes it when a rule's
1017
+ * pattern matches its real path and no ignore pattern does (Jest's
1018
+ * `ScriptTransformer.shouldTransform`), and it is transformed only when Node can't load it
1019
+ * natively: an extension Node doesn't run as JavaScript (`NODE_EXTENSIONS`), or ES module syntax,
1020
+ * whose imports Jest resolves as `require`s. A CommonJS file a transform takes is `native`, shared
1021
+ * and loaded by Node, until its native load fails to parse (`demoteOnParseFailure`). One regular
1022
+ * expression test for a file the ignore patterns opt out, and each verdict is kept for the worker.
1023
+ */
1024
+ function claimVerdict(claims, path) {
1025
+ let verdict = claims.verdicts.get(path);
1026
+ if (verdict === void 0) {
1027
+ if (claims.ignore?.test(path) === true || !claims.patterns.some((p) => p.test(path))) verdict = "ignored";
1028
+ else {
1029
+ const extension = extname(path);
1030
+ verdict = !NODE_EXTENSIONS.has(extension) || !NEVER_READ.has(extension) && isEsmFile(claims, path, extension) ? "user" : "native";
1031
+ }
1032
+ if (verdict === "user") markUser(claims, path);
1033
+ else claims.verdicts.set(path, verdict);
1034
+ }
1035
+ return verdict;
1036
+ }
1037
+ /**
1038
+ * The verdict for `path`, or `undefined` when it is not a third-party file (an `inline` rule names
1039
+ * it, or it is outside `node_modules`). A path asked about before skips the third-party test: only
1040
+ * third-party paths have a verdict.
1041
+ */
1042
+ function thirdPartyVerdict(claims, path) {
1043
+ return claims.verdicts.get(path) ?? (isThirdParty(path, claims.inlineRules) ? claimVerdict(claims, path) : void 0);
1044
+ }
1045
+ /**
1046
+ * Whether a `node_modules` file is a user module because a transform takes it, so a shared
1047
+ * external whose closure reaches it is inlined too (`claimedReach`): loaded natively, it would
1048
+ * `require` Node's copy, a second instance, or a crash on what the transform resolves.
1049
+ */
1050
+ function isClaimedUserModule(claims, path) {
1051
+ return thirdPartyVerdict(claims, path) === "user";
1052
+ }
1053
+ /**
1054
+ * Whether a resolved file loads natively, shared by the worker: a `node_modules` file `inline`
1055
+ * doesn't name and no transform takes as a user module. (An addon is the caller's own test.)
1056
+ */
1057
+ function isClaimedExternal(claims, path) {
1058
+ const verdict = thirdPartyVerdict(claims, path);
1059
+ return verdict !== void 0 && verdict !== "user";
1060
+ }
1061
+ /**
1062
+ * What an edge to the external at `path` has to do about the claims, from one read of its verdict:
1063
+ * `user` (a claimed file that became a user module since it was resolved), `untried` (a claimed
1064
+ * file Node loads that has not loaded yet in this worker: load it now, so a native load Node can't
1065
+ * parse turns it into a user module before the edge takes its route), or `native`.
1066
+ */
1067
+ function claimedLoad(claims, path) {
1068
+ const verdict = claims.verdicts.get(path);
1069
+ if (verdict === "user") return "user";
1070
+ if (verdict === "native" && !claims.required.has(path) && !claims.externals.has(path)) return "untried";
1071
+ return "native";
1072
+ }
1073
+ /** Whether `error` is a `SyntaxError`, by name as jest-runtime tests it (any realm's). */
1074
+ function isSyntaxError(error) {
1075
+ return error instanceof Error && error.name === "SyntaxError";
1076
+ }
1077
+ /**
1078
+ * Whether the file at `path` compiles as Node compiles a CommonJS module (its wrapper, a hashbang
1079
+ * and a byte order mark dropped). A file that can't be read is taken to: its load's error stands.
1080
+ */
1081
+ function compilesAsCommonJs(path) {
1082
+ let source = readSource(path);
1083
+ if (source === void 0) return true;
1084
+ if (source.charCodeAt(0) === 65279) source = source.slice(1);
1085
+ try {
1086
+ compileFunction(blankHashbang(source), CJS_WRAPPER, { filename: path });
1087
+ return true;
1088
+ } catch (error) {
1089
+ return !isSyntaxError(error);
1090
+ }
1091
+ }
1092
+ /**
1093
+ * Handles the native load of a `native` claimed file throwing `error`: whether it threw because
1094
+ * Node can't parse the file (JSX, Flow or TypeScript syntax in a CommonJS `.js` file: a React
1095
+ * Native package under `transformIgnorePatterns: ['node_modules/(?!react-native/)']`). Nothing of it
1096
+ * ran, so it becomes a user module for the worker (transformed, and evaluated per file; the
1097
+ * verdicts it changes are the walk's, cleared), and the edge takes that route. A `SyntaxError` the
1098
+ * module's own code threw (`JSON.parse`, `new Function`) leaves it `native`: it ran, and running it
1099
+ * again would repeat what it did. So would a file that requires a module Node can't parse: the
1100
+ * error is that module's, and the file itself parses. Asked only after a native load threw, so a
1101
+ * load that works pays nothing; the compile is once per file that threw.
1102
+ */
1103
+ function demoteOnParseFailure(claims, path, error) {
1104
+ if (!isSyntaxError(error) || !/\.c?js$/.test(path) || compilesAsCommonJs(path)) return false;
1105
+ markUser(claims, path);
1106
+ claims.inline.claimed.clear();
1107
+ return true;
1108
+ }
1109
+
1110
+ // src/internal/records.ts
1111
+ /** The wrapper parameters, in order. ESM gets Vite's linkers and the late import; CJS gets Node's wrapper. */
1112
+ const DYNAMIC_IMPORT = "__vite_ssr_dynamic_import__";
1113
+ const ESM_PARAMS = `__vite_ssr_exports__, __vite_ssr_import_meta__, __vite_ssr_import__, ${DYNAMIC_IMPORT}, __vite_ssr_exportAll__, ${LATE_IMPORT}`;
1114
+ /** What an ES module gets under `ModulePolicy.injectCjsGlobals`, when its source names them. */
1115
+ const CJS_GLOBALS = [
1116
+ "require",
1117
+ "__filename",
1118
+ "__dirname"
1119
+ ];
1120
+ function toModuleId(path) {
1121
+ return path;
1122
+ }
1123
+ /**
1124
+ * Whether a resolved file loads natively, shared by the worker: an addon, or a `node_modules` file
1125
+ * `inline` doesn't name and no transform takes as a user module.
1126
+ */
1127
+ function isExternal(state, path) {
1128
+ if (path.endsWith(".node")) return true;
1129
+ return state.claims === null ? isThirdParty(path, state.inlineRules) : isClaimedExternal(state.claims, path);
1130
+ }
1131
+ function escapeRegExp(text) {
1132
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1133
+ }
1134
+ /** `runtime` is what this Node can do, probed when first asked for; a test passes its own. */
1135
+ function createRecords(options, runtime) {
1136
+ const dialect = options.moduleScope?.names ?? [];
1137
+ const esm = [...dialect, ...options.policy.injectCjsGlobals ? CJS_GLOBALS.filter((name) => !dialect.includes(name)) : []];
1138
+ const scopePatterns = new Map(esm.map((name) => [name, new RegExp(`(?<![\\w$])${escapeRegExp(name)}(?![\\w$])`)]));
1139
+ const inline = createInlineState();
1140
+ const externals = /* @__PURE__ */ new Map();
1141
+ const required = /* @__PURE__ */ new Map();
1142
+ const edgeKinds = createEdgeKindState(options, runtime);
1143
+ const inlineRules = options.inline ?? NO_RULES;
1144
+ const claims = compileClaims(options, {
1145
+ edgeKinds,
1146
+ inline,
1147
+ inlineRules,
1148
+ required,
1149
+ externals
1150
+ });
1151
+ const evaluable = (path) => isEvaluableExternal(path, inlineRules);
1152
+ const userEdges = (path) => userEdgesOf(state, path);
1153
+ const served = options.moduleScope?.modules ?? [];
1154
+ const state = {
1155
+ options,
1156
+ inline,
1157
+ records: /* @__PURE__ */ new Map(),
1158
+ externals,
1159
+ required,
1160
+ listeners: /* @__PURE__ */ new Set(),
1161
+ reevaluate: createReevaluateState(),
1162
+ edgeKinds,
1163
+ inlineRules,
1164
+ claims,
1165
+ evaluable,
1166
+ userEdges,
1167
+ perFileSources: {
1168
+ claimed: claims?.users ?? [],
1169
+ loaded: required,
1170
+ keep: evaluable,
1171
+ userEdges,
1172
+ elsewhere: served.length === 0 ? null : (path) => inGraph(path) && servedReach(inline, options, path, served, userEdges)
1173
+ },
1174
+ scopeNames: {
1175
+ esm,
1176
+ cjs: dialect
1177
+ },
1178
+ scopePatterns,
1179
+ importers: /* @__PURE__ */ new Map(),
1180
+ graphsDirty: /* @__PURE__ */ new Set(),
1181
+ codeCache: options.codeCache == null ? null : openV8Pack({ dir: options.codeCache })
1182
+ };
1183
+ return state;
1184
+ }
1185
+ /**
1186
+ * The error for a specifier that doesn't resolve: the dialect's `module-not-found` text, with
1187
+ * Node's code for the kind of call (`MODULE_NOT_FOUND` for `require`, else `ERR_MODULE_NOT_FOUND`).
1188
+ */
1189
+ function notFound(state, specifier, importer, kind, miss) {
1190
+ const from = relative(state.options.root, importer).split(sep).join("/");
1191
+ const message = (miss === void 0 ? void 0 : mapperMissMessage(state, specifier, miss)) ?? loaderMessage(state.options.policy, "module-not-found", {
1192
+ specifier,
1193
+ from,
1194
+ importer
1195
+ }) ?? `Cannot find module '${specifier}' imported from ${importer}`;
1196
+ return new ModuleNotFoundError(kind === "require" ? "MODULE_NOT_FOUND" : "ERR_MODULE_NOT_FOUND", message);
1197
+ }
1198
+ /**
1199
+ * The text for a name-mapper rule that matched with no target resolving, or `undefined` when the
1200
+ * miss isn't one, or the dialect has no text for it.
1201
+ */
1202
+ function mapperMissMessage(state, specifier, miss) {
1203
+ const { mappedBy, declared, tried } = miss;
1204
+ const { formatMapperMiss } = state.options;
1205
+ if (formatMapperMiss === void 0 || mappedBy === null || declared === void 0) return;
1206
+ return formatMapperMiss({
1207
+ specifier,
1208
+ rule: mappedBy,
1209
+ declared,
1210
+ tried,
1211
+ resolver: state.options.resolverName
1212
+ });
1213
+ }
1214
+ /**
1215
+ * Whether a name-mapper rule takes over a served module (`ModuleScope.mappable`): the rule matches,
1216
+ * whether or not its target resolves.
1217
+ */
1218
+ function mapperTakes(state, specifier, importer, kind) {
1219
+ if (state.options.moduleScope?.mappable?.includes(specifier) !== true) return false;
1220
+ const result = state.options.resolver.resolve(specifier, {
1221
+ importer,
1222
+ kind,
1223
+ conditions: edgeConditions(state.edgeKinds, kind)
1224
+ });
1225
+ return (result.type === "file" || result.type === "not-found") && result.mappedBy !== null;
1226
+ }
1227
+ /**
1228
+ * Resolves `specifier` from `importer` to a target; one that doesn't resolve is `missing`. The edge
1229
+ * resolves as the kind `ModulePolicy.edgeResolveKind` gives it from `kind` and its importer (a
1230
+ * mock call's specifier, `exact`, as `kind` itself: `ModulePolicy.mockResolveKind`).
1231
+ */
1232
+ function resolveOrMissing(state, specifier, importer, written, exact = false) {
1233
+ const kind = exact ? written : edgeKind(state.edgeKinds, importer, written);
1234
+ if (state.options.moduleScope?.modules?.includes(specifier) === true && !mapperTakes(state, specifier, importer, kind)) return {
1235
+ kind: "served",
1236
+ get error() {
1237
+ return notFound(state, specifier, importer, kind);
1238
+ }
1239
+ };
1240
+ const result = state.options.resolver.resolve(specifier, {
1241
+ importer,
1242
+ kind,
1243
+ conditions: edgeConditions(state.edgeKinds, kind)
1244
+ });
1245
+ if (result.type === "builtin") return {
1246
+ kind: "builtin",
1247
+ id: result.id
1248
+ };
1249
+ if (result.type === "file") {
1250
+ if (result.format === "addon" || isExternal(state, result.path)) return {
1251
+ kind: "external",
1252
+ path: result.path
1253
+ };
1254
+ return {
1255
+ kind: "user",
1256
+ id: toModuleId(result.path)
1257
+ };
1258
+ }
1259
+ return {
1260
+ kind: "missing",
1261
+ error: notFound(state, specifier, importer, kind, result.type === "not-found" ? result : void 0)
1262
+ };
1263
+ }
1264
+ /** Resolves `specifier` from `importer` to a target, or throws `ERR_MODULE_NOT_FOUND` (`MODULE_NOT_FOUND` for `require`). */
1265
+ function resolveTarget(state, specifier, importer, kind) {
1266
+ const target = resolveOrMissing(state, specifier, importer, kind);
1267
+ if (target.kind === "missing" || target.kind === "served") throw target.error;
1268
+ return target;
1269
+ }
1270
+ /**
1271
+ * The target behind an id the module-mock registry hands back (`loadActual`): `node:<name>` is a
1272
+ * builtin, a path under `node_modules` that `inline` doesn't match and no transform takes (or an
1273
+ * addon) is an external, any other path a user module.
1274
+ */
1275
+ function targetOfId(state, id) {
1276
+ if (id.startsWith("node:")) return {
1277
+ kind: "builtin",
1278
+ id
1279
+ };
1280
+ if (isExternal(state, id)) return {
1281
+ kind: "external",
1282
+ path: id
1283
+ };
1284
+ return {
1285
+ kind: "user",
1286
+ id: toModuleId(id)
1287
+ };
1288
+ }
1289
+ /**
1290
+ * The edges of the user module at `path` as the loader holds them: its static deps (and the late
1291
+ * ones) resolved from it, as an edge would. `null` when its file does not compile. Used to follow
1292
+ * a closure of node_modules files through a workspace package linked into them (T2.6).
1293
+ */
1294
+ function userEdgesOf(state, path) {
1295
+ let record;
1296
+ try {
1297
+ record = recordFor(state, toModuleId(path), false);
1298
+ } catch {
1299
+ return null;
1300
+ }
1301
+ const kind = record.format === "cjs" ? "require" : "import";
1302
+ return [...record.deps, ...record.lateDeps].map((specifier) => {
1303
+ let target = null;
1304
+ try {
1305
+ const found = resolveOrMissing(state, specifier, path, kind);
1306
+ if (found.kind === "user") target = found.id;
1307
+ else if (found.kind === "external") target = found.path;
1308
+ else if (found.kind === "builtin") target = found.id;
1309
+ } catch {}
1310
+ return {
1311
+ specifier,
1312
+ kind,
1313
+ target
1314
+ };
1315
+ });
1316
+ }
1317
+ /** The key of an external or builtin in `externals` and `required`. */
1318
+ function externalKey(target) {
1319
+ if (target.kind === "builtin") return target.id;
1320
+ if (target.kind === "external") return target.path;
1321
+ throw new Error(`${target.kind} is not an external`);
1322
+ }
1323
+ /** Transforms a user module once per worker. */
1324
+ function recordFor(state, id, isTest) {
1325
+ const existing = state.records.get(id);
1326
+ if (existing !== void 0) return existing;
1327
+ const path = id;
1328
+ const text = readFileSync(path, "utf8");
1329
+ const thirdParty = isThirdParty(path, state.inlineRules);
1330
+ let record;
1331
+ let transformKeyOf = "";
1332
+ if (path.endsWith(".json")) record = makeRecord(id, "json", text, () => null, [], [], false, false);
1333
+ else if (/\.(?:wasm|node)$/.test(path)) throw new LoaderError("LOADER_UNSUPPORTED_MODULE", `cannot load ${path} as a user module`);
1334
+ else {
1335
+ const transformed = state.options.transformer.transform({
1336
+ filename: path,
1337
+ source: text,
1338
+ role: thirdParty ? "dependency" : isTest ? "test" : "source",
1339
+ consumer: "import",
1340
+ instrument: state.options.shouldInstrument?.(path) === true
1341
+ });
1342
+ transformKeyOf = transformed.cacheKey;
1343
+ const error = transformed.diagnostics.find((diagnostic) => diagnostic.severity === "error");
1344
+ if (error?.thrown !== void 0) {
1345
+ const message = loaderMessage(state.options.policy, "transformer-failed", {
1346
+ file: path,
1347
+ message: error.message
1348
+ }) ?? error.message;
1349
+ const failure = new LoaderError("LOADER_TRANSFORM_FAILED", error.codeFrame === void 0 ? message : `${message}\n\n${error.codeFrame}`);
1350
+ failure.name = error.thrown.name ?? "Error";
1351
+ throw failure;
1352
+ }
1353
+ if (error !== void 0) {
1354
+ const where = error.loc === void 0 ? "" : `:${error.loc.line}:${error.loc.column}`;
1355
+ const message = loaderMessage(state.options.policy, "transform-failed", {
1356
+ file: path,
1357
+ where,
1358
+ message: error.message
1359
+ }) ?? `${path}${where}: ${error.message}`;
1360
+ throw new LoaderError("LOADER_TRANSFORM_FAILED", error.codeFrame === void 0 ? message : `${message}\n\n${error.codeFrame}`);
1361
+ }
1362
+ if (usesModuleRunnerForm(transformed)) {
1363
+ const runner = toModuleRunner(path, transformed);
1364
+ record = makeRecord(id, "esm", runner.code, () => runner.map, runner.deps, transformed.lateDeps, transformed.hasTopLevelAwait, thirdParty);
1365
+ } else {
1366
+ const requires = transformed.imports.filter((entry) => entry.kind === "require").map((entry) => entry.specifier);
1367
+ const dynamicImport = transformed.imports.some((entry) => entry.kind === "dynamic");
1368
+ const source = dynamicImport ? toModuleRunner(path, transformed, { commonjs: true }) : transformed;
1369
+ record = makeRecord(id, "cjs", source.code, () => source.map, requires, [], false, thirdParty, dynamicImport);
1370
+ }
1371
+ }
1372
+ if (!path.endsWith(".json")) record.transformKey = transformKeyOf;
1373
+ state.records.set(id, record);
1374
+ const importers = state.importers.get(id);
1375
+ if (importers !== void 0) for (const importer of importers) state.graphsDirty.add(importer);
1376
+ return record;
1377
+ }
1378
+ function makeRecord(id, format, source, mapOf, deps, lateDeps, hasTopLevelAwait, thirdParty, dynamicImport = false) {
1379
+ return {
1380
+ id,
1381
+ path: id,
1382
+ format,
1383
+ source,
1384
+ get map() {
1385
+ return mapOf();
1386
+ },
1387
+ deps,
1388
+ lateDeps,
1389
+ hasTopLevelAwait,
1390
+ thirdParty,
1391
+ dynamicImport,
1392
+ asyncGraph: hasTopLevelAwait,
1393
+ lateGraph: lateDeps.length > 0,
1394
+ resolved: /* @__PURE__ */ new Map(),
1395
+ linked: false,
1396
+ compiledSync: null,
1397
+ compiledAsync: null,
1398
+ scope: null,
1399
+ transformKey: "",
1400
+ wrapperLength: null
1401
+ };
1402
+ }
1403
+ /**
1404
+ * Preloads a shared external natively with `import()`, for the async path under `interopDefault:
1405
+ * 'node'` (Node's own namespaces). Under `babel` nothing is preloaded: the edge `require`s the
1406
+ * external when it runs, as Jest's CommonJS output does, so a mocked package never loads.
1407
+ */
1408
+ async function preloadAsync(state, target) {
1409
+ if (target.kind !== "external" && target.kind !== "builtin") return;
1410
+ if (state.options.policy.interopDefault !== "node") return;
1411
+ const key = externalKey(target);
1412
+ if (state.externals.has(key)) return;
1413
+ const namespace = await (target.kind === "builtin" ? import(target.id) : import(pathToFileURL(target.path).href));
1414
+ state.externals.set(key, namespace);
1415
+ }
1416
+ /**
1417
+ * One dep of `record` at link time: its target, with a user module transformed (and queued on
1418
+ * `stack`) or, when it doesn't transform, recorded `failed`. A mocked module is never evaluated,
1419
+ * so its transform error only matters if the edge decides on the real module.
1420
+ */
1421
+ function linkDep(state, record, specifier, stack) {
1422
+ let target = resolveOrMissing(state, specifier, record.path, record.format === "cjs" ? "require" : "import");
1423
+ if (target.kind === "user") try {
1424
+ stack.push(recordFor(state, target.id, false));
1425
+ } catch (error) {
1426
+ target = {
1427
+ kind: "failed",
1428
+ id: target.id,
1429
+ error
1430
+ };
1431
+ }
1432
+ setResolved(state, record, specifier, target);
1433
+ return target;
1434
+ }
1435
+ /**
1436
+ * Links a module's static subgraph (Track 2 R1 step 2): resolve every dep, transform user modules,
1437
+ * and preload externals the ESM code imports. A dep that doesn't resolve is recorded `missing`, one
1438
+ * that doesn't transform `failed`; each fails only when its edge runs. Late deps are not linked:
1439
+ * the mocks register first.
1440
+ */
1441
+ async function linkAsync(state, root) {
1442
+ const stack = [root];
1443
+ while (stack.length > 0) {
1444
+ const record = stack.pop();
1445
+ if (record === void 0 || record.linked) continue;
1446
+ record.linked = true;
1447
+ for (const specifier of record.deps) {
1448
+ const target = linkDep(state, record, specifier, stack);
1449
+ if (record.format === "esm") await preloadAsync(state, target);
1450
+ }
1451
+ }
1452
+ markAsyncGraphs(state);
1453
+ }
1454
+ function linkSync(state, root) {
1455
+ const stack = [root];
1456
+ while (stack.length > 0) {
1457
+ const record = stack.pop();
1458
+ if (record === void 0 || record.linked) continue;
1459
+ record.linked = true;
1460
+ for (const specifier of record.deps) linkDep(state, record, specifier, stack);
1461
+ }
1462
+ markAsyncGraphs(state);
1463
+ }
1464
+ /**
1465
+ * Sets `specifier`'s target on `record`. The only writer of `resolved`, so it can keep the
1466
+ * importers index and mark `record` for `markAsyncGraphs`.
1467
+ */
1468
+ function setResolved(state, record, specifier, target) {
1469
+ record.resolved.set(specifier, target);
1470
+ if (target.kind !== "user") return;
1471
+ let importers = state.importers.get(target.id);
1472
+ if (importers === void 0) {
1473
+ importers = /* @__PURE__ */ new Set();
1474
+ state.importers.set(target.id, importers);
1475
+ }
1476
+ importers.add(record);
1477
+ state.graphsDirty.add(record);
1478
+ }
1479
+ /**
1480
+ * Marks every module whose static subgraph has top-level await (`asyncGraph`) or late deps
1481
+ * (`lateGraph`), to a fixed point over cycles.
1482
+ *
1483
+ * Incremental: only the records whose inputs changed since the last run (`Records.graphsDirty`: a
1484
+ * `user` target written to `resolved`, which every link of a dep goes through, and the importers of
1485
+ * a module whose record was made) are looked at, and a record that gains a
1486
+ * flag puts its importers (`Records.importers`) on the worklist, so a run costs the edges around
1487
+ * what changed, not every record in the worker. The result is the one a scan of every record to a
1488
+ * fixed point gives: the flags only ever go from `false` to `true`, a linked record takes a flag
1489
+ * when a `user` target's live record has it, and a record whose inputs did not change already
1490
+ * satisfies that from the last run. A record that is no longer the live one for its id is never
1491
+ * looked at: `dropRecords` takes it out of the dirty set and the importers index.
1492
+ */
1493
+ function markAsyncGraphs(state) {
1494
+ const work = state.graphsDirty;
1495
+ for (const record of work) {
1496
+ work.delete(record);
1497
+ if (!record.linked || record.asyncGraph && record.lateGraph) continue;
1498
+ let changed = false;
1499
+ for (const target of record.resolved.values()) {
1500
+ const dep = target.kind === "user" ? state.records.get(target.id) : void 0;
1501
+ if (dep === void 0) continue;
1502
+ if (dep.asyncGraph && !record.asyncGraph) {
1503
+ record.asyncGraph = true;
1504
+ changed = true;
1505
+ }
1506
+ if (dep.lateGraph && !record.lateGraph) {
1507
+ record.lateGraph = true;
1508
+ changed = true;
1509
+ }
1510
+ }
1511
+ if (changed) {
1512
+ const importers = state.importers.get(record.id);
1513
+ if (importers !== void 0) for (const importer of importers) work.add(importer);
1514
+ }
1515
+ }
1516
+ }
1517
+ /** The scope bindings `record`'s source names, found once. */
1518
+ function scopeOf(state, record) {
1519
+ if (record.scope !== null) return record.scope;
1520
+ const names = record.format === "esm" ? state.scopeNames.esm : state.scopeNames.cjs;
1521
+ record.scope = record.format === "json" ? [] : names.filter((name) => state.scopePatterns.get(name)?.test(record.source) === true);
1522
+ return record.scope;
1523
+ }
1524
+ /**
1525
+ * A record's wrapper function for one evaluation in `mode`. The script is compiled once per worker
1526
+ * and mode (`wrapperScript`). `fresh` (an evaluation in a registry of one file) runs it again for a
1527
+ * new function; otherwise (a registry shared across files, which evaluates a module once) the
1528
+ * function of its first run is called again.
1529
+ *
1530
+ * Why fresh: V8 keeps a function's feedback (its inline caches, and the optimized code built on
1531
+ * them) in a cell its closure shares with every closure the same enclosing function object made. A
1532
+ * module evaluated in every file through one wrapper function would give every file's copy of its
1533
+ * functions one feedback vector, and each file's new classes (new hidden classes) would add maps to
1534
+ * the same inline caches until they went megamorphic. A new run of the script makes a new wrapper
1535
+ * with feedback of its own, as Jest's compile of each module for every test file does, at the cost
1536
+ * of one script run and of each file's copy warming up again, as it does in Jest
1537
+ * (`pnpm bench:loader megamorphic` shows what the shared feedback cost).
1538
+ */
1539
+ function compile(state, record, mode, fresh) {
1540
+ const wrapper = wrapperScript(state, record, mode);
1541
+ if (fresh) return runWrapper(wrapper.script, record);
1542
+ wrapper.shared ??= runWrapper(wrapper.script, record);
1543
+ return wrapper.shared;
1544
+ }
1545
+ function runWrapper(script, record) {
1546
+ const compiled = script.runInThisContext();
1547
+ if (typeof compiled !== "function") throw new Error(`the wrapper for ${record.path} is not a function`);
1548
+ return compiled;
1549
+ }
1550
+ /**
1551
+ * Compiles a record's wrapper script once per worker and mode (filename = the real path, for
1552
+ * stacks and coverage), and reports it to the compile listeners then, once. `sync` strips the
1553
+ * `await` from the import calls, which only the sync path may do; `async` keeps them. A module
1554
+ * with scope bindings gets an outer function taking them, so a module's own `const require = …`
1555
+ * shadows the binding instead of clashing with a parameter.
1556
+ */
1557
+ function wrapperScript(state, record, mode) {
1558
+ const cached = mode === "sync" ? record.compiledSync : record.compiledAsync;
1559
+ if (cached !== null) return cached;
1560
+ const scope = scopeOf(state, record);
1561
+ let body = blankHashbang(record.source);
1562
+ let inner;
1563
+ let head = "";
1564
+ if (record.format === "esm") {
1565
+ if (mode === "sync") body = body.replaceAll("await __vite_ssr_import__(", " __vite_ssr_import__(").replaceAll(`await ${LATE_IMPORT}(`, ` ${LATE_IMPORT}(`);
1566
+ head = "'use strict';";
1567
+ inner = `${mode === "async" ? "async " : " "}function (${ESM_PARAMS}) {`;
1568
+ } else inner = `function (${CJS_PARAMS}${record.dynamicImport ? `, ${DYNAMIC_IMPORT}` : ""}) {`;
1569
+ const prefix = scope.length === 0 ? `${head}(${inner}` : `${head}(function (${scope.join(", ")}) { return ${inner}`;
1570
+ const suffix = scope.length === 0 ? "\n})" : "\n}})";
1571
+ const code = `${prefix}${body}${suffix}`;
1572
+ const options = {
1573
+ filename: record.path,
1574
+ columnOffset: -prefix.length
1575
+ };
1576
+ const wrapper = {
1577
+ script: state.codeCache === null ? new Script(code, options) : state.codeCache.compile(code, options),
1578
+ shared: null
1579
+ };
1580
+ if (mode === "sync") record.compiledSync = wrapper;
1581
+ else record.compiledAsync = wrapper;
1582
+ record.wrapperLength = prefix.length;
1583
+ for (const listener of state.listeners) listener({
1584
+ id: record.id,
1585
+ scriptUrl: record.path,
1586
+ wrapperColumnOffset: prefix.length,
1587
+ get map() {
1588
+ return record.map;
1589
+ },
1590
+ thirdParty: record.thirdParty,
1591
+ transformKey: record.transformKey
1592
+ });
1593
+ return wrapper;
1594
+ }
1595
+ /**
1596
+ * Forgets the records of these modules (absolute paths), so the next load reads and compiles them
1597
+ * again. Watch mode's stale modules (B23c). A path with no record is skipped. The flags of the
1598
+ * records that pointed at one stay (they only ever rise, as before); the record made next marks its
1599
+ * importers for `markAsyncGraphs`.
1600
+ */
1601
+ function dropRecords(state, paths) {
1602
+ for (const path of paths) {
1603
+ const id = toModuleId(path);
1604
+ const record = state.records.get(id);
1605
+ if (record === void 0) continue;
1606
+ state.records.delete(id);
1607
+ for (const target of record.resolved.values()) if (target.kind === "user") state.importers.get(target.id)?.delete(record);
1608
+ state.graphsDirty.delete(record);
1609
+ }
1610
+ }
1611
+
1612
+ // src/reevaluation.ts
1613
+ /**
1614
+ * Every reevaluate key off: what a loader that outlives its files spreads over its policy (the
1615
+ * coordinator's). A new key fails to compile here until it is listed.
1616
+ * @public
1617
+ */
1618
+ const NO_REEVALUATION = {
1619
+ reevaluateHookingExternals: false,
1620
+ reevaluatePatchingExternals: false
1621
+ };
1622
+ const REEVALUATE_KEYS = Object.keys(NO_REEVALUATION).filter((key) => key in NO_REEVALUATION);
1623
+ /**
1624
+ * Whether a policy evaluates shared externals per file: any reevaluate key on. The loader then
1625
+ * opens a window on each external's first load and inlines what it learns; what a window counts
1626
+ * (a read, a write) is the worker's watcher's business.
1627
+ * @public
1628
+ */
1629
+ function reevaluatesExternals(policy) {
1630
+ return REEVALUATE_KEYS.some((key) => policy[key]);
1631
+ }
1632
+
1633
+ // src/internal/interop.ts
1634
+ function createInteropCache() {
1635
+ return {
1636
+ babel: /* @__PURE__ */ new WeakMap(),
1637
+ node: /* @__PURE__ */ new WeakMap()
1638
+ };
1639
+ }
1640
+ function isObjectLike(value) {
1641
+ return value !== null && (typeof value === "object" || typeof value === "function");
1642
+ }
1643
+ /** Whether `value` is a module namespace already (an ES module's, or one we built). */
1644
+ function isNamespace(value) {
1645
+ return isObjectLike(value) && Reflect.get(value, Symbol.toStringTag) === "Module";
1646
+ }
1647
+ /** A fresh exports object for one ES module instance. */
1648
+ function esmExports(interop) {
1649
+ if (interop === "babel") {
1650
+ const exports = {};
1651
+ Object.defineProperty(exports, "__esModule", { value: true });
1652
+ return exports;
1653
+ }
1654
+ const namespace = Object.create(null);
1655
+ Object.defineProperty(namespace, Symbol.toStringTag, { value: "Module" });
1656
+ return namespace;
1657
+ }
1658
+ function copyKey(target, source, key) {
1659
+ const descriptor = Object.getOwnPropertyDescriptor(source, key);
1660
+ if (descriptor !== void 0) Object.defineProperty(target, key, descriptor);
1661
+ }
1662
+ /**
1663
+ * A CommonJS value (or a mocked module's value under `factoryShape: 'module-value'`) seen through
1664
+ * `import`. Built once per value and interop when `cache` is given.
1665
+ */
1666
+ function cjsNamespace(value, interop, cache) {
1667
+ if (!isObjectLike(value)) return { default: value };
1668
+ if (isNamespace(value)) return value;
1669
+ if (interop === "babel" && Reflect.get(value, "__esModule") === true) return value;
1670
+ const known = cache?.[interop].get(value);
1671
+ if (known !== void 0) return known;
1672
+ const namespace = Object.create(null);
1673
+ const keys = Object.keys(value).filter((key) => key !== "default");
1674
+ if (interop === "babel") {
1675
+ namespace.default = value;
1676
+ for (const key of keys) copyKey(namespace, value, key);
1677
+ } else {
1678
+ for (const key of [...keys, "default"].sort()) if (key === "default") namespace.default = value;
1679
+ else copyKey(namespace, value, key);
1680
+ Object.defineProperty(namespace, Symbol.toStringTag, { value: "Module" });
1681
+ }
1682
+ cache?.[interop].set(value, namespace);
1683
+ return namespace;
1684
+ }
1685
+ /** The view of an ES module's exports that the actual paths and automock get: getters over the live exports. */
1686
+ function actualView(exports, interop) {
1687
+ const view = Object.create(null);
1688
+ if (interop === "babel") Object.defineProperty(view, "__esModule", { value: true });
1689
+ else Object.defineProperty(view, Symbol.toStringTag, { value: "Module" });
1690
+ const keys = Object.keys(exports);
1691
+ for (const key of interop === "babel" ? keys.sort() : keys) Object.defineProperty(view, key, {
1692
+ enumerable: true,
1693
+ get: () => Reflect.get(exports, key)
1694
+ });
1695
+ return view;
1696
+ }
1697
+
1698
+ // src/internal/node-loader.ts
1699
+ /**
1700
+ * The registered symbol the first Provino code in the process records the loader under. `provino`'s
1701
+ * bin (`internal/node-loader.ts`) writes the same record under the same key.
1702
+ */
1703
+ const NODE_LOADER_KEY = Symbol.for("provino.nodeLoader");
1704
+ const internals = Module;
1705
+ function isNodeLoader(value) {
1706
+ if (typeof value !== "object" || value === null) return false;
1707
+ const record = value;
1708
+ return typeof record.require === "function" && typeof record.load === "function" && typeof record.resolveFilename === "function";
1709
+ }
1710
+ /** The record the process holds, made now when none is there. */
1711
+ function adopt() {
1712
+ const recorded = globalThis[NODE_LOADER_KEY];
1713
+ if (isNodeLoader(recorded)) return recorded;
1714
+ const record = Object.freeze({
1715
+ require: internals.prototype.require,
1716
+ load: internals._load,
1717
+ resolveFilename: internals._resolveFilename
1718
+ });
1719
+ Object.defineProperty(globalThis, NODE_LOADER_KEY, {
1720
+ value: record,
1721
+ configurable: true
1722
+ });
1723
+ return record;
1724
+ }
1725
+ const found = adopt();
1726
+ /**
1727
+ * Runs `load` (a synchronous native load) with Node's loader as Provino found it, and puts the
1728
+ * process's functions back after it. A function the load itself replaced is left as the load left
1729
+ * it (a package that hooks the loader on purpose keeps its hook). Nothing is swapped when the
1730
+ * loader is as found.
1731
+ */
1732
+ function withNodeLoader(load) {
1733
+ const prototype = internals.prototype;
1734
+ const current = {
1735
+ require: prototype.require,
1736
+ load: internals._load,
1737
+ resolveFilename: internals._resolveFilename
1738
+ };
1739
+ if (current.require === found.require && current.load === found.load && current.resolveFilename === found.resolveFilename) return load();
1740
+ prototype.require = found.require;
1741
+ internals._load = found.load;
1742
+ internals._resolveFilename = found.resolveFilename;
1743
+ try {
1744
+ return load();
1745
+ } finally {
1746
+ if (prototype.require === found.require) prototype.require = current.require;
1747
+ if (internals._load === found.load) internals._load = current.load;
1748
+ if (internals._resolveFilename === found.resolveFilename) internals._resolveFilename = current.resolveFilename;
1749
+ }
1750
+ }
1751
+
1752
+ // src/internal/require-esm.ts
1753
+ /** Files that are never source text: an addon or WebAssembly module (binary), JSON (data). */
1754
+ const NEVER_SOURCE = /\.(?:node|wasm|json)$/;
1755
+ /**
1756
+ * The error for a shared external whose native load threw (`require-esm`), as jest-runtime's
1757
+ * `CjsLoader` raises it (L171-L180, `createRequireEsmError` L336-L349): the dialect's text when the
1758
+ * file has ES module syntax (`esmSyntaxOf`, a file the lexer rejects counting as none), is not
1759
+ * explicitly CommonJS (`.cjs`, or `"type": "commonjs"` for a `.js`), and Node can't evaluate an ES
1760
+ * module graph synchronously (`supportsSyncEvaluate`, where Jest loads it as an ES module instead).
1761
+ * `undefined` otherwise, so the load's own error stands; with it, that error is the `cause`.
1762
+ *
1763
+ * Jest's third condition, a `SyntaxError`, is its own CommonJS compile of the file, which every
1764
+ * file with ES module syntax fails: Jest never runs one. Node loads it as an ES module
1765
+ * (`require(esm)`), so its error is whatever that load met (`ERR_MODULE_NOT_FOUND` for an
1766
+ * extensionless import, `cli/transform-node-modules-ignored`), and any error stands for Jest's.
1767
+ * Read only after a load failed, so a load that works pays nothing. An addon, a WebAssembly module
1768
+ * or JSON file is never read as source.
1769
+ */
1770
+ function requireEsmError(options, edgeKinds, path, error) {
1771
+ const message = loaderMessage(options.policy, "require-esm", { path });
1772
+ if (message === void 0 || !inGraph(path) || edgeKinds.runtime().syncEvaluate) return;
1773
+ if (NEVER_SOURCE.test(path) || isExplicitlyCommonjs(edgeKinds, path)) return void 0;
1774
+ const source = readSource(path);
1775
+ if (source === void 0 || esmSyntaxOf(source) !== true) return void 0;
1776
+ return new RequireEsmError(message, { cause: error });
1777
+ }
1778
+
1779
+ // src/internal/registry.ts
1780
+ /** The served modules of a dialect that serves none. */
1781
+ const NO_MODULES = [];
1782
+ /**
1783
+ * A mock's value that isn't ready (a factory's Promise under `awaitFactory`), kept apart from a
1784
+ * module whose own value is a Promise.
1785
+ */
1786
+ var Pending = class {
1787
+ promise;
1788
+ constructor(promise) {
1789
+ this.promise = promise;
1790
+ }
1791
+ };
1792
+ /** No file's context: nothing is mocked, and a module that names a binding sees the global. */
1793
+ const NO_FILE = Object.freeze({
1794
+ mocks: null,
1795
+ scope: null
1796
+ });
1797
+ /** A specifier that names a file or a URL, not a package or a builtin. */
1798
+ const FILE_SPECIFIER = /^(?:\.{1,2}\/|\/|file:)/;
1799
+ /** Not mocked: the edge loads the real module. */
1800
+ const REAL = Symbol("real");
1801
+ function moduleNamespace() {
1802
+ const namespace = Object.create(null);
1803
+ Object.defineProperty(namespace, Symbol.toStringTag, { value: "Module" });
1804
+ return namespace;
1805
+ }
1806
+ function isThenable(value) {
1807
+ return value !== null && (typeof value === "object" || typeof value === "function") && typeof Reflect.get(value, "then") === "function";
1808
+ }
1809
+ /** `__vite_ssr_exportAll__`: re-export every name except `default` that isn't already set. */
1810
+ function exportAll(target, source) {
1811
+ if (source === null || typeof source !== "object") return;
1812
+ for (const key in source) {
1813
+ if (key === "default" || key in target) continue;
1814
+ Object.defineProperty(target, key, {
1815
+ enumerable: true,
1816
+ configurable: true,
1817
+ get: () => Reflect.get(source, key)
1818
+ });
1819
+ }
1820
+ }
1821
+ /** A `require()` of something that can only be loaded asynchronously. */
1822
+ function requireError(what, why) {
1823
+ return new LoaderError("ERR_REQUIRE_ASYNC_MODULE", `require() cannot load ${what}: ${why}`);
1824
+ }
1825
+ /** A load inside a module evaluating synchronously, of something that can't be. */
1826
+ function syncLoadError(what, why) {
1827
+ return new LoaderError("ERR_REQUIRE_ASYNC_MODULE", `${what} can't be loaded synchronously: ${why}`);
1828
+ }
1829
+ /**
1830
+ * One stack of instance maps: the top is used; `isolateModules` pushes a fresh one and removes
1831
+ * that same map when it finishes, wherever it ended up in the stack. A scratch load (automock's
1832
+ * real load) has a map of its own, carried in its own async context, so a load running beside it
1833
+ * never shares it.
1834
+ */
1835
+ var Registry = class {
1836
+ #state;
1837
+ #maps;
1838
+ /** Namespaces built for CommonJS values and mocks, one per value, as Babel caches its wildcard. */
1839
+ #cache = createInteropCache();
1840
+ /** The scratch load's own instance map, in its async context; made on the first scratch load. */
1841
+ #scratch = null;
1842
+ /** How many scratch loads are running: with none, `#instances` asks no async context. */
1843
+ #scratchLoads = 0;
1844
+ /**
1845
+ * How each node_modules file was served, per instance map (T2.6, B13d Gap 3): shared (`false`),
1846
+ * inlined because the file's mocks reach it (`'mocks'`, the ones `dropInlined` drops under
1847
+ * `none`), or inlined for another reason (`'kept'`: a served module, or evaluated per file, which
1848
+ * is the worker's for good). A module already served keeps its instance, so a `doMock` that comes
1849
+ * after its first load doesn't change it, `resetModules` forgets it, and an `isolateModules`
1850
+ * layer decides afresh.
1851
+ */
1852
+ #memory = /* @__PURE__ */ new WeakMap();
1853
+ /** What this file inlined, for the budget and `LeakReport.inlinedForMocks`. */
1854
+ #ledger = createLedger();
1855
+ /** The running file's context. Under `none` the registry is shared, and each file sets its own. */
1856
+ context = NO_FILE;
1857
+ /**
1858
+ * The user modules the running file asked for (under `none`, where the registry outlives the
1859
+ * file): a module an earlier file evaluated is found, not evaluated again, and is still one the
1860
+ * file loaded. `null` outside `beginFile`/`endFile`.
1861
+ */
1862
+ #touched = null;
1863
+ /**
1864
+ * The user modules each module loaded through an edge its static deps don't name (a
1865
+ * `require(variable)`, a runtime `import()`), by importing module, noted while a file is being
1866
+ * counted (`#touched` is set). Under `none` a later file finds the importer evaluated, not
1867
+ * evaluated again, so what it loaded then is what `loadedByFile` follows for it.
1868
+ */
1869
+ #dynamicLoads = /* @__PURE__ */ new Map();
1870
+ /**
1871
+ * Whether this registry evaluates externals again per file (`reevaluateHookingExternals` or
1872
+ * `reevaluatePatchingExternals`, D127, D132): never one that outlives its files
1873
+ * (`sharedAcrossFiles`, isolation `none`), which keeps every module it evaluated, so neither
1874
+ * watches nor inlines for it. Each file is not evaluated again under `none` by design, so
1875
+ * neither is an external.
1876
+ */
1877
+ #reevaluates;
1878
+ /**
1879
+ * Whether each evaluation runs a fresh wrapper function (`compile`'s `fresh`): in a registry of
1880
+ * one file, every module evaluated here is evaluated again in the next file's, and a fresh
1881
+ * wrapper keeps one file's feedback out of the next. A registry shared across files (`none`)
1882
+ * evaluates a module once, and calls the one wrapper the worker made.
1883
+ */
1884
+ #freshWrappers;
1885
+ constructor(state, sharedAcrossFiles = false) {
1886
+ this.#state = state;
1887
+ this.#maps = [/* @__PURE__ */ new Map()];
1888
+ this.#reevaluates = reevaluatesExternals(state.options.policy) && !sharedAcrossFiles;
1889
+ this.#freshWrappers = !sharedAcrossFiles;
1890
+ }
1891
+ get #instances() {
1892
+ if (this.#scratchLoads > 0) {
1893
+ const scratch = this.#scratch?.getStore();
1894
+ if (scratch !== void 0) return scratch;
1895
+ }
1896
+ const top = this.#maps.at(-1);
1897
+ if (top === void 0) throw new Error("registry has no instance map");
1898
+ return top;
1899
+ }
1900
+ get #interop() {
1901
+ return this.#state.options.policy.interopDefault;
1902
+ }
1903
+ /** Whether a mocked edge may be a Promise to wait for (`awaitFactory`, with mocks in play). */
1904
+ get #mocksMayWait() {
1905
+ return this.#state.options.policy.awaitFactory && this.context.mocks !== null;
1906
+ }
1907
+ loaded() {
1908
+ return [...new Set(this.#maps.flatMap((map) => [...map.keys()]))];
1909
+ }
1910
+ /** Starts counting the modules a file asks for (the shared registry of tier `none`). */
1911
+ beginFile() {
1912
+ this.#touched = /* @__PURE__ */ new Set();
1913
+ }
1914
+ /** Stops counting; the next `beginFile` starts over. */
1915
+ endFile() {
1916
+ this.#touched = null;
1917
+ }
1918
+ /**
1919
+ * What the file loaded, under `none`: the modules it asked for and, through each one's
1920
+ * dependency edges, the loaded modules those reach (an evaluated module's imports are part of
1921
+ * what the file needs, though the file didn't evaluate them). Over-approximate for a CommonJS
1922
+ * module, whose edges are its `require` calls as the scan sees them. Without `beginFile`, every
1923
+ * instance.
1924
+ */
1925
+ loadedByFile() {
1926
+ const touched = this.#touched;
1927
+ if (touched === null) return this.loaded();
1928
+ const seen = new Set(touched);
1929
+ const queue = [...touched];
1930
+ const reach = (target) => {
1931
+ if (seen.has(target) || !this.#maps.some((map) => map.has(target))) return;
1932
+ seen.add(target);
1933
+ queue.push(target);
1934
+ };
1935
+ for (let at = 0; at < queue.length; at++) {
1936
+ const id = queue[at];
1937
+ if (id === void 0) continue;
1938
+ const record = this.#state.records.get(id);
1939
+ if (record !== void 0) {
1940
+ for (const target of record.resolved.values()) if (target.kind === "user") reach(target.id);
1941
+ else if (target.kind === "external") reach(toModuleId(target.path));
1942
+ }
1943
+ const loads = this.#dynamicLoads.get(id);
1944
+ if (loads !== void 0) for (const target of loads) reach(target);
1945
+ }
1946
+ return [...seen];
1947
+ }
1948
+ /**
1949
+ * Notes that `importer` loaded the user module `id` through an edge that can be dynamic. Only
1950
+ * while a file is counted: a registry of any other tier is the file's own and never asks.
1951
+ */
1952
+ #noteLoad(importer, id) {
1953
+ if (this.#touched === null) return;
1954
+ const key = toModuleId(importer);
1955
+ let loads = this.#dynamicLoads.get(key);
1956
+ if (loads === void 0) {
1957
+ loads = /* @__PURE__ */ new Set();
1958
+ this.#dynamicLoads.set(key, loads);
1959
+ }
1960
+ loads.add(id);
1961
+ }
1962
+ /**
1963
+ * Empties every layer of the stack and keeps its depth, so an `isolateModules` call that is
1964
+ * still running removes its own (now empty) map when it finishes.
1965
+ */
1966
+ reset() {
1967
+ for (const map of this.#maps) {
1968
+ map.clear();
1969
+ this.#memory.delete(map);
1970
+ }
1971
+ }
1972
+ /** The modules this file inlined for its mocks, in the order they were. */
1973
+ inlined() {
1974
+ return [...this.#ledger.modules];
1975
+ }
1976
+ /**
1977
+ * Ends the file's inlining for its mocks under `none`: the registry is shared and outlives the
1978
+ * file, so the instances inlined for its mocks go and the next file sees the shared module, and
1979
+ * every verdict but a positive one for a served module is forgotten (the next file's mocks
1980
+ * decide afresh). An external inlined for a served module keeps its instance: under `none` no
1981
+ * module is evaluated again. Any other tier's registry is the file's own and is reset instead.
1982
+ */
1983
+ dropInlined() {
1984
+ for (const map of this.#maps) {
1985
+ const memory = this.#memory.get(map);
1986
+ if (memory === void 0) continue;
1987
+ for (const [path, inlined] of memory) {
1988
+ if (inlined === "mocks") map.delete(toModuleId(path));
1989
+ if (inlined !== "kept") memory.delete(path);
1990
+ }
1991
+ }
1992
+ this.#ledger = createLedger();
1993
+ }
1994
+ /**
1995
+ * Drops the live instance of the user module `specifier` resolves to from `importer`, so its
1996
+ * next import or require evaluates it again. The specifier is resolved as an `import` and as a
1997
+ * `require`, since a package's `exports` can map them to different files and either may be the
1998
+ * one that was loaded. Records stay (compiled code is shared), and so does every other
1999
+ * instance: the module's dependencies keep theirs. An external, a builtin, a module that was
2000
+ * never loaded or a specifier that doesn't resolve (for that kind) is a no-op; the import
2001
+ * itself reports the last one.
2002
+ */
2003
+ invalidate(specifier, importer) {
2004
+ for (const kind of ["import", "require"]) {
2005
+ const target = resolveOrMissing(this.#state, specifier, importer, kind);
2006
+ if (target.kind === "user") this.#instances.delete(target.id);
2007
+ }
2008
+ }
2009
+ isolate(fn) {
2010
+ const map = this.#push();
2011
+ try {
2012
+ return fn();
2013
+ } finally {
2014
+ this.#remove(map);
2015
+ }
2016
+ }
2017
+ async isolateAsync(fn) {
2018
+ const map = this.#push();
2019
+ try {
2020
+ return await fn();
2021
+ } finally {
2022
+ this.#remove(map);
2023
+ }
2024
+ }
2025
+ #push() {
2026
+ const map = /* @__PURE__ */ new Map();
2027
+ this.#maps.push(map);
2028
+ return map;
2029
+ }
2030
+ /** Removes `map` itself, not whatever is on top: isolated calls can overlap and finish in any order. */
2031
+ #remove(map) {
2032
+ const index = this.#maps.lastIndexOf(map);
2033
+ if (index > 0) this.#maps.splice(index, 1);
2034
+ }
2035
+ /**
2036
+ * Runs `load` with a fresh instance map of its own, in its async context: everything it loads,
2037
+ * synchronously or after an await, lands there and is dropped with it, and a load started
2038
+ * outside it never sees it.
2039
+ */
2040
+ #inScratch(load) {
2041
+ this.#scratch ??= new AsyncLocalStorage();
2042
+ this.#scratchLoads++;
2043
+ let result;
2044
+ try {
2045
+ result = this.#scratch.run(/* @__PURE__ */ new Map(), load);
2046
+ } catch (error) {
2047
+ this.#scratchLoads--;
2048
+ throw error;
2049
+ }
2050
+ if (result instanceof Promise) return result.finally(() => {
2051
+ this.#scratchLoads--;
2052
+ });
2053
+ this.#scratchLoads--;
2054
+ return result;
2055
+ }
2056
+ /**
2057
+ * The runner's `import(specifier)` of a setup or test file: link asynchronously, then evaluate.
2058
+ * `evaluated` is called as the file's own evaluation ends (`ImportFile`): at once for a module
2059
+ * that evaluates synchronously, when its promise settles for one that waits.
2060
+ */
2061
+ async load(specifier, importer, isTest, evaluated) {
2062
+ const target = this.#maybeInline(resolveTarget(this.#state, specifier, importer, "import"), true);
2063
+ if (target.kind !== "user") return this.#externalAsync(target);
2064
+ this.#touched?.add(target.id);
2065
+ const record = recordFor(this.#state, target.id, isTest);
2066
+ await linkAsync(this.#state, record);
2067
+ const value = this.#evaluateForImport(record);
2068
+ if (evaluated === void 0) return value;
2069
+ if (!(value instanceof Promise)) {
2070
+ evaluated();
2071
+ return value;
2072
+ }
2073
+ return value.then((settled) => {
2074
+ evaluated();
2075
+ return settled;
2076
+ });
2077
+ }
2078
+ /** The runner's `require(specifier)`: link and evaluate synchronously. */
2079
+ loadSync(specifier, importer, isTest) {
2080
+ const target = this.#maybeInline(resolveTarget(this.#state, specifier, importer, "require"), true);
2081
+ if (target.kind !== "user") return this.#requireExternal(target);
2082
+ this.#touched?.add(target.id);
2083
+ const record = recordFor(this.#state, target.id, isTest);
2084
+ linkSync(this.#state, record);
2085
+ return this.#requireRecord(record);
2086
+ }
2087
+ /** An `import()` from `importer`, through the mock decision. */
2088
+ async importFrom(specifier, importer) {
2089
+ const target = resolveOrMissing(this.#state, specifier, importer, "import");
2090
+ const mocked = this.#mockOf(target, specifier, importer, "esm");
2091
+ if (mocked !== REAL) return await this.#settleFor(mocked, specifier, "async");
2092
+ const found = this.#maybeInline(target);
2093
+ if (found.kind !== "user") return this.#externalAsync(found);
2094
+ this.#noteLoad(importer, found.id);
2095
+ const record = recordFor(this.#state, found.id, false);
2096
+ await linkAsync(this.#state, record);
2097
+ return this.#evaluateForImport(record);
2098
+ }
2099
+ /** A `require` from `importer` (from `record`, whose linked targets it reuses), through the mock decision. */
2100
+ requireFrom(specifier, importer, record) {
2101
+ const target = record === void 0 ? resolveOrMissing(this.#state, specifier, importer, "require") : this.#targetOf(record, specifier, "require");
2102
+ const mocked = this.#mockOf(target, specifier, importer, "cjs");
2103
+ if (mocked !== REAL) {
2104
+ if (mocked instanceof Pending) throw requireError(`'${specifier}'`, "its mock is asynchronous");
2105
+ return mocked;
2106
+ }
2107
+ const found = this.#maybeInline(target);
2108
+ if (found.kind !== "user") return this.#requireExternal(found);
2109
+ if (record?.resolved.get(specifier) !== target) this.#noteLoad(importer, found.id);
2110
+ const dep = recordFor(this.#state, found.id, false);
2111
+ linkSync(this.#state, dep);
2112
+ return this.#requireRecord(dep);
2113
+ }
2114
+ /** A static import inside `record`'s wrapper, evaluating in `mode`: its target was linked ahead. */
2115
+ #importEdge(record, specifier, mode) {
2116
+ const target = this.#targetOf(record, specifier, "import");
2117
+ const mocked = this.#mockOf(target, specifier, record.path, "esm");
2118
+ if (mocked !== REAL) return this.#settleFor(mocked, specifier, mode);
2119
+ const found = this.#maybeInline(target);
2120
+ if (found.kind !== "user") return this.#externalImport(found);
2121
+ const dep = this.#state.records.get(found.id) ?? this.#linkNow(found.id);
2122
+ return this.#importRecord(dep, mode);
2123
+ }
2124
+ /** A late import (D38) on the sync path: what `require()` of a rewritten ES module needs. */
2125
+ #lateImportSync(record, specifier) {
2126
+ const target = resolveOrMissing(this.#state, specifier, record.path, "import");
2127
+ const mocked = this.#mockOf(target, specifier, record.path, "esm");
2128
+ if (mocked !== REAL) return this.#settleFor(mocked, specifier, "sync");
2129
+ const found = this.#maybeInline(target);
2130
+ if (found.kind !== "user") return this.#externalImport(found);
2131
+ this.#noteLoad(record.path, found.id);
2132
+ const dep = recordFor(this.#state, found.id, false);
2133
+ linkSync(this.#state, dep);
2134
+ return this.#importRecord(dep, "sync");
2135
+ }
2136
+ /** A mocked value for a wrapper in `mode`: an async one awaits a pending mock, a sync one can't. */
2137
+ #settleFor(mocked, specifier, mode) {
2138
+ if (!(mocked instanceof Pending)) return mocked;
2139
+ if (mode === "async") return mocked.promise;
2140
+ throw syncLoadError(`'${specifier}'`, "its mock is asynchronous");
2141
+ }
2142
+ /**
2143
+ * The mock decision for an edge: the mocked value shaped for the edge, or `REAL`. A specifier
2144
+ * that didn't resolve is mocked only if `decideUnresolved` says so, and a module that didn't
2145
+ * transform only if `decide` does; otherwise its error is thrown here, when the edge runs.
2146
+ */
2147
+ #mockOf(target, specifier, importer, style) {
2148
+ const mocks = this.context.mocks;
2149
+ if (target.kind === "missing" || target.kind === "served") {
2150
+ const served = target.kind === "served" ? this.#served(specifier, importer, style) : REAL;
2151
+ if (served !== REAL) return served;
2152
+ const found = mocks?.decideUnresolved(specifier, importer);
2153
+ if (mocks !== null && found?.mocked === true) return this.#mocked(mocks, found.id, style);
2154
+ throw new ModuleNotFoundError(target.error.code, target.error.message);
2155
+ }
2156
+ if (mocks === null) {
2157
+ if (target.kind === "failed") throw target.error;
2158
+ return REAL;
2159
+ }
2160
+ const id = target.kind === "user" || target.kind === "failed" ? target.id : externalKey(target);
2161
+ const decision = mocks.decide(id, importer, target.kind === "builtin" ? "builtin" : style, specifier);
2162
+ if (decision.mocked) return this.#mocked(mocks, decision.id, style);
2163
+ if (target.kind === "failed") throw target.error;
2164
+ return REAL;
2165
+ }
2166
+ /**
2167
+ * The value of a module the dialect serves (`ModuleScope.modules`) for `importer`, or `REAL`.
2168
+ * Only a `served` target gets here: no name-mapper rule took it over.
2169
+ */
2170
+ #served(specifier, importer, style) {
2171
+ const scope = this.context.scope;
2172
+ const values = scope?.(importer);
2173
+ if (values === void 0 || !Object.hasOwn(values, specifier)) return REAL;
2174
+ const value = values[specifier];
2175
+ const policy = this.#state.options.policy;
2176
+ return style === "esm" && policy.factoryShape === "module-value" ? cjsNamespace(value, policy.interopDefault, this.#cache) : value;
2177
+ }
2178
+ /**
2179
+ * A mocked module's value for an edge. Under `factoryShape: 'module-value'` an `import` sees it
2180
+ * through the CommonJS interop, as it would the real `module.exports`; under `awaitFactory` a
2181
+ * Promise is a result to wait for, otherwise it is the module itself.
2182
+ */
2183
+ #mocked(mocks, id, style) {
2184
+ const policy = this.#state.options.policy;
2185
+ const served = mocks.materialize(id);
2186
+ const shape = style === "esm" && policy.factoryShape === "module-value" ? (value) => cjsNamespace(value, policy.interopDefault, this.#cache) : (value) => value;
2187
+ if (policy.awaitFactory && isThenable(served)) return new Pending(Promise.resolve(served).then(shape));
2188
+ return shape(served);
2189
+ }
2190
+ /**
2191
+ * An external as the edge should load it: the same external, or a user module (inlined) for one
2192
+ * of four reasons. It is in the per-file set (`reevaluateHookingExternals`, `evaluatedPerFile`:
2193
+ * its first load in this worker read a per-file global, D127, or the transforms make it a user
2194
+ * module, D130; it imports such a file through any chain, so it shares the file's copy and never
2195
+ * Node's cached one; or it is a dependency of the set that only files evaluated per file import,
2196
+ * D132, such as a registry a per-file plugin writes into); its closure reaches a module the dialect
2197
+ * serves (`@jest/globals`, which only the registry can serve); its closure reaches a
2198
+ * `node_modules` file the transforms make a user module (B23e, `claimedReach`); or
2199
+ * `mocksReachShared` is on and the file's mocks take an edge in its graph closure. The answer is
2200
+ * kept for the instance map in play, and later edges follow it. The runner's own loads (`runner`)
2201
+ * never ask the mocks, as the module itself is never mocked.
2202
+ *
2203
+ * A claimed file Node loads (`native`) is also loaded here, the first time, so that a native load
2204
+ * Node can't parse turns it into a user module before the edge takes its route
2205
+ * (`demoteOnParseFailure`); a file that became one since it was resolved goes that way too.
2206
+ */
2207
+ #maybeInline(target, runner = false) {
2208
+ if (target.kind !== "external") return target;
2209
+ const path = target.path;
2210
+ if (this.#inlines(path, runner) || this.#loadClaimedNatively(target)) return {
2211
+ kind: "user",
2212
+ id: toModuleId(path)
2213
+ };
2214
+ return target;
2215
+ }
2216
+ /**
2217
+ * Whether a claimed external is a user module for this edge: it became one after its native load
2218
+ * failed to parse, or its first native load, made now, fails to parse. Nothing without claims.
2219
+ */
2220
+ #loadClaimedNatively(target) {
2221
+ const claims = this.#state.claims;
2222
+ if (claims === null) return false;
2223
+ const load = claimedLoad(claims, target.path);
2224
+ if (load !== "untried") return load === "user";
2225
+ try {
2226
+ this.#requireExternal(target);
2227
+ } catch (error) {
2228
+ if (demoteOnParseFailure(claims, target.path, error)) return true;
2229
+ throw error;
2230
+ }
2231
+ return false;
2232
+ }
2233
+ /** Whether the external at `path` is inlined for the instance map in play (`#maybeInline`). */
2234
+ #inlines(path, runner) {
2235
+ const inlined = this.#decideInline(path, runner);
2236
+ if (this.#reevaluates) this.#state.reevaluate.perFile.answered = true;
2237
+ return inlined;
2238
+ }
2239
+ #decideInline(path, runner) {
2240
+ const state = this.#state;
2241
+ const policy = state.options.policy;
2242
+ const claims = state.claims;
2243
+ const seeded = this.#reevaluates && (state.reevaluate.active.size > 0 || claims !== null && claims.users.length > 0);
2244
+ const served = state.options.moduleScope?.modules ?? NO_MODULES;
2245
+ const mocks = runner || !policy.mocksReachShared ? null : this.context.mocks;
2246
+ if (!seeded && served.length === 0 && claims === null && mocks === null) return false;
2247
+ const map = this.#instances;
2248
+ let memory = this.#memory.get(map);
2249
+ if (memory === void 0) {
2250
+ memory = /* @__PURE__ */ new Map();
2251
+ this.#memory.set(map, memory);
2252
+ }
2253
+ let inlined = memory.get(path);
2254
+ if (inlined === void 0) {
2255
+ inlined = false;
2256
+ if (!path.endsWith(".node")) {
2257
+ const userEdges = state.userEdges;
2258
+ if (seeded && evaluatedPerFile(state.inline, state.options, path, state.reevaluate, state.perFileSources) || served.length > 0 && servedReach(state.inline, state.options, path, served, userEdges) || claims !== null && claimedReach(state.inline, state.options, path, (file) => isClaimedUserModule(claims, file), userEdges)) inlined = "kept";
2259
+ else if (mocks?.active()) {
2260
+ const mockedId = mockedReach(state.inline, state.options, path, mocks, userEdges);
2261
+ if (mockedId !== null) {
2262
+ inlined = "mocks";
2263
+ noteInlined(state.inline, state.options, this.#ledger, toModuleId(path), mockedId);
2264
+ }
2265
+ }
2266
+ }
2267
+ memory.set(path, inlined);
2268
+ }
2269
+ return inlined !== false;
2270
+ }
2271
+ /** The record of a module an edge inlined, linked now: nothing linked it ahead. */
2272
+ #linkNow(id) {
2273
+ const record = recordFor(this.#state, id, false);
2274
+ linkSync(this.#state, record);
2275
+ return record;
2276
+ }
2277
+ /** An external's natively required value, shared by the worker (`require`, or the builtin). */
2278
+ #requireExternal(target) {
2279
+ const key = externalKey(target);
2280
+ const state = this.#state;
2281
+ if (state.required.has(key)) return state.required.get(key);
2282
+ if (target.kind !== "external") {
2283
+ const value = createRequire(state.options.root)(key);
2284
+ state.required.set(key, value);
2285
+ return value;
2286
+ }
2287
+ const native = () => createRequire(target.path)(key);
2288
+ const skipsPatches = state.options.policy.nativeLoadPatches === "skip";
2289
+ const load = () => {
2290
+ try {
2291
+ return skipsPatches ? withNodeLoader(native) : native();
2292
+ } catch (error) {
2293
+ throw requireEsmError(state.options, state.edgeKinds, target.path, error) ?? error;
2294
+ }
2295
+ };
2296
+ const value = this.#reevaluates ? watchedLoad(state.reevaluate, target.path, load, state.evaluable, (file) => packageClosure(state.inline, state.options, file)) : load();
2297
+ state.required.set(key, value);
2298
+ return value;
2299
+ }
2300
+ /** What an `import` of an external sees, synchronously: Node's namespace when preloaded, else the interop over `require`. */
2301
+ #externalImport(target) {
2302
+ if (this.#interop === "node") {
2303
+ const native = this.#state.externals.get(externalKey(target));
2304
+ if (native !== void 0) return native;
2305
+ }
2306
+ return cjsNamespace(this.#requireExternal(target), this.#interop, this.#cache);
2307
+ }
2308
+ async #externalAsync(target) {
2309
+ await preloadAsync(this.#state, target);
2310
+ return this.#externalImport(target);
2311
+ }
2312
+ /**
2313
+ * The real module behind `id` (a resolved path, a `node:` builtin), synchronously: `require`'s
2314
+ * view of it. A scratch load runs in an instance map of its own, dropped afterwards.
2315
+ */
2316
+ actualSync(id, scratch = false) {
2317
+ return scratch ? this.#inScratch(() => this.#actualSync(id)) : this.#actualSync(id);
2318
+ }
2319
+ /** The same through `import`: a CommonJS module as its namespace. */
2320
+ actualAsync(id, scratch = false) {
2321
+ return scratch ? this.#inScratch(() => this.#actualAsync(id)) : this.#actualAsync(id);
2322
+ }
2323
+ #actualTarget(id) {
2324
+ if (id.startsWith("virtual:")) throw new LoaderError("LOADER_NO_REAL_MODULE", `there is no real module behind ${id}`);
2325
+ return targetOfId(this.#state, id);
2326
+ }
2327
+ #actualSync(id) {
2328
+ const target = this.#maybeInline(this.#actualTarget(id));
2329
+ if (target.kind !== "user") return this.#requireExternal(target);
2330
+ this.#touched?.add(target.id);
2331
+ const record = recordFor(this.#state, target.id, false);
2332
+ linkSync(this.#state, record);
2333
+ if (record.format === "esm" && record.asyncGraph) throw syncLoadError(record.path, "its graph has top-level await");
2334
+ const instance = this.#evaluateSync(record);
2335
+ if (record.format === "cjs") return instance.module?.exports;
2336
+ if (record.format === "json") return Reflect.get(instance.exports ?? {}, "default");
2337
+ return this.#viewOf(instance);
2338
+ }
2339
+ async #actualAsync(id) {
2340
+ const target = this.#maybeInline(this.#actualTarget(id));
2341
+ if (target.kind !== "user") return cjsNamespace(this.#requireExternal(target), this.#interop, this.#cache);
2342
+ this.#touched?.add(target.id);
2343
+ const record = recordFor(this.#state, target.id, false);
2344
+ await linkAsync(this.#state, record);
2345
+ const evaluated = this.#evaluateForImport(record);
2346
+ const instance = this.#instances.get(record.id);
2347
+ if (instance === void 0) throw new Error(`${record.id} was evaluated in no instance map`);
2348
+ await evaluated;
2349
+ if (record.format !== "esm") return this.#importValueOfInstance(instance);
2350
+ return this.#viewOf(instance);
2351
+ }
2352
+ #viewOf(instance) {
2353
+ instance.view ??= actualView(instance.exports ?? {}, this.#interop);
2354
+ return instance.view;
2355
+ }
2356
+ /**
2357
+ * Whether `record`, loaded through an async path, evaluates with the async wrapper: its graph
2358
+ * awaits, reaches a late import (which may await), or may meet a pending mock.
2359
+ */
2360
+ #waitsWhenImported(record) {
2361
+ return record.format === "esm" && (record.asyncGraph || record.lateGraph || this.#mocksMayWait);
2362
+ }
2363
+ /** What `import` of `record` resolves to. */
2364
+ #evaluateForImport(record) {
2365
+ if (this.#waitsWhenImported(record)) return this.#evaluateAsync(record);
2366
+ return this.#importValueOfInstance(this.#evaluateSync(record));
2367
+ }
2368
+ #requireRecord(record) {
2369
+ if (record.format === "esm" && record.asyncGraph) throw requireError(record.path, "its graph has top-level await");
2370
+ const instance = this.#evaluateSync(record);
2371
+ if (instance.module !== null) return instance.module.exports;
2372
+ return record.format === "json" ? Reflect.get(instance.exports ?? {}, "default") : instance.exports;
2373
+ }
2374
+ /**
2375
+ * What a static import of `dep` sees from a wrapper in `mode`: a namespace, or inside an async
2376
+ * wrapper a Promise of one. A module already evaluating (a cycle) gives its partial namespace.
2377
+ */
2378
+ #importRecord(dep, mode) {
2379
+ const instance = this.#instances.get(dep.id);
2380
+ const settled = instance?.status === "evaluating" || instance?.status === "done";
2381
+ if (!settled && mode === "async" && this.#waitsWhenImported(dep)) return this.#evaluateAsync(dep);
2382
+ if (!settled && dep.format === "esm" && dep.asyncGraph) throw syncLoadError(dep.path, "its graph has top-level await");
2383
+ return this.#importValueOfInstance(this.#evaluateSync(dep));
2384
+ }
2385
+ /**
2386
+ * The namespace an `import` of an evaluated (or evaluating) instance sees. A CommonJS module's is
2387
+ * built from `module.exports` as it stands, and kept once the module has finished.
2388
+ */
2389
+ #importValueOfInstance(instance) {
2390
+ if (instance.module === null) return instance.exports ?? {};
2391
+ return cjsNamespace(instance.module.exports, this.#interop, instance.status === "done" ? this.#cache : void 0);
2392
+ }
2393
+ #newInstance(record) {
2394
+ const instance = {
2395
+ status: "evaluating",
2396
+ exports: record.format === "cjs" ? null : record.format === "json" ? moduleNamespace() : esmExports(this.#interop),
2397
+ module: record.format === "cjs" ? { exports: {} } : null,
2398
+ promise: null,
2399
+ error: void 0,
2400
+ view: null
2401
+ };
2402
+ this.#instances.set(record.id, instance);
2403
+ this.#touched?.add(record.id);
2404
+ return instance;
2405
+ }
2406
+ #evaluateSync(record) {
2407
+ const instances = this.#instances;
2408
+ const existing = instances.get(record.id);
2409
+ if (existing !== void 0) {
2410
+ if (existing.status === "errored") throw existing.error;
2411
+ return existing;
2412
+ }
2413
+ const instance = this.#newInstance(record);
2414
+ try {
2415
+ if (record.format === "json") Object.defineProperty(instance.exports, "default", {
2416
+ enumerable: true,
2417
+ value: JSON.parse(record.source)
2418
+ });
2419
+ else if (record.format === "cjs") {
2420
+ const module = instance.module;
2421
+ if (module === null) throw new Error("a CJS instance has no module object");
2422
+ this.#wrapper(record, "sync").call(module.exports, module.exports, this.#requireFor(record), module, record.path, dirname(record.path), record.dynamicImport ? this.#importFor(record) : void 0);
2423
+ } else {
2424
+ const exports = instance.exports ?? {};
2425
+ this.#wrapper(record, "sync")(exports, this.#importMeta(record), (specifier) => this.#importEdge(record, specifier, "sync"), this.#importFor(record), (source) => exportAll(exports, source), (specifier) => this.#lateImportSync(record, specifier));
2426
+ }
2427
+ instance.status = "done";
2428
+ return instance;
2429
+ } catch (error) {
2430
+ instance.status = "errored";
2431
+ instance.error = error;
2432
+ if (record.format === "cjs" && instances.get(record.id) === instance) instances.delete(record.id);
2433
+ throw error;
2434
+ }
2435
+ }
2436
+ /** `import()` as `record`'s code makes it: the registry's `importFrom`, from the record's own path. */
2437
+ #importFor(record) {
2438
+ return (specifier) => this.importFrom(specifier, record.path);
2439
+ }
2440
+ #evaluateAsync(record) {
2441
+ const existing = this.#instances.get(record.id);
2442
+ if (existing !== void 0) {
2443
+ if (existing.status === "errored") return Promise.reject(existing.error);
2444
+ return existing.promise ?? Promise.resolve(existing.exports ?? {});
2445
+ }
2446
+ const instance = this.#newInstance(record);
2447
+ const exports = instance.exports ?? {};
2448
+ const run = async () => {
2449
+ try {
2450
+ await this.#wrapper(record, "async")(exports, this.#importMeta(record), (specifier) => this.#importEdge(record, specifier, "async"), this.#importFor(record), (source) => exportAll(exports, source), this.#importFor(record));
2451
+ instance.status = "done";
2452
+ return exports;
2453
+ } catch (error) {
2454
+ instance.status = "errored";
2455
+ instance.error = error;
2456
+ throw error;
2457
+ }
2458
+ };
2459
+ instance.promise = run();
2460
+ return instance.promise;
2461
+ }
2462
+ /** The record's wrapper for one evaluation in `mode`, with its scope bindings applied. */
2463
+ #wrapper(record, mode) {
2464
+ const compiled = compile(this.#state, record, mode, this.#freshWrappers);
2465
+ const scope = scopeOf(this.#state, record);
2466
+ if (scope.length === 0) return compiled;
2467
+ return compiled(...this.#scopeValues(record, scope));
2468
+ }
2469
+ /** The values of `record`'s scope bindings: the dialect's from the file, the CommonJS ones from the record. */
2470
+ #scopeValues(record, scope) {
2471
+ const dialect = this.#state.options.moduleScope?.names ?? [];
2472
+ let values;
2473
+ return scope.map((name) => {
2474
+ if (!dialect.includes(name)) {
2475
+ if (name === "require") return this.#requireFor(record);
2476
+ if (name === "__filename") return record.path;
2477
+ if (name === "__dirname") return dirname(record.path);
2478
+ }
2479
+ values ??= this.context.scope?.(record.id) ?? {};
2480
+ return Object.hasOwn(values, name) ? values[name] : Reflect.get(globalThis, name);
2481
+ });
2482
+ }
2483
+ /** `record`'s target for `specifier`, from its link when the kind is the one it was linked with. */
2484
+ #targetOf(record, specifier, kind) {
2485
+ if (kind !== (record.format === "cjs" ? "require" : "import")) return resolveOrMissing(this.#state, specifier, record.path, kind);
2486
+ const target = record.resolved.get(specifier);
2487
+ if (target !== void 0) return target;
2488
+ const resolved = resolveOrMissing(this.#state, specifier, record.path, kind);
2489
+ setResolved(this.#state, record, specifier, resolved);
2490
+ return resolved;
2491
+ }
2492
+ #requireFor(record) {
2493
+ const native = createRequire(record.path);
2494
+ const require = ((specifier) => this.requireFrom(specifier, record.path, record));
2495
+ const resolve = ((specifier) => {
2496
+ const target = resolveTarget(this.#state, specifier, record.path, "require");
2497
+ return target.kind === "external" ? target.path : target.id;
2498
+ });
2499
+ resolve.paths = native.resolve.paths;
2500
+ require.resolve = resolve;
2501
+ require.cache = native.cache;
2502
+ require.extensions = native.extensions;
2503
+ require.main = void 0;
2504
+ return require;
2505
+ }
2506
+ #importMeta(record) {
2507
+ return Object.assign(Object.create(null), {
2508
+ url: pathToFileURL(record.path).href,
2509
+ filename: record.path,
2510
+ dirname: dirname(record.path),
2511
+ main: false,
2512
+ resolve: (specifier) => {
2513
+ const target = resolveOrMissing(this.#state, specifier, record.path, "import-meta-resolve");
2514
+ if (target.kind === "missing" && FILE_SPECIFIER.test(specifier)) return new URL(specifier, pathToFileURL(record.path)).href;
2515
+ if (target.kind === "missing" || target.kind === "served") throw target.error;
2516
+ return target.kind === "builtin" ? target.id : pathToFileURL(target.kind === "user" ? target.id : target.path).href;
2517
+ }
2518
+ });
2519
+ }
2520
+ };
2521
+
2522
+ // src/tier.ts
2523
+ /** The docblock pragma that raises a file's tier: `@provino-isolate realm`. */
2524
+ const ISOLATE_PRAGMA = "provino-isolate";
2525
+ /** The tiers from the least isolated to the most. */
2526
+ const TIERS = [
2527
+ "none",
2528
+ "registry",
2529
+ "realm",
2530
+ "process"
2531
+ ];
2532
+ function rank(tier) {
2533
+ return TIERS.indexOf(tier);
2534
+ }
2535
+ /** Whether `value` names an isolation tier. */
2536
+ function isIsolationTier(value) {
2537
+ return TIERS.some((tier) => tier === value);
2538
+ }
2539
+ /** The values of `pragma` in `pragmas`: none, one, or the several a repeated pragma holds. */
2540
+ function valuesOf(pragmas, pragma) {
2541
+ const value = pragmas?.[pragma];
2542
+ if (value === void 0) return [];
2543
+ return typeof value === "string" ? [value] : value;
2544
+ }
2545
+ /**
2546
+ * The tier a test file runs at, from the sources that name one.
2547
+ *
2548
+ * - It **raises and never lowers**: a docblock or a learned tier below the project's changes
2549
+ * nothing (and says nothing: a shared template may name a tier a stricter project already
2550
+ * exceeds).
2551
+ * - A `@provino-isolate` value that is not a tier (`none`, `registry`, `realm`, `process`) is
2552
+ * ignored with a warning, and the file keeps what the other sources give it. A pragma given
2553
+ * twice counts each value.
2554
+ * - When two sources name the tier chosen, `source` is the first of `config`, `docblock`,
2555
+ * `learned`.
2556
+ * - `testFile` only names the file in a warning.
2557
+ * @public
2558
+ */
2559
+ function tierFor(testFile, sources) {
2560
+ let tier = sources.configured;
2561
+ let source = "config";
2562
+ const warnings = [];
2563
+ const consider = (candidate, from) => {
2564
+ if (rank(candidate) > rank(tier)) {
2565
+ tier = candidate;
2566
+ source = from;
2567
+ }
2568
+ };
2569
+ for (const value of valuesOf(sources.docblock, ISOLATE_PRAGMA)) if (isIsolationTier(value)) consider(value, "docblock");
2570
+ else warnings.push(`${testFile}: @${ISOLATE_PRAGMA} ${JSON.stringify(value)} is not an isolation tier (use ${TIERS.join(", ")}); the file keeps its tier`);
2571
+ if (sources.learned !== void 0) consider(sources.learned, "learned");
2572
+ return {
2573
+ tier,
2574
+ source,
2575
+ warnings
2576
+ };
2577
+ }
2578
+ /** How much of a file is read first: nearly every docblock fits. */
2579
+ const HEAD_BYTES = 4096;
2580
+ /** A carriage return not before `\n`, or a line separator: jest-docblock's `.` skips them inside a comment. */
2581
+ const NOT_IN_COMMENT = /\r(?!\n)|[\u2028\u2029]/;
2582
+ /**
2583
+ * The `@provino-isolate` pragma of the leading block comment of `source`, as `Pragmas`; `undefined`
2584
+ * when there is none. The grammar is jest-docblock's for one pragma: the first comment only (after
2585
+ * whitespace), an optional `*` before each line, `@provino-isolate value` on its own line, `//`
2586
+ * comments dropped from the value, and a repeated pragma as a list. A comment that is not closed
2587
+ * has no pragma.
2588
+ * @public
2589
+ */
2590
+ function isolatePragmaOf(source) {
2591
+ const start = source.length - source.trimStart().length;
2592
+ if (source.charCodeAt(start) !== 47 || source.charCodeAt(start + 1) !== 42) return void 0;
2593
+ const end = source.indexOf("*/", start + 2);
2594
+ if (end < 0) return void 0;
2595
+ const comment = source.slice(start, end + 2);
2596
+ if (NOT_IN_COMMENT.test(comment) || !comment.includes(`@${"provino-isolate"}`)) return void 0;
2597
+ const inner = comment.replace(/^\/\*\*?/, "").replace(/\*\/$/, "").replaceAll(/(\r?\n|^) *\* ?/g, "$1");
2598
+ const values = [];
2599
+ for (const line of inner.split(/\r?\n/)) {
2600
+ const match = /^ *@provino-isolate(?![\w-])[ \t]*(.*)$/.exec(line);
2601
+ if (match === null) continue;
2602
+ values.push((match[1] ?? "").replaceAll(/(^|\s+)\/\/.*$/g, "").trim());
2603
+ }
2604
+ if (values.length === 0) return void 0;
2605
+ return { [ISOLATE_PRAGMA]: values.length === 1 ? values[0] : values };
2606
+ }
2607
+ /**
2608
+ * `isolatePragmaOf` of the file at `path`, reading its first 4 KiB (all of it when the leading
2609
+ * comment does not end there). A file that can't be read has no pragma: the worker reports it
2610
+ * when it loads the file.
2611
+ * @public
2612
+ */
2613
+ async function readIsolatePragma(path) {
2614
+ try {
2615
+ const handle = await open(path, "r");
2616
+ try {
2617
+ const head = Buffer.allocUnsafe(HEAD_BYTES);
2618
+ const { bytesRead } = await handle.read(head, 0, HEAD_BYTES, 0);
2619
+ const text = head.toString("utf8", 0, bytesRead);
2620
+ const trimmed = text.trimStart();
2621
+ if (!(trimmed.startsWith("/*") && !trimmed.includes("*/", 2)) || bytesRead < HEAD_BYTES) return isolatePragmaOf(text);
2622
+ } finally {
2623
+ await handle.close();
2624
+ }
2625
+ return isolatePragmaOf(await readFile(path, "utf8"));
2626
+ } catch {
2627
+ return;
2628
+ }
2629
+ }
2630
+
2631
+ // src/loader.ts
2632
+ function notYet(what, task) {
2633
+ return new LoaderError("LOADER_NOT_IMPLEMENTED", `${what} is not implemented yet (${task}).`);
2634
+ }
2635
+ /** The code of the module-mock registry's error for a mock that can't stand in for a relative path. */
2636
+ const UNRESOLVED_RELATIVE_MOCK = "unresolved-relative-mock";
2637
+ /**
2638
+ * Creates a worker's loader.
2639
+ * @public
2640
+ */
2641
+ const createLoader = (options) => {
2642
+ if (options.engine !== "runner") throw notYet("engine: 'native'", "T2.10");
2643
+ const state = createRecords(options);
2644
+ const conditions = edgeConditions(state.edgeKinds, options.policy.mockResolveKind);
2645
+ const shared = new Registry(state, true);
2646
+ function fileRegistry(testFile, registryOptions) {
2647
+ if (registryOptions.tier === "realm") throw notYet("the realm tier", "T2.8");
2648
+ promoteLearned(state.reevaluate);
2649
+ const registry = registryOptions.tier === "none" ? shared : new Registry(state);
2650
+ const importer = (parent) => parent ?? testFile;
2651
+ /** The id the actual paths load: the specifier resolved as a mock registration resolves it. */
2652
+ const actualId = (specifier, from) => {
2653
+ const target = resolveOrMissing(state, specifier, from, options.policy.mockResolveKind, true);
2654
+ if (target.kind === "missing" || target.kind === "served") throw target.error;
2655
+ return target.kind === "external" ? target.path : target.id;
2656
+ };
2657
+ const loadActual = (id, _importer, actualOptions) => {
2658
+ const scratch = actualOptions?.scratch === true;
2659
+ return options.policy.actual === "sync-require" ? registry.actualSync(id, scratch) : registry.actualAsync(id, scratch);
2660
+ };
2661
+ const mocks = registryOptions.moduleMocks?.({
2662
+ loadActual,
2663
+ resolver: options.resolver,
2664
+ conditions
2665
+ }) ?? null;
2666
+ const context = {
2667
+ mocks,
2668
+ scope: registryOptions.moduleScope ?? null
2669
+ };
2670
+ registry.context = context;
2671
+ if (registryOptions.tier === "none") registry.beginFile();
2672
+ const needMocks = () => {
2673
+ if (mocks === null) throw new LoaderError("LOADER_NO_MODULE_MOCKS", `${testFile}'s registry has no module-mock registry (FileRegistryOptions.moduleMocks)`);
2674
+ return mocks;
2675
+ };
2676
+ /**
2677
+ * The test file's own load. Where a mock can't stand in for a relative path, the dialect may
2678
+ * name the test file in the error (Vitest's module runner does; an import from inside a test
2679
+ * doesn't go through here).
2680
+ */
2681
+ const loadEntry = async (specifier, evaluated) => {
2682
+ try {
2683
+ return await registry.load(specifier, testFile, true, evaluated);
2684
+ } catch (error) {
2685
+ if ((error instanceof Error ? Reflect.get(error, "code") : void 0) !== UNRESOLVED_RELATIVE_MOCK || !(error instanceof Error)) throw error;
2686
+ const message = loaderMessage(options.policy, "unresolved-mock-import", {
2687
+ message: error.message,
2688
+ importer: testFile
2689
+ });
2690
+ if (message === void 0) throw error;
2691
+ throw new LoaderError("LOADER_UNRESOLVED_MOCK", message, { cause: error });
2692
+ }
2693
+ };
2694
+ const fileRegistry = {
2695
+ file: testFile,
2696
+ tier: registryOptions.tier,
2697
+ import: (specifier, parent, evaluated) => parent == null ? specifier === testFile ? loadEntry(specifier, evaluated) : registry.load(specifier, testFile, false) : registry.importFrom(specifier, parent),
2698
+ require: (specifier, parent) => parent == null ? registry.loadSync(specifier, testFile, specifier === testFile) : registry.requireFrom(specifier, parent),
2699
+ importActual: async (specifier, parent) => await registry.actualAsync(actualId(specifier, importer(parent))),
2700
+ requireActual: (specifier, parent) => registry.actualSync(actualId(specifier, importer(parent))),
2701
+ registerMock: (specifier, parent, spec, mockOptions) => {
2702
+ needMocks().register(specifier, spec, {
2703
+ from: importer(parent),
2704
+ ...mockOptions?.virtual === true ? { virtual: true } : {}
2705
+ });
2706
+ },
2707
+ unregisterMock: (specifier, parent) => {
2708
+ needMocks().register(specifier, { kind: "unmock" }, { from: importer(parent) });
2709
+ },
2710
+ resetModules: () => {
2711
+ registry.reset();
2712
+ mocks?.onResetModules();
2713
+ },
2714
+ invalidate: (specifier, parent) => registry.invalidate(specifier, importer(parent)),
2715
+ isolateModules: (fn) => {
2716
+ mocks?.enterIsolation("isolateModules", "isolateModulesAsync");
2717
+ try {
2718
+ return registry.isolate(fn);
2719
+ } finally {
2720
+ mocks?.exitIsolation();
2721
+ }
2722
+ },
2723
+ isolateModulesAsync: async (fn) => {
2724
+ mocks?.enterIsolation("isolateModulesAsync", "isolateModules");
2725
+ try {
2726
+ return await registry.isolateAsync(fn);
2727
+ } finally {
2728
+ mocks?.exitIsolation();
2729
+ }
2730
+ },
2731
+ loadedModules: () => registry.loadedByFile(),
2732
+ leakTargets: () => [registry],
2733
+ dispose: () => {
2734
+ mocks?.dispose();
2735
+ const inlinedForMocks = registry.inlined();
2736
+ if (registryOptions.tier === "none") registry.dropInlined();
2737
+ if (registry.context === context) {
2738
+ registry.context = NO_FILE;
2739
+ registry.endFile();
2740
+ }
2741
+ if (registryOptions.tier !== "none") registry.reset();
2742
+ const { codeCache } = state;
2743
+ if (codeCache !== null && codeCache.pending >= 64) codeCache.write();
2744
+ return {
2745
+ restored: [],
2746
+ prototypePatches: [],
2747
+ listenersAdded: [],
2748
+ activeResources: [],
2749
+ inlinedForMocks
2750
+ };
2751
+ },
2752
+ [Symbol.dispose]: () => {
2753
+ fileRegistry.dispose();
2754
+ }
2755
+ };
2756
+ return fileRegistry;
2757
+ }
2758
+ return {
2759
+ engine: "runner",
2760
+ createFileRegistry: fileRegistry,
2761
+ tierFor,
2762
+ onModuleCompiled: (listener) => {
2763
+ state.listeners.add(listener);
2764
+ return () => {
2765
+ state.listeners.delete(listener);
2766
+ };
2767
+ },
2768
+ getSourceMap: (id) => state.records.get(id)?.map ?? null,
2769
+ dropRecords: (paths) => {
2770
+ dropRecords(state, paths);
2771
+ },
2772
+ compiledModule: (url) => {
2773
+ const path = url.startsWith("file:") ? fileURLToPath(url) : url;
2774
+ const record = state.records.get(toModuleId(path));
2775
+ if (record === void 0 || record.wrapperLength === null) return null;
2776
+ return {
2777
+ path: record.path,
2778
+ code: blankHashbang(record.source),
2779
+ wrapperLength: record.wrapperLength,
2780
+ map: record.map,
2781
+ transformKey: record.transformKey
2782
+ };
2783
+ },
2784
+ watchExternalLoads: (watcher) => {
2785
+ if (!reevaluatesExternals(options.policy)) return () => {};
2786
+ state.reevaluate.watchers.add(watcher);
2787
+ return () => {
2788
+ state.reevaluate.watchers.delete(watcher);
2789
+ };
2790
+ },
2791
+ takeLearnedExternals: () => takeLearned(state.reevaluate),
2792
+ reevaluateExternals: (paths) => {
2793
+ if (!reevaluatesExternals(options.policy)) return;
2794
+ activate(state.reevaluate, paths.filter((path) => isEvaluableExternal(path, state.inlineRules) && existsSync(path)));
2795
+ },
2796
+ [Symbol.dispose]: () => {
2797
+ saveGraph(state.inline);
2798
+ state.codeCache?.write();
2799
+ state.codeCache?.close();
2800
+ state.records.clear();
2801
+ state.externals.clear();
2802
+ state.required.clear();
2803
+ state.listeners.clear();
2804
+ state.reevaluate.watchers.clear();
2805
+ shared.reset();
2806
+ shared.context = NO_FILE;
2807
+ }
2808
+ };
2809
+ };
2810
+
2811
+ // src/project.ts
2812
+ /**
2813
+ * The config's `tsconfig` for the resolver and the pipeline: `'auto'` and `false` pass through, and
2814
+ * any other string is the path of the tsconfig file, read against `root` (not the process cwd) and
2815
+ * required to exist. (`'auto'` is a string too, so a bare `typeof` check would take it for a file.)
2816
+ */
2817
+ function tsconfigFor(root, tsconfig) {
2818
+ if (tsconfig === "auto" || tsconfig === false) return tsconfig;
2819
+ const file = resolve(root, tsconfig);
2820
+ if (!statSync(file, { throwIfNoEntry: false })?.isFile()) throw new LoaderError("LOADER_TSCONFIG_NOT_FOUND", `loader.tsconfig ${JSON.stringify(tsconfig)} is not a file: ${file} (a relative path is read against ${root})`);
2821
+ return file;
2822
+ }
2823
+ /** Whether a mapper factory's result is a `ModuleMapper`: a string `id` and a `map` function. */
2824
+ function isModuleMapper(value) {
2825
+ return typeof value === "object" && value !== null && typeof Reflect.get(value, "id") === "string" && typeof Reflect.get(value, "map") === "function";
2826
+ }
2827
+ /**
2828
+ * Calls the mapper factory loaded for `loader.mappers[index]`. A factory that throws, or returns
2829
+ * anything but a mapper, is a coded error naming the entry instead of a crash in the resolver.
2830
+ */
2831
+ function buildMapper(factory, options, index) {
2832
+ const entry = `loader.mappers[${index}]`;
2833
+ let mapper;
2834
+ try {
2835
+ mapper = factory(options);
2836
+ } catch (cause) {
2837
+ throw new LoaderError("LOADER_INVALID_MAPPER", `${entry}: the mapper factory threw`, { cause });
2838
+ }
2839
+ if (!isModuleMapper(mapper)) throw new LoaderError("LOADER_INVALID_MAPPER", `${entry}: the mapper factory must return an object with a string id and a map function`);
2840
+ return mapper;
2841
+ }
2842
+ /** Loads a Jest `resolver` module by ref: a function, or an object with `sync` and/or `async`. */
2843
+ async function loadCustomResolver(behaviours, ref) {
2844
+ const loaded = await behaviours.load(ref);
2845
+ if (typeof loaded === "function") return loaded;
2846
+ if (typeof loaded === "object" && loaded !== null && (typeof Reflect.get(loaded, "sync") === "function" || typeof Reflect.get(loaded, "async") === "function")) return loaded;
2847
+ throw new LoaderError("LOADER_INVALID_MAPPER", `loader.resolver: the module must export a function or an object with sync/async`);
2848
+ }
2849
+ /**
2850
+ * Creates the worker's loader for one project. `config.mappers` are loaded by `ModuleRef` first,
2851
+ * which is why this is async. Mock hoisting follows `config.hoist` (the dialect's policy, by
2852
+ * value), and every module's wrapper declares `config.moduleScope`'s names. `config.transform`'s
2853
+ * transformers are loaded here, in the worker, from their own paths (T3.8); a file one of them
2854
+ * matches goes through it, every other file through Oxc. `config.cacheDir` turns the transform cache
2855
+ * on (T3.6): a file's record is read from it before any work and written after.
2856
+ * @public
2857
+ */
2858
+ async function createProjectLoader(root, config, policy, options = {}) {
2859
+ return (await buildProjectLoader(root, config, policy, options)).loader;
2860
+ }
2861
+ /**
2862
+ * A project's loader with the pipeline it transforms through: the coordinator transforms files the
2863
+ * tests never loaded with it, for coverage.
2864
+ */
2865
+ async function buildProjectLoader(root, config, policy, options) {
2866
+ const tsconfig = tsconfigFor(root, config.tsconfig);
2867
+ const behaviours = createBehaviourLoader();
2868
+ const mappers = await Promise.all(config.mappers.map(async (mapper, index) => buildMapper(await behaviours.load(mapper.factory), mapper.options, index)));
2869
+ const transformers = config.transform === void 0 || config.transform.rules.length === 0 ? void 0 : await createJestHost(config.transform);
2870
+ const aliases = config.aliases ?? [];
2871
+ if (aliases.length > 0) mappers.unshift(createNameMapper({
2872
+ rootDir: root,
2873
+ rules: aliases.map(({ pattern, targets }) => ({
2874
+ pattern,
2875
+ targets
2876
+ }))
2877
+ }));
2878
+ const custom = config.resolver === void 0 ? void 0 : await loadCustomResolver(behaviours, config.resolver);
2879
+ const walksGraph = policy.mocksReachShared || (config.scopeModules ?? []).length > 0;
2880
+ if (walksGraph) await initLexer();
2881
+ const pipeline = createPipeline({
2882
+ root,
2883
+ typescript: config.typescript,
2884
+ tsconfig,
2885
+ hoist: config.hoist,
2886
+ runnerForm: true,
2887
+ cache: config.cacheDir === void 0 ? false : { dir: config.cacheDir },
2888
+ ...config.codeIdentity === void 0 ? {} : { codeIdentity: config.codeIdentity },
2889
+ ...transformers === void 0 ? {} : { transformers },
2890
+ ...options.coverage === void 0 ? {} : { instrumenter: options.coverage.instrumenter }
2891
+ });
2892
+ const resolver = createResolver({
2893
+ root,
2894
+ mappers,
2895
+ extensions: config.extensions,
2896
+ tsconfig: tsconfig === "auto" || tsconfig === false ? tsconfig : { configFile: tsconfig },
2897
+ ...config.moduleDirectories === void 0 ? {} : { moduleDirectories: config.moduleDirectories },
2898
+ ...config.modulePaths === void 0 ? {} : { modulePaths: config.modulePaths },
2899
+ ...custom === void 0 ? {} : { custom }
2900
+ });
2901
+ const loader = createLoader({
2902
+ root,
2903
+ engine: "runner",
2904
+ graphCache: config.cacheDir ?? null,
2905
+ lockfileHash: walksGraph && config.cacheDir !== void 0 ? lockfileHash(root) : null,
2906
+ codeCache: config.cacheDir !== void 0 && options.codeCache === "on" && cacheModeFor({ coverage: options.coverage !== void 0 }) === "on" ? config.cacheDir : null,
2907
+ resolver,
2908
+ transformer: pipeline,
2909
+ policy,
2910
+ ...options.coverage === void 0 ? {} : { shouldInstrument: options.coverage.shouldInstrument },
2911
+ conditions: config.conditions,
2912
+ ...config.esmExtensions === void 0 ? {} : { esmExtensions: config.esmExtensions },
2913
+ ...config.transformClaims === void 0 ? {} : { transformClaims: config.transformClaims },
2914
+ ...config.resolver === void 0 ? {} : { resolverName: config.resolver.module },
2915
+ ...policy.mapperMiss === null ? {} : { formatMapperMiss: await behaviours.load(policy.mapperMiss) },
2916
+ ...config.moduleScope.length === 0 && (config.scopeModules ?? []).length === 0 ? {} : { moduleScope: {
2917
+ names: config.moduleScope,
2918
+ modules: config.scopeModules ?? [],
2919
+ ...config.scopeMappable === void 0 ? {} : { mappable: config.scopeMappable }
2920
+ } }
2921
+ });
2922
+ if (config.reevaluate !== void 0) loader.reevaluateExternals(config.reevaluate);
2923
+ return {
2924
+ loader,
2925
+ pipeline,
2926
+ resolver
2927
+ };
2928
+ }
2929
+
2930
+ // src/coordinator.ts
2931
+ /**
2932
+ * The part of a worker's loader config a coordinator-mode loader leaves out: the dialect's mock
2933
+ * hoisting (there is no mock registry for a hoisted call to reach) and its per-module bindings.
2934
+ */
2935
+ function withoutMocks(config) {
2936
+ const { scopeModules: _modules, scopeMappable: _mappable, ...rest } = config;
2937
+ return {
2938
+ ...rest,
2939
+ hoist: null,
2940
+ moduleScope: []
2941
+ };
2942
+ }
2943
+ /**
2944
+ * The module policy a coordinator-mode loader runs under: no mock reaches a shared package (no
2945
+ * mocks), and no external is evaluated per file (one registry serves every import, so nothing is
2946
+ * evaluated again): every reevaluate key off, through `NO_REEVALUATION`, which a new key must join.
2947
+ * @internal
2948
+ */
2949
+ function coordinatorModulePolicy(policy) {
2950
+ return {
2951
+ ...policy,
2952
+ mocksReachShared: false,
2953
+ ...NO_REEVALUATION
2954
+ };
2955
+ }
2956
+ /**
2957
+ * Creates the coordinator-mode loader of one project: its resolver, mappers and transform (the
2958
+ * Jest transformers load here, in this process, from their own paths), at the isolation tier
2959
+ * `none`. `config` is the project's `SerializedLoaderConfig`, the one its workers build theirs
2960
+ * from, so a file resolves and transforms here as it does there.
2961
+ * @public
2962
+ */
2963
+ async function createCoordinatorLoader(root, config, policy, options = {}) {
2964
+ const { loader, pipeline, resolver } = await buildProjectLoader(root, withoutMocks(config), coordinatorModulePolicy(policy), options);
2965
+ const registries = [];
2966
+ const coordinator = {
2967
+ import: (file) => {
2968
+ const registry = loader.createFileRegistry(file, { tier: "none" });
2969
+ registries.push(registry);
2970
+ return registry.import(file);
2971
+ },
2972
+ transformForCoverage: (file) => {
2973
+ if (options.coverage === void 0) throw new Error("transformForCoverage needs a loader created with `coverage`");
2974
+ const record = pipeline.transform({
2975
+ filename: file,
2976
+ source: readFileSync(file, "utf8"),
2977
+ role: "source",
2978
+ consumer: "import",
2979
+ instrument: true
2980
+ });
2981
+ const error = record.diagnostics.find((diagnostic) => diagnostic.severity === "error");
2982
+ if (error !== void 0) {
2983
+ const where = error.loc === void 0 ? "" : `:${error.loc.line}:${error.loc.column}`;
2984
+ throw new LoaderError("LOADER_TRANSFORM_FAILED", `${file}${where}: ${error.message}`);
2985
+ }
2986
+ return {
2987
+ code: record.code,
2988
+ map: record.map
2989
+ };
2990
+ },
2991
+ resolveDependency: (specifier, from, options) => {
2992
+ const result = resolver.resolve(specifier, {
2993
+ importer: from,
2994
+ kind: "require",
2995
+ conditions: options?.conditions ?? config.conditions
2996
+ });
2997
+ if (result.type !== "file") return void 0;
2998
+ if (config.skipNodeResolution === true && !specifier.includes(sep) && result.mappedBy === null) return;
2999
+ return result.path;
3000
+ },
3001
+ invalidateResolution: (paths) => {
3002
+ resolver.invalidate(paths);
3003
+ },
3004
+ dispose: () => {
3005
+ for (const registry of registries.splice(0)) registry.dispose();
3006
+ loader[Symbol.dispose]();
3007
+ },
3008
+ [Symbol.dispose]: () => {
3009
+ coordinator.dispose();
3010
+ }
3011
+ };
3012
+ return coordinator;
3013
+ }
3014
+
3015
+ // src/stacks.ts
3016
+ /** Words that start an expression but name nothing a frame could be called after. */
3017
+ const RESERVED = /* @__PURE__ */ new Set([
3018
+ "new",
3019
+ "throw",
3020
+ "await",
3021
+ "yield",
3022
+ "return",
3023
+ "typeof",
3024
+ "void",
3025
+ "delete",
3026
+ "function",
3027
+ "class",
3028
+ "async",
3029
+ "this",
3030
+ "super",
3031
+ "import",
3032
+ "if",
3033
+ "for",
3034
+ "while",
3035
+ "switch",
3036
+ "try",
3037
+ "catch",
3038
+ "var",
3039
+ "let",
3040
+ "const",
3041
+ "null",
3042
+ "true",
3043
+ "false",
3044
+ "in",
3045
+ "of",
3046
+ "do",
3047
+ "else",
3048
+ "with"
3049
+ ]);
3050
+ /**
3051
+ * The registered symbol the installed formatter carries its frame mapper under: `(sites) => sites`,
3052
+ * each mapped as `.stack` maps it. Code that swaps the formatter out to read structured call sites
3053
+ * (the coordinator's `--detectOpenHandles`, in the process an inline worker runs in) finds it on the
3054
+ * formatter it swapped out, so it never imports the loader.
3055
+ */
3056
+ const MAP_CALL_SITES = Symbol.for("provino.mapCallSites");
3057
+ /**
3058
+ * Installs an `Error.prepareStackTrace` that maps each frame in a module `loader` compiled through
3059
+ * that module's source map, then formats the stack with the formatter it found (Node's own, which
3060
+ * keeps Node's header for its coded errors). A frame keeps its file and its function name; only
3061
+ * its line and column change, and only when the map has a segment on the frame's own line at or
3062
+ * before its column (the lookup `source-map-support` and `@jridgewell/trace-mapping` make). A
3063
+ * frame the map can't place, or one in a file the loader didn't compile, stays as V8 gave it.
3064
+ * The formatter also carries the frame mapper itself, under `MAP_CALL_SITES`. Returns the
3065
+ * uninstall, which puts the previous formatter back if this one is still installed.
3066
+ * Process-wide: the worker installs it once, after it made its loader.
3067
+ * @public
3068
+ */
3069
+ function installSourceMappedStacks(loader, options = {}) {
3070
+ const renames = options.frameNames === "mapped-name";
3071
+ const previous = Object.getOwnPropertyDescriptor(Error, "prepareStackTrace");
3072
+ const format = previous?.value;
3073
+ const decoded = /* @__PURE__ */ new WeakMap();
3074
+ /** The decoded map of the module V8 calls `file`, or `null` when it has none or it can't be read. */
3075
+ function mapOf(file) {
3076
+ const map = loader.getSourceMap(file);
3077
+ if (map === null) return null;
3078
+ let sourceMap = decoded.get(map);
3079
+ if (sourceMap === void 0) {
3080
+ try {
3081
+ sourceMap = new SourceMap({
3082
+ version: map.version,
3083
+ file: map.file ?? "",
3084
+ sourceRoot: map.sourceRoot ?? "",
3085
+ sources: map.sources.map((source) => source ?? ""),
3086
+ sourcesContent: [],
3087
+ names: [...map.names],
3088
+ mappings: map.mappings
3089
+ });
3090
+ } catch {
3091
+ sourceMap = null;
3092
+ }
3093
+ decoded.set(map, sourceMap);
3094
+ }
3095
+ return sourceMap;
3096
+ }
3097
+ const sourceLines = /* @__PURE__ */ new WeakMap();
3098
+ /**
3099
+ * The name Jest's source-map support would give the frame: the map's own `names` entry, or, when
3100
+ * the map has none (Oxc's don't), the identifier the original source holds at the mapped
3101
+ * position, which is where Babel puts one. A reserved word (`new`, `throw`) isn't one.
3102
+ */
3103
+ function nameAt(file, entry) {
3104
+ const named = entry.name;
3105
+ if (typeof named === "string" && named !== "") return named;
3106
+ const raw = loader.getSourceMap(file);
3107
+ if (raw === null || typeof entry.originalSource !== "string") return null;
3108
+ const index = raw.sources.indexOf(entry.originalSource);
3109
+ const content = index === -1 ? void 0 : raw.sourcesContent?.[index];
3110
+ if (typeof content !== "string") return null;
3111
+ let byIndex = sourceLines.get(raw);
3112
+ if (byIndex === void 0) {
3113
+ byIndex = /* @__PURE__ */ new Map();
3114
+ sourceLines.set(raw, byIndex);
3115
+ }
3116
+ let lines = byIndex.get(index);
3117
+ if (lines === void 0) {
3118
+ lines = content.split("\n");
3119
+ byIndex.set(index, lines);
3120
+ }
3121
+ const text = lines[entry.originalLine ?? -1];
3122
+ if (text === void 0) return null;
3123
+ const word = /^[A-Za-z_$][\w$]*/.exec(text.slice(entry.originalColumn ?? 0))?.[0];
3124
+ return word === void 0 || RESERVED.has(word) ? null : word;
3125
+ }
3126
+ function mapped(site) {
3127
+ try {
3128
+ if (site.isEval() || site.isNative()) return site;
3129
+ const file = site.getFileName();
3130
+ const line = site.getLineNumber();
3131
+ const column = site.getColumnNumber();
3132
+ if (typeof file !== "string" || line === null || column === null) return site;
3133
+ const sourceMap = mapOf(file);
3134
+ if (sourceMap === null) return site;
3135
+ const entry = sourceMap.findEntry(line - 1, column - 1);
3136
+ if (entry.generatedLine !== line - 1 || typeof entry.originalSource !== "string" || typeof entry.originalLine !== "number" || typeof entry.originalColumn !== "number") return site;
3137
+ const name = renames ? nameAt(file, entry) : null;
3138
+ return new MappedCallSite(site, entry.originalLine + 1, entry.originalColumn + 1, name);
3139
+ } catch {
3140
+ return site;
3141
+ }
3142
+ }
3143
+ const prepareStackTrace = Object.assign((error, sites) => {
3144
+ const frames = sites.map(mapped);
3145
+ if (typeof format === "function") return format(error, frames);
3146
+ return defaultFormat(error, frames);
3147
+ }, { [MAP_CALL_SITES]: (sites) => sites.map(mapped) });
3148
+ Error.prepareStackTrace = prepareStackTrace;
3149
+ return () => {
3150
+ if (Error.prepareStackTrace !== prepareStackTrace) return;
3151
+ if (previous === void 0) Reflect.deleteProperty(Error, "prepareStackTrace");
3152
+ else Object.defineProperty(Error, "prepareStackTrace", previous);
3153
+ };
3154
+ }
3155
+ /** V8's own layout, for a process with no formatter to hand the frames to. */
3156
+ function defaultFormat(error, sites) {
3157
+ let header;
3158
+ try {
3159
+ header = Error.prototype.toString.call(error);
3160
+ } catch {
3161
+ header = "Error";
3162
+ }
3163
+ return sites.length === 0 ? header : `${header}\n at ${sites.join("\n at ")}`;
3164
+ }
3165
+ /**
3166
+ * A V8 call site at another line and column. Every method answers as the site does except the
3167
+ * position, and `toString` is the site's own text with its position swapped, so the frame keeps
3168
+ * V8's layout (`async`, `new`, `[as m]`, the function and type names).
3169
+ */
3170
+ var MappedCallSite = class {
3171
+ #site;
3172
+ #line;
3173
+ #column;
3174
+ #name;
3175
+ constructor(site, line, column, name = null) {
3176
+ this.#site = site;
3177
+ this.#line = line;
3178
+ this.#column = column;
3179
+ this.#name = name;
3180
+ }
3181
+ getLineNumber() {
3182
+ return this.#line;
3183
+ }
3184
+ getColumnNumber() {
3185
+ return this.#column;
3186
+ }
3187
+ toString() {
3188
+ if (this.#name !== null) return this.#named(this.#name);
3189
+ const text = this.#site.toString();
3190
+ const position = `:${this.#site.getLineNumber()}:${this.#site.getColumnNumber()}`;
3191
+ const at = text.lastIndexOf(position);
3192
+ if (at === -1) return text;
3193
+ return `${text.slice(0, at)}:${this.#line}:${this.#column}${text.slice(at + position.length)}`;
3194
+ }
3195
+ getThis() {
3196
+ return this.#site.getThis();
3197
+ }
3198
+ getTypeName() {
3199
+ return this.#site.getTypeName();
3200
+ }
3201
+ getFunction() {
3202
+ return this.#site.getFunction();
3203
+ }
3204
+ getFunctionName() {
3205
+ return this.#name ?? this.#site.getFunctionName();
3206
+ }
3207
+ /**
3208
+ * The frame with the map's name as its function name, laid out as V8 lays out a call site
3209
+ * (`Type.name [as method] (file:line:column)`), the layout Jest's source-map support rebuilds
3210
+ * (jest-source-map `callSiteToString`).
3211
+ */
3212
+ #named(name) {
3213
+ const site = this.#site;
3214
+ const where = `${site.getScriptNameOrSourceURL() ?? site.getFileName() ?? "<anonymous>"}:${this.#line}:${this.#column}`;
3215
+ if (site.isConstructor()) return `new ${name} (${where})`;
3216
+ if (site.isToplevel()) return `${name} (${where})`;
3217
+ const type = site.getTypeName();
3218
+ const method = site.getMethodName();
3219
+ let line = "";
3220
+ if (type !== null && type !== "" && !name.startsWith(type)) line += `${type}.`;
3221
+ line += name;
3222
+ if (method !== null && method !== "" && name.indexOf(`.${method}`) !== name.length - method.length - 1) line += ` [as ${method}]`;
3223
+ return `${line} (${where})`;
3224
+ }
3225
+ getMethodName() {
3226
+ return this.#site.getMethodName();
3227
+ }
3228
+ getFileName() {
3229
+ return this.#site.getFileName();
3230
+ }
3231
+ getEnclosingLineNumber() {
3232
+ return this.#site.getEnclosingLineNumber();
3233
+ }
3234
+ getEnclosingColumnNumber() {
3235
+ return this.#site.getEnclosingColumnNumber();
3236
+ }
3237
+ getEvalOrigin() {
3238
+ return this.#site.getEvalOrigin();
3239
+ }
3240
+ getScriptNameOrSourceURL() {
3241
+ return this.#site.getScriptNameOrSourceURL();
3242
+ }
3243
+ getScriptHash() {
3244
+ return this.#site.getScriptHash();
3245
+ }
3246
+ getPosition() {
3247
+ return this.#site.getPosition();
3248
+ }
3249
+ getPromiseIndex() {
3250
+ return this.#site.getPromiseIndex();
3251
+ }
3252
+ isToplevel() {
3253
+ return this.#site.isToplevel();
3254
+ }
3255
+ isEval() {
3256
+ return this.#site.isEval();
3257
+ }
3258
+ isNative() {
3259
+ return this.#site.isNative();
3260
+ }
3261
+ isConstructor() {
3262
+ return this.#site.isConstructor();
3263
+ }
3264
+ isAsync() {
3265
+ return this.#site.isAsync();
3266
+ }
3267
+ isPromiseAll() {
3268
+ return this.#site.isPromiseAll();
3269
+ }
3270
+ };
3271
+
3272
+ export { ISOLATE_PRAGMA, LoaderError, ModuleNotFoundError, NO_REEVALUATION, RequireEsmError, createCoordinatorLoader, createLoader, createProjectLoader, installSourceMappedStacks, isIsolationTier, isolatePragmaOf, readIsolatePragma, reevaluatesExternals, tierFor };