supercov 4.29.19 → 4.30.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.
@@ -0,0 +1,212 @@
1
+ // A resident Vitest for a strong pass's Browser Mode jobs (strongJobs.mjs):
2
+ // one process that keeps Vitest, its Vite server and its browser running and
3
+ // runs one job after another, where each job used to start the command, and
4
+ // with it Vitest, Vite and Chromium, again.
5
+ //
6
+ // What a fresh command gave each job, this keeps:
7
+ //
8
+ // - A fresh page and a fresh browser context for every job. Vitest reuses
9
+ // its browser sessions from one run to the next, and with them the
10
+ // context's cookies, storage, permissions and routes; before each job the
11
+ // last job's pages and contexts are closed and Vitest's sessions for them
12
+ // forgotten, so the run opens new ones. After the run, each context that
13
+ // served it must be one no earlier job used, or the job's outcome is
14
+ // thrown away and it runs as a command of its own.
15
+ // - The mutant switched on in the page before the test file loads, through
16
+ // Supercov's browser command, which reads the job from the environment
17
+ // this process sets for each job.
18
+ // - Nothing of the project's code loaded in this process before a job: the
19
+ // job's mutant is on in every process of a command from its start, and a
20
+ // module this process loaded earlier ran its top level without it. A job
21
+ // starts here only while no instrumented module has loaded in node.
22
+ //
23
+ // It refuses (and the driver starts the command for the job, as before)
24
+ // where it cannot keep that: a Vitest without the runner API it drives
25
+ // (before 4), a browser provider other than Playwright's or a persistent
26
+ // context, a global setup, browser commands of the project's own, a Vite
27
+ // plugin of the project's that serves requests itself (a mock API keeps what
28
+ // one job left for the next), or a job file that a project without a
29
+ // browser runs too.
30
+ //
31
+ // The driver forks it in the project's copy and sends
32
+ // { type: "init", args: [<the command's arguments to vitest>] }
33
+ // { type: "job", id, file: <absolute test file>, mutant: { file, index } | null, environment: {...} }
34
+ // and it answers { type: "ready", error? } and { type: "done", id, error?, fallback?, tainted? }:
35
+ // `fallback` that the job did not run here (or ran where its outcome cannot
36
+ // stand) and runs as a command of its own; `tainted` that this process can
37
+ // run no further job.
38
+ import { existsSync } from "node:fs";
39
+ import { createRequire } from "node:module";
40
+ import { join, relative, resolve, sep } from "node:path";
41
+ import { pathToFileURL } from "node:url";
42
+
43
+ globalThis.__SUPERCOV_DIRECT_RUNTIME__ ??= await import("./runtime.mjs");
44
+ process.__SUPERCOV_DIRECT_RUNTIME__ ??= globalThis.__SUPERCOV_DIRECT_RUNTIME__;
45
+ const runtime = globalThis.__SUPERCOV_DIRECT_RUNTIME__;
46
+ const root = process.cwd();
47
+
48
+ // Vite plugins known to keep no state a request can change: Vite's own,
49
+ // Vitest's, and the frameworks' compilers.
50
+ const STATELESS_PLUGIN = /^(?:vite:|vitest|@vitest\/|@vitejs\/|vite-plugin-svelte|vite-plugin-solid|solid|svelte|vue|react|preact|supercov)/;
51
+
52
+ class Refusal extends Error {
53
+ }
54
+
55
+ let vitest;
56
+ // Every browser context a job ran in.
57
+ const used = new WeakSet();
58
+
59
+ // The modules of the project's code this process loaded: each instrumented
60
+ // module takes its slot as it loads.
61
+ function loadedSources() {
62
+ return globalThis[Symbol.for("supercov.strongMutation")]?.slots?.size ?? 0;
63
+ }
64
+
65
+ function browserProjects() {
66
+ return vitest.projects.filter((project) => project.config?.browser?.enabled);
67
+ }
68
+
69
+ // The browser provider's sessions: what Vitest keeps for each, where this
70
+ // Vitest keeps it as this process knows how to reset.
71
+ function sessionsOf(project) {
72
+ const provider = project.browser?.provider;
73
+ const orchestrators = project.browser?.state?.orchestrators;
74
+ const ready = project._browserReadySessions;
75
+ const ids = vitest._browserSessions?.sessionIds;
76
+ if (provider?.name !== "playwright" || !(provider.pages instanceof Map) || !(provider.contexts instanceof Map) || provider.persistentContext)
77
+ throw new Refusal("its browser provider is not Playwright's with a context per session");
78
+ if (!(orchestrators instanceof Map) || !(ready instanceof Set) || !(ids instanceof Set))
79
+ throw new Refusal("this Vitest keeps its browser sessions where the pass cannot reset them");
80
+ return { provider, orchestrators, ready, ids };
81
+ }
82
+
83
+ async function init(args) {
84
+ process.env.SUPERCOV_INSIDE_VITEST = "1";
85
+ process.env.SUPERCOV_STRONG_PLAN = "";
86
+ process.env.SUPERCOV_ACTIVE_MUTANT = "-";
87
+ const generated = process.env.SUPERCOV_GENERATED_VITEST_CONFIG;
88
+ if (!generated || !existsSync(generated))
89
+ throw new Refusal("no generated Vitest configuration");
90
+ const fromRoot = createRequire(join(root, "package.json"));
91
+ const node = await import(pathToFileURL(fromRoot.resolve("vitest/node")).href);
92
+ if (typeof node.parseCLI !== "function" || typeof node.createVitest !== "function")
93
+ throw new Refusal("this Vitest has no runner API");
94
+ const { options } = node.parseCLI(["vitest", ...args]);
95
+ // The project's own configuration, read by Supercov's, as runnerEntry.mjs
96
+ // hands it to a command.
97
+ if (options.config && resolve(root, String(options.config)) !== resolve(generated))
98
+ process.env.SUPERCOV_ORIGINAL_VITEST_CONFIG = resolve(root, String(options.config));
99
+ delete options.config;
100
+ vitest = await node.createVitest("test", { ...options, config: generated, watch: false, run: true });
101
+ if (typeof vitest.runTestSpecifications !== "function" || typeof vitest.globTestSpecifications !== "function")
102
+ throw new Refusal("this Vitest cannot run a file it is given (before 3)");
103
+ // Reporters' onInit (Supercov's sets each project's setup file).
104
+ await (typeof vitest.standalone === "function" ? vitest.standalone() : vitest.init());
105
+ if (vitest.config.globalSetup?.length || vitest.projects.some((project) => project.config.globalSetup?.length))
106
+ throw new Refusal("a global setup runs once for every job here");
107
+ for (const project of browserProjects()) {
108
+ const commands = Object.keys(project.config.browser?.commands ?? {}).filter((name) => !name.startsWith("__supercov"));
109
+ if (commands.length)
110
+ throw new Refusal(`the project's own browser commands (${commands.join(", ")}) may keep state between jobs`);
111
+ const serving = (project.vite?.config?.plugins ?? []).filter((plugin) => plugin?.configureServer && !STATELESS_PLUGIN.test(String(plugin.name ?? "")));
112
+ if (serving.length)
113
+ throw new Refusal(`a Vite plugin serves requests itself (${serving.map((plugin) => plugin.name).join(", ")})`);
114
+ }
115
+ if (!browserProjects().length)
116
+ throw new Refusal("no project runs in a browser");
117
+ }
118
+
119
+ // Closes the last job's pages and contexts, and forgets Vitest's sessions
120
+ // for them: the next run opens new ones.
121
+ async function freshSessions() {
122
+ for (const project of browserProjects()) {
123
+ if (!project.browser)
124
+ continue;
125
+ const { provider, orchestrators, ready, ids } = sessionsOf(project);
126
+ const sessions = new Set([...provider.pages.keys(), ...provider.contexts.keys(), ...orchestrators.keys(), ...ready]);
127
+ for (const sessionId of sessions) {
128
+ const page = provider.pages.get(sessionId);
129
+ const context = provider.contexts.get(sessionId);
130
+ provider.pages.delete(sessionId);
131
+ provider.contexts.delete(sessionId);
132
+ await page?.close().catch(() => { });
133
+ await context?.close().catch(() => { });
134
+ ready.delete(sessionId);
135
+ ids.delete(sessionId);
136
+ }
137
+ // The orchestrator's socket closes with its page, and Vitest forgets it.
138
+ const until = Date.now() + 10_000;
139
+ while (orchestrators.size > 0) {
140
+ if (Date.now() > until)
141
+ throw new Refusal("a browser session did not close");
142
+ await new Promise((done) => setTimeout(done, 10));
143
+ }
144
+ }
145
+ }
146
+
147
+ // Each context that served the run, never one an earlier job used.
148
+ function contextsWereFresh() {
149
+ let fresh = true;
150
+ for (const project of browserProjects()) {
151
+ if (!project.browser)
152
+ continue;
153
+ const { provider, orchestrators } = sessionsOf(project);
154
+ for (const sessionId of orchestrators.keys()) {
155
+ const context = provider.contexts.get(sessionId);
156
+ if (!context || used.has(context))
157
+ fresh = false;
158
+ else
159
+ used.add(context);
160
+ }
161
+ }
162
+ return fresh;
163
+ }
164
+
165
+ async function runJob({ file, mutant, environment }) {
166
+ // A module of the project's code loaded here ran its top level without
167
+ // this job's mutant.
168
+ if (loadedSources() > 0)
169
+ return { fallback: "the project's code loaded in Vitest's process", tainted: true };
170
+ // The file as the command names it, from the project's root.
171
+ const specifications = await vitest.globTestSpecifications([relative(root, file).split(sep).join("/")]);
172
+ if (!specifications.length)
173
+ return { fallback: "Vitest found no such test file" };
174
+ if (specifications.some((specification) => !specification.project.config?.browser?.enabled))
175
+ return { fallback: "a project without a browser runs the file too" };
176
+ await freshSessions();
177
+ Object.assign(process.env, environment, { SUPERCOV_ACTIVE_MUTANT: mutant ? `${mutant.file}#${mutant.index}` : "-" });
178
+ if (mutant)
179
+ runtime.setActiveMutant(mutant.file, mutant.index);
180
+ else
181
+ runtime.clearActiveMutant();
182
+ try {
183
+ await vitest.runTestSpecifications(specifications, false);
184
+ }
185
+ finally {
186
+ runtime.clearActiveMutant();
187
+ }
188
+ if (!contextsWereFresh())
189
+ return { fallback: "a browser context served two jobs", tainted: true };
190
+ if (loadedSources() > 0)
191
+ // This job's own loads ran with its mutant on, as a command's would;
192
+ // the next job's would not.
193
+ return { tainted: true };
194
+ return {};
195
+ }
196
+
197
+ let queue = Promise.resolve();
198
+ process.on("message", (message) => {
199
+ const reply = (answer) => process.send?.(answer);
200
+ if (message?.type === "init") {
201
+ init(message.args ?? []).then(() => reply({ type: "ready" }), (error) => {
202
+ // A Vitest this process cannot drive is the command's to run,
203
+ // job by job, as before.
204
+ reply({ type: "ready", error: String(error instanceof Refusal ? error.message : error?.stack ?? error) });
205
+ });
206
+ return;
207
+ }
208
+ if (message?.type === "job") {
209
+ queue = queue.then(() => runJob(message)).then((outcome) => reply({ type: "done", id: message.id, ...outcome }), (error) => reply({ type: "done", id: message.id, fallback: String(error?.stack ?? error), tainted: true }));
210
+ }
211
+ });
212
+ process.send?.({ type: "started" });
@@ -43,6 +43,10 @@ const PROFILED_STAGES = 50;
43
43
  // their ends).
