supercov 4.25.0 → 4.26.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,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.26.0",
4
4
  "description": "Coverage, security and code quality for coding agents",
5
5
  "keywords": [
6
6
  "coverage",
@@ -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.26.0",
128
+ "@supercov/cli-darwin-x64": "4.26.0",
129
+ "@supercov/cli-linux-arm64-gnu": "4.26.0",
130
+ "@supercov/cli-linux-arm64-musl": "4.26.0",
131
+ "@supercov/cli-linux-x64-gnu": "4.26.0",
132
+ "@supercov/cli-linux-x64-musl": "4.26.0",
133
+ "@supercov/cli-win32-arm64": "4.26.0",
134
+ "@supercov/cli-win32-x64": "4.26.0"
134
135
  },
135
136
  "peerDependencies": {
136
137
  "@playwright/test": ">=1.55.0",
@@ -2,7 +2,7 @@ import fs, { appendFileSync, chmodSync, existsSync, mkdirSync, openSync, closeSy
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { 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
7
 
8
8
  // In a container Supercov's `docker` launcher mounts the run's directory
@@ -159,6 +159,16 @@ export function appendEvidenceRecord(directory, prefix, payload) {
159
159
  // whole, or is not there yet and is compiled again. A file written beside the
160
160
  // cache's folders, not in one, is never taken for an old entry and removed.
161
161
  //
162
+ // Nor is an entry removed. Before it writes one, Playwright removes every
163
+ // cached file of that source, the entry another process has just written
164
+ // for the same content among them, and a process that had read that entry's
165
+ // code reads its source map only when a test is declared: in between, the
166
+ // map was gone, the test was placed by the compiled file's lines, and a
167
+ // `file:line` filter found no tests -- one test of a file, now and then, in
168
+ // a sealed suite whose containers start Playwright side by side. An entry is
169
+ // named by its source's content, so an old one is never read for new
170
+ // content; the cache is the run's own and goes with it.
171
+ //
162
172
  // Playwright compiles in two threads: the config and CommonJS files in the
163
173
  // process's own, ES modules in the thread its loader hooks run in, which has
164
174
  // its own `fs` and does not run `--import`. Each calls this. The partial
@@ -171,9 +181,16 @@ export function writePlaywrightCacheWhole() {
171
181
  return;
172
182
  cacheWritesWhole = true;
173
183
  const cacheFolder = resolve(transformCache) + sep;
184
+ const inCache = (file) => typeof file === "string" && resolve(file).startsWith(cacheFolder);
174
185
  const writeFileSync = fs.writeFileSync;
186
+ const rmSync = fs.rmSync;
187
+ fs.rmSync = function (file, ...rest) {
188
+ if (inCache(file) && !basename(file).startsWith(".writing-"))
189
+ return;
190
+ return rmSync.call(this, file, ...rest);
191
+ };
175
192
  fs.writeFileSync = function (file, ...rest) {
176
- if (typeof file !== "string" || !resolve(file).startsWith(cacheFolder))
193
+ if (!inCache(file))
177
194
  return writeFileSync.call(this, file, ...rest);
178
195
  const partial = resolve(transformCache, `.writing-${process.pid}-${threadId}-${randomUUID()}`);
179
196
  try {
@@ -181,7 +198,7 @@ export function writePlaywrightCacheWhole() {
181
198
  fs.renameSync(partial, file);
182
199
  }
183
200
  finally {
184
- fs.rmSync(partial, { force: true });
201
+ rmSync(partial, { force: true });
185
202
  }
186
203
  };
187
204
  syncBuiltinESMExports();
@@ -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);
@@ -598,9 +617,11 @@ class CoveragePhaseController {
598
617
  const registerServiceWorker = (worker) => {
599
618
  void this.registerWorker(worker);
600
619
  };
620
+ const closed = () => this.closedContexts.add(context);
601
621
  context.on("page", register);
602
622
  context.on("serviceworker", registerServiceWorker);
603
- this.contextListeners.set(context, [["page", register], ["serviceworker", registerServiceWorker]]);
623
+ context.on("close", closed);
624
+ this.contextListeners.set(context, [["page", register], ["serviceworker", registerServiceWorker], ["close", closed]]);
604
625
  for (const worker of context.serviceWorkers())
605
626
  void this.registerWorker(worker);
606
627
  for (const page of context.pages())
@@ -894,7 +915,7 @@ class CoveragePhaseController {
894
915
  async activateInBrowserNow(phaseId, documentPhaseId) {
895
916
  await Promise.all([
896
917
  timed("activate.contextHeaders", () => Promise.all([...this.contexts]
897
- .filter((context) => !this.adoptedContexts.has(context))
918
+ .filter((context) => !this.adoptedContexts.has(context) && !this.closedContexts.has(context))
898
919
  .map((context) => this.updateContextHeaders(context, phaseId, documentPhaseId)))),
899
920
  this.activateFrames(phaseId),
900
921
  this.activateWorkers(phaseId),
@@ -903,6 +924,31 @@ class CoveragePhaseController {
903
924
  timed("activate.pageScript", () => Promise.all([...this.pages]
904
925
  .filter((page) => this.adoptedContexts.has(page.context()))
905
926
  .map((page) => this.activatePage(page, phaseId)))),
927
+ timingBuckets ? this.probeRoundTrips() : undefined,
928
+ ]);
929
+ }
930
+ /**
931
+ * While timing, beside each activation: how long a call that does nothing
932
+ * takes to reach a page and come back, and a cookie read of the browser,
933
+ * so an activation's time can be told apart from the round trip's.
934
+ */
935
+ async probeRoundTrips() {
936
+ const page = [...this.pages].find((candidate) => !candidate.isClosed?.());
937
+ if (!page)
938
+ return;
939
+ const clock = () => performance.timeOrigin + performance.now();
940
+ await Promise.all([
941
+ (async () => {
942
+ const sent = clock();
943
+ const inPage = await page.mainFrame().evaluate(() => performance.timeOrigin + performance.now()).catch(() => undefined);
944
+ const back = clock();
945
+ timingCount("probe.noopEvaluate", back - sent);
946
+ if (typeof inPage === "number") {
947
+ timingCount("probe.toPage", inPage - sent);
948
+ timingCount("probe.fromPage", back - inPage);
949
+ }
950
+ })(),
951
+ timed("probe.noopCookies", () => page.context().cookies("http://supercov.invalid/").catch(() => undefined)),
906
952
  ]);
907
953
  }
908
954
  async activateFrames(phaseId, pages = this.pages) {
@@ -913,7 +959,7 @@ class CoveragePhaseController {
913
959
  const covered = (page) => this.adoptedContexts.has(page.context())
914
960
  ? []
915
961
  : 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
962
+ 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
963
  .evaluate(({ id, attemptId, storageKey, scopeCookie, scopeValue, phaseCookie, scopeSiteCookie, phaseSiteCookie, coveredHosts }) => {
918
964
  globalThis.__SUPERCOV_PHASE_ID__ = id;
919
965
  const coverageGlobal = globalThis;
@@ -1017,8 +1063,8 @@ class CoveragePhaseController {
1017
1063
  if (!distinct.has(key))
1018
1064
  distinct.set(key, cookie);
1019
1065
  }
1020
- await context.addCookies([...distinct.values()]).catch(() => {
1021
- timingCount("activate.cookiesRefused");
1066
+ await context.addCookies([...distinct.values()]).catch((error) => {
1067
+ timingCount(timingBuckets ? `activate.cookiesRefused: ${String(error?.message ?? error).split("\n")[0].slice(0, 120)}` : "activate.cookiesRefused");
1022
1068
  return Promise.all(byHost.map((cookies) => context.addCookies(cookies).catch(() => timingCount("activate.hostCookiesRefused"))));
1023
1069
  });
1024
1070
  }
@@ -1099,6 +1145,9 @@ function announceAttempt({ attemptId, scopeHeader, scopeValue, scopeCookie, scop
1099
1145
  // Browser instrumentation must not change application behavior.
1100
1146
  }
1101
1147
  }
1148
+ // While timing: how many tests' scripts each context has run (a context
1149
+ // that outlives its test is registered by every later test).
1150
+ const contextScriptCopies = new WeakMap();
1102
1151
  const LEAVING_BINDING = "__supercovLeaving";
1103
1152
  /** Scripts as one, each part run on its own as separate scripts were. */
1104
1153
  function separately(parts) {
@@ -1716,42 +1765,6 @@ function mergeCollectedPhases(controllerPhases, fallbackPhases) {
1716
1765
  * thousands of them were most of a test's record. The engine decodes the
1717
1766
  * columns into exactly these events, in this order.
1718
1767
  */
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
1768
  function appendEvidenceLine(serialized) {
1756
1769
  const evidenceDirectory = process.env["SUPERCOV_EVIDENCE_DIR"] ??
1757
1770
  (GENERATED_EVIDENCE_DIRECTORY.startsWith("__")
@@ -170,7 +170,9 @@ function createState() {
170
170
  // Per value-position logical expression (`a && b`, `a || b`, `a ?? b`): the distinct
171
171
  // (right operand evaluated?, result truthy?) pairs seen, keyed by branch id.
172
172
  logicals: /* @__PURE__ */ new Map(),
173
- eventKeys: /* @__PURE__ */ new Set(),
173
+ // The events already recorded, by phase: a hit by its id, anything else
174
+ // by its type and what tells it apart (eventSeen).
175
+ eventKeys: /* @__PURE__ */ new Map(),
174
176
  bufferedAttempts: /* @__PURE__ */ new Set(),
175
177
  serverBuffers: /* @__PURE__ */ new Map(),
176
178
  persistedServerRecords: /* @__PURE__ */ new Set(),
@@ -207,7 +209,7 @@ function createState() {
207
209
  state2.hits.add(id);
208
210
  for (const event of (_d = stored.events) != null ? _d : []) {
209
211
  state2.events.push(event);
210
- state2.eventKeys.add(eventKey(event));
212
+ eventSeen(state2.eventKeys, event);
211
213
  }
212
214
  } catch (e) {
213
215
  }
@@ -261,7 +263,7 @@ function activateProbeV2Key(key, force = false) {
261
263
  file.decisionObservationCounts.fill(0);
262
264
  file.decisionCompleteEpochs.fill(0);
263
265
  for (const vectors of file.decisionEpochs) {
264
- if (vectors instanceof Uint32Array)
266
+ if (vectors.size === void 0)
265
267
  vectors.fill(0);
266
268
  else
267
269
  vectors.clear();
@@ -1171,24 +1173,10 @@ function appendServer(record) {
1171
1173
  var _a8, _b, _c, _d;
1172
1174
  if (state.runtimeSnapshots) {
1173
1175
  const timestampMs = (_a8 = record.timestampMs) != null ? _a8 : Date.now();
1174
- if (record.type === "decision") {
1175
- recordBrowserEvent(__spreadProps(__spreadValues({
1176
- type: "decision",
1177
- id: record.id,
1178
- vector: record.vector,
1179
- timestampMs
1180
- }, record.phaseId ? { phaseId: record.phaseId } : {}), {
1181
- environment: "server"
1182
- }));
1183
- } else {
1184
- recordBrowserEvent(__spreadProps(__spreadValues({
1185
- type: "hit",
1186
- id: record.id,
1187
- timestampMs
1188
- }, record.phaseId ? { phaseId: record.phaseId } : {}), {
1189
- environment: "server"
1190
- }));
1191
- }
1176
+ if (record.type === "decision")
1177
+ recordBrowserEvent(decisionEvent(record.id, record.vector, timestampMs, record.phaseId, "server"));
1178
+ else
1179
+ recordBrowserEvent(hitEvent(record.id, timestampMs, record.phaseId, "server"));
1192
1180
  return;
1193
1181
  }
1194
1182
  const fs = getFs();
@@ -1236,18 +1224,22 @@ function appendServer(record) {
1236
1224
  throw serverTransportError(runId, cause);
1237
1225
  }
1238
1226
  }
1239
- // Read on every probe outside a test, and the variable rarely changes: decode
1240
- // it once per value.
1241
- var decodedEnvironmentCarrier = { raw: void 0, context: void 0 };
1227
+ // The context a parent process gave this one, in SUPERCOV_CONTEXT: read on
1228
+ // every first hit, and fixed for the process's life. Supercov only ever gives
1229
+ // it to a child, at spawn, so it is read once per environment object: a
1230
+ // read of process.env, an interceptor, on every first hit of a large suite's
1231
+ // tests was the runtime's largest cost. A suite that swaps process.env for
1232
+ // another object is read again.
1233
+ var decodedEnvironmentCarrier = { env: void 0, context: void 0 };
1242
1234
  function environmentRequestContext() {
1243
1235
  if (isBrowser || typeof process === "undefined")
1244
1236
  return void 0;
1245
- const raw = process.env[COVERAGE_CARRIER_ENV];
1246
- if (raw === decodedEnvironmentCarrier.raw)
1237
+ const env = process.env;
1238
+ if (env === decodedEnvironmentCarrier.env)
1247
1239
  return decodedEnvironmentCarrier.context;
1248
- const carrier = decodeCoverageCarrier(raw);
1240
+ const carrier = decodeCoverageCarrier(env[COVERAGE_CARRIER_ENV]);
1249
1241
  const context = carrier ? __spreadValues(__spreadValues({}, carrier.scope ? { scope: carrier.scope } : {}), carrier.phaseId ? { phaseId: carrier.phaseId } : {}) : void 0;
1250
- decodedEnvironmentCarrier = { raw, context };
1242
+ decodedEnvironmentCarrier = { env, context };
1251
1243
  return context;
1252
1244
  }
1253
1245
  function currentRequestContext() {
@@ -1942,16 +1934,25 @@ function withRequestPhase(handler, event) {
1942
1934
  return requestContext !== void 0 || context.scope || context.phaseId ? serverPhaseStorage.run(context, () => withProbeV2Context(context, invoke)) : invoke();
1943
1935
  };
1944
1936
  }
1945
- function eventKey(event) {
1946
- var _a8;
1947
- const suffix = event.type === "decision" ? `${event.id}:${vectorKey(event.vector)}` : event.id;
1948
- return `${(_a8 = event.phaseId) != null ? _a8 : "unscoped"}:${event.type}:${suffix}`;
1937
+ // Whether `event` was already recorded, recording it if not. Kept per phase,
1938
+ // so a first hit looks up its id alone: one key joining the phase, the type
1939
+ // and the id was built and hashed for every first hit of every test.
1940
+ function eventSeen(seen, event) {
1941
+ const phase = event.phaseId != null ? event.phaseId : "unscoped";
1942
+ let keys = seen.get(phase);
1943
+ if (keys === void 0) {
1944
+ keys = /* @__PURE__ */ new Set();
1945
+ seen.set(phase, keys);
1946
+ }
1947
+ const key = event.type === "hit" ? event.id : `${event.type}\0${event.type === "decision" ? `${event.id}:${vectorKey(event.vector)}` : event.id}`;
1948
+ if (keys.has(key))
1949
+ return true;
1950
+ keys.add(key);
1951
+ return false;
1949
1952
  }
1950
1953
  function recordBrowserEvent(event) {
1951
- const key = eventKey(event);
1952
- if (state.eventKeys.has(key))
1954
+ if (eventSeen(state.eventKeys, event))
1953
1955
  return false;
1954
- state.eventKeys.add(key);
1955
1956
  state.events.push(event);
1956
1957
  workerEvidenceChanged();
1957
1958
  return true;
@@ -1988,47 +1989,74 @@ function recordCoverageHit(id) {
1988
1989
  const timestampMs = Date.now();
1989
1990
  const phaseId = currentPhaseId();
1990
1991
  if (isBrowser) {
1991
- if (recordBrowserEvent(__spreadProps(__spreadValues({
1992
- type: "hit",
1993
- id,
1994
- timestampMs
1995
- }, phaseId ? { phaseId } : {}), {
1996
- environment: "browser"
1997
- })))
1992
+ if (recordBrowserEvent(hitEvent(id, timestampMs, phaseId, "browser")))
1998
1993
  persistBrowser();
1999
1994
  } else {
2000
- appendServer(__spreadValues({
2001
- type: "hit",
2002
- id,
2003
- timestampMs
2004
- }, phaseId ? { phaseId } : {}));
1995
+ appendServer(phaseId ? { type: "hit", id, timestampMs, phaseId } : { type: "hit", id, timestampMs });
1996
+ }
1997
+ }
1998
+ // A first hit's event, built as one literal in the order the spread helpers
1999
+ // gave its keys: they walked every key of three objects for each first hit
2000
+ // of every statement in every test.
2001
+ function hitEvent(id, timestampMs, phaseId, environment) {
2002
+ return phaseId ? { type: "hit", id, timestampMs, phaseId, environment } : { type: "hit", id, timestampMs, environment };
2003
+ }
2004
+ function decisionEvent(id, vector, timestampMs, phaseId, environment) {
2005
+ return phaseId ? { type: "decision", id, vector, timestampMs, phaseId, environment } : { type: "decision", id, vector, timestampMs, environment };
2006
+ }
2007
+ // A module carries the key of its table of ids, which the manifest holds, and
2008
+ // how many points and decisions it numbers: evidence names a probe by the key
2009
+ // and its place, `~p<key>.<place>` or `~d<key>.<place>`, and the report reads
2010
+ // the id there. A place whose id an earlier place has is named as that one,
2011
+ // as it was one id: a selection's two short outcomes are one point.
2012
+ function probeAliases(flat) {
2013
+ const aliases = /* @__PURE__ */ new Map();
2014
+ for (let index = 0; flat && index + 1 < flat.length; index += 2)
2015
+ aliases.set(flat[index], flat[index + 1]);
2016
+ return aliases;
2017
+ }
2018
+ function probePlaceName(names, aliases, count, kind, key, place) {
2019
+ if (!(place >= 0 && place < count))
2020
+ return void 0;
2021
+ let name = names[place];
2022
+ if (name === void 0) {
2023
+ const first = aliases.get(place);
2024
+ name = names[place] = first === void 0 ? `~${kind}${key}.${place}` : probePlaceName(names, aliases, count, kind, key, first);
2005
2025
  }
2026
+ return name;
2027
+ }
2028
+ function probePointName(file, place) {
2029
+ return probePlaceName(file.pointNames, file.pointAliases, file.pointCount, "p", file.key, place);
2006
2030
  }
2007
- // A file's ids, as the instrumenter writes them: one string of ids separated
2008
- // by spaces, or a list where an id holds one.
2009
- function listedIds(ids) {
2010
- return typeof ids === "string" ? ids === "" ? [] : ids.split(" ") : ids;
2031
+ function probeDecisionName(file, place) {
2032
+ return probePlaceName(file.decisionNames, file.decisionAliases, file.decisionWidths.length, "d", file.key, place);
2011
2033
  }
2012
2034
  function registerProbeV2(definition) {
2013
2035
  var _a8, _b;
2014
- const decisions = listedIds(definition.decisions);
2015
- const pointIds = listedIds(definition.pointIds);
2036
+ const pointCount = definition.points;
2037
+ const decisionCount = definition.decisionWidths.length;
2016
2038
  const file = {
2017
- // Each decision's id and its number of conditions: the module carries
2018
- // no source text, which the manifest holds.
2019
- decisions,
2039
+ key: definition.key,
2040
+ pointCount,
2041
+ pointNames: [],
2042
+ pointAliases: probeAliases(definition.pointAliases),
2043
+ decisionNames: [],
2044
+ decisionAliases: probeAliases(definition.decisionAliases),
2020
2045
  decisionWidths: definition.decisionWidths,
2021
- pointIds,
2022
2046
  clock: state.probeV2Clock,
2023
- hitEpochs: new Uint32Array(pointIds.length),
2047
+ hitEpochs: new Uint32Array(pointCount),
2048
+ // A narrow decision's vectors in an array, a wide one's in a Map, told
2049
+ // apart by `size`, which only the Map has: `instanceof Uint32Array` read
2050
+ // the global on every evaluation, and under Vitest's jsdom environment
2051
+ // each read is a getter call, most of a canvas app's measured unit time.
2024
2052
  decisionEpochs: definition.decisionWidths.map((width) => width <= 6 ? new Uint32Array(2 * 3 ** width) : /* @__PURE__ */ new Map()),
2025
- decisionVectorCounts: decisions.map((_, index) => {
2053
+ decisionVectorCounts: definition.decisionWidths.map((_, index) => {
2026
2054
  var _a9, _b2;
2027
2055
  return (_b2 = (_a9 = definition.decisionVectorCounts) == null ? void 0 : _a9[index]) != null ? _b2 : 0;
2028
2056
  }),
2029
- decisionObservationEpochs: new Uint32Array(decisions.length),
2030
- decisionObservationCounts: new Uint16Array(decisions.length),
2031
- decisionCompleteEpochs: new Uint32Array(decisions.length),
2057
+ decisionObservationEpochs: new Uint32Array(decisionCount),
2058
+ decisionObservationCounts: new Uint16Array(decisionCount),
2059
+ decisionCompleteEpochs: new Uint32Array(decisionCount),
2032
2060
  pendingDefaults: new Uint32Array(definition.defaultCount || 0),
2033
2061
  // A selection's outcomes -- short falsy, short truthy, right falsy, right
2034
2062
  // truthy -- are four consecutive points per site from the first index.
@@ -2066,7 +2094,7 @@ function coverageHitV2(file, index) {
2066
2094
  recordCoverageHitV2(file, index);
2067
2095
  }
2068
2096
  function recordCoverageHitV2(file, index) {
2069
- const id = file.pointIds[index];
2097
+ const id = probePointName(file, index);
2070
2098
  if (!id)
2071
2099
  return;
2072
2100
  const fallbackEpoch = !file.clock.fast;
@@ -2083,7 +2111,7 @@ function recordCoverageHitV2(file, index) {
2083
2111
  coverageHit(id);
2084
2112
  const selections = file.selectionPoints;
2085
2113
  if (selections !== void 0 && index >= selections[0] && index < selections[0] + 4 * selections[1])
2086
- recordSelectionOutcome(id, index - selections[0] & 3);
2114
+ recordLogicalOutcome(id, index - selections[0] & 3);
2087
2115
  } finally {
2088
2116
  if (fallbackEpoch)
2089
2117
  file.clock.epoch = previousEpoch;
@@ -2109,14 +2137,14 @@ function mcdcEndV2(file, decisionIndex, encoded, value) {
2109
2137
  const clock = file.clock;
2110
2138
  if (clock.fast) {
2111
2139
  const seen = file.decisionEpochs[decisionIndex];
2112
- if (seen instanceof Uint32Array && seen[encoded * 2 + (value ? 1 : 0)] === clock.epoch)
2140
+ if (seen !== void 0 && seen.size === void 0 && seen[encoded * 2 + (value ? 1 : 0)] === clock.epoch)
2113
2141
  return value;
2114
2142
  }
2115
2143
  return recordMcdcEndV2(file, decisionIndex, encoded, value);
2116
2144
  }
2117
2145
  function recordMcdcEndV2(file, decisionIndex, encoded, value) {
2118
2146
  var _a8, _b;
2119
- const id = file.decisions[decisionIndex];
2147
+ const id = probeDecisionName(file, decisionIndex);
2120
2148
  if (!id || !Number.isSafeInteger(encoded) || encoded < 0)
2121
2149
  return value;
2122
2150
  const outcome = Boolean(value);
@@ -2134,7 +2162,7 @@ function recordMcdcEndV2(file, decisionIndex, encoded, value) {
2134
2162
  const seen = file.decisionEpochs[decisionIndex];
2135
2163
  if (!seen)
2136
2164
  return value;
2137
- if (seen instanceof Uint32Array) {
2165
+ if (seen.size === void 0) {
2138
2166
  if (seen[vectorIndex] === epoch)
2139
2167
  return value;
2140
2168
  seen[vectorIndex] = epoch;
@@ -2208,8 +2236,12 @@ function recordSelectionOutcome(id, outcome) {
2208
2236
  branchId = separator > 0 ? id.slice(0, separator) : null;
2209
2237
  selectionBranchIds.set(id, branchId);
2210
2238
  }
2211
- if (branchId === null)
2212
- return;
2239
+ if (branchId !== null)
2240
+ recordLogicalOutcome(branchId, outcome);
2241
+ }
2242
+ // The outcomes of a selection by its branch id, or by the name of its point
2243
+ // that was hit, whose branch the report reads from the point's id.
2244
+ function recordLogicalOutcome(branchId, outcome) {
2213
2245
  let vectors = state.logicals.get(branchId);
2214
2246
  if (!vectors) {
2215
2247
  vectors = /* @__PURE__ */ new Map();
@@ -2467,22 +2499,10 @@ function mcdcEnd(frame, value) {
2467
2499
  const timestampMs = Date.now();
2468
2500
  const phaseId = currentPhaseId();
2469
2501
  if (isBrowser) {
2470
- if (recordBrowserEvent(__spreadProps(__spreadValues({
2471
- type: "decision",
2472
- id: decision.id,
2473
- vector,
2474
- timestampMs
2475
- }, phaseId ? { phaseId } : {}), {
2476
- environment: "browser"
2477
- })))
2502
+ if (recordBrowserEvent(decisionEvent(decision.id, vector, timestampMs, phaseId, "browser")))
2478
2503
  persistBrowser();
2479
2504
  } else {
2480
- appendServer(__spreadValues({
2481
- type: "decision",
2482
- id: decision.id,
2483
- vector,
2484
- timestampMs
2485
- }, phaseId ? { phaseId } : {}));
2505
+ appendServer(phaseId ? { type: "decision", id: decision.id, vector, timestampMs, phaseId } : { type: "decision", id: decision.id, vector, timestampMs });
2486
2506
  }
2487
2507
  return value;
2488
2508
  }
@@ -106,3 +106,44 @@ export function expandSnapshot(value) {
106
106
  snapshot[key] = key === "events" ? events : key === "hits" ? hits.map((index) => strings[index]) : rest[key];
107
107
  return snapshot;
108
108
  }
109
+ /**
110
+ * A snapshot's events as columns: each event's type, phase and environment
111
+ * as an index into a table of the distinct ones, its time as the difference
112
+ * from the event before it. The reader gives back the same events.
113
+ */
114
+ export function columnarEvents(snapshot) {
115
+ const events = snapshot?.events;
116
+ if (!Array.isArray(events) || events.length === 0)
117
+ return snapshot;
118
+ const tables = { types: new Map(), phases: new Map(), environments: new Map() };
119
+ const index = (table, value) => {
120
+ let found = table.get(value);
121
+ if (found === undefined) {
122
+ found = table.size;
123
+ table.set(value, found);
124
+ }
125
+ return found;
126
+ };
127
+ const columns = { id: [], type: [], phase: [], environment: [], t: [], vector: {} };
128
+ let previous = 0;
129
+ events.forEach((event, position) => {
130
+ columns.id.push(event.id);
131
+ columns.type.push(index(tables.types, event.type));
132
+ columns.phase.push(event.phaseId == null ? -1 : index(tables.phases, event.phaseId));
133
+ columns.environment.push(index(tables.environments, event.environment));
134
+ columns.t.push(event.timestampMs - previous);
135
+ previous = event.timestampMs;
136
+ if (event.vector !== undefined)
137
+ columns.vector[position] = event.vector;
138
+ });
139
+ const { events: _events, ...rest } = snapshot;
140
+ return {
141
+ ...rest,
142
+ eventColumns: {
143
+ types: [...tables.types.keys()],
144
+ phases: [...tables.phases.keys()],
145
+ environments: [...tables.environments.keys()],
146
+ ...columns,
147
+ },
148
+ };
149
+ }
@@ -4,6 +4,7 @@ import { afterEach, beforeEach } from "vitest";
4
4
  import { coverageSnapshot as localCoverageSnapshot, activateCoverageScope as localActivateCoverageScope, enableRuntimeSnapshotEvidence as localEnableRuntimeSnapshotEvidence, resetCoverage as localResetCoverage, takeNodeAssertionPhases as localTakeNodeAssertionPhases, } from "./runtime.mjs";
5
5
  import { inferTestProvenance, testTags } from "./provenance.mjs";
6
6
  import { appendEvidenceRecord } from "./atomic.mjs";
7
+ import { columnarEvents } from "./snapshots.mjs";
7
8
  const evidenceDirectory = process.env["SUPERCOV_EVIDENCE_DIR"];
8
9
  const emittedSetupFiles = new Set();
9
10
  const attempts = new Map();
@@ -66,7 +67,7 @@ beforeEach((context) => {
66
67
  explicitKind: process.env["SUPERCOV_TEST_KIND"],
67
68
  }),
68
69
  role: "setup",
69
- runtime: [setupSnapshot],
70
+ runtime: [columnarEvents(setupSnapshot)],
70
71
  browser: [],
71
72
  server: [],
72
73
  });
@@ -112,7 +113,10 @@ afterEach((context) => {
112
113
  tags: testTags(task.tags, [...titlePath(task)]),
113
114
  }),
114
115
  ...(scope ? { phases: runtime.takeNodeAssertionPhases(scope) } : {}),
115
- runtime: [runtime.coverageSnapshot()],
116
+ // Its events as columns, as Playwright's are written: a test's first
117
+ // hits written as objects repeated every key and phase for each, and
118
+ // serializing them was most of what a test's teardown cost.
119
+ runtime: [columnarEvents(runtime.coverageSnapshot())],
116
120
  browser: [],
117
121
  server: [],
118
122
  };