vitest-native 0.14.1 → 0.15.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +11 -10
  2. package/dist/cli.d.mts +9 -1
  3. package/dist/cli.mjs +2609 -361
  4. package/dist/context.d.mts +19 -0
  5. package/dist/context.mjs +47 -1
  6. package/dist/docs-url.d.mts +4 -0
  7. package/dist/docs-url.mjs +9 -0
  8. package/dist/errors.d.mts +21 -1
  9. package/dist/hang-watch-setup.mjs +55 -0
  10. package/dist/hang-watch.d.mts +56 -0
  11. package/dist/hang-watch.mjs +343 -0
  12. package/dist/helpers.cjs +24 -53
  13. package/dist/helpers.mjs +22 -1
  14. package/dist/host-D0r3P_T1.mjs +1985 -0
  15. package/dist/{index-aNBCTfA5.d.mts → index-JOR602XU.d.mts} +105 -2
  16. package/dist/index.d.mts +2 -1
  17. package/dist/index.mjs +723 -149
  18. package/dist/jest-compat/aliases.d.mts +1 -0
  19. package/dist/jest-compat/aliases.mjs +11 -0
  20. package/dist/jest-compat/interop.mjs +1 -1
  21. package/dist/jest-compat/jest-object.mjs +23 -5
  22. package/dist/jest-compat/node-registry.mjs +836 -68
  23. package/dist/jest-compat/setup.mjs +205 -12
  24. package/dist/jest-compat.cjs +383 -47
  25. package/dist/jest-compat.d.cts +19 -2
  26. package/dist/jest-compat.d.mts +19 -2
  27. package/dist/jest-compat.mjs +232 -47
  28. package/dist/matchers.d.cts +0 -1
  29. package/dist/matchers.d.mts +0 -1
  30. package/dist/native/assets.mjs +3 -1
  31. package/dist/native/babel-caller.d.mts +13 -0
  32. package/dist/native/babel-caller.mjs +24 -0
  33. package/dist/native/babel-toolchain.mjs +27 -3
  34. package/dist/native/boundary.mjs +45 -8
  35. package/dist/native/bounded-process.mjs +63 -5
  36. package/dist/native/bridge-client.mjs +133 -0
  37. package/dist/native/bridge-server.mjs +215 -0
  38. package/dist/native/bridge-thread.mjs +79 -0
  39. package/dist/native/bridge.mjs +512 -0
  40. package/dist/native/compile-error.mjs +120 -0
  41. package/dist/native/explain.mjs +3 -2
  42. package/dist/native/expo-module-mocks.mjs +2 -0
  43. package/dist/native/export-condition-recovery.mjs +20 -99
  44. package/dist/native/hooks.mjs +256 -133
  45. package/dist/native/jest-resolvers.mjs +94 -0
  46. package/dist/native/library-jest.mjs +352 -0
  47. package/dist/native/loader.mjs +167 -73
  48. package/dist/native/match.mjs +67 -7
  49. package/dist/native/module-reset.mjs +44 -49
  50. package/dist/native/ownership-ledger.d.mts +87 -0
  51. package/dist/native/ownership-ledger.mjs +524 -0
  52. package/dist/native/ownership.d.mts +20 -0
  53. package/dist/native/ownership.mjs +114 -0
  54. package/dist/native/registry-compiler.mjs +39 -5
  55. package/dist/native/registry-process.mjs +327 -28
  56. package/dist/native/registry.mjs +752 -200
  57. package/dist/native/resident-health.mjs +1 -0
  58. package/dist/native/resolve.d.mts +7 -0
  59. package/dist/native/resolve.mjs +119 -4
  60. package/dist/native/rntl-hooks.mjs +9 -5
  61. package/dist/native/rntl-text-host.mjs +5 -15
  62. package/dist/native/root-spelling.d.mts +6 -0
  63. package/dist/native/root-spelling.mjs +77 -0
  64. package/dist/native/runner.mjs +2 -19
  65. package/dist/native/setup.mjs +119 -38
  66. package/dist/native/shared-resolver.d.mts +141 -0
  67. package/dist/native/shared-resolver.mjs +719 -0
  68. package/dist/native/test-runner.mjs +26 -0
  69. package/dist/native/transform.mjs +18 -22
  70. package/dist/native/worker.mjs +9 -4
  71. package/dist/node-dispatch.mjs +293 -0
  72. package/dist/{preset-map-CogjYmSw.mjs → preset-map-DdAexIwz.mjs} +113 -2
  73. package/dist/{presets-CXDyg51l.mjs → presets-_EaSw29m.mjs} +710 -130
  74. package/dist/presets.d.mts +1 -1
  75. package/dist/presets.mjs +1 -1
  76. package/dist/rntl-matchers.d.ts +11 -15
  77. package/dist/rntl-support.mjs +28 -13
  78. package/dist/root-mocks-BNXeosbR.mjs +155 -0
  79. package/dist/serializer.cjs +7 -5
  80. package/dist/serializer.d.cts +7 -5
  81. package/dist/serializer.d.mts +7 -5
  82. package/dist/serializer.mjs +7 -5
  83. package/dist/setup.mjs +26 -27
  84. package/docs/migrating-from-jest.md +9 -232
  85. package/docs/migrating-from-vitest-react-native.md +4 -4
  86. package/docs/release-readiness.md +9 -11
  87. package/docs/versioning.md +38 -9
  88. package/package.json +59 -33
  89. package/dist/host-BAAAlSkO.mjs +0 -1028
