supercov 4.25.0 → 4.27.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/README.md CHANGED
@@ -412,3 +412,4 @@ Ask questions, share what you measured, and talk to the people building Supercov
412
412
  - [@maik-intellicoach](https://github.com/maik-intellicoach)
413
413
  - [@untitaker](https://github.com/untitaker)
414
414
  - [@artile](https://github.com/artile)
415
+ - [@Fidasek009](https://github.com/Fidasek009)
@@ -0,0 +1,26 @@
1
+ // Yarn 1 runs `yarn supercov --exact-attribution -- npm test` as `supercov
2
+ // npm test`: it takes the options before `--` for its own and drops the
3
+ // `--`. The binary would measure without the option and never know. Yarn
4
+ // keeps what was typed in `npm_config_argv`, and it is used when it is this
5
+ // executable's command line: one Yarn started for `supercov`, of which what
6
+ // arrived is the words in order with some taken out. A variable inherited
7
+ // from an outer run names other words and is left alone. (A `--` lost on its
8
+ // own the binary recovers itself: it reads a first word that names a
9
+ // program as the test command.)
10
+ export function argumentsAsTyped(received, environment) {
11
+ if (!/^yarn\/1\./.test(environment.npm_config_user_agent ?? "")) return received;
12
+ let original;
13
+ try {
14
+ original = JSON.parse(environment.npm_config_argv ?? "").original;
15
+ } catch {
16
+ return received;
17
+ }
18
+ if (!Array.isArray(original) || !original.every((word) => typeof word === "string"))
19
+ return received;
20
+ const start = original[0] === "run" || original[0] === "exec" ? 1 : 0;
21
+ if (original[start] !== "supercov") return received;
22
+ const typed = original.slice(start + 1);
23
+ let matched = 0;
24
+ for (const word of typed) if (matched < received.length && word === received[matched]) matched += 1;
25
+ return matched === received.length && typed.length > received.length ? typed : received;
26
+ }
package/bin/supercov.js CHANGED
@@ -3,6 +3,7 @@
3
3
  import { spawn } from "node:child_process";
4
4
  import { dirname } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
+ import { argumentsAsTyped } from "./arguments.js";
6
7
  import { resolveNativeBinary } from "./native.js";
7
8
 
8
9
  let rustBinary;
@@ -14,7 +15,7 @@ try {
14
15
  }
15
16
  const child = spawn(
16
17
  rustBinary,
17
- process.argv.slice(2),
18
+ argumentsAsTyped(process.argv.slice(2), process.env),
18
19
  {
19
20
  stdio: "inherit",
20
21
  env: {
package/docs/cli.md CHANGED
@@ -122,6 +122,15 @@ npx supercov -- cargo nextest run
122
122
  Use the complete command you rely on before merging or deploying. A coverage run
123
123
  preserves the wrapped command's exit status, so it can remain a CI gate.
124
124
 
125
+ Some launchers drop the `--` before Supercov sees it: Bun when it runs the
126
+ script (`[run] bun = true`, `bun --bun run`, `bun run supercov`), Yarn 1's
127
+ `yarn supercov -- ...`, and PowerShell on its way into a package manager's
128
+ `.ps1` shim. A first word that is no Supercov command but a program on `PATH`,
129
+ or a path to one, is then still measured as the test command, and Yarn 1's
130
+ `--exact-attribution` is restored from what Yarn recorded. Under Yarn 1 in
131
+ PowerShell, a `--` of the test command's own is lost before Supercov runs:
132
+ put that command in a package script.
133
+
125
134
  A script that queries the run it just recorded can have Supercov write the
126
135
  run's id to a file. `latest` is the newest run, which is another one when two
127
136
  commands record runs side by side:
@@ -838,6 +847,13 @@ own:
838
847
  - run: npx supercov merge
839
848
  ```
840
849
 
850
+ Every machine must install the same dependencies. With a lockfile committed,
851
+ install it as it is in each job (`npm ci`, `pnpm install --frozen-lockfile`,
852
+ `yarn install --immutable`, `bun install --frozen-lockfile`). A repository
853
+ without one resolves its dependencies anew in each job, and `merge` leaves
854
+ every run out as `the dependencies have changed`: resolve the lockfile once in
855
+ a first job, pass it to the others as an artifact, and `npm ci` it there.
856
+
841
857
  `assertions assess` assesses a merged run across every suite merged into it,
842
858
  reusing the answers saved when its parts were assessed. `tests affected` of a
843
859
  merged run is answered from the runs it was merged from, which hold the record
@@ -81,6 +81,9 @@ npx supercov -- sh -c "npm run build && npm test"
81
81
  ```
82
82
 
83
83
  A `pretest` script, or a Playwright `webServer` that builds, does the same.
84
+ When this checkout holds build output the copy starts without, and the command
85
+ does not run the `build` script, Supercov says so before the suite runs, so a
86
+ long suite can be stopped and started again with the build in its command.
84
87
  When a run fails, it names the tests that failed. When none did and the
85
88
  project has a `build` script the command does not reach, it says the build
86
89
  output may be what is missing. `SUPERCOV_KEEP_WORKSPACE=1` leaves the instrumented copy
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "supercov",
3
- "version": "4.25.0",
3
+ "version": "4.27.0",
4
4
  "description": "Coverage, security and code quality for coding agents",
5
5
  "keywords": [
6
6
  "coverage",
@@ -82,7 +82,7 @@
82
82
  "eval:skill": "claude plugin eval plugins/supercov --scaffold --trust-plugin --no-publish --model claude-sonnet-5 --judge-model claude-haiku-4-5 --threshold 0.66 --tag behavior trigger --allow-tools Bash Edit Write --max-cost-usd 15",
83
83
  "eval:skill-triggers": "claude plugin eval plugins/supercov --scaffold --trust-plugin --no-publish --model claude-sonnet-5 --judge-model claude-haiku-4-5 --threshold 0.66 --tag trigger --ablation none --max-cost-usd 5",
84
84
  "test:engine": "cargo fmt --all -- --check && cargo clippy --workspace --all-targets -- -D warnings && cargo test --workspace && npm run test:runtime && npm run test:rust-assets && npm run test:engine-integrations",
85
- "test:engine-integrations": "cargo build -p supercov && node scripts/html-report-integration.mjs && node scripts/rust-process-supervision.mjs && node scripts/rust-direct-node-integration.mjs && node scripts/rust-public-run-integration.mjs && node scripts/rust-embedded-runtime-integration.mjs && node scripts/rust-direct-vitest-integration.mjs && node scripts/rust-nested-vitest-integration.mjs && node scripts/rust-direct-jest-integration.mjs && node scripts/mocha-failure-output.mjs && node scripts/failure-output.mjs node ava tap && node scripts/side-by-side.mjs node && node scripts/merge-across.mjs && node scripts/import-line-evidence.mjs && node scripts/mock-reach.mjs && node scripts/rust-direct-playwright-integration.mjs && node scripts/rust-custom-browser-playwright-integration.mjs && node scripts/cross-origin-requests.mjs && node scripts/leaving-page.mjs && node scripts/shared-page.mjs && node scripts/context-headers.mjs && node scripts/context-cookies.mjs && node scripts/hidden-request-emit.mjs && node scripts/js-syntax-zoo.mjs && node scripts/ruby-syntax-zoo.mjs && node scripts/rust-syntax-zoo.mjs && node scripts/python-syntax-zoo.mjs && node scripts/go-syntax-zoo.mjs && node scripts/java-syntax-zoo.mjs && node scripts/background-by-time.mjs && node scripts/python-server-playwright.mjs && node scripts/ruby-server-playwright.mjs && node scripts/go-server-playwright.mjs && node scripts/jvm-server-playwright.mjs && node scripts/docker-server-playwright.mjs && node scripts/docker-clients-playwright.mjs && node scripts/docker-exec-playwright.mjs && node scripts/rust-classic-browser-integration.mjs && node scripts/exec-handover.mjs && node scripts/rust-region-container.mjs && node scripts/rust-top-packages-integration.mjs && node scripts/rust-generic-esbuild-integration.mjs && node scripts/rust-generic-tsc-integration.mjs && node scripts/rust-generic-build-matrix.mjs && node scripts/rust-vite-playwright-integration.mjs && node scripts/workspace-crash-integration.mjs",
85
+ "test:engine-integrations": "cargo build -p supercov && node scripts/html-report-integration.mjs && node scripts/rust-process-supervision.mjs && node scripts/rust-direct-node-integration.mjs && node scripts/rust-public-run-integration.mjs && node scripts/rust-embedded-runtime-integration.mjs && node scripts/rust-direct-vitest-integration.mjs && node scripts/rust-nested-vitest-integration.mjs && node scripts/rust-direct-jest-integration.mjs && node scripts/mocha-failure-output.mjs && node scripts/failure-output.mjs node ava tap && node scripts/side-by-side.mjs node && node scripts/merge-across.mjs && node scripts/import-line-evidence.mjs && node scripts/mock-reach.mjs && node scripts/rust-direct-playwright-integration.mjs && node scripts/rust-custom-browser-playwright-integration.mjs && node scripts/cross-origin-requests.mjs && node scripts/leaving-page.mjs && node scripts/shared-page.mjs && node scripts/context-script-copies.mjs && node scripts/context-headers.mjs && node scripts/context-cookies.mjs && node scripts/hidden-request-emit.mjs && node scripts/js-syntax-zoo.mjs && node scripts/ruby-syntax-zoo.mjs && node scripts/rust-syntax-zoo.mjs && node scripts/python-syntax-zoo.mjs && node scripts/go-syntax-zoo.mjs && node scripts/java-syntax-zoo.mjs && node scripts/background-by-time.mjs && node scripts/python-server-playwright.mjs && node scripts/ruby-server-playwright.mjs && node scripts/go-server-playwright.mjs && node scripts/jvm-server-playwright.mjs && node scripts/docker-server-playwright.mjs && node scripts/docker-clients-playwright.mjs && node scripts/docker-exec-playwright.mjs && node scripts/rust-classic-browser-integration.mjs && node scripts/exec-handover.mjs && node scripts/rust-region-container.mjs && node scripts/rust-top-packages-integration.mjs && node scripts/rust-generic-esbuild-integration.mjs && node scripts/rust-generic-tsc-integration.mjs && node scripts/rust-generic-build-matrix.mjs && node scripts/rust-vite-playwright-integration.mjs && node scripts/workspace-crash-integration.mjs",
86
86
  "test:platform": "cargo test --workspace && cargo build -p supercov && node scripts/rust-process-supervision.mjs && node scripts/workspace-crash-integration.mjs",
87
87
  "test:native-package": "cargo build --release -p supercov && node scripts/native-package-integration.mjs && node scripts/native-release-set-integration.mjs",
88
88
  "test:pypi-wheel": "node scripts/pypi-wheel-integration.mjs",
@@ -117,20 +117,21 @@
117
117
  "docs:sync": "node scripts/sync-docs.mjs",
118
118
  "docs:check": "node scripts/sync-docs.mjs --check",
119
119
  "test:launcher": "go vet ./cmd/... && go test ./cmd/...",
120
+ "test:launch-arguments": "cargo build -p supercov && node scripts/launch-arguments-integration.mjs --binary target/debug/supercov",
120
121
  "test:sweep-target": "node scripts/sweep-target-test.mjs",
121
122
  "test:go-versions": "cargo build -p supercov-engine --tests && node scripts/go-version-matrix.mjs",
122
123
  "test:skip-guard": "node scripts/skip-guard-test.mjs",
123
124
  "test:windows-tls": "node scripts/windows-tls-test.mjs"
124
125
  },
125
126
  "optionalDependencies": {
126
- "@supercov/cli-darwin-arm64": "4.25.0",
127
- "@supercov/cli-darwin-x64": "4.25.0",
128
- "@supercov/cli-linux-arm64-gnu": "4.25.0",
129
- "@supercov/cli-linux-arm64-musl": "4.25.0",
130
- "@supercov/cli-linux-x64-gnu": "4.25.0",
131
- "@supercov/cli-linux-x64-musl": "4.25.0",
132
- "@supercov/cli-win32-arm64": "4.25.0",
133
- "@supercov/cli-win32-x64": "4.25.0"
127
+ "@supercov/cli-darwin-arm64": "4.27.0",
128
+ "@supercov/cli-darwin-x64": "4.27.0",
129
+ "@supercov/cli-linux-arm64-gnu": "4.27.0",
130
+ "@supercov/cli-linux-arm64-musl": "4.27.0",
131
+ "@supercov/cli-linux-x64-gnu": "4.27.0",
132
+ "@supercov/cli-linux-x64-musl": "4.27.0",
133
+ "@supercov/cli-win32-arm64": "4.27.0",
134
+ "@supercov/cli-win32-x64": "4.27.0"
134
135
  },
135
136
  "peerDependencies": {
136
137
  "@playwright/test": ">=1.55.0",
@@ -1,9 +1,10 @@
1
- import fs, { appendFileSync, chmodSync, existsSync, mkdirSync, openSync, closeSync, fsyncSync, renameSync, rmSync, statSync, writeFileSync, } from "node:fs";
2
- import { randomUUID } from "node:crypto";
3
- import { syncBuiltinESMExports } from "node:module";
1
+ import fs, { appendFileSync, chmodSync, existsSync, mkdirSync, openSync, closeSync, readFileSync, fsyncSync, renameSync, rmSync, statSync, writeFileSync, } from "node:fs";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import Module, { syncBuiltinESMExports } from "node:module";
4
4
  import { threadId } from "node:worker_threads";
5
- import { dirname, resolve, sep } from "node:path";
5
+ import { basename, dirname, resolve, sep } from "node:path";
6
6
  import { Buffer } from "node:buffer";
7
+ import vm from "node:vm";
7
8
 
8
9
  // In a container Supercov's `docker` launcher mounts the run's directory
9
10
  // into, its user (root) owns what it creates there; a directory made with
@@ -159,6 +160,16 @@ export function appendEvidenceRecord(directory, prefix, payload) {
159
160
  // whole, or is not there yet and is compiled again. A file written beside the
160
161
  // cache's folders, not in one, is never taken for an old entry and removed.
161
162
  //
163
+ // Nor is an entry removed. Before it writes one, Playwright removes every
164
+ // cached file of that source, the entry another process has just written
165
+ // for the same content among them, and a process that had read that entry's
166
+ // code reads its source map only when a test is declared: in between, the
167
+ // map was gone, the test was placed by the compiled file's lines, and a
168
+ // `file:line` filter found no tests -- one test of a file, now and then, in
169
+ // a sealed suite whose containers start Playwright side by side. An entry is
170
+ // named by its source's content, so an old one is never read for new
171
+ // content; the cache is the run's own and goes with it.
172
+ //
162
173
  // Playwright compiles in two threads: the config and CommonJS files in the
163
174
  // process's own, ES modules in the thread its loader hooks run in, which has
164
175
  // its own `fs` and does not run `--import`. Each calls this. The partial
@@ -171,9 +182,16 @@ export function writePlaywrightCacheWhole() {
171
182
  return;
172
183
  cacheWritesWhole = true;
173
184
  const cacheFolder = resolve(transformCache) + sep;
185
+ const inCache = (file) => typeof file === "string" && resolve(file).startsWith(cacheFolder);
174
186
  const writeFileSync = fs.writeFileSync;
187
+ const rmSync = fs.rmSync;
188
+ fs.rmSync = function (file, ...rest) {
189
+ if (inCache(file) && !basename(file).startsWith(".writing-"))
190
+ return;
191
+ return rmSync.call(this, file, ...rest);
192
+ };
175
193
  fs.writeFileSync = function (file, ...rest) {
176
- if (typeof file !== "string" || !resolve(file).startsWith(cacheFolder))
194
+ if (!inCache(file))
177
195
  return writeFileSync.call(this, file, ...rest);
178
196
  const partial = resolve(transformCache, `.writing-${process.pid}-${threadId}-${randomUUID()}`);
179
197
  try {
@@ -181,8 +199,105 @@ export function writePlaywrightCacheWhole() {
181
199
  fs.renameSync(partial, file);
182
200
  }
183
201
  finally {
184
- fs.rmSync(partial, { force: true });
202
+ rmSync(partial, { force: true });
185
203
  }
186
204
  };
187
205
  syncBuiltinESMExports();
188
206
  }
207
+
208
+ // Compiled code for instrumented modules, kept for the rest of the run.
209
+ //
210
+ // Vitest evaluates every module a test file imports in a fresh worker for
211
+ // each test file, and compiles each again: an instrumented module is several
212
+ // times its source, so most of what Supercov added to a large unit suite was
213
+ // V8 compiling the same instrumented text over and over. V8 can start from
214
+ // code it compiled before (a script's cached data), checks it against the
215
+ // source and its own version and flags, and compiles afresh when it does not
216
+ // match, so a module behaves as it would have either way.
217
+ //
218
+ // `vm.runInThisContext` is what Vitest's module runner calls; it is wrapped
219
+ // for instrumented text alone. Each compiled module's code is written once
220
+ // its test file is done, when it holds the functions the file ran as well as
221
+ // the module's top level, for the workers after it to start from.
222
+
223
+ // The installed wrapper carries its state: where the cache is, and the
224
+ // scripts compiled with no cached data that matched, each with where to keep
225
+ // its code. Any copy of this module saves what the one wrapper compiled.
226
+ const STATE = Symbol.for("supercov.compileCache");
227
+ const MARK = "__supercov";
228
+
229
+ /**
230
+ * Wraps `vm.runInThisContext` in this process to compile instrumented text
231
+ * from what `directory` keeps. Once per process: every copy of the runtime
232
+ * shares the one wrapper.
233
+ */
234
+ /**
235
+ * Node's own compile cache for every module Node loads in this process --
236
+ * its CommonJS and ES modules, the runtime's among them -- kept in `directory`
237
+ * for the processes after it: a runner that starts a fresh process or worker
238
+ * per test file compiled the same packages again in each. A command that set
239
+ * NODE_COMPILE_CACHE keeps its own. Only how long compiling takes changes.
240
+ * Not on Windows: there `node --test`'s child for a test file never finished
241
+ * once the cache was on.
242
+ */
243
+ export function enableNodeCompileCache(directory) {
244
+ if (!directory || process.platform === "win32" || process.env.NODE_COMPILE_CACHE !== undefined ||
245
+ typeof Module.enableCompileCache !== "function")
246
+ return;
247
+ Module.enableCompileCache(resolve(directory, "node"));
248
+ }
249
+ export function installCompileCache(directory) {
250
+ if (!directory || vm.runInThisContext[STATE])
251
+ return;
252
+ const original = vm.runInThisContext;
253
+ const state = { directory, unsaved: [] };
254
+ const cached = function runInThisContext(code, options) {
255
+ // The filename-only form and anything not instrumented go as they
256
+ // came.
257
+ if (typeof code !== "string" || (options !== undefined && (options === null || typeof options !== "object")) || !code.includes(MARK))
258
+ return Reflect.apply(original, this, arguments);
259
+ const key = createHash("sha256")
260
+ .update(code)
261
+ .update("\0")
262
+ .update(JSON.stringify([options?.filename, options?.lineOffset, options?.columnOffset]))
263
+ .digest("hex");
264
+ const file = resolve(directory, key);
265
+ let cachedData;
266
+ try {
267
+ cachedData = readFileSync(file);
268
+ }
269
+ catch {
270
+ cachedData = undefined;
271
+ }
272
+ // What `vm.runInThisContext` does, with the cached data.
273
+ const script = new vm.Script(code, { ...options, cachedData });
274
+ if (cachedData === undefined || script.cachedDataRejected)
275
+ state.unsaved.push([file, script]);
276
+ return script.runInThisContext(options);
277
+ };
278
+ cached[STATE] = state;
279
+ vm.runInThisContext = cached;
280
+ }
281
+
282
+ /**
283
+ * Writes the code of each module compiled since the last save without cached
284
+ * data: what V8 holds of it now, the functions run so far included. A file
285
+ * another worker wrote meanwhile is replaced whole, never torn.
286
+ */
287
+ export function saveCompileCache() {
288
+ const state = vm.runInThisContext[STATE];
289
+ if (!state || state.unsaved.length === 0)
290
+ return;
291
+ const scripts = state.unsaved.splice(0);
292
+ try {
293
+ makeDirectory(state.directory);
294
+ for (const [file, script] of scripts) {
295
+ const partial = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}`;
296
+ writeFileSync(partial, script.createCachedData(), { mode: fileMode() });
297
+ renameSync(partial, file);
298
+ }
299
+ }
300
+ catch {
301
+ // A cache that cannot be written is compiled again next time.
302
+ }
303
+ }
@@ -18,7 +18,7 @@ import * as standardPlaywright from "@playwright/test";
18
18
  import * as coverageRuntime from "./runtime.mjs";
19
19
  import { inferTestProvenance, testTags } from "./provenance.mjs";
20
20
  import { appendJsonLineDurableSync, appendJsonLineSync } from "./atomic.mjs";
21
- import { expandSnapshot, mergeSnapshots } from "./snapshots.mjs";
21
+ import { expandSnapshot, mergeSnapshots, columnarEvents } from "./snapshots.mjs";
22
22
  import { COVERAGE_DOCUMENT_PHASE_COOKIE, COVERAGE_DOCUMENT_PHASE_SITE_COOKIE, COVERAGE_PHASE_HEADER, COVERAGE_PHASE_COOKIE, COVERAGE_PHASE_SITE_COOKIE, COVERAGE_SCOPE_COOKIE, COVERAGE_SCOPE_HEADER, COVERAGE_SCOPE_SITE_COOKIE, COVERAGE_CARRIER_ENV, encodeCoverageCarrier, encodeCoverageScope, serverEvidenceDirectory, serverEvidencePath, startDocumentInPhase, } from "./transport.mjs";
23
23
  export * from "@playwright/test";
24
24
  const generatedTargetModule = "__SUPERCOV_PLAYWRIGHT_MODULE__";
@@ -124,6 +124,17 @@ function timingCount(bucket, milliseconds = 0) {
124
124
  entry.ms += milliseconds;
125
125
  timingBuckets.set(bucket, entry);
126
126
  }
127
+ // How late the test process's event loop runs, while timing: an awaited
128
+ // round trip waits for its reply on this loop as well as on the browser.
129
+ if (timingBuckets) {
130
+ let expected = performance.now() + 5;
131
+ setInterval(() => {
132
+ const now = performance.now();
133
+ if (now - expected > 1)
134
+ timingCount("probe.loopLag", now - expected);
135
+ expected = now + 5;
136
+ }, 5).unref?.();
137
+ }
127
138
  async function timed(bucket, work) {
128
139
  if (!timingBuckets)
129
140
  return work();
@@ -240,6 +251,9 @@ class CoveragePhaseController {
240
251
  // dispose so a worker-scoped context does not keep registering pages with
241
252
  // controllers of tests that already finished.
242
253
  contextListeners = new Map();
254
+ // Contexts that closed during the test: a phase sent to one failed, and
255
+ // its cookies were then tried again host by host.
256
+ closedContexts = new WeakSet();
243
257
  // Snapshots read from pages the suite closed before teardown. A `page`
244
258
  // fixture override tears down before the collector's own fixture, and a
245
259
  // closed page cannot be evaluated, so the evidence is taken on the way out.
@@ -556,6 +570,11 @@ class CoveragePhaseController {
556
570
  return internally(context, () => this.registerContextNow(context, adopted));
557
571
  }
558
572
  async registerContextNow(context, adopted) {
573
+ if (timingBuckets) {
574
+ const copies = (contextScriptCopies.get(context) ?? 0) + 1;
575
+ contextScriptCopies.set(context, copies);
576
+ timingCount(copies > 1 ? "registerContext.again" : "registerContext.first", copies);
577
+ }
559
578
  // The context's own scripts first: sent when it was made, so they
560
579
  // are in place, or sent now for a context made some other way.
561
580
  await prepareContext(context);
@@ -566,12 +585,14 @@ class CoveragePhaseController {
566
585
  // leaves the others.
567
586
  const parts = [];
568
587
  // A context that outlives its test (a worker-scoped browser fixture)
569
- // is registered again by every later test, so this script accumulates
570
- // on it and each new document runs every copy in registration order.
571
- // That is made harmless rather than avoided: every copy publishes its
572
- // own attempt, so the newest wins; the fetch patch is installed once
573
- // and reads the attempt at call time, so a stale copy can never pin an
574
- // old scope onto a request the way nested wrappers would.
588
+ // is registered again by every later test. Every copy publishes its
589
+ // own attempt, so the newest wins, and the fetch patch is installed
590
+ // once and reads the attempt at call time: a stale copy can never pin
591
+ // an old scope onto a request. Where Playwright can remove a script
592
+ // (its `addInitScript` returns a disposable), the previous test's copy is
593
+ // removed once this one is in place, so a document runs one copy:
594
+ // they accumulated to some fifty per context on a long suite, each
595
+ // sent to every new page and frame and run by every document.
575
596
  parts.push(`(${announceAttempt})(${JSON.stringify({
576
597
  attemptId: this.scope.attemptId,
577
598
  scopeHeader: COVERAGE_SCOPE_HEADER,
@@ -587,10 +608,20 @@ class CoveragePhaseController {
587
608
  phaseCookie: COVERAGE_DOCUMENT_PHASE_COOKIE,
588
609
  phaseSiteCookie: COVERAGE_DOCUMENT_PHASE_SITE_COOKIE,
589
610
  })});`);
590
- await Promise.all([
611
+ const [added] = await Promise.all([
591
612
  context.addInitScript({ content: separately(parts) }).catch(() => undefined),
592
613
  adopted ? undefined : this.updateContextHeaders(context, this.requestPhaseId(), this.lastActionId),
593
614
  ]);
615
+ if (typeof added?.dispose === "function") {
616
+ const previous = contextInitScripts.get(context);
617
+ contextInitScripts.set(context, added);
618
+ // Not awaited: the test waits for nothing it needs here, and a
619
+ // context closed meanwhile has no script left to remove.
620
+ if (previous)
621
+ void internally(context, () => previous.dispose()).catch(() => undefined);
622
+ if (timingBuckets)
623
+ contextScriptCopies.set(context, 1);
624
+ }
594
625
  const register = (page) => {
595
626
  const pending = this.registerPage(page).finally(() => this.pendingRegistrations.delete(pending));
596
627
  this.pendingRegistrations.add(pending);
@@ -598,9 +629,11 @@ class CoveragePhaseController {
598
629
  const registerServiceWorker = (worker) => {
599
630
  void this.registerWorker(worker);
600
631
  };
632
+ const closed = () => this.closedContexts.add(context);
601
633
  context.on("page", register);
602
634
  context.on("serviceworker", registerServiceWorker);
603
- this.contextListeners.set(context, [["page", register], ["serviceworker", registerServiceWorker]]);
635
+ context.on("close", closed);
636
+ this.contextListeners.set(context, [["page", register], ["serviceworker", registerServiceWorker], ["close", closed]]);
604
637
  for (const worker of context.serviceWorkers())
605
638
  void this.registerWorker(worker);
606
639
  for (const page of context.pages())
@@ -894,7 +927,7 @@ class CoveragePhaseController {
894
927
  async activateInBrowserNow(phaseId, documentPhaseId) {
895
928
  await Promise.all([
896
929
  timed("activate.contextHeaders", () => Promise.all([...this.contexts]
897
- .filter((context) => !this.adoptedContexts.has(context))
930
+ .filter((context) => !this.adoptedContexts.has(context) && !this.closedContexts.has(context))
898
931
  .map((context) => this.updateContextHeaders(context, phaseId, documentPhaseId)))),
899
932
  this.activateFrames(phaseId),
900
933
  this.activateWorkers(phaseId),
@@ -903,6 +936,31 @@ class CoveragePhaseController {
903
936
  timed("activate.pageScript", () => Promise.all([...this.pages]
904
937
  .filter((page) => this.adoptedContexts.has(page.context()))
905
938
  .map((page) => this.activatePage(page, phaseId)))),
939
+ timingBuckets ? this.probeRoundTrips() : undefined,
940
+ ]);
941
+ }
942
+ /**
943
+ * While timing, beside each activation: how long a call that does nothing
944
+ * takes to reach a page and come back, and a cookie read of the browser,
945
+ * so an activation's time can be told apart from the round trip's.
946
+ */
947
+ async probeRoundTrips() {
948
+ const page = [...this.pages].find((candidate) => !candidate.isClosed?.());
949
+ if (!page)
950
+ return;
951
+ const clock = () => performance.timeOrigin + performance.now();
952
+ await Promise.all([
953
+ (async () => {
954
+ const sent = clock();
955
+ const inPage = await page.mainFrame().evaluate(() => performance.timeOrigin + performance.now()).catch(() => undefined);
956
+ const back = clock();
957
+ timingCount("probe.noopEvaluate", back - sent);
958
+ if (typeof inPage === "number") {
959
+ timingCount("probe.toPage", inPage - sent);
960
+ timingCount("probe.fromPage", back - inPage);
961
+ }
962
+ })(),
963
+ timed("probe.noopCookies", () => page.context().cookies("http://supercov.invalid/").catch(() => undefined)),
906
964
  ]);
907
965
  }
908
966
  async activateFrames(phaseId, pages = this.pages) {
@@ -913,7 +971,7 @@ class CoveragePhaseController {
913
971
  const covered = (page) => this.adoptedContexts.has(page.context())
914
972
  ? []
915
973
  : this.appHosts.map((url) => new URL(url).hostname);
916
- await timed("activate.frameEvaluate", () => Promise.all([...pages].flatMap((page) => page.frames().map((frame) => [frame, covered(page)])).map(([frame, coveredHosts]) => frame
974
+ await timed("activate.frameEvaluate", () => Promise.all([...pages].filter((page) => !page.isClosed?.()).flatMap((page) => page.frames().map((frame) => [frame, covered(page)])).map(([frame, coveredHosts]) => frame
917
975
  .evaluate(({ id, attemptId, storageKey, scopeCookie, scopeValue, phaseCookie, scopeSiteCookie, phaseSiteCookie, coveredHosts }) => {
918
976
  globalThis.__SUPERCOV_PHASE_ID__ = id;
919
977
  const coverageGlobal = globalThis;
@@ -1017,8 +1075,8 @@ class CoveragePhaseController {
1017
1075
  if (!distinct.has(key))
1018
1076
  distinct.set(key, cookie);
1019
1077
  }
1020
- await context.addCookies([...distinct.values()]).catch(() => {
1021
- timingCount("activate.cookiesRefused");
1078
+ await context.addCookies([...distinct.values()]).catch((error) => {
1079
+ timingCount(timingBuckets ? `activate.cookiesRefused: ${String(error?.message ?? error).split("\n")[0].slice(0, 120)}` : "activate.cookiesRefused");
1022
1080
  return Promise.all(byHost.map((cookies) => context.addCookies(cookies).catch(() => timingCount("activate.hostCookiesRefused"))));
1023
1081
  });
1024
1082
  }
@@ -1099,6 +1157,11 @@ function announceAttempt({ attemptId, scopeHeader, scopeValue, scopeCookie, scop
1099
1157
  // Browser instrumentation must not change application behavior.
1100
1158
  }
1101
1159
  }
1160
+ // While timing: how many tests' scripts each context has run (a context
1161
+ // that outlives its test is registered by every later test).
1162
+ const contextScriptCopies = new WeakMap();
1163
+ // The disposable of the script each context's newest registration added.
1164
+ const contextInitScripts = new WeakMap();
1102
1165
  const LEAVING_BINDING = "__supercovLeaving";
1103
1166
  /** Scripts as one, each part run on its own as separate scripts were. */
1104
1167
  function separately(parts) {
@@ -1716,42 +1779,6 @@ function mergeCollectedPhases(controllerPhases, fallbackPhases) {
1716
1779
  * thousands of them were most of a test's record. The engine decodes the
1717
1780
  * columns into exactly these events, in this order.
1718
1781
  */
1719
- function columnarEvents(snapshot) {
1720
- const events = snapshot?.events;
1721
- if (!Array.isArray(events) || events.length === 0)
1722
- return snapshot;
1723
- const tables = { types: new Map(), phases: new Map(), environments: new Map() };
1724
- const index = (table, value) => {
1725
- let found = table.get(value);
1726
- if (found === undefined) {
1727
- found = table.size;
1728
- table.set(value, found);
1729
- }
1730
- return found;
1731
- };
1732
- const columns = { id: [], type: [], phase: [], environment: [], t: [], vector: {} };
1733
- let previous = 0;
1734
- events.forEach((event, position) => {
1735
- columns.id.push(event.id);
1736
- columns.type.push(index(tables.types, event.type));
1737
- columns.phase.push(event.phaseId == null ? -1 : index(tables.phases, event.phaseId));
1738
- columns.environment.push(index(tables.environments, event.environment));
1739
- columns.t.push(event.timestampMs - previous);
1740
- previous = event.timestampMs;
1741
- if (event.vector !== undefined)
1742
- columns.vector[position] = event.vector;
1743
- });
1744
- const { events: _events, ...rest } = snapshot;
1745
- return {
1746
- ...rest,
1747
- eventColumns: {
1748
- types: [...tables.types.keys()],
1749
- phases: [...tables.phases.keys()],
1750
- environments: [...tables.environments.keys()],
1751
- ...columns,
1752
- },
1753
- };
1754
- }
1755
1782
  function appendEvidenceLine(serialized) {
1756
1783
  const evidenceDirectory = process.env["SUPERCOV_EVIDENCE_DIR"] ??
1757
1784
  (GENERATED_EVIDENCE_DIRECTORY.startsWith("__")
@@ -13,7 +13,7 @@ import { fileURLToPath } from "node:url";
13
13
  import { installLaunchSupervisor, wrapImportedCapability } from "./launchSupervisor.mjs";
14
14
  import { __supercovBindCapabilityWrapper } from "./capability.mjs";
15
15
  import { adaptRunnerEntry, noteSkippedCoverageThresholds } from "./runnerEntry.mjs";
16
- import { writePlaywrightCacheWhole } from "./atomic.mjs";
16
+ import { enableNodeCompileCache, writePlaywrightCacheWhole } from "./atomic.mjs";
17
17
  // Supercov runs Node with --enable-source-maps so a stack through an
18
18
  // instrumented copy names the project's file. The flag also reads the maps
19
19
  // every package ships, which a plain run never does: a third of the CPU a
@@ -24,6 +24,9 @@ if ((process.env.NODE_OPTIONS ?? "").split(/\s+/).filter((option) => option ===
24
24
  !process.execArgv.includes("--enable-source-maps") &&
25
25
  typeof Module.setSourceMapsSupport === "function")
26
26
  Module.setSourceMapsSupport(true, { nodeModules: false, generatedCode: true });
27
+ // Before anything else loads: every module after this compiles from the
28
+ // code the run's earlier processes left (atomic.mjs says why).
29
+ enableNodeCompileCache(process.env.SUPERCOV_COMPILE_CACHE);
27
30
  installLaunchSupervisor();
28
31
  // Playwright's compile cache, written whole (atomic.mjs says why).
29
32
  writePlaywrightCacheWhole();