44
44
  const CONTINUOUS_LOOK_MS = 50;
45
45
  // How much each of a mutant's batches of later files grows over the one before.
46
+ // How many of a test file's runs against mutants of one source file its
47
+ // kills of every mutant count for, where it ran few of that file's: the
48
+ // file's chance to kill a mutant there starts at its chance anywhere.
49
+ const PAIR_PRIOR = 2;
46
50
  const BATCH_GROWTH = Math.max(1, Number(process.env["SUPERCOV_STRONG_BATCH_GROWTH"]) || 4);
47
51
  // A continuous run's slots beyond each file's own, and the bytes of test
48
52
  // files they may name: Vitest reads every slot's file at once as the run
@@ -1230,13 +1234,33 @@ async function drive(vitest, runFiles, specs, plan, resultsPath) {
1230
1234
  }
1231
1235
  // How often each test file killed the mutants it ran, learned as the
1232
1236
  // pass goes: a file's chance to kill over its cost (its tests' measured
1233
- // time and a copy's start) orders a mutant's later files.
1237
+ // time and a copy's start) orders a mutant's files. The chance is the
1238
+ // file's kills of mutants in the same source file as this one where it
1239
+ // ran some (a file that tests one module kills its mutants, not
1240
+ // another's), drawn toward the file's kills of every mutant while it
1241
+ // ran few of them.
1234
1242
  const fileRuns = new Map();
