supercov 4.27.0 → 4.29.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.
Files changed (32) hide show
  1. package/README.md +43 -16
  2. package/docs/cli.md +358 -9
  3. package/docs/getting-started.md +18 -0
  4. package/docs/mutation.md +539 -0
  5. package/docs/supported-suites.md +109 -60
  6. package/package.json +11 -10
  7. package/runtime/javascript/atomic.mjs +6 -2
  8. package/runtime/javascript/ava.mjs +12 -0
  9. package/runtime/javascript/bunTest.mjs +17 -0
  10. package/runtime/javascript/jest.cjs +67 -0
  11. package/runtime/javascript/jest.config.mjs +46 -6
  12. package/runtime/javascript/jestReporter.mjs +5 -2
  13. package/runtime/javascript/mocha.mjs +79 -5
  14. package/runtime/javascript/nodeTest.mjs +28 -0
  15. package/runtime/javascript/playwright.mjs +33 -0
  16. package/runtime/javascript/playwrightStrong.mjs +477 -0
  17. package/runtime/javascript/playwrightStrongReporter.mjs +377 -0
  18. package/runtime/javascript/runnerEntry.mjs +62 -0
  19. package/runtime/javascript/runtime.mjs +752 -13
  20. package/runtime/javascript/snapshots.mjs +16 -1
  21. package/runtime/javascript/strongJestHost.mjs +103 -0
  22. package/runtime/javascript/strongJob.mjs +78 -0
  23. package/runtime/javascript/strongJobs.mjs +809 -0
  24. package/runtime/javascript/strongMochaHost.mjs +166 -0
  25. package/runtime/javascript/strongWasmOut.cjs +96 -0
  26. package/runtime/javascript/tap.mjs +43 -1
  27. package/runtime/javascript/transport.mjs +5 -0
  28. package/runtime/javascript/vitest.mjs +74 -2
  29. package/runtime/javascript/vitestBrowser.mjs +34 -2
  30. package/runtime/javascript/vitestStrong.mjs +234 -0
  31. package/runtime/javascript/vitestStrongReporter.mjs +2268 -0
  32. package/runtime/javascript/vitestStrongSpawner.mjs +248 -0