@@ -6,6 +6,7 @@
6
6
  // stdout/stderr remain available to arbitrary user/toolchain code without being
7
7
  // able to corrupt the protocol.
8
8
  import { spawn } from "node:child_process";
9
+ import os from "node:os";
9
10
 
10
11
  // The protocol channel carries the one answer and is capped strictly. stdout/stderr
11
12
  // belong to arbitrary user and toolchain code, which may log freely: only a tail is
@@ -15,8 +16,34 @@ const LOG_TAIL_BYTES = 64 * 1024;
15
16
  const DEFAULT_TIMEOUT_MS = 120_000;
16
17
  const OOM_RE = /heap out of memory|reached heap limit|allocation failed.*heap/i;
17
18
 
18
- function attempt(entryFile, input, heapMb, spawnProcess, timeoutMs, label) {
19
+ // Refused (sandbox, platform) or exited: keep the default priority. Others throw.
20
+ const PRIORITY_REFUSED = new Set(["EACCES", "EPERM", "ESRCH", "ENOSYS"]);
21
+ export function lowerPriority(pid, priority, setPriority = os.setPriority) {
22
+ try {
23
+ setPriority(pid, priority);
24
+ return true;
25
+ } catch (error) {
26
+ if (!PRIORITY_REFUSED.has(error?.info?.code)) throw error;
27
+ return false;
28
+ }
29
+ }
30
+
31
+ function attempt(
32
+ entryFile,
33
+ input,
34
+ heapMb,
35
+ spawnProcess,
36
+ timeoutMs,
37
+ label,
38
+ signal,
39
+ priority,
40
+ unref,
41
+ ) {
19
42
  return new Promise((resolve) => {
43
+ if (signal?.aborted) {
44
+ resolve({ ok: false, oom: false, cancelled: true, error: `${label} was cancelled`, heapMb });
45
+ return;
46
+ }
20
47
  let child;
21
48
  try {
22
49
  child = spawnProcess(process.execPath, [`--max-old-space-size=${heapMb}`, entryFile], {
@@ -33,6 +60,23 @@ function attempt(entryFile, input, heapMb, spawnProcess, timeoutMs, label) {
33
60
  return;
34
61
  }
35
62
 
63
+ // A background helper must not keep this process alive by itself: if everything
64
+ // else is done, the process exits and its exit hook stops the helper.
65
+ if (unref) {
66
+ child.unref?.();
67
+ for (const stream of child.stdio ?? []) stream?.unref?.();
68
+ }
69
+
70
+ // A background helper yields the CPU to the work it runs beside.
71
+ if (priority !== undefined && child.pid !== undefined) {
72
+ try {
73
+ lowerPriority(child.pid, priority);
74
+ } catch (error) {
75
+ child.kill("SIGKILL");
76
+ throw error;
77
+ }
78
+ }
79
+
36
80
  let stdout = "";
37
81
  let stderr = "";
38
82
  let protocol = "";
@@ -40,12 +84,18 @@ function attempt(entryFile, input, heapMb, spawnProcess, timeoutMs, label) {
40
84
  let overflow = false;
41
85
  let settled = false;
42
86
  let timer;
87
+ const onAbort = () => {
88
+ child.kill("SIGKILL");
89
+ finish({ ok: false, oom: false, cancelled: true, error: `${label} was cancelled`, heapMb });
90
+ };
43
91
  const finish = (result) => {
44
92
  if (settled) return;
45
93
  settled = true;
46
94
  clearTimeout(timer);
95
+ signal?.removeEventListener("abort", onAbort);
47
96
  resolve(result);
48
97
  };
98
+ signal?.addEventListener("abort", onAbort, { once: true });
49
99
  const appendProtocol = (current, chunk) => {
50
100
  outputBytes += Buffer.byteLength(chunk);
51
101
  if (outputBytes > MAX_OUTPUT_BYTES) {
@@ -89,7 +139,7 @@ function attempt(entryFile, input, heapMb, spawnProcess, timeoutMs, label) {
89
139
  // A helper may exit before draining input. EPIPE is emitted asynchronously;
90
140
  // catching stdin.end() does not catch it. The close event reports the cause.
91
141
  child.stdin?.on("error", () => {});
92
- child.on("close", (code, signal) => {
142
+ child.on("close", (code, exitSignal) => {
93
143
  if (settled) return;
94
144
  const oom = OOM_RE.test(stderr);
95
145
  if (overflow) {
@@ -112,7 +162,7 @@ function attempt(entryFile, input, heapMb, spawnProcess, timeoutMs, label) {
112
162
  response?.error ||
113
163
  stderr.trim().split("\n")[0] ||
114
164
  stdout.trim().split("\n")[0] ||
115
- `${label} exited ${code ?? `on ${signal ?? "an unknown signal"}`}`,
165
+ `${label} exited ${code ?? `on ${exitSignal ?? "an unknown signal"}`}`,
116
166
  });
117
167
  });
118
168
  timer = setTimeout(() => {
@@ -149,13 +199,21 @@ export async function runBoundedProcess(
149
199
  timeoutMs = DEFAULT_TIMEOUT_MS,
150
200
  spawnProcess = spawn,
151
201
  label = "helper",
202
+ // Aborting kills the child and resolves with `cancelled: true`.
203
+ signal,
204
+ // os.setPriority value for the child (19 is the lowest priority).
205
+ priority,
206
+ // Let this process exit while the child runs (the child's timer is unref'd too).
207
+ unref = false,
152
208
  },
153
209
  ) {
154
- const first = await attempt(entryFile, input, initialHeapMb, spawnProcess, timeoutMs, label);
210
+ const run = (heapMb) =>
211
+ attempt(entryFile, input, heapMb, spawnProcess, timeoutMs, label, signal, priority, unref);
212
+ const first = await run(initialHeapMb);
155
213
  if (first.ok || !first.oom || retryHeapMb <= initialHeapMb) {
156
214
  return { ...first, attempts: 1 };
157
215
  }
158
- const retry = await attempt(entryFile, input, retryHeapMb, spawnProcess, timeoutMs, label);
216
+ const retry = await run(retryHeapMb);
159
217
  return { ...retry, attempts: 2 };
160
218
  }
161
219
 
@@ -0,0 +1,133 @@
1
+ // The require bridge's synchronous client, in a test worker. `fetchSync` asks the main
2
+ // process (bridge-server.mjs) for Vite's transform of one module and waits for it, as
3
+ // the Babel toolchain call waits for its thread (transform.mjs): the helper thread
4
+ // (bridge-thread.mjs) starts on the first request, so a worker that never takes the
5
+ // bridge starts nothing.
6
+ import fs from "node:fs";
7
+ import { MessageChannel, receiveMessageOnPort, Worker } from "node:worker_threads";
8
+ import { VitestNativeError } from "../errors.mjs";
9
+ import { BRIDGE_PROVIDE_KEY } from "./bridge-server.mjs";
10
+
11
+ // Captured as this module loads: the call below runs while test code is on the stack,
12
+ // and a test that stubs one of these (or fakes the clock) must not stop the bridge.
13
+ const atomicsLoad = Atomics.load;
14
+ const atomicsStore = Atomics.store;
15
+ const atomicsWait = Atomics.wait;
16
+ const SharedArrayBufferCtor = SharedArrayBuffer;
17
+ const Int32ArrayCtor = Int32Array;
18
+ const now = performance.now.bind(performance);
19
+
20
+ /** How long one fetch may take: Vite transforms the file in the main process. */
21
+ const FETCH_DEADLINE_MS = 30_000;
22
+
23
+ let bridge = null;
24
+ let seq = 0;
25
+ let options = {};
26
+
27
+ /** Counters for tests and the count gate: starts, fetches, and time spent waiting. */
28
+ export const bridgeStats = (globalThis[Symbol.for("vitest-native.bridge")] ??= {
29
+ threadStarts: 0,
30
+ fetches: 0,
31
+ fetchMs: 0,
32
+ });
33
+
34
+ /** Internal test seam: the helper thread now running, or null. */
35
+ export function _bridgeThread() {
36
+ return bridge?.worker ?? null;
37
+ }
38
+
39
+ /** Internal test seam: `{ deadlineMs, endpoint, token }`; stops the current thread. */
40
+ export function _setBridgeOptions(next = {}) {
41
+ bridge?.worker.terminate();
42
+ bridge = null;
43
+ options = next;
44
+ }
45
+
46
+ function provided() {
47
+ const value = globalThis.__vitest_worker__?.providedContext?.[BRIDGE_PROVIDE_KEY];
48
+ const endpoint = options.endpoint ?? value?.endpoint;
49
+ const token = options.token ?? value?.token;
50
+ if (typeof endpoint !== "string" || typeof token !== "string") {
51
+ throw new VitestNativeError(
52
+ "BRIDGE_UNAVAILABLE",
53
+ `experimental.ownershipModel 'resolution': this worker has no bridge to the main ` +
54
+ `process (Vitest's provided context has no ${BRIDGE_PROVIDE_KEY}). Report this, ` +
55
+ `with the Vitest config, as a vitest-native bug.`,
56
+ );
57
+ }
58
+ return { endpoint, token };
59
+ }
60
+
61
+ function startBridge() {
62
+ bridgeStats.threadStarts++;
63
+ const { port1, port2 } = new MessageChannel();
64
+ const signal = new Int32ArrayCtor(new SharedArrayBufferCtor(8));
65
+ const worker = new Worker(new URL("./bridge-thread.mjs", import.meta.url), {
66
+ workerData: { port: port2, signal, ...provided() },
67
+ transferList: [port2],
68
+ execArgv: [],
69
+ });
70
+ worker.on("error", (err) => {
71
+ process.stderr.write(`[vitest-native] the require bridge's thread: ${err?.stack ?? err}\n`);
72
+ });
73
+ worker.unref();
74
+ port1.unref();
75
+ return { port: port1, signal, worker };
76
+ }
77
+
78
+ /**
79
+ * Vitest's fetch result for `url` (from `importer`, in `environment`), synchronously:
80
+ * `{ code, file, id, url, invalidate }` for a module Vite evaluates, `{ externalize, type }`
81
+ * for one Node loads. Fails by name when the main process does not answer in time (the
82
+ * thread is then stopped, so a late answer cannot be taken for a later request), when the
83
+ * thread ends, or when the main process refuses or fails the fetch.
84
+ */
85
+ export function fetchSync(url, importer, environment) {
86
+ if (bridge === null || atomicsLoad(bridge.signal, 1) === 1) bridge = startBridge();
87
+ const { port, signal, worker } = bridge;
88
+ const deadlineMs = options.deadlineMs ?? FETCH_DEADLINE_MS;
89
+ const started = now();
90
+ const request = { seq: ++seq, url, importer, environment };
91
+ atomicsStore(signal, 0, 0);
92
+ port.postMessage(request);
93
+ const deadline = started + deadlineMs;
94
+ for (;;) {
95
+ const left = deadline - now();
96
+ if (left <= 0) break;
97
+ if (atomicsWait(signal, 0, 0, Math.min(left, 1000)) !== "timed-out") break;
98
+ if (atomicsLoad(signal, 1) === 1) break;
99
+ }
100
+ bridgeStats.fetchMs += now() - started;
101
+ const reply = receiveMessageOnPort(port)?.message;
102
+ if (reply === undefined || reply.seq !== request.seq) {
103
+ const ended = atomicsLoad(signal, 1) === 1;
104
+ bridge = null;
105
+ if (!ended) {
106
+ worker.terminate();
107
+ throw new VitestNativeError(
108
+ "VITE_FETCH_TIMEOUT",
109
+ `experimental.ownershipModel 'resolution': the main process did not return Vite's ` +
110
+ `transform of ${url} within ${Math.round(deadlineMs / 1000)} s, so the require ` +
111
+ `that reached it cannot be answered. The bridge's thread was stopped.`,
112
+ );
113
+ }
114
+ throw new VitestNativeError(
115
+ "VITE_FETCH_FAILED",
116
+ `experimental.ownershipModel 'resolution': the require bridge's thread ended before ` +
117
+ `it returned ${url}. Its own error, if it has one, is printed as "the require ` +
118
+ `bridge's thread:".`,
119
+ );
120
+ }
121
+ bridgeStats.fetches++;
122
+ if (reply.error) {
123
+ const message = `experimental.ownershipModel 'resolution': ${reply.error.message}`;
124
+ if (reply.error.code === "BRIDGE_FILE_REFUSED") {
125
+ throw new VitestNativeError("BRIDGE_FILE_REFUSED", message);
126
+ }
127
+ throw new VitestNativeError("VITE_FETCH_FAILED", message);
128
+ }
129
+ // As Vitest's own worker reads a fetch answered from its module cache: the code is in
130
+ // the file `tmp` names (vitest's module-runner transport, `"cached" in result`).
131
+ if ("cached" in reply.ok) return { code: fs.readFileSync(reply.ok.tmp, "utf-8"), ...reply.ok };
132
+ return reply.ok;
133
+ }
@@ -0,0 +1,215 @@
1
+ // The main-process half of the require bridge (experimental.ownershipModel: 'resolution';
2
+ // docs/ownership-model.md). A worker whose Node `require` reaches a file Vite owns, before
3
+ // Vite evaluated it, asks here for Vite's transform of that file, synchronously, through a
4
+ // helper thread (bridge-client.mjs), and evaluates it in Vite's own module map.
5
+ //
6
+ // The listener is private to the run:
7
+ // - a Unix socket in a fresh directory only this user can enter (mkdtemp: 0700), or on
8
+ // Windows a named pipe with a random name; never a TCP port;
9
+ // - every request carries a random token the workers receive through Vitest's
10
+ // `provide`; a line without it, or not well-formed, is ignored (no reply);
11
+ // - it answers only for files inside the directories Vite serves and allowed by Vite's
12
+ // own file rules (server.fs.allow and server.fs.deny), checked before anything is read
13
+ // when the request names a file, and again on the answer. What it answers is Vitest's
14
+ // own fetch: code for a module Vite evaluates, `externalize` for one Node loads. Which
15
+ // of Node's requires are bridged at all is the worker's decision (the ownership policy).
16
+ // Replies echo the request's `seq`, so a client matches each reply to its request.
17
+ import crypto from "node:crypto";
18
+ import fs from "node:fs";
19
+ import net from "node:net";
20
+ import os from "node:os";
21
+ import path from "node:path";
22
+ import { VitestNativeError } from "../errors.mjs";
23
+
24
+ /** What a worker reads through `inject` (Vitest's provided context) to reach this server. */
25
+ export const BRIDGE_PROVIDE_KEY = "vitestNativeRequireBridge";
26
+
27
+ /** The longest line a request may be; longer input is not ours and is dropped. */
28
+ const MAX_LINE = 64 * 1024;
29
+
30
+ /**
31
+ * Start the bridge for one Vitest project.
32
+ *
33
+ * @param {object} options
34
+ * @param {(url: string, importer: string | undefined, environment: string) => Promise<object>} options.fetch
35
+ * Vitest's own fetch of a module for a worker (externalization rules included)
36
+ * @param {(file: string) => boolean} options.mayServe whether the server may answer for
37
+ * `file`: inside the directories Vite serves and allowed by Vite's own file rules
38
+ * (server.fs.deny included). Which requires the bridge takes over is the worker's call.
39
+ * @param {string} options.root Vite's root, for a request spelled as a root-relative URL
40
+ * @returns {Promise<{ endpoint: string, token: string, close(): Promise<void> }>}
41
+ */
42
+ export async function startBridgeServer({ fetch, mayServe, root = process.cwd() }) {
43
+ const token = crypto.randomBytes(24).toString("hex");
44
+ let dir = null;
45
+ let endpoint;
46
+ if (process.platform === "win32") {
47
+ endpoint = `\\\\.\\pipe\\vitest-native-bridge-${crypto.randomUUID()}`;
48
+ } else {
49
+ // A Unix socket path is limited (104 bytes on macOS, 108 on Linux): a long TMPDIR
50
+ // falls back to /tmp, which every Unix has.
51
+ const base = os.tmpdir().length > 60 ? "/tmp" : os.tmpdir();
52
+ try {
53
+ dir = fs.mkdtempSync(path.join(base, "vn-bridge-"));
54
+ } catch (error) {
55
+ throw unavailable(base, error);
56
+ }
57
+ endpoint = path.join(dir, "b.sock");
58
+ }
59
+ // A process that ends without close() (a crash, a signal) still removes its directory.
60
+ const removeDir = () => {
61
+ if (dir !== null) fs.rmSync(dir, { recursive: true, force: true });
62
+ };
63
+ process.once("exit", removeDir);
64
+ const sockets = new Set();
65
+ const server = net.createServer((socket) => {
66
+ sockets.add(socket);
67
+ socket.on("close", () => sockets.delete(socket));
68
+ socket.on("error", () => socket.destroy());
69
+ socket.setEncoding("utf8");
70
+ let buffered = "";
71
+ socket.on("data", (chunk) => {
72
+ buffered += chunk;
73
+ if (buffered.length > MAX_LINE && !buffered.includes("\n")) {
74
+ socket.destroy();
75
+ return;
76
+ }
77
+ let newline;
78
+ while ((newline = buffered.indexOf("\n")) !== -1) {
79
+ const line = buffered.slice(0, newline);
80
+ buffered = buffered.slice(newline + 1);
81
+ const request = parseRequest(line, token);
82
+ if (request === null) continue;
83
+ answer(request).then((reply) => {
84
+ if (!socket.destroyed) socket.write(`${reply}\n`);
85
+ });
86
+ }
87
+ });
88
+ });
89
+
90
+ async function answer({ seq, url, importer, environment }) {
91
+ // A request naming a file is checked before anything reads or transforms it.
92
+ const named = fileOfUrl(url, root);
93
+ if (named !== null && !mayServe(named)) return refused(seq, url);
94
+ try {
95
+ const result = await fetch(url, importer, environment);
96
+ // Code is served only for a file Vite owns, whether it comes inline or through
97
+ // Vitest's module cache (`cached` + `tmp`). An externalized module carries no code:
98
+ // the worker loads it through Node, as Vitest would.
99
+ // A virtual module (a plugin's `\0…` id, React Native's facade) has no file: it is
100
+ // generated, not read, and is answered as Vitest answers it.
101
+ const fromFile = typeof result.file === "string" && path.isAbsolute(result.file);
102
+ if (!("externalize" in result) && fromFile && !mayServe(result.file)) {
103
+ return refused(seq, url);
104
+ }
105
+ return JSON.stringify({ seq, ok: result });
106
+ } catch (error) {
107
+ return JSON.stringify({
108
+ seq,
109
+ error: { code: "VITE_FETCH_FAILED", message: String(error?.message ?? error) },
110
+ });
111
+ }
112
+ }
113
+
114
+ try {
115
+ await new Promise((resolve, reject) => {
116
+ server.once("error", reject);
117
+ server.listen(endpoint, () => {
118
+ server.off("error", reject);
119
+ resolve();
120
+ });
121
+ });
122
+ } catch (error) {
123
+ removeDir();
124
+ process.off("exit", removeDir);
125
+ throw unavailable(endpoint, error);
126
+ }
127
+ server.unref();
128
+
129
+ return {
130
+ endpoint,
131
+ token,
132
+ async close() {
133
+ for (const socket of sockets) socket.destroy();
134
+ await new Promise((resolve) => server.close(() => resolve()));
135
+ removeDir();
136
+ process.off("exit", removeDir);
137
+ },
138
+ };
139
+ }
140
+
141
+ function unavailable(where, error) {
142
+ return new VitestNativeError(
143
+ "BRIDGE_UNAVAILABLE",
144
+ `experimental.ownershipModel 'resolution': the require bridge could not listen at ` +
145
+ `${where} (${error?.code ?? error?.message ?? error}).`,
146
+ );
147
+ }
148
+
149
+ function refused(seq, url) {
150
+ return JSON.stringify({
151
+ seq,
152
+ error: {
153
+ code: "BRIDGE_FILE_REFUSED",
154
+ message: `${url} is outside the files Vite serves for this project`,
155
+ },
156
+ });
157
+ }
158
+
159
+ /**
160
+ * The file a request URL names, or null for one that does not (a bare specifier, which
161
+ * Vitest resolves; its answer is checked after). `/@fs/` and absolute paths name a file;
162
+ * a root-relative URL names one under Vite's root. A query (`?raw`) does not change which.
163
+ */
164
+ export function fileOfUrl(url, root) {
165
+ const bare = url.replace(/[?#].*$/, "");
166
+ // Vite's ids for modules that are not files: a virtual module (`/@id/__x00__…`) or a
167
+ // bare id Vite could not resolve to one (`/@id/…`), and its client (`/@vite/…`).
168
+ if (bare.startsWith("/@id/") || bare.startsWith("/@vite/")) return null;
169
+ if (bare.startsWith("/@fs/")) {
170
+ const rest = bare.slice(4);
171
+ return /^\/[A-Za-z]:\//.test(rest) ? path.resolve(rest.slice(1)) : path.resolve(rest);
172
+ }
173
+ if (path.isAbsolute(bare) && !bare.startsWith("/")) return path.resolve(bare);
174
+ if (bare.startsWith("/")) {
175
+ // An absolute POSIX path, or a root-relative URL: a path that exists as given is a file.
176
+ return fs.existsSync(bare) ? path.resolve(bare) : path.join(root, bare);
177
+ }
178
+ return null;
179
+ }
180
+
181
+ /** A request line, or null when it is not one of ours (wrong token, malformed). */
182
+ export function parseRequest(line, token) {
183
+ let message;
184
+ try {
185
+ message = JSON.parse(line);
186
+ } catch {
187
+ return null;
188
+ }
189
+ if (
190
+ message === null ||
191
+ typeof message !== "object" ||
192
+ !safeEqual(message.token, token) ||
193
+ !Number.isSafeInteger(message.seq) ||
194
+ typeof message.url !== "string" ||
195
+ message.url.length === 0 ||
196
+ (message.importer !== undefined && typeof message.importer !== "string") ||
197
+ typeof message.environment !== "string"
198
+ ) {
199
+ return null;
200
+ }
201
+ return {
202
+ seq: message.seq,
203
+ url: message.url,
204
+ importer: message.importer,
205
+ environment: message.environment,
206
+ };
207
+ }
208
+
209
+ function safeEqual(given, token) {
210
+ if (typeof given !== "string") return false;
211
+ // Compared as bytes: a string of the token's length in characters can be longer in bytes.
212
+ const a = Buffer.from(given);
213
+ const b = Buffer.from(token);
214
+ return a.length === b.length && crypto.timingSafeEqual(a, b);
215
+ }
@@ -0,0 +1,79 @@
1
+ // The require bridge's helper thread (bridge-client.mjs): it holds the connection to the
2
+ // main process's bridge server (bridge-server.mjs) and relays one request at a time,
3
+ // while the test thread waits on `signal`. Same protocol as Babel's thread
4
+ // (babel-worker.mjs): signal[0] 0 waiting, 1 answered, 2 this thread ended; signal[1] 1
5
+ // once it has ended.
6
+ import net from "node:net";
7
+ import { workerData } from "node:worker_threads";
8
+
9
+ const { port, signal, endpoint, token } = workerData;
10
+
11
+ function settle(message) {
12
+ port.postMessage(message);
13
+ Atomics.store(signal, 0, 1);
14
+ Atomics.notify(signal, 0);
15
+ }
16
+
17
+ process.on("exit", () => {
18
+ Atomics.store(signal, 1, 1);
19
+ Atomics.store(signal, 0, 2);
20
+ Atomics.notify(signal, 0);
21
+ });
22
+
23
+ /** A reply line, or null when it is not JSON (it is then not an answer to anything). */
24
+ function parseReply(line) {
25
+ try {
26
+ return JSON.parse(line);
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+
32
+ let socket = null;
33
+ let pending = null; // { seq }
34
+ let buffered = "";
35
+
36
+ function connect() {
37
+ socket = net.createConnection(endpoint);
38
+ socket.setEncoding("utf8");
39
+ socket.on("data", (chunk) => {
40
+ buffered += chunk;
41
+ let newline;
42
+ while ((newline = buffered.indexOf("\n")) !== -1) {
43
+ const line = buffered.slice(0, newline);
44
+ buffered = buffered.slice(newline + 1);
45
+ const reply = parseReply(line);
46
+ // Only the answer to the request the test thread is waiting for: anything else
47
+ // (a reply to a request it gave up on) is dropped.
48
+ if (pending === null || reply?.seq !== pending.seq) continue;
49
+ pending = null;
50
+ settle(reply);
51
+ }
52
+ });
53
+ socket.on("error", (error) => {
54
+ socket = null;
55
+ if (pending !== null) {
56
+ const { seq } = pending;
57
+ pending = null;
58
+ settle({
59
+ seq,
60
+ error: { code: "VITE_FETCH_FAILED", message: `bridge connection: ${error.message}` },
61
+ });
62
+ }
63
+ });
64
+ socket.on("close", () => {
65
+ socket = null;
66
+ // Closed under a waiting request: answered now, not left to the caller's deadline.
67
+ if (pending !== null) {
68
+ const { seq } = pending;
69
+ pending = null;
70
+ settle({ seq, error: { code: "VITE_FETCH_FAILED", message: "bridge connection closed" } });
71
+ }
72
+ });
73
+ }
74
+
75
+ port.on("message", (request) => {
76
+ if (socket === null) connect();
77
+ pending = { seq: request.seq };
78
+ socket.write(`${JSON.stringify({ ...request, token })}\n`);
79
+ });