1235
1243
  const fileKills = new Map();
1244
+ const pairRuns = new Map();
1245
+ const pairKills = new Map();
1246
+ const pairOf = (job, group) => `${job.mutant.file}\0${group.file}`;
1247
+ const noteRun = (job, group) => {
1248
+ fileRuns.set(group.file, (fileRuns.get(group.file) ?? 0) + 1);
1249
+ pairRuns.set(pairOf(job, group), (pairRuns.get(pairOf(job, group)) ?? 0) + 1);
1250
+ };
1251
+ const noteKill = (job, group) => {
1252
+ fileKills.set(group.file, (fileKills.get(group.file) ?? 0) + 1);
1253
+ pairKills.set(pairOf(job, group), (pairKills.get(pairOf(job, group)) ?? 0) + 1);
1254
+ };
1255
+ const killChance = (job, group) => {
1256
+ const overall = ((fileKills.get(group.file) ?? 0) + 1) / ((fileRuns.get(group.file) ?? 0) + 2);
1257
+ const pair = pairOf(job, group);
1258
+ return ((pairKills.get(pair) ?? 0) + PAIR_PRIOR * overall) / ((pairRuns.get(pair) ?? 0) + PAIR_PRIOR);
1259
+ };
1236
1260
  const startCost = () => profile.copies ? profile.startMs / profile.copies : 300;
1237
- const killScore = (group) => ((fileKills.get(group.file) ?? 0) + 1) / ((fileRuns.get(group.file) ?? 0) + 2) / (estimateOf(group) + startCost());
1261
+ const killScore = (job, group) => killChance(job, group) / (estimateOf(group) + startCost());
1238
1262
  const nextBatch = (job) => {
1239
- job.later.sort((a, b) => killScore(b) - killScore(a));
1263
+ job.later.sort((a, b) => killScore(job, b) - killScore(job, a));
1240
1264
  const batch = job.later.splice(0, job.batch);
1241
1265
  job.batch *= BATCH_GROWTH;
1242
1266
  return batch;
@@ -1383,9 +1407,9 @@ async function drive(vitest, runFiles, specs, plan, resultsPath) {
1383
1407
  }
1384
1408
  job.ran += outcome.tests.length;
1385
1409
  const chosen = claim.tests;
1386
- fileRuns.set(group.file, (fileRuns.get(group.file) ?? 0) + 1);
1410
+ noteRun(job, group);
1387
1411
  const kill = (evidence, verdict) => {
1388
- fileKills.set(group.file, (fileKills.get(group.file) ?? 0) + 1);
1412
+ noteKill(job, group);
1389
1413
  if (certain(group, chosen, evidence))
1390
1414
  finish(job, verdict);
1391
1415
  else if (evidence.test && !group.whole) {
@@ -1609,7 +1633,7 @@ async function drive(vitest, runFiles, specs, plan, resultsPath) {
1609
1633
  const estimateC = (group) => shapeOf(group) === "whole"
1610
1634
  ? overheadOf(group.file) + (testsOf.get(group.file) ?? []).reduce((sum, id) => sum + testMsOf(id), 0)
1611
1635
  : estimateOf(group);
1612
- const scoreC = (group) => ((fileKills.get(group.file) ?? 0) + 1) / ((fileRuns.get(group.file) ?? 0) + 2) / (estimateC(group) + startCost());
1636
+ const scoreC = (job, group) => killChance(job, group) / (estimateC(group) + startCost());
1613
1637
  const remainingOf = (job) => job.chain.reduce((sum, group) => sum + estimateC(group) + startCost(), 0);
1614
1638
  // A mutant's copies running, and its kills waiting on a confirmation.
1615
1639
  for (const job of pending) {
@@ -1643,7 +1667,7 @@ async function drive(vitest, runFiles, specs, plan, resultsPath) {
1643
1667
  for (const group of job.chain) {
1644
1668
  if (!baselineReady(group) || unusable(group))
1645
1669
  continue;
1646
- if (!best || scoreC(group) > scoreC(best))
1670
+ if (!best || scoreC(job, group) > scoreC(job, best))
1647
1671
  best = group;
1648
1672
  }
1649
1673
  return best;
@@ -1798,7 +1822,7 @@ async function drive(vitest, runFiles, specs, plan, resultsPath) {
1798
1822
  };
1799
1823
  // What a copy's end says.
1800
1824
  const kill = (job, group, claim, outcome, evidence, verdict) => {
1801
- fileKills.set(group.file, (fileKills.get(group.file) ?? 0) + 1);
1825
+ noteKill(job, group);
1802
1826
  const shape = claim.wholeFile ? "whole" : "union";
1803
1827
  const entry = baseOf(group.file)[shape];
1804
1828
  let sure;
@@ -1850,7 +1874,7 @@ async function drive(vitest, runFiles, specs, plan, resultsPath) {
1850
1874
  return;
1851
1875
  }
1852
1876
  job.ran += outcome.tests.length;
1853
- fileRuns.set(group.file, (fileRuns.get(group.file) ?? 0) + 1);
1877
+ noteRun(job, group);
1854
1878
  const entry = baseOf(group.file)[claim.wholeFile ? "whole" : "union"];
1855
1879
  const failed = outcome.tests.find((test) => test.failed && !entry.failed?.has(test.test));
1856
1880
  const outside = entry.outside ? undefined : outcome.outside[0];