@@ -0,0 +1,166 @@
1
+ // A resident Mocha for a strong pass's jobs (strongJobs.mjs), as StrykerJS's
2
+ // Mocha runner keeps one: one process that keeps Mocha and the project's
3
+ // required modules loaded, and runs one job after another. Before each job
4
+ // every CommonJS module of the project is taken out of `require.cache`, so the
5
+ // job's test file and the code it tests load afresh, with the job's mutant
6
+ // switched on, as in a process of their own. (A suite of ES modules, which
7
+ // cannot be loaded again, runs a process per job instead: the driver does
8
+ // not start this for it.) Its tests and outcomes go through the Mocha adapter.
9
+ //
10
+ // A suite of ES modules (SUPERCOV_MOCHA_FRESH_WORKERS=1) runs each job in a
11
+ // worker thread of its own instead: a thread has a module graph of its own,
12
+ // so the job's modules load afresh as in a process of their own, and the
13
+ // next job's thread starts, and loads Mocha, while this one runs.
14
+ //
15
+ // The driver forks it in the project's copy and sends
16
+ // { type: "init", args: [<the command's arguments to mocha>] }
17
+ // { type: "job", id, file: <absolute test file>, mutant: { file, index } | null, environment: {...} }
18
+ // and it answers { type: "ready" } and { type: "done", id, error? }.
19
+ import { existsSync } from "node:fs";
20
+ import { createRequire } from "node:module";
21
+ import { join, resolve, sep } from "node:path";
22
+ import { fileURLToPath, pathToFileURL } from "node:url";
23
+ import { Worker, isMainThread, parentPort } from "node:worker_threads";
24
+
25
+ globalThis.__SUPERCOV_DIRECT_RUNTIME__ ??= await import("./runtime.mjs");
26
+ process.__SUPERCOV_DIRECT_RUNTIME__ ??= globalThis.__SUPERCOV_DIRECT_RUNTIME__;
27
+ const runtime = globalThis.__SUPERCOV_DIRECT_RUNTIME__;
28
+ const root = process.cwd();
29
+ const require = createRequire(join(root, "package.json"));
30
+
31
+ let Mocha;
32
+ let options;
33
+ let rootHooks;
34
+
35
+ async function init(args) {
36
+ const mochaRoot = resolve(require.resolve("mocha/package.json"), "..");
37
+ const { adaptMocha } = await import(new URL("./mocha.mjs", import.meta.url).href);
38
+ await adaptMocha(join(mochaRoot, "package.json"));
39
+ // Loaded as the adapter loads Mocha's runner, so both see one Mocha.
40
+ // Mocha 10 and 11 name these .js; Mocha 12, .cjs where they are CommonJS.
41
+ const load = async (name) => {
42
+ for (const extension of [".js", ".cjs"]) {
43
+ const path = join(mochaRoot, "lib", `${name}${extension}`);
44
+ if (!existsSync(path))
45
+ continue;
46
+ const loaded = await import(pathToFileURL(path).href);
47
+ return loaded.default ?? loaded;
48
+ }
49
+ throw new Error(`Mocha has no lib/${name}`);
50
+ };
51
+ const mocha = await load("mocha");
52
+ Mocha = mocha.Mocha ?? mocha;
53
+ const { loadOptions } = await load("cli/options");
54
+ const { handleRequires } = await load("cli/run-helpers");
55
+ options = loadOptions(args);
56
+ // What --require loads (a root hooks plugin, a register hook) is loaded
57
+ // once, as the command loads it once.
58
+ const plugins = await handleRequires(options.require ?? [], { ignoredPlugins: ["mochaGlobalSetup", "mochaGlobalTeardown"] });
59
+ rootHooks = plugins?.rootHooks;
60
+ }
61
+
62
+ // The project's own modules, outside node_modules and Supercov's directory.
63
+ function forgetProjectModules() {
64
+ const ours = `${sep}.supercov${sep}node_modules${sep}`;
65
+ for (const file of Object.keys(require.cache)) {
66
+ if (file.startsWith(root + sep) && !file.includes(`${sep}node_modules${sep}`) && !file.includes(ours))
67
+ delete require.cache[file];
68
+ }
69
+ }
70
+
71
+ async function runJob({ file, mutant, environment }, fresh) {
72
+ Object.assign(process.env, environment);
73
+ if (!fresh)
74
+ forgetProjectModules();
75
+ if (mutant)
76
+ runtime.setActiveMutant(mutant.file, mutant.index);
77
+ else
78
+ runtime.clearActiveMutant();
79
+ try {
80
+ const mocha = new Mocha({ ...options, rootHooks, parallel: false, watch: false });
81
+ mocha.files = [...[].concat(options.file ?? []).map((name) => resolve(root, name)), file];
82
+ // In a process that keeps them, loaded by require, which loads a
83
+ // file again once it is out of require.cache (Mocha's loadFilesAsync
84
+ // imports it, and an import is never loaded again); in a fresh
85
+ // thread, imported.
86
+ if (fresh)
87
+ await mocha.loadFilesAsync();
88
+ else
89
+ mocha.loadFiles();
90
+ mocha.lazyLoadFiles?.(true);
91
+ await new Promise((done) => mocha.run(() => done()));
92
+ try {
93
+ mocha.dispose();
94
+ }
95
+ catch {
96
+ // An older Mocha disposes nothing.
97
+ }
98
+ }
99
+ finally {
100
+ runtime.clearActiveMutant();
101
+ }
102
+ }
103
+
104
+ const failure = (error) => String(error?.stack ?? error);
105
+
106
+ if (!isMainThread) {
107
+ // A fresh thread: Mocha loaded once it is made, one job, then its end.
108
+ parentPort.on("message", (message) => {
109
+ if (message?.type === "init")
110
+ init(message.args).then(() => parentPort.postMessage({ type: "ready" }), (error) => parentPort.postMessage({ type: "ready", error: failure(error) }));
111
+ else if (message?.type === "job")
112
+ runJob(message, true).then(() => parentPort.postMessage({ type: "done" }), (error) => parentPort.postMessage({ type: "done", error: failure(error) }));
113
+ });
114
+ }
115
+ else {
116
+ const fresh = process.env.SUPERCOV_MOCHA_FRESH_WORKERS === "1";
117
+ let args = [];
118
+ // The next job's thread, made and readied while a job runs.
119
+ let spare;
120
+ const thread = () => new Promise((resolveThread) => {
121
+ const worker = new Worker(fileURLToPath(import.meta.url), { stdout: false, stderr: false });
122
+ worker.once("message", (message) => resolveThread(message.error ? { error: message.error, worker } : { worker }));
123
+ worker.once("error", (error) => resolveThread({ error: failure(error), worker }));
124
+ worker.postMessage({ type: "init", args });
125
+ });
126
+ const inThread = async (job) => {
127
+ const ready = await spare;
128
+ spare = thread();
129
+ if (ready.error) {
130
+ await ready.worker.terminate();
131
+ throw new Error(ready.error);
132
+ }
133
+ try {
134
+ const done = await new Promise((resolveDone, rejectDone) => {
135
+ ready.worker.on("message", (message) => {
136
+ if (message?.type === "done")
137
+ resolveDone(message);
138
+ });
139
+ ready.worker.once("error", rejectDone);
140
+ ready.worker.once("exit", () => rejectDone(new Error("the job's thread ended")));
141
+ ready.worker.postMessage(job);
142
+ });
143
+ if (done.error)
144
+ throw new Error(done.error);
145
+ }
146
+ finally {
147
+ await ready.worker.terminate();
148
+ }
149
+ };
150
+ process.on("message", (message) => {
151
+ const reply = (answer) => process.send?.(answer);
152
+ if (message?.type === "init") {
153
+ args = message.args;
154
+ const started = fresh ? (spare = thread()).then((ready) => {
155
+ if (ready.error)
156
+ throw new Error(ready.error);
157
+ }) : init(message.args);
158
+ started.then(() => reply({ type: "ready" }), (error) => reply({ type: "ready", error: failure(error) }));
159
+ return;
160
+ }
161
+ if (message?.type === "job") {
162
+ (fresh ? inThread(message) : runJob(message, false)).then(() => reply({ type: "done", id: message.id }), (error) => reply({ type: "done", id: message.id, error: failure(error) }));
163
+ }
164
+ });
165
+ process.send?.({ type: "started" });
166
+ }
@@ -0,0 +1,96 @@
1
+ #!/usr/bin/env node
2
+ // A strong pass over Rust compiled to wasm (strongJobs.mjs): each job that
3
+ // starts the command builds the wasm again, and wasm-bindgen (or wasm-pack
4
+ // build) writes its glue where every other job's tests load it. This stands
5
+ // in for the tool on the jobs' PATH: the tool writes into a fresh directory
6
+ // beside its output directory, and each file is then renamed into place, and
7
+ // only where its bytes changed. A rebuild of the same wasm changes nothing,
8
+ // and a test never reads a file half written. It notes that it ran (`used`
9
+ // beside it), so the driver knows the wasm is built this way.
10
+ // CommonJS, as Node loads a file without an extension.
11
+ const { spawnSync } = require("node:child_process");
12
+ const { accessSync, constants, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } = require("node:fs");
13
+ const { basename, delimiter, dirname, join, resolve } = require("node:path");
14
+
15
+ const here = dirname(process.argv[1]);
16
+ const tool = basename(process.argv[1]);
17
+ const real = (process.env.PATH ?? "")
18
+ .split(delimiter)
19
+ .filter((directory) => directory && resolve(directory) !== here)
20
+ .map((directory) => join(directory, tool))
21
+ .find((candidate) => {
22
+ try {
23
+ accessSync(candidate, constants.X_OK);
24
+ return true;
25
+ }
26
+ catch {
27
+ return false;
28
+ }
29
+ });
30
+ if (!real) {
31
+ console.error(`supercov: no ${tool} on PATH`);
32
+ process.exit(127);
33
+ }
34
+ const args = process.argv.slice(2);
35
+ const passThrough = () => process.exit(spawnSync(real, args, { stdio: "inherit" }).status ?? 1);
36
+
37
+ // The output directory the tool was asked for, and where it is in `args`.
38
+ let output;
39
+ let at = -1;
40
+ for (let index = 0; index < args.length; index += 1) {
41
+ const argument = args[index];
42
+ if (argument === "--out-dir" || (tool === "wasm-pack" && argument === "-d")) {
43
+ output = args[index + 1];
44
+ at = index + 1;
45
+ break;
46
+ }
47
+ if (argument.startsWith("--out-dir=")) {
48
+ output = argument.slice("--out-dir=".length);
49
+ at = index;
50
+ break;
51
+ }
52
+ }
53
+ let base = process.cwd();
54
+ if (tool === "wasm-pack") {
55
+ if (args[0] !== "build")
56
+ passThrough();
57
+ // wasm-pack reads its output directory against the crate's, `pkg`
58
+ // where none is given.
59
+ const crate = args.slice(1).find((argument, index, rest) => !argument.startsWith("-") && !["-d", "--out-dir", "-t", "--target", "--scope", "--mode", "--out-name", "--profile"].includes(rest[index - 1]));
60
+ base = resolve(crate ?? ".");
61
+ output ??= "pkg";
62
+ }
63
+ if (output === undefined)
64
+ passThrough();
65
+ const target = resolve(base, output);
66
+ const fresh = `${target}.supercov-${process.pid}`;
67
+ rmSync(fresh, { recursive: true, force: true });
68
+ const changed = [...args];
69
+ if (at < 0)
70
+ changed.push("--out-dir", fresh);
71
+ else if (changed[at].startsWith("--out-dir="))
72
+ changed[at] = `--out-dir=${fresh}`;
73
+ else
74
+ changed[at] = fresh;
75
+ const ran = spawnSync(real, changed, { stdio: "inherit" });
76
+ if (ran.status === 0) {
77
+ const move = (from, to) => {
78
+ for (const name of readdirSync(from)) {
79
+ const source = join(from, name);
80
+ const destination = join(to, name);
81
+ if (statSync(source).isDirectory()) {
82
+ mkdirSync(destination, { recursive: true });
83
+ move(source, destination);
84
+ continue;
85
+ }
86
+ const same = existsSync(destination) && readFileSync(destination).equals(readFileSync(source));
87
+ if (!same)
88
+ renameSync(source, destination);
89
+ }
90
+ };
91
+ mkdirSync(target, { recursive: true });
92
+ move(fresh, target);
93
+ writeFileSync(join(here, "used"), "");
94
+ }
95
+ rmSync(fresh, { recursive: true, force: true });
96
+ process.exit(ran.status ?? 1);
@@ -12,8 +12,9 @@ import { realpathSync } from "node:fs";
12
12
  import { createRequire } from "node:module";
13
13
  import { dirname, join } from "node:path";
14
14
  import { pathToFileURL } from "node:url";
15
- import { beginBufferedServerEvidence, flushBufferedServerEvidence, takeNodeAssertionPhases, withCoverageCarrier, } from "./runtime.mjs";
15
+ import { activateCoverageScope, beginBufferedServerEvidence, flushBufferedServerEvidence, takeNodeAssertionPhases, withCoverageCarrier, } from "./runtime.mjs";
16
16
  import { runnerExecutionScope, writeRunnerEvidence } from "./runnerEvidence.mjs";
17
+ import { strongJob } from "./strongJob.mjs";
17
18
 
18
19
  // The classes that make subtests in the project's tap.
19
20
  async function subtestClasses() {
@@ -72,6 +73,7 @@ async function subtestClasses() {
72
73
  // Frames stay as libtap writes them.
73
74
  }
74
75
  classes.push(createRequire(import.meta.url)(join(lib, "test.js")));
76
+ topLevel.libtap = true;
75
77
  }
76
78
  catch {
77
79
  // Neither tap's own classes nor libtap's: tap 14 or older.
@@ -122,6 +124,13 @@ function nameFromTheCopy(StackUtils) {
122
124
  };
123
125
  }
124
126
 
127
+ // tap counts a test file as a test of its own: assertions at its top level,
128
+ // outside any subtest, pass or fail it. What runs there is that test's, the
129
+ // file's top level, which tap's own report names after the file, and it is
130
+ // written as a test where the file asserts there (or has no subtest), as the
131
+ // file's module setup otherwise.
132
+ const topLevel = { subtests: 0, points: 0, libtap: false };
133
+
125
134
  export async function adaptTap(testFile) {
126
135
  const evidenceDirectory = process.env.SUPERCOV_EVIDENCE_DIR;
127
136
  if (!evidenceDirectory)
@@ -130,6 +139,16 @@ export async function adaptTap(testFile) {
130
139
  if (typeof Class?.prototype?.sub === "function" && !Class.prototype.sub.supercovTap)
131
140
  patch(Class, testFile, evidenceDirectory);
132
141
  }
142
+ const identity = { runner: "tap", file: testFile, name: "(top level)" };
143
+ const scope = runnerExecutionScope(identity);
144
+ beginBufferedServerEvidence(scope);
145
+ activateCoverageScope(scope);
146
+ process.once("exit", (code) => {
147
+ // libtap passes or fails a subtest's point on its parent too.
148
+ const asserts = topLevel.points > (topLevel.libtap ? topLevel.subtests : 0);
149
+ const written = asserts ? identity : { ...identity, role: "setup" };
150
+ writeRunnerEvidence(written, !asserts || code === 0 ? "passed" : "failed", scope, evidenceDirectory, takeNodeAssertionPhases(scope), flushBufferedServerEvidence(scope));
151
+ });
133
152
  }
134
153
 
135
154
  function patch(TestBase, testFile, evidenceDirectory) {
@@ -152,12 +171,23 @@ function patch(TestBase, testFile, evidenceDirectory) {
152
171
  ...(ordinal ? { registrationOrdinal: ordinal } : {}),
153
172
  };
154
173
  const scope = runnerExecutionScope(identity);
174
+ // A strong pass's job runs its own tests, none after its first
175
+ // failure. A subtest runs with its parent, as it does without
176
+ // Supercov.
177
+ const job = strongJob();
178
+ const atTop = !this.parent;
179
+ if (atTop)
180
+ topLevel.subtests += 1;
181
+ if (job && (job.stopped || (atTop && !job.selects(testFile, scope.testId))))
182
+ extra = { ...extra, skip: true };
155
183
  beginBufferedServerEvidence(scope);
156
184
  let written = false;
157
185
  const finish = (status) => {
158
186
  if (written)
159
187
  return;
160
188
  written = true;
189
+ if (status === "failed")
190
+ job?.fail();
161
191
  writeRunnerEvidence(identity, status, scope, evidenceDirectory, takeNodeAssertionPhases(scope), flushBufferedServerEvidence(scope));
162
192
  };
163
193
  // Both libtap and @tapjs/core announce the subtest they make, before
@@ -187,4 +217,16 @@ function patch(TestBase, testFile, evidenceDirectory) {
187
217
  return result;
188
218
  };
189
219
  TestBase.prototype.sub.supercovTap = true;
220
+ // Every assertion passes or fails through these: those of a file's top
221
+ // level, outside any subtest, are counted.
222
+ for (const name of ["pass", "fail"]) {
223
+ const assertion = TestBase.prototype[name];
224
+ if (typeof assertion !== "function")
225
+ continue;
226
+ TestBase.prototype[name] = function supercovTapAssertion(...args) {
227
+ if (!this.parent)
228
+ topLevel.points += 1;
229
+ return Reflect.apply(assertion, this, args);
230
+ };
231
+ }
190
232
  }
@@ -75,6 +75,8 @@ export function encodeCoverageScope(scope) {
75
75
  k: scope.testKey,
76
76
  a: String(scope.retry),
77
77
  i: scope.attemptId,
78
+ // A strong pass's attempt names its mutant (`file#index`, `-` for none).
79
+ ...(scope.mutant ? { m: scope.mutant } : {}),
78
80
  }).toString();
79
81
  }
80
82
  export function decodeCoverageScope(encoded) {
@@ -88,7 +90,9 @@ export function decodeCoverageScope(encoded) {
88
90
  const testKey = values.get("k");
89
91
  const attemptId = values.get("i");
90
92
  const retry = Number(values.get("a"));
93
+ const mutant = values.get("m");
91
94
  if (values.get("v") !== "1" ||
95
+ (mutant !== null && !/^(?:-|.+#\d+)$/.test(mutant)) ||
92
96
  !nonEmpty(runId) ||
93
97
  !nonEmpty(workerId) ||
94
98
  !nonEmpty(testId) ||
@@ -107,6 +111,7 @@ export function decodeCoverageScope(encoded) {
107
111
  testKey,
108
112
  retry,
109
113
  attemptId,
114
+ ...(mutant !== null ? { mutant } : {}),
110
115
  };
111
116
  }
112
117
  catch {
@@ -3,11 +3,18 @@ import { relative, resolve, sep } from "node:path";
3
3
  import { afterAll, afterEach, beforeEach } from "vitest";
4
4
  import { coverageSnapshot as localCoverageSnapshot, coverageSnapshotColumns as localCoverageSnapshotColumns, activateCoverageScope as localActivateCoverageScope, enableRuntimeSnapshotEvidence as localEnableRuntimeSnapshotEvidence, resetCoverage as localResetCoverage, takeNodeAssertionPhases as localTakeNodeAssertionPhases, } from "./runtime.mjs";
5
5
  import { inferTestProvenance, testTags } from "./provenance.mjs";
6
+ import { strongJob } from "./strongJob.mjs";
6
7
  import { appendEvidenceRecord, installCompileCache, saveCompileCache } from "./atomic.mjs";
7
8
  const evidenceDirectory = process.env["SUPERCOV_EVIDENCE_DIR"];
8
9
  const emittedSetupFiles = new Set();
9
10
  const attempts = new Map();
10
11
  const activeScopes = new Map();
12
+ // When each test began, for the time it took: the strong pass orders a
13
+ // mutant's tests by it and sets their time limits from it.
14
+ const startedAt = new Map();
15
+ // The clock as it is now: a test that fakes timers fakes `performance.now`
16
+ // too, and a duration read from it can come out negative.
17
+ const realNow = performance.now.bind(performance);
11
18
  const runtimeGlobal = globalThis;
12
19
  const runtime = runtimeGlobal.__SUPERCOV_DIRECT_RUNTIME__ ?? {
13
20
  activateCoverageScope: localActivateCoverageScope,
@@ -48,8 +55,62 @@ function writeEvidence(payload) {
48
55
  return;
49
56
  appendEvidenceRecord(resolve(process.cwd(), evidenceDirectory), "vitest-worker", payload);
50
57
  }
58
+ // Work a test file did while none of its tests ran: a `beforeAll` of a
59
+ // later `describe`, an `afterAll`, async work a test left going. It is the
60
+ // file's, as its module setup is, and no test's: written as one more setup
61
+ // record of the file. A test's afterEach clears what it ran, so what is
62
+ // there at the next test's start, or at the file's end, is that work.
63
+ const fileWork = new Map();
64
+ function writeFileWork(file, testFile, title) {
65
+ const snapshot = runtime.coverageSnapshotColumns();
66
+ if (!snapshot.hits.length && !snapshot.decisions.length)
67
+ return;
68
+ const nth = (fileWork.get(file.id) ?? 0) + 1;
69
+ fileWork.set(file.id, nth);
70
+ writeEvidence({
71
+ testId: `vitest:${file.id}:between:${nth}`,
72
+ test: `${testFile} > ${title}`,
73
+ testFile,
74
+ title,
75
+ retry: 0,
76
+ status: "passed",
77
+ provenance: inferTestProvenance({
78
+ runner: "vitest",
79
+ file: testFile,
80
+ project: file.projectName,
81
+ explicitKind: process.env["SUPERCOV_TEST_KIND"],
82
+ }),
83
+ role: "setup",
84
+ runtime: [snapshot],
85
+ browser: [],
86
+ server: [],
87
+ });
88
+ }
89
+ // The file this worker is running: hooks take no argument, since Vitest 3
90
+ // and later read a hook's first parameter as a fixture context.
91
+ let currentFile;
92
+ afterAll(() => {
93
+ const file = currentFile;
94
+ if (!file?.filepath)
95
+ return;
96
+ const testFile = relative(process.cwd(), file.filepath).split(sep).join("/");
97
+ if (emittedSetupFiles.has(testFile))
98
+ writeFileWork(file, testFile, "after the tests");
99
+ });
100
+ // The test a hook runs for: Vitest before 0.30 gives it as `meta`, and
101
+ // gives an afterEach hook no context of its test where its beforeEach had one.
102
+ let currentTask;
51
103
  beforeEach((context) => {
52
- const task = context.task;
104
+ const task = context.task ?? context.meta;
105
+ currentTask = task;
106
+ currentFile = task.file;
107
+ // A strong pass's job (strongJobs.mjs, where the run also had browser
108
+ // tests): its own tests, none after its first failure.
109
+ const job = strongJob();
110
+ if (job && (job.stopped || !job.selects(task.file.filepath, `vitest:${task.id}`))) {
111
+ context.skip();
112
+ return;
113
+ }
53
114
  const testFile = relative(process.cwd(), task.file.filepath)
54
115
  .split(sep)
55
116
  .join("/");
@@ -78,6 +139,9 @@ beforeEach((context) => {
78
139
  });
79
140
  }
80
141
  }
142
+ else {
143
+ writeFileWork(task.file, testFile, "between tests");
144
+ }
81
145
  const testId = `vitest:${task.id}`;
82
146
  const retry = attempts.get(testId) ?? 0;
83
147
  attempts.set(testId, retry + 1);
@@ -92,16 +156,21 @@ beforeEach((context) => {
92
156
  attemptId: `${testKey}-${retry}`,
93
157
  };
94
158
  activeScopes.set(task.id, scope);
159
+ startedAt.set(task.id, realNow());
95
160
  runtime.activateCoverageScope(scope);
96
161
  runtime.resetCoverage(testId);
97
162
  });
98
163
  afterEach((context) => {
99
- const task = context.task;
164
+ const task = context?.task ?? context?.meta ?? currentTask;
165
+ if (task.result?.state === "fail")
166
+ strongJob()?.fail();
100
167
  const testFile = relative(process.cwd(), task.file.filepath)
101
168
  .split(sep)
102
169
  .join("/");
103
170
  const scope = activeScopes.get(task.id);
104
171
  const retry = scope?.retry ?? task.result?.retryCount ?? 0;
172
+ const began = startedAt.get(task.id);
173
+ startedAt.delete(task.id);
105
174
  const payload = {
106
175
  testId: scope?.testId ?? `vitest:${task.id}`,
107
176
  ...(scope ? { scope } : {}),
@@ -110,6 +179,7 @@ afterEach((context) => {
110
179
  title: task.name,
111
180
  retry,
112
181
  status: attemptStatus(task.result?.state),
182
+ ...(began === undefined ? {} : { durationMs: Math.max(0, Math.round(realNow() - began)) }),
113
183
  provenance: inferTestProvenance({
114
184
  runner: "vitest",
115
185
  file: testFile,
@@ -128,4 +198,6 @@ afterEach((context) => {
128
198
  writeEvidence(payload);
129
199
  activeScopes.delete(task.id);
130
200
  runtime.activateCoverageScope();
201
+ // What runs from here to the next test is the file's (writeFileWork).
202
+ runtime.resetCoverage(`vitest:${task.file.id}:between`);
131
203
  });
@@ -8,13 +8,37 @@
8
8
  // write a file -- it hands to node over Vitest's browser command channel, so
9
9
  // that contract has one implementation.
10
10
  import { afterEach, beforeEach } from "vitest";
11
- import { coverageSnapshot, activateCoverageScope, enableRuntimeSnapshotEvidence, resetCoverage, takeNodeAssertionPhases, } from "./runtime.mjs";
11
+ import { coverageSnapshot, activateCoverageScope, enableRuntimeSnapshotEvidence, resetCoverage, setActiveMutant, takeNodeAssertionPhases, } from "./runtime.mjs";
12
12
  // Vitest exposes the command channel at "vitest/browser" from v4 and at
13
13
  // "@vitest/browser/context" before that. Both are tried so a project is not
14
14
  // forced onto one Vitest line to be measured.
15
15
  const browserContext = await import("vitest/browser").catch(() =>
16
16
  import("@vitest/browser/context"));
17
17
  const { commands } = browserContext;
18
+ // A strong pass's job (strongJob.mjs): its mutant is switched on here,
19
+ // before the test file's imports, and only its tests run, none after its
20
+ // first failure. The browser has no environment: node hands both over.
21
+ const strong = typeof commands.__supercovStrongJob === "function" ? await commands.__supercovStrongJob() : null;
22
+ let strongFailed = false;
23
+ if (strong) {
24
+ const at = strong.mutant.lastIndexOf("#");
25
+ if (at > 0)
26
+ setActiveMutant(strong.mutant.slice(0, at), Number(strong.mutant.slice(at + 1)));
27
+ // Past the hit limit the switch throws where it runs; node records it,
28
+ // as the browser can write nothing.
29
+ const state = globalThis[Symbol.for("supercov.strongMutation")];
30
+ if (state)
31
+ state.onTimeout = (file, index) => {
32
+ commands.__supercovMutantTimeout(`${file}#${index}`).catch(() => { });
33
+ };
34
+ }
35
+ function strongSelects(task) {
36
+ const files = strong.job.files ?? {};
37
+ if (!(strong.file in files))
38
+ return !(strong.job.known ?? []).includes(strong.file);
39
+ const tests = files[strong.file];
40
+ return tests === null || tests.includes(`vitest:${task.id}`);
41
+ }
18
42
  const attempts = new Map();
19
43
  const activeScopes = new Map();
20
44
  const emittedSetupFiles = new Set();
@@ -63,6 +87,10 @@ async function sendEvidence(payload, suffix) {
63
87
  }
64
88
  beforeEach(async (context) => {
65
89
  const task = context.task;
90
+ if (strong && ((strong.job.bail && strongFailed) || !strongSelects(task))) {
91
+ context.skip();
92
+ return;
93
+ }
66
94
  // Module imports and shared setup execute before the first test. Save
67
95
  // them before resetCoverage clears the snapshot, with a setup identity
68
96
  // rather than crediting that execution to the first test.
@@ -104,6 +132,8 @@ beforeEach(async (context) => {
104
132
  afterEach(async (context) => {
105
133
  const task = context.task;
106
134
  const scope = activeScopes.get(task.id);
135
+ if (strong && task.result?.state === "fail")
136
+ strongFailed = true;
107
137
  const retry = scope?.retry ?? task.result?.retryCount ?? 0;
108
138
  // Node relativises the test file Vitest reports and infers provenance, so
109
139
  // both environments describe a test the same way and neither trusts the
@@ -115,7 +145,9 @@ afterEach(async (context) => {
115
145
  projectName: task.file?.projectName,
116
146
  title: task.name,
117
147
  retry,
118
- status: attemptStatus(task.result?.state),
148
+ // A test still running in its afterEach has passed so far; a job
149
+ // reads its outcome from this record.
150
+ status: strong && task.result?.state === "run" ? "passed" : attemptStatus(task.result?.state),
119
151
  ...(scope ? { phases: takeNodeAssertionPhases(scope) } : {}),
120
152
  // Browser-mode evidence is a runtime snapshot like node's: the code
121
153
  // under test runs in the same realm as the probes.