supercov 0.0.7 → 0.0.9

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 (78) hide show
  1. package/README.md +18 -1
  2. package/dist/agentJson.d.ts +1 -1
  3. package/dist/agentJson.d.ts.map +1 -1
  4. package/dist/agentJson.js.map +1 -1
  5. package/dist/analyze.d.ts.map +1 -1
  6. package/dist/analyze.js +0 -1
  7. package/dist/analyze.js.map +1 -1
  8. package/dist/cli.js +62 -10
  9. package/dist/cli.js.map +1 -1
  10. package/dist/directInstrumenter.d.ts +1 -1
  11. package/dist/directInstrumenter.d.ts.map +1 -1
  12. package/dist/directInstrumenter.js +30 -6
  13. package/dist/directInstrumenter.js.map +1 -1
  14. package/dist/instrumenter.d.ts.map +1 -1
  15. package/dist/instrumenter.js +107 -33
  16. package/dist/instrumenter.js.map +1 -1
  17. package/dist/integrity.d.ts.map +1 -1
  18. package/dist/integrity.js +11 -0
  19. package/dist/integrity.js.map +1 -1
  20. package/dist/nodeAssert.d.ts +31 -0
  21. package/dist/nodeAssert.d.ts.map +1 -0
  22. package/dist/nodeAssert.js +30 -0
  23. package/dist/nodeAssert.js.map +1 -0
  24. package/dist/nodeAssertAdapter.d.ts +6 -0
  25. package/dist/nodeAssertAdapter.d.ts.map +1 -0
  26. package/dist/nodeAssertAdapter.js +94 -0
  27. package/dist/nodeAssertAdapter.js.map +1 -0
  28. package/dist/nodeAssertStrict.d.ts +31 -0
  29. package/dist/nodeAssertStrict.d.ts.map +1 -0
  30. package/dist/nodeAssertStrict.js +28 -0
  31. package/dist/nodeAssertStrict.js.map +1 -0
  32. package/dist/nodeAssertionInstrumenter.d.ts +8 -0
  33. package/dist/nodeAssertionInstrumenter.d.ts.map +1 -0
  34. package/dist/nodeAssertionInstrumenter.js +263 -0
  35. package/dist/nodeAssertionInstrumenter.js.map +1 -0
  36. package/dist/nodeTest.d.ts.map +1 -1
  37. package/dist/nodeTest.js +6 -2
  38. package/dist/nodeTest.js.map +1 -1
  39. package/dist/playwright.d.ts.map +1 -1
  40. package/dist/playwright.js +8 -18
  41. package/dist/playwright.js.map +1 -1
  42. package/dist/project.d.ts +1 -0
  43. package/dist/project.d.ts.map +1 -1
  44. package/dist/project.js +4 -0
  45. package/dist/project.js.map +1 -1
  46. package/dist/query.d.ts +3 -2
  47. package/dist/query.d.ts.map +1 -1
  48. package/dist/query.js +74 -11
  49. package/dist/query.js.map +1 -1
  50. package/dist/register.mjs +46 -5
  51. package/dist/register.mjs.map +1 -1
  52. package/dist/resolve-loader.d.mts.map +1 -1
  53. package/dist/resolve-loader.mjs +20 -0
  54. package/dist/resolve-loader.mjs.map +1 -1
  55. package/dist/runAnalysis.d.ts.map +1 -1
  56. package/dist/runAnalysis.js +37 -18
  57. package/dist/runAnalysis.js.map +1 -1
  58. package/dist/runnerEvidence.d.ts +2 -2
  59. package/dist/runnerEvidence.d.ts.map +1 -1
  60. package/dist/runnerEvidence.js +3 -2
  61. package/dist/runnerEvidence.js.map +1 -1
  62. package/dist/runtime.d.ts +37 -1
  63. package/dist/runtime.d.ts.map +1 -1
  64. package/dist/runtime.js +713 -526
  65. package/dist/runtime.js.map +1 -1
  66. package/dist/runtimeIsolation.d.ts +3 -0
  67. package/dist/runtimeIsolation.d.ts.map +1 -0
  68. package/dist/runtimeIsolation.js +9 -0
  69. package/dist/runtimeIsolation.js.map +1 -0
  70. package/dist/sourceDiscovery.d.ts.map +1 -1
  71. package/dist/sourceDiscovery.js +11 -0
  72. package/dist/sourceDiscovery.js.map +1 -1
  73. package/dist/types.d.ts +2 -0
  74. package/dist/types.d.ts.map +1 -1
  75. package/dist/workspace.d.ts.map +1 -1
  76. package/dist/workspace.js +4 -1
  77. package/dist/workspace.js.map +1 -1
  78. package/package.json +2 -2
package/dist/runtime.js CHANGED
@@ -1,591 +1,778 @@
1
- import { backgroundEvidenceDirectory, backgroundEvidencePath, COVERAGE_CARRIER_ENV, COVERAGE_PHASE_HEADER, COVERAGE_PHASE_COOKIE, COVERAGE_SCOPE_COOKIE, COVERAGE_SCOPE_HEADER, decodeCoverageCarrier, decodeCoverageScope, encodeCoverageCarrier, encodeCoverageScope, serverEvidenceDirectory, serverEvidencePath, } from "./transport.js";
2
- const runtimeGlobal = globalThis;
3
- const runtimeInstanceToken = "__SUPERCOV_RUNTIME_INSTANCE__";
4
- const runtimeInstance = runtimeInstanceToken === "__SUPERCOV_" + "RUNTIME_INSTANCE__"
5
- ? "application"
6
- : runtimeInstanceToken;
7
- const isBrowser = !(typeof process !== "undefined" &&
8
- typeof process.versions?.node === "string");
9
- const testId = runtimeGlobal.__SUPERCOV_MCDC_TEST_ID__ ?? "unscoped";
10
- const storageKey = "__supercov_coverage_" + testId;
11
- const phaseStorageKey = "__supercov_phase";
12
- const pendingDefaults = new Map();
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+
21
+ // dist/transport.js
22
+ var COVERAGE_SCOPE_HEADER = "x-supercov-scope";
23
+ var COVERAGE_PHASE_HEADER = "x-supercov-phase";
24
+ var COVERAGE_SCOPE_COOKIE = "__supercov_scope";
25
+ var COVERAGE_PHASE_COOKIE = "__supercov_phase";
26
+ var COVERAGE_CARRIER_ENV = "SUPERCOV_CONTEXT";
27
+ var DEFAULT_SERVER_EVIDENCE_ROOT = "/tmp/supercov-server-evidence";
28
+ function configuredServerEvidenceRoot() {
29
+ var _a8;
30
+ return typeof process !== "undefined" && ((_a8 = process.env) == null ? void 0 : _a8["SUPERCOV_SERVER_EVIDENCE_ROOT"]) ? process.env["SUPERCOV_SERVER_EVIDENCE_ROOT"] : DEFAULT_SERVER_EVIDENCE_ROOT;
31
+ }
32
+ function nonEmpty(value) {
33
+ return typeof value === "string" && value.length > 0;
34
+ }
35
+ function safeKey(value) {
36
+ return /^[a-zA-Z0-9_-]+$/.test(value);
37
+ }
38
+ function pathComponent(value) {
39
+ const safe = value.replace(/[^a-zA-Z0-9_-]/g, "_");
40
+ return safe || "unscoped";
41
+ }
42
+ function encodeCoverageScope(scope) {
43
+ return new URLSearchParams({
44
+ v: String(scope.version),
45
+ r: scope.runId,
46
+ w: scope.workerId,
47
+ t: scope.testId,
48
+ k: scope.testKey,
49
+ a: String(scope.retry),
50
+ i: scope.attemptId
51
+ }).toString();
52
+ }
53
+ function decodeCoverageScope(encoded) {
54
+ if (!encoded)
55
+ return void 0;
56
+ try {
57
+ const values = new URLSearchParams(encoded);
58
+ const runId = values.get("r");
59
+ const workerId = values.get("w");
60
+ const testId2 = values.get("t");
61
+ const testKey = values.get("k");
62
+ const attemptId = values.get("i");
63
+ const retry = Number(values.get("a"));
64
+ if (values.get("v") !== "1" || !nonEmpty(runId) || !nonEmpty(workerId) || !nonEmpty(testId2) || !nonEmpty(testKey) || !safeKey(testKey) || !nonEmpty(attemptId) || !safeKey(attemptId) || !Number.isSafeInteger(retry) || retry < 0)
65
+ return void 0;
66
+ return {
67
+ version: 1,
68
+ runId,
69
+ workerId,
70
+ testId: testId2,
71
+ testKey,
72
+ retry,
73
+ attemptId
74
+ };
75
+ } catch (e) {
76
+ return void 0;
77
+ }
78
+ }
79
+ function encodeCoverageCarrier(carrier) {
80
+ return Buffer.from(JSON.stringify(carrier), "utf8").toString("base64url");
81
+ }
82
+ function decodeCoverageCarrier(encoded) {
83
+ if (!encoded)
84
+ return void 0;
85
+ try {
86
+ const value = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
87
+ if (value.version !== 1)
88
+ return void 0;
89
+ if (value.scope) {
90
+ const roundTrip = decodeCoverageScope(encodeCoverageScope(value.scope));
91
+ if (!roundTrip)
92
+ return void 0;
93
+ }
94
+ if (value.phaseId !== void 0 && value.phaseId.length === 0)
95
+ return void 0;
96
+ return value;
97
+ } catch (e) {
98
+ return void 0;
99
+ }
100
+ }
101
+ function serverRunEvidenceDirectory(runId, root = configuredServerEvidenceRoot()) {
102
+ return `${root.replace(/\/+$/, "")}/${pathComponent(runId)}`;
103
+ }
104
+ function serverEvidenceDirectory(scope, root = configuredServerEvidenceRoot()) {
105
+ return `${serverRunEvidenceDirectory(scope.runId, root)}/${pathComponent(scope.workerId)}/${scope.testKey}/${scope.retry}`;
106
+ }
107
+ function serverEvidencePath(scope, root = configuredServerEvidenceRoot()) {
108
+ return `${serverEvidenceDirectory(scope, root)}/server.jsonl`;
109
+ }
110
+ function backgroundEvidenceDirectory(runId, root = configuredServerEvidenceRoot()) {
111
+ return `${serverRunEvidenceDirectory(runId, root)}/background`;
112
+ }
113
+ function backgroundEvidencePath(runId, processId = typeof process === "undefined" ? "unknown" : String(process.pid), root = configuredServerEvidenceRoot()) {
114
+ return `${backgroundEvidenceDirectory(runId, root)}/${pathComponent(processId)}.jsonl`;
115
+ }
116
+
117
+ // dist/runtime.js
118
+ var runtimeGlobal = globalThis;
119
+ var runtimeInstanceToken = "__SUPERCOV_RUNTIME_INSTANCE__";
120
+ var runtimeInstance = runtimeInstanceToken === "__SUPERCOV_RUNTIME_INSTANCE__" ? "application" : runtimeInstanceToken;
121
+ var _a;
122
+ var isBrowser = !(typeof process !== "undefined" && typeof ((_a = process.versions) == null ? void 0 : _a.node) === "string");
123
+ var _a2;
124
+ var testId = (_a2 = runtimeGlobal.__SUPERCOV_MCDC_TEST_ID__) != null ? _a2 : "unscoped";
125
+ var storageKey = "__supercov_coverage_" + testId;
126
+ var phaseStorageKey = "__supercov_phase";
127
+ var pendingDefaults = /* @__PURE__ */ new Map();
13
128
  function vectorKey(vector) {
14
- return (vector.values
15
- .map((value) => (value === null ? "-" : value ? "T" : "F"))
16
- .join("") +
17
- ":" +
18
- (vector.outcome ? "T" : "F"));
129
+ return vector.values.map((value) => value === null ? "-" : value ? "T" : "F").join("") + ":" + (vector.outcome ? "T" : "F");
19
130
  }
20
131
  function getFs() {
21
- if (isBrowser || typeof process === "undefined")
22
- return undefined;
23
- try {
24
- const getBuiltinModule = process.getBuiltinModule;
25
- return getBuiltinModule?.("node:fs");
26
- }
27
- catch {
28
- return undefined;
29
- }
132
+ if (isBrowser || typeof process === "undefined")
133
+ return void 0;
134
+ try {
135
+ const getBuiltinModule = process.getBuiltinModule;
136
+ return getBuiltinModule == null ? void 0 : getBuiltinModule("node:fs");
137
+ } catch (e) {
138
+ return void 0;
139
+ }
30
140
  }
31
141
  function createState() {
32
- const state = {
33
- decisions: new Map(),
34
- hits: new Set(),
35
- events: [],
36
- eventKeys: new Set(),
37
- bufferedAttempts: new Set(),
38
- serverBuffers: new Map(),
39
- runtimeSnapshots: false,
40
- };
41
- if (!isBrowser)
42
- return state;
43
- try {
44
- const stored = JSON.parse(localStorage.getItem(storageKey) ?? "{}");
45
- for (const snapshot of stored.decisions ?? []) {
46
- state.decisions.set(snapshot.meta.id, {
47
- meta: snapshot.meta,
48
- vectors: new Map(snapshot.vectors.map((vector) => [vectorKey(vector), vector])),
49
- });
50
- }
51
- for (const id of stored.hits ?? [])
52
- state.hits.add(id);
53
- for (const event of stored.events ?? []) {
54
- state.events.push(event);
55
- state.eventKeys.add(eventKey(event));
56
- }
142
+ var _a8, _b, _c, _d;
143
+ const state2 = {
144
+ decisions: /* @__PURE__ */ new Map(),
145
+ hits: /* @__PURE__ */ new Set(),
146
+ events: [],
147
+ eventKeys: /* @__PURE__ */ new Set(),
148
+ bufferedAttempts: /* @__PURE__ */ new Set(),
149
+ serverBuffers: /* @__PURE__ */ new Map(),
150
+ persistedServerRecords: /* @__PURE__ */ new Set(),
151
+ backgroundSequence: 0,
152
+ runtimeSnapshots: false,
153
+ assertionPhases: /* @__PURE__ */ new Map()
154
+ };
155
+ if (!isBrowser)
156
+ return state2;
157
+ try {
158
+ const stored = JSON.parse((_a8 = localStorage.getItem(storageKey)) != null ? _a8 : "{}");
159
+ for (const snapshot of (_b = stored.decisions) != null ? _b : []) {
160
+ state2.decisions.set(snapshot.meta.id, {
161
+ meta: snapshot.meta,
162
+ vectors: new Map(snapshot.vectors.map((vector) => [vectorKey(vector), vector]))
163
+ });
57
164
  }
58
- catch {
59
- // Corrupt or unavailable storage must not affect application execution.
165
+ for (const id of (_c = stored.hits) != null ? _c : [])
166
+ state2.hits.add(id);
167
+ for (const event of (_d = stored.events) != null ? _d : []) {
168
+ state2.events.push(event);
169
+ state2.eventKeys.add(eventKey(event));
60
170
  }
61
- return state;
171
+ } catch (e) {
172
+ }
173
+ return state2;
62
174
  }
63
- const runtimeStates = runtimeGlobal.__SUPERCOV_MCDC_STATES__ ?? new Map();
175
+ var _a3;
176
+ var runtimeStates = (_a3 = runtimeGlobal.__SUPERCOV_MCDC_STATES__) != null ? _a3 : /* @__PURE__ */ new Map();
64
177
  runtimeGlobal.__SUPERCOV_MCDC_STATES__ = runtimeStates;
65
- const state = runtimeStates.get(runtimeInstance) ?? createState();
178
+ var _a4;
179
+ var state = (_a4 = runtimeStates.get(runtimeInstance)) != null ? _a4 : createState();
66
180
  runtimeStates.set(runtimeInstance, state);
67
181
  function createServerPhaseStorage() {
68
- if (isBrowser || typeof process === "undefined")
69
- return undefined;
70
- try {
71
- const getBuiltinModule = process.getBuiltinModule;
72
- const AsyncLocalStorage = getBuiltinModule?.("node:async_hooks")?.AsyncLocalStorage;
73
- return AsyncLocalStorage ? new AsyncLocalStorage() : undefined;
74
- }
75
- catch {
76
- return undefined;
77
- }
78
- }
79
- const serverPhaseStorages = runtimeGlobal.__SUPERCOV_SERVER_PHASE_STORAGES__ ?? new Map();
182
+ var _a8;
183
+ if (isBrowser || typeof process === "undefined")
184
+ return void 0;
185
+ try {
186
+ const getBuiltinModule = process.getBuiltinModule;
187
+ const AsyncLocalStorage = (_a8 = getBuiltinModule == null ? void 0 : getBuiltinModule("node:async_hooks")) == null ? void 0 : _a8.AsyncLocalStorage;
188
+ return AsyncLocalStorage ? new AsyncLocalStorage() : void 0;
189
+ } catch (e) {
190
+ return void 0;
191
+ }
192
+ }
193
+ var _a5;
194
+ var serverPhaseStorages = (_a5 = runtimeGlobal.__SUPERCOV_SERVER_PHASE_STORAGES__) != null ? _a5 : /* @__PURE__ */ new Map();
80
195
  runtimeGlobal.__SUPERCOV_SERVER_PHASE_STORAGES__ = serverPhaseStorages;
81
- const serverPhaseStorage = serverPhaseStorages.get(runtimeInstance) ?? createServerPhaseStorage();
196
+ var _a6;
197
+ var serverPhaseStorage = (_a6 = serverPhaseStorages.get(runtimeInstance)) != null ? _a6 : createServerPhaseStorage();
82
198
  if (serverPhaseStorage)
83
- serverPhaseStorages.set(runtimeInstance, serverPhaseStorage);
199
+ serverPhaseStorages.set(runtimeInstance, serverPhaseStorage);
84
200
  function decisionSnapshot() {
85
- return [...state.decisions.values()].map((decision) => ({
86
- meta: decision.meta,
87
- vectors: [...decision.vectors.values()],
88
- }));
89
- }
90
- export function coverageSnapshot() {
91
- return {
92
- decisions: decisionSnapshot(),
93
- hits: [...state.hits],
94
- events: state.events,
95
- };
96
- }
97
- export function resetCoverage(testId) {
98
- state.decisions.clear();
99
- state.hits.clear();
100
- state.events.length = 0;
101
- state.eventKeys.clear();
102
- if (testId)
103
- runtimeGlobal.__SUPERCOV_MCDC_TEST_ID__ = testId;
104
- if (isBrowser) {
105
- try {
106
- localStorage.removeItem(storageKey);
107
- }
108
- catch {
109
- // Storage is optional in test environments.
110
- }
201
+ return [...state.decisions.values()].map((decision) => ({
202
+ meta: decision.meta,
203
+ vectors: [...decision.vectors.values()]
204
+ }));
205
+ }
206
+ function coverageSnapshot() {
207
+ return {
208
+ decisions: decisionSnapshot(),
209
+ hits: [...state.hits],
210
+ events: state.events
211
+ };
212
+ }
213
+ function resetCoverage(testId2) {
214
+ state.decisions.clear();
215
+ state.hits.clear();
216
+ state.events.length = 0;
217
+ state.eventKeys.clear();
218
+ if (testId2)
219
+ runtimeGlobal.__SUPERCOV_MCDC_TEST_ID__ = testId2;
220
+ if (isBrowser) {
221
+ try {
222
+ localStorage.removeItem(storageKey);
223
+ } catch (e) {
111
224
  }
225
+ }
112
226
  }
113
227
  runtimeGlobal.__SUPERCOV_MCDC_SNAPSHOT__ = decisionSnapshot;
114
228
  runtimeGlobal.__SUPERCOV_COVERAGE_SNAPSHOT__ = coverageSnapshot;
115
229
  runtimeGlobal.__SUPERCOV_RESET__ = resetCoverage;
116
230
  function persistBrowser() {
117
- if (!isBrowser)
118
- return;
119
- try {
120
- localStorage.setItem(storageKey, JSON.stringify(coverageSnapshot()));
121
- }
122
- catch {
123
- // Coverage persistence is best-effort and must never change app behavior.
124
- }
231
+ if (!isBrowser)
232
+ return;
233
+ try {
234
+ localStorage.setItem(storageKey, JSON.stringify(coverageSnapshot()));
235
+ } catch (e) {
236
+ }
125
237
  }
126
238
  function attemptKey(scope) {
127
- return `${scope.runId}\0${scope.workerId}\0${scope.attemptId}`;
239
+ return `${scope.runId}\0${scope.workerId}\0${scope.attemptId}`;
128
240
  }
129
241
  function serverRecordKey(record) {
130
- const suffix = record.type === "decision"
131
- ? `${record.meta.id}:${vectorKey(record.vector)}`
132
- : record.id;
133
- return `${record.phaseId ?? "unscoped"}:${record.type}:${suffix}`;
134
- }
135
- /** Buffer and de-duplicate local Node evidence until its test attempt ends. */
136
- export function beginBufferedServerEvidence(scope) {
137
- if (isBrowser)
138
- return;
139
- state.bufferedAttempts.add(attemptKey(scope));
140
- }
141
- /** Publish one local test attempt with one filesystem append. */
142
- export function flushBufferedServerEvidence(scope) {
143
- if (isBrowser)
144
- return;
145
- const key = attemptKey(scope);
146
- state.bufferedAttempts.delete(key);
147
- const buffered = state.serverBuffers.get(key);
148
- if (!buffered)
149
- return;
150
- state.serverBuffers.delete(key);
151
- const fs = getFs();
152
- if (!fs || buffered.records.size === 0)
153
- return;
154
- try {
155
- fs.mkdirSync(buffered.directory, { recursive: true });
156
- fs.appendFileSync(buffered.path, [...buffered.records.values()]
157
- .map((record) => JSON.stringify(record))
158
- .join("\n") + "\n");
159
- }
160
- catch {
161
- // Collection is best-effort and must never change test behavior.
162
- }
163
- }
164
- /** A local runner will persist coverageSnapshot(), so avoid duplicate files. */
165
- export function enableRuntimeSnapshotEvidence() {
166
- state.runtimeSnapshots = true;
242
+ var _a8;
243
+ const suffix = record.type === "decision" ? `${record.meta.id}:${vectorKey(record.vector)}` : record.id;
244
+ return `${(_a8 = record.phaseId) != null ? _a8 : "unscoped"}:${record.type}:${suffix}`;
245
+ }
246
+ function beginBufferedServerEvidence(scope) {
247
+ if (isBrowser)
248
+ return;
249
+ state.bufferedAttempts.add(attemptKey(scope));
250
+ }
251
+ function flushBufferedServerEvidence(scope) {
252
+ if (isBrowser)
253
+ return;
254
+ const key = attemptKey(scope);
255
+ state.bufferedAttempts.delete(key);
256
+ const buffered = state.serverBuffers.get(key);
257
+ if (!buffered)
258
+ return;
259
+ state.serverBuffers.delete(key);
260
+ const fs = getFs();
261
+ if (!fs || buffered.records.size === 0)
262
+ return;
263
+ try {
264
+ fs.mkdirSync(buffered.directory, { recursive: true });
265
+ fs.appendFileSync(buffered.path, [...buffered.records.values()].map((record) => JSON.stringify(record)).join("\n") + "\n");
266
+ } catch (e) {
267
+ }
268
+ }
269
+ function enableRuntimeSnapshotEvidence() {
270
+ state.runtimeSnapshots = true;
167
271
  }
168
272
  function flushAllBufferedServerEvidence() {
169
- for (const buffered of [...state.serverBuffers.values()])
170
- flushBufferedServerEvidence(buffered.scope);
273
+ for (const buffered of [...state.serverBuffers.values()])
274
+ flushBufferedServerEvidence(buffered.scope);
171
275
  }
172
- if (!isBrowser) {
173
- const flushers = runtimeGlobal.__SUPERCOV_BUFFER_FLUSHERS__ ?? new Set();
174
- runtimeGlobal.__SUPERCOV_BUFFER_FLUSHERS__ = flushers;
175
- flushers.add(flushAllBufferedServerEvidence);
176
- if (!runtimeGlobal.__SUPERCOV_BUFFER_EXIT_INSTALLED__) {
177
- process.once("exit", () => {
178
- for (const flush of runtimeGlobal.__SUPERCOV_BUFFER_FLUSHERS__ ?? [])
179
- flush();
180
- });
181
- runtimeGlobal.__SUPERCOV_BUFFER_EXIT_INSTALLED__ = true;
276
+ function writeExclusiveBackgroundRecord(fs, runId, writer, initialSequence, payload) {
277
+ let sequence = initialSequence;
278
+ for (let attempt = 0; attempt < 1e4; attempt += 1) {
279
+ const candidate = backgroundEvidencePath(runId, `${writer}-${sequence++}`);
280
+ try {
281
+ fs.writeFileSync(candidate, payload, { flag: "wx" });
282
+ return sequence;
283
+ } catch (error) {
284
+ if (error.code === "EEXIST")
285
+ continue;
286
+ throw error;
182
287
  }
288
+ }
289
+ throw Object.assign(new Error("Could not allocate a collision-free Supercov background evidence record"), { code: "SUPERCOV_BACKGROUND_COLLISION_LIMIT" });
290
+ }
291
+ var _a7;
292
+ if (!isBrowser) {
293
+ const flushers = (_a7 = runtimeGlobal.__SUPERCOV_BUFFER_FLUSHERS__) != null ? _a7 : /* @__PURE__ */ new Set();
294
+ runtimeGlobal.__SUPERCOV_BUFFER_FLUSHERS__ = flushers;
295
+ flushers.add(flushAllBufferedServerEvidence);
296
+ if (!runtimeGlobal.__SUPERCOV_BUFFER_EXIT_INSTALLED__) {
297
+ process.once("exit", () => {
298
+ var _a8;
299
+ for (const flush of (_a8 = runtimeGlobal.__SUPERCOV_BUFFER_FLUSHERS__) != null ? _a8 : [])
300
+ flush();
301
+ });
302
+ runtimeGlobal.__SUPERCOV_BUFFER_EXIT_INSTALLED__ = true;
303
+ }
183
304
  }
184
305
  function appendServer(record) {
185
- if (state.runtimeSnapshots)
186
- return;
187
- const fs = getFs();
188
- if (!fs)
189
- return;
190
- const context = currentRequestContext();
191
- const scope = context.scope;
192
- const runId = scope?.runId ??
193
- (typeof process !== "undefined"
194
- ? process.env["SUPERCOV_RUN_ID"]
195
- : undefined);
196
- if (!runId)
197
- return;
198
- try {
199
- const directory = scope
200
- ? serverEvidenceDirectory(scope)
201
- : backgroundEvidenceDirectory(runId);
202
- const path = scope
203
- ? serverEvidencePath(scope)
204
- : backgroundEvidencePath(runId);
205
- const serialized = { ...record, ...(scope ? { scope } : {}) };
206
- if (scope && state.bufferedAttempts.has(attemptKey(scope))) {
207
- const key = attemptKey(scope);
208
- const buffered = state.serverBuffers.get(key) ?? {
209
- scope,
210
- directory,
211
- path,
212
- records: new Map(),
213
- };
214
- buffered.records.set(serverRecordKey(serialized), serialized);
215
- state.serverBuffers.set(key, buffered);
216
- return;
217
- }
218
- fs.mkdirSync(directory, { recursive: true });
219
- fs.appendFileSync(path, JSON.stringify(serialized) + "\n");
306
+ var _a8, _b, _c;
307
+ if (state.runtimeSnapshots)
308
+ return;
309
+ const fs = getFs();
310
+ if (!fs)
311
+ return;
312
+ const context = currentRequestContext();
313
+ const scope = context.scope;
314
+ const runId = (_a8 = scope == null ? void 0 : scope.runId) != null ? _a8 : typeof process !== "undefined" ? process.env["SUPERCOV_RUN_ID"] : void 0;
315
+ if (!runId)
316
+ return;
317
+ try {
318
+ const directory = scope ? serverEvidenceDirectory(scope) : backgroundEvidenceDirectory(runId);
319
+ const path = scope ? serverEvidencePath(scope) : void 0;
320
+ const serialized = __spreadValues(__spreadValues({}, record), scope ? { scope } : {});
321
+ if (scope && state.bufferedAttempts.has(attemptKey(scope))) {
322
+ const key = attemptKey(scope);
323
+ const buffered = (_b = state.serverBuffers.get(key)) != null ? _b : {
324
+ scope,
325
+ directory,
326
+ path,
327
+ records: /* @__PURE__ */ new Map()
328
+ };
329
+ buffered.records.set(serverRecordKey(serialized), serialized);
330
+ state.serverBuffers.set(key, buffered);
331
+ return;
220
332
  }
221
- catch {
222
- // The instrumented build must remain behaviorally identical if collection fails.
333
+ const deduplicationKey = scope && serialized.phaseId ? `${attemptKey(scope)}:${serverRecordKey(serialized)}` : void 0;
334
+ if (deduplicationKey && state.persistedServerRecords.has(deduplicationKey))
335
+ return;
336
+ fs.mkdirSync(directory, { recursive: true });
337
+ if (!path) {
338
+ const shard = (_c = process.env["SUPERCOV_EXECUTION_LOG_SHARD"]) != null ? _c : "process";
339
+ const writer = `${shard}-${process.pid}`;
340
+ const payload = JSON.stringify(serialized) + "\n";
341
+ state.backgroundSequence = writeExclusiveBackgroundRecord(fs, runId, writer, state.backgroundSequence, payload);
342
+ return;
223
343
  }
344
+ fs.appendFileSync(path, JSON.stringify(serialized) + "\n");
345
+ if (deduplicationKey)
346
+ state.persistedServerRecords.add(deduplicationKey);
347
+ } catch (e) {
348
+ }
224
349
  }
225
350
  function environmentRequestContext() {
226
- if (isBrowser || typeof process === "undefined")
227
- return undefined;
228
- const carrier = decodeCoverageCarrier(process.env[COVERAGE_CARRIER_ENV]);
229
- return carrier
230
- ? {
231
- ...(carrier.scope ? { scope: carrier.scope } : {}),
232
- ...(carrier.phaseId ? { phaseId: carrier.phaseId } : {}),
233
- }
234
- : undefined;
351
+ if (isBrowser || typeof process === "undefined")
352
+ return void 0;
353
+ const carrier = decodeCoverageCarrier(process.env[COVERAGE_CARRIER_ENV]);
354
+ return carrier ? __spreadValues(__spreadValues({}, carrier.scope ? { scope: carrier.scope } : {}), carrier.phaseId ? { phaseId: carrier.phaseId } : {}) : void 0;
235
355
  }
236
356
  function currentRequestContext() {
237
- return serverPhaseStorage?.getStore() ?? environmentRequestContext() ?? {};
238
- }
239
- export function coverageCarrier() {
240
- const context = currentRequestContext();
241
- return {
242
- version: 1,
243
- ...(context.scope ? { scope: context.scope } : {}),
244
- ...(context.phaseId ? { phaseId: context.phaseId } : {}),
245
- };
246
- }
247
- export function withCoverageCarrier(carrier, callback) {
248
- const decoded = typeof carrier === "string" ? decodeCoverageCarrier(carrier) : carrier;
249
- if (!serverPhaseStorage || !decoded)
250
- return callback();
251
- return serverPhaseStorage.run({
252
- ...(decoded.scope ? { scope: decoded.scope } : {}),
253
- ...(decoded.phaseId ? { phaseId: decoded.phaseId } : {}),
254
- }, callback);
255
- }
256
- export function bindCoverageContext(callback, carrier = coverageCarrier()) {
257
- return function boundCoverageContext(...args) {
258
- return withCoverageCarrier(carrier, () => Reflect.apply(callback, this, args));
259
- };
260
- }
261
- export function coverageContextHeaders() {
262
- const context = currentRequestContext();
263
- if (!context.scope)
264
- return {};
265
- return {
266
- [COVERAGE_SCOPE_HEADER]: encodeCoverageScope(context.scope),
267
- ...(context.phaseId
268
- ? { [COVERAGE_PHASE_HEADER]: context.phaseId }
269
- : {}),
270
- };
271
- }
272
- export function coverageContextEnvironment() {
273
- return { [COVERAGE_CARRIER_ENV]: encodeCoverageCarrier(coverageCarrier()) };
357
+ var _a8, _b;
358
+ return (_b = (_a8 = serverPhaseStorage == null ? void 0 : serverPhaseStorage.getStore()) != null ? _a8 : environmentRequestContext()) != null ? _b : {};
359
+ }
360
+ function coverageCarrier() {
361
+ const context = currentRequestContext();
362
+ return __spreadValues(__spreadValues({
363
+ version: 1
364
+ }, context.scope ? { scope: context.scope } : {}), context.phaseId ? { phaseId: context.phaseId } : {});
365
+ }
366
+ function withCoverageCarrier(carrier, callback) {
367
+ const decoded = typeof carrier === "string" ? decodeCoverageCarrier(carrier) : carrier;
368
+ if (!serverPhaseStorage || !decoded)
369
+ return callback();
370
+ return serverPhaseStorage.run(__spreadValues(__spreadValues({}, decoded.scope ? { scope: decoded.scope } : {}), decoded.phaseId ? { phaseId: decoded.phaseId } : {}), callback);
371
+ }
372
+ function assertionPhaseState(scope) {
373
+ const key = attemptKey(scope);
374
+ const existing = state.assertionPhases.get(key);
375
+ if (existing)
376
+ return existing;
377
+ const created = { counter: 0, phases: [] };
378
+ state.assertionPhases.set(key, created);
379
+ return created;
380
+ }
381
+ function finishAssertionPhase(phase, error) {
382
+ phase.endedAtMs = Date.now();
383
+ phase.status = error === void 0 ? "passed" : "failed";
384
+ if (error !== void 0)
385
+ phase.error = error instanceof Error ? error.message : String(error);
386
+ }
387
+ function withNodeAssertionPhase(operation, source, callback) {
388
+ const context = currentRequestContext();
389
+ const scope = context.scope;
390
+ if (!scope)
391
+ return callback();
392
+ const existing = context.phaseId ? assertionPhaseState(scope).phases.find((phase2) => phase2.id === context.phaseId && phase2.kind === "assertion") : void 0;
393
+ if (existing)
394
+ return callback();
395
+ const attempt = assertionPhaseState(scope);
396
+ const phase = __spreadProps(__spreadValues({
397
+ id: `${scope.attemptId}:phase:${++attempt.counter}`,
398
+ kind: "assertion",
399
+ operation
400
+ }, source ? { source } : {}), {
401
+ startedAtMs: Date.now()
402
+ });
403
+ attempt.phases.push(phase);
404
+ try {
405
+ const result = withCoverageCarrier({ version: 1, scope, phaseId: phase.id }, callback);
406
+ if (result && typeof result.then === "function")
407
+ return Promise.resolve(result).then((value) => {
408
+ finishAssertionPhase(phase);
409
+ return value;
410
+ }, (error) => {
411
+ finishAssertionPhase(phase, error);
412
+ throw error;
413
+ });
414
+ finishAssertionPhase(phase);
415
+ return result;
416
+ } catch (error) {
417
+ finishAssertionPhase(phase, error);
418
+ throw error;
419
+ }
420
+ }
421
+ function takeNodeAssertionPhases(scope) {
422
+ var _a8, _b;
423
+ const key = attemptKey(scope);
424
+ const phases = (_b = (_a8 = state.assertionPhases.get(key)) == null ? void 0 : _a8.phases) != null ? _b : [];
425
+ state.assertionPhases.delete(key);
426
+ return phases;
427
+ }
428
+ function bindCoverageContext(callback, carrier = coverageCarrier()) {
429
+ return function boundCoverageContext(...args) {
430
+ return withCoverageCarrier(carrier, () => Reflect.apply(callback, this, args));
431
+ };
432
+ }
433
+ function coverageContextHeaders() {
434
+ const context = currentRequestContext();
435
+ if (!context.scope)
436
+ return {};
437
+ return __spreadValues({
438
+ [COVERAGE_SCOPE_HEADER]: encodeCoverageScope(context.scope)
439
+ }, context.phaseId ? { [COVERAGE_PHASE_HEADER]: context.phaseId } : {});
440
+ }
441
+ function coverageContextEnvironment() {
442
+ return { [COVERAGE_CARRIER_ENV]: encodeCoverageCarrier(coverageCarrier()) };
274
443
  }
275
444
  function installServerFetchPropagation() {
276
- if (isBrowser ||
277
- runtimeGlobal.__SUPERCOV_FETCH_PATCHED__ ||
278
- typeof globalThis.fetch !== "function")
279
- return;
280
- const originalFetch = globalThis.fetch.bind(globalThis);
281
- globalThis.fetch = ((input, init) => {
282
- const coverage = coverageContextHeaders();
283
- if (Object.keys(coverage).length === 0)
284
- return originalFetch(input, init);
285
- const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
286
- for (const [name, value] of Object.entries(coverage))
287
- headers.set(name, value);
288
- return originalFetch(input, { ...init, headers });
289
- });
290
- runtimeGlobal.__SUPERCOV_FETCH_PATCHED__ = true;
445
+ if (isBrowser || runtimeGlobal.__SUPERCOV_FETCH_PATCHED__ || typeof globalThis.fetch !== "function")
446
+ return;
447
+ const originalFetch = globalThis.fetch.bind(globalThis);
448
+ globalThis.fetch = ((input, init) => {
449
+ var _a8;
450
+ const coverage = coverageContextHeaders();
451
+ if (Object.keys(coverage).length === 0)
452
+ return originalFetch(input, init);
453
+ const headers = new Headers((_a8 = init == null ? void 0 : init.headers) != null ? _a8 : input instanceof Request ? input.headers : void 0);
454
+ for (const [name, value] of Object.entries(coverage))
455
+ headers.set(name, value);
456
+ return originalFetch(input, __spreadProps(__spreadValues({}, init), { headers }));
457
+ });
458
+ runtimeGlobal.__SUPERCOV_FETCH_PATCHED__ = true;
291
459
  }
292
460
  installServerFetchPropagation();
293
461
  function installServerChildPropagation() {
294
- if (isBrowser ||
295
- runtimeGlobal.__SUPERCOV_CHILD_PATCHED__ ||
296
- typeof process === "undefined")
297
- return;
298
- const getBuiltinModule = process.getBuiltinModule;
299
- const child = getBuiltinModule?.("node:child_process");
300
- if (!child)
301
- return;
302
- const mutableChild = child;
303
- const optionIndex = (method, args) => {
304
- if (method === "spawn" ||
305
- method === "spawnSync" ||
306
- method === "fork" ||
307
- method === "execFile" ||
308
- method === "execFileSync")
309
- return Array.isArray(args[1]) || (args.length > 2 && args[2] !== undefined)
310
- ? 2
311
- : 1;
312
- return 1;
462
+ var _a8;
463
+ if (isBrowser || runtimeGlobal.__SUPERCOV_CHILD_PATCHED__ || typeof process === "undefined")
464
+ return;
465
+ const getBuiltinModule = process.getBuiltinModule;
466
+ const child = getBuiltinModule == null ? void 0 : getBuiltinModule("node:child_process");
467
+ if (!child)
468
+ return;
469
+ const mutableChild = child;
470
+ const optionIndex = (method, args) => {
471
+ if (method === "spawn" || method === "spawnSync" || method === "fork" || method === "execFile" || method === "execFileSync")
472
+ return Array.isArray(args[1]) || args.length > 2 && args[2] !== void 0 ? 2 : 1;
473
+ return 1;
474
+ };
475
+ for (const method of [
476
+ "exec",
477
+ "execFile",
478
+ "execFileSync",
479
+ "execSync",
480
+ "fork",
481
+ "spawn",
482
+ "spawnSync"
483
+ ]) {
484
+ const original = mutableChild[method];
485
+ if (typeof original !== "function")
486
+ continue;
487
+ mutableChild[method] = function(...args) {
488
+ var _a9;
489
+ const index = optionIndex(method, args);
490
+ const existing = args[index] && typeof args[index] === "object" ? args[index] : {};
491
+ const options = __spreadProps(__spreadValues({}, existing), {
492
+ env: __spreadValues(__spreadValues(__spreadValues({}, process.env), (_a9 = existing.env) != null ? _a9 : {}), coverageContextEnvironment())
493
+ });
494
+ const scoped = [...args];
495
+ if (typeof scoped[index] === "function")
496
+ scoped.splice(index, 0, options);
497
+ else
498
+ scoped[index] = options;
499
+ return Reflect.apply(original, child, scoped);
313
500
  };
314
- for (const method of [
315
- "exec",
316
- "execFile",
317
- "execFileSync",
318
- "execSync",
319
- "fork",
320
- "spawn",
321
- "spawnSync",
322
- ]) {
323
- const original = mutableChild[method];
324
- if (typeof original !== "function")
325
- continue;
326
- mutableChild[method] = function (...args) {
327
- const index = optionIndex(method, args);
328
- const existing = args[index] && typeof args[index] === "object"
329
- ? args[index]
330
- : {};
331
- const options = {
332
- ...existing,
333
- env: {
334
- ...process.env,
335
- ...(existing.env ?? {}),
336
- ...coverageContextEnvironment(),
337
- },
338
- };
339
- const scoped = [...args];
340
- if (typeof scoped[index] === "function")
341
- scoped.splice(index, 0, options);
342
- else
343
- scoped[index] = options;
344
- return Reflect.apply(original, child, scoped);
345
- };
346
- }
347
- const moduleBuiltin = getBuiltinModule?.("node:module");
348
- moduleBuiltin?.syncBuiltinESMExports?.();
349
- runtimeGlobal.__SUPERCOV_CHILD_PATCHED__ = true;
501
+ }
502
+ const moduleBuiltin = getBuiltinModule == null ? void 0 : getBuiltinModule("node:module");
503
+ (_a8 = moduleBuiltin == null ? void 0 : moduleBuiltin.syncBuiltinESMExports) == null ? void 0 : _a8.call(moduleBuiltin);
504
+ runtimeGlobal.__SUPERCOV_CHILD_PATCHED__ = true;
350
505
  }
351
506
  installServerChildPropagation();
352
507
  function currentPhaseId() {
353
- if (runtimeGlobal.__SUPERCOV_PHASE_ID__)
354
- return runtimeGlobal.__SUPERCOV_PHASE_ID__;
355
- if (!isBrowser)
356
- return currentRequestContext().phaseId;
357
- try {
358
- const local = localStorage.getItem(phaseStorageKey);
359
- if (local)
360
- return local;
361
- return undefined;
362
- }
363
- catch {
364
- return undefined;
365
- }
508
+ if (runtimeGlobal.__SUPERCOV_PHASE_ID__)
509
+ return runtimeGlobal.__SUPERCOV_PHASE_ID__;
510
+ if (!isBrowser)
511
+ return currentRequestContext().phaseId;
512
+ try {
513
+ const local = localStorage.getItem(phaseStorageKey);
514
+ if (local)
515
+ return local;
516
+ return void 0;
517
+ } catch (e) {
518
+ return void 0;
519
+ }
366
520
  }
367
521
  function requestHeaders(value) {
368
- if (!value || typeof value !== "object")
369
- return undefined;
370
- const directHeaders = value.headers;
371
- const request = directHeaders && typeof directHeaders === "object"
372
- ? value
373
- : value.request;
374
- if (!request || typeof request !== "object")
375
- return undefined;
376
- const headers = request.headers;
377
- if (!headers || typeof headers !== "object")
378
- return undefined;
379
- const get = headers.get;
380
- if (typeof get === "function")
381
- return {
382
- get(name) {
383
- return Reflect.apply(get, headers, [name]);
384
- },
385
- };
386
- const values = headers;
387
- return Object.keys(values).length > 0
388
- ? {
389
- get(name) {
390
- return values[name] ?? values[name.toLowerCase()];
391
- },
392
- }
393
- : undefined;
394
- }
395
- function requestCoverageContext(value) {
396
- const headers = requestHeaders(value);
397
- if (!headers)
398
- return {};
399
- const rawCookie = headers.get("cookie");
400
- const cookies = new Map();
401
- if (typeof rawCookie === "string") {
402
- for (const part of rawCookie.split(";")) {
403
- const separator = part.indexOf("=");
404
- if (separator < 0)
405
- continue;
406
- const name = part.slice(0, separator).trim();
407
- const encoded = part.slice(separator + 1).trim();
408
- try {
409
- cookies.set(name, decodeURIComponent(encoded));
410
- }
411
- catch {
412
- // Ignore a malformed unrelated cookie.
413
- }
414
- }
415
- }
416
- const encodedScope = headers.get(COVERAGE_SCOPE_HEADER) ?? cookies.get(COVERAGE_SCOPE_COOKIE);
417
- const rawPhaseId = headers.get(COVERAGE_PHASE_HEADER) ?? cookies.get(COVERAGE_PHASE_COOKIE);
418
- const scope = decodeCoverageScope(typeof encodedScope === "string" ? encodedScope : undefined);
419
- const phaseId = typeof rawPhaseId === "string" && rawPhaseId.length > 0
420
- ? rawPhaseId
421
- : undefined;
522
+ if (!value || typeof value !== "object")
523
+ return void 0;
524
+ const directHeaders = value.headers;
525
+ const request = directHeaders && typeof directHeaders === "object" ? value : value.request;
526
+ if (!request || typeof request !== "object")
527
+ return void 0;
528
+ const headers = request.headers;
529
+ if (!headers || typeof headers !== "object")
530
+ return void 0;
531
+ const get = headers.get;
532
+ if (typeof get === "function")
422
533
  return {
423
- ...(scope ? { scope } : {}),
424
- ...(phaseId ? { phaseId } : {}),
534
+ get(name) {
535
+ return Reflect.apply(get, headers, [name]);
536
+ }
425
537
  };
538
+ const values = headers;
539
+ return Object.keys(values).length > 0 ? {
540
+ get(name) {
541
+ var _a8;
542
+ return (_a8 = values[name]) != null ? _a8 : values[name.toLowerCase()];
543
+ }
544
+ } : void 0;
426
545
  }
427
- export function withRequestPhase(handler) {
428
- if (!serverPhaseStorage)
429
- return handler;
430
- return function coverageRequestPhase(...args) {
431
- const requestContext = args
432
- .map((argument) => requestCoverageContext(argument))
433
- .find((context) => context.scope || context.phaseId) ?? {};
434
- const inheritedContext = currentRequestContext();
435
- const context = {
436
- ...(requestContext.scope ?? inheritedContext.scope
437
- ? { scope: requestContext.scope ?? inheritedContext.scope }
438
- : {}),
439
- ...(requestContext.phaseId ?? inheritedContext.phaseId
440
- ? { phaseId: requestContext.phaseId ?? inheritedContext.phaseId }
441
- : {}),
442
- };
443
- const invoke = () => Reflect.apply(handler, this, args);
444
- return context.scope || context.phaseId
445
- ? serverPhaseStorage.run(context, invoke)
446
- : invoke();
447
- };
546
+ function requestCoverageContext(value) {
547
+ var _a8, _b;
548
+ const headers = requestHeaders(value);
549
+ if (!headers)
550
+ return {};
551
+ const rawCookie = headers.get("cookie");
552
+ const cookies = /* @__PURE__ */ new Map();
553
+ if (typeof rawCookie === "string") {
554
+ for (const part of rawCookie.split(";")) {
555
+ const separator = part.indexOf("=");
556
+ if (separator < 0)
557
+ continue;
558
+ const name = part.slice(0, separator).trim();
559
+ const encoded = part.slice(separator + 1).trim();
560
+ try {
561
+ cookies.set(name, decodeURIComponent(encoded));
562
+ } catch (e) {
563
+ }
564
+ }
565
+ }
566
+ const encodedScope = (_a8 = headers.get(COVERAGE_SCOPE_HEADER)) != null ? _a8 : cookies.get(COVERAGE_SCOPE_COOKIE);
567
+ const rawPhaseId = (_b = headers.get(COVERAGE_PHASE_HEADER)) != null ? _b : cookies.get(COVERAGE_PHASE_COOKIE);
568
+ const scope = decodeCoverageScope(typeof encodedScope === "string" ? encodedScope : void 0);
569
+ const phaseId = typeof rawPhaseId === "string" && rawPhaseId.length > 0 ? rawPhaseId : void 0;
570
+ return __spreadValues(__spreadValues({}, scope ? { scope } : {}), phaseId ? { phaseId } : {});
571
+ }
572
+ function withRequestPhase(handler) {
573
+ if (!serverPhaseStorage)
574
+ return handler;
575
+ return function coverageRequestPhase(...args) {
576
+ var _a8, _b, _c, _d, _e;
577
+ const requestContext = (_a8 = args.map((argument) => requestCoverageContext(argument)).find((context2) => context2.scope || context2.phaseId)) != null ? _a8 : {};
578
+ const inheritedContext = currentRequestContext();
579
+ const context = __spreadValues(__spreadValues({}, ((_b = requestContext.scope) != null ? _b : inheritedContext.scope) ? { scope: (_c = requestContext.scope) != null ? _c : inheritedContext.scope } : {}), ((_d = requestContext.phaseId) != null ? _d : inheritedContext.phaseId) ? { phaseId: (_e = requestContext.phaseId) != null ? _e : inheritedContext.phaseId } : {});
580
+ const invoke = () => Reflect.apply(handler, this, args);
581
+ return context.scope || context.phaseId ? serverPhaseStorage.run(context, invoke) : invoke();
582
+ };
448
583
  }
449
584
  function eventKey(event) {
450
- const suffix = event.type === "decision"
451
- ? `${event.id}:${vectorKey(event.vector)}`
452
- : event.id;
453
- return `${event.phaseId ?? "unscoped"}:${event.type}:${suffix}`;
585
+ var _a8;
586
+ const suffix = event.type === "decision" ? `${event.id}:${vectorKey(event.vector)}` : event.id;
587
+ return `${(_a8 = event.phaseId) != null ? _a8 : "unscoped"}:${event.type}:${suffix}`;
454
588
  }
455
589
  function recordBrowserEvent(event) {
456
- const key = eventKey(event);
457
- if (state.eventKeys.has(key))
458
- return false;
459
- state.eventKeys.add(key);
460
- state.events.push(event);
461
- return true;
462
- }
463
- export function coverageHit(id) {
464
- state.hits.add(id);
465
- const timestampMs = Date.now();
466
- const phaseId = currentPhaseId();
467
- if (isBrowser) {
468
- if (recordBrowserEvent({
469
- type: "hit",
470
- id,
471
- timestampMs,
472
- ...(phaseId ? { phaseId } : {}),
473
- environment: "browser",
474
- }))
475
- persistBrowser();
476
- }
477
- else {
478
- // Request servers retain repeated executions for phase-window correlation.
479
- // Local runner adapters explicitly buffer and de-duplicate per test/phase.
480
- appendServer({
481
- type: "hit",
482
- id,
483
- timestampMs,
484
- ...(phaseId ? { phaseId } : {}),
485
- });
486
- }
487
- }
488
- export function selectionBegin(shortId, rightId) {
489
- return { shortId, rightId, rightEvaluated: false };
590
+ const key = eventKey(event);
591
+ if (state.eventKeys.has(key))
592
+ return false;
593
+ state.eventKeys.add(key);
594
+ state.events.push(event);
595
+ return true;
596
+ }
597
+ function coverageHit(id) {
598
+ state.hits.add(id);
599
+ const timestampMs = Date.now();
600
+ const phaseId = currentPhaseId();
601
+ if (isBrowser) {
602
+ if (recordBrowserEvent(__spreadProps(__spreadValues({
603
+ type: "hit",
604
+ id,
605
+ timestampMs
606
+ }, phaseId ? { phaseId } : {}), {
607
+ environment: "browser"
608
+ })))
609
+ persistBrowser();
610
+ } else {
611
+ appendServer(__spreadValues({
612
+ type: "hit",
613
+ id,
614
+ timestampMs
615
+ }, phaseId ? { phaseId } : {}));
616
+ }
617
+ }
618
+ function selectionBegin(shortId, rightId) {
619
+ return { shortId, rightId, rightEvaluated: false };
490
620
  }
491
621
  function applyInferredName(value, inferredName) {
492
- if (inferredName &&
493
- typeof value === "function" &&
494
- value.name === "") {
495
- Object.defineProperty(value, "name", {
496
- value: inferredName,
497
- configurable: true,
498
- });
499
- }
500
- return value;
501
- }
502
- export function selectionRight(frame, value, inferredName) {
503
- frame.rightEvaluated = true;
504
- return applyInferredName(value, inferredName);
505
- }
506
- export function selectionEnd(frame, value) {
507
- coverageHit(frame.rightEvaluated ? frame.rightId : frame.shortId);
508
- return value;
509
- }
510
- export function optionalSelect(shortId, continuedId, value) {
511
- coverageHit(value === null || value === undefined ? shortId : continuedId);
512
- return value;
513
- }
514
- export function defaultSelected(defaultId, value, inferredName) {
515
- pendingDefaults.set(defaultId, (pendingDefaults.get(defaultId) ?? 0) + 1);
516
- return applyInferredName(value, inferredName);
517
- }
518
- export function defaultEntered(defaultId, providedId) {
519
- const pending = pendingDefaults.get(defaultId) ?? 0;
520
- if (pending > 0) {
521
- pendingDefaults.set(defaultId, pending - 1);
522
- coverageHit(defaultId);
523
- }
524
- else {
525
- coverageHit(providedId);
526
- }
527
- }
528
- export function tryBegin(successId, catchId) {
529
- return { successId, catchId, caught: false };
622
+ if (inferredName && typeof value === "function" && value.name === "") {
623
+ Object.defineProperty(value, "name", {
624
+ value: inferredName,
625
+ configurable: true
626
+ });
627
+ }
628
+ return value;
530
629
  }
531
- export function tryCatch(frame, value) {
532
- frame.caught = true;
533
- return value;
630
+ function selectionRight(frame, value, inferredName) {
631
+ frame.rightEvaluated = true;
632
+ return applyInferredName(value, inferredName);
534
633
  }
535
- export function tryEnd(frame) {
536
- coverageHit(frame.caught ? frame.catchId : frame.successId);
634
+ function selectionEnd(frame, value) {
635
+ coverageHit(frame.rightEvaluated ? frame.rightId : frame.shortId);
636
+ return value;
537
637
  }
538
- export function loopBegin(zeroId, enteredId) {
539
- return { zeroId, enteredId, entered: false };
638
+ function optionalSelect(shortId, continuedId, value) {
639
+ coverageHit(value === null || value === void 0 ? shortId : continuedId);
640
+ return value;
540
641
  }
541
- export function loopEntered(frame) {
542
- frame.entered = true;
642
+ function optionalCallBegin(shortId, continuedId) {
643
+ return { shortId, continuedId, reached: false, continued: false };
543
644
  }
544
- export function loopEnd(frame) {
545
- coverageHit(frame.entered ? frame.enteredId : frame.zeroId);
645
+ function optionalCallReached(frame, value) {
646
+ frame.reached = true;
647
+ return value;
546
648
  }
547
- export function mcdcBegin(id, meta) {
548
- if (!state.decisions.has(id)) {
549
- state.decisions.set(id, { meta, vectors: new Map() });
550
- }
649
+ var optionalCallEmptySpread = {
650
+ [Symbol.iterator]() {
551
651
  return {
552
- meta,
553
- values: Array.from({ length: meta.conditions.length }, () => null),
652
+ next() {
653
+ return { done: true, value: void 0 };
654
+ }
554
655
  };
555
- }
556
- export function mcdcCondition(frame, index, value) {
557
- frame.values[index] = Boolean(value);
558
- return value;
559
- }
560
- export function mcdcEnd(frame, value) {
561
- const decision = state.decisions.get(frame.meta.id);
562
- if (!decision)
563
- return value;
564
- const vector = { values: frame.values, outcome: Boolean(value) };
565
- const key = vectorKey(vector);
566
- decision.vectors.set(key, vector);
567
- const timestampMs = Date.now();
568
- const phaseId = currentPhaseId();
569
- if (isBrowser) {
570
- if (recordBrowserEvent({
571
- type: "decision",
572
- id: decision.meta.id,
573
- vector,
574
- timestampMs,
575
- ...(phaseId ? { phaseId } : {}),
576
- environment: "browser",
577
- }))
578
- persistBrowser();
579
- }
580
- else {
581
- appendServer({
582
- type: "decision",
583
- meta: decision.meta,
584
- vector,
585
- timestampMs,
586
- ...(phaseId ? { phaseId } : {}),
587
- });
588
- }
656
+ }
657
+ };
658
+ function optionalCallContinued(frame) {
659
+ frame.continued = true;
660
+ return optionalCallEmptySpread;
661
+ }
662
+ function optionalCallEnd(frame, value) {
663
+ if (frame.reached)
664
+ coverageHit(frame.continued ? frame.continuedId : frame.shortId);
665
+ return value;
666
+ }
667
+ function defaultSelected(defaultId, value, inferredName) {
668
+ var _a8;
669
+ pendingDefaults.set(defaultId, ((_a8 = pendingDefaults.get(defaultId)) != null ? _a8 : 0) + 1);
670
+ return applyInferredName(value, inferredName);
671
+ }
672
+ function defaultEntered(defaultId, providedId) {
673
+ var _a8;
674
+ const pending = (_a8 = pendingDefaults.get(defaultId)) != null ? _a8 : 0;
675
+ if (pending > 0) {
676
+ pendingDefaults.set(defaultId, pending - 1);
677
+ coverageHit(defaultId);
678
+ } else {
679
+ coverageHit(providedId);
680
+ }
681
+ }
682
+ function tryBegin(successId, catchId) {
683
+ return { successId, catchId, caught: false };
684
+ }
685
+ function tryCatch(frame, value) {
686
+ frame.caught = true;
687
+ return value;
688
+ }
689
+ function tryEnd(frame) {
690
+ coverageHit(frame.caught ? frame.catchId : frame.successId);
691
+ }
692
+ function loopBegin(zeroId, enteredId) {
693
+ return { zeroId, enteredId, entered: false };
694
+ }
695
+ function loopEntered(frame) {
696
+ frame.entered = true;
697
+ }
698
+ function loopEnd(frame) {
699
+ coverageHit(frame.entered ? frame.enteredId : frame.zeroId);
700
+ }
701
+ function mcdcBegin(id, meta) {
702
+ if (!state.decisions.has(id)) {
703
+ state.decisions.set(id, { meta, vectors: /* @__PURE__ */ new Map() });
704
+ }
705
+ return {
706
+ meta,
707
+ values: Array.from({ length: meta.conditions.length }, () => null)
708
+ };
709
+ }
710
+ function mcdcCondition(frame, index, value) {
711
+ frame.values[index] = Boolean(value);
712
+ return value;
713
+ }
714
+ function mcdcEnd(frame, value) {
715
+ const decision = state.decisions.get(frame.meta.id);
716
+ if (!decision)
589
717
  return value;
590
- }
591
- //# sourceMappingURL=runtime.js.map
718
+ const vector = { values: frame.values, outcome: Boolean(value) };
719
+ const key = vectorKey(vector);
720
+ decision.vectors.set(key, vector);
721
+ const timestampMs = Date.now();
722
+ const phaseId = currentPhaseId();
723
+ if (isBrowser) {
724
+ if (recordBrowserEvent(__spreadProps(__spreadValues({
725
+ type: "decision",
726
+ id: decision.meta.id,
727
+ vector,
728
+ timestampMs
729
+ }, phaseId ? { phaseId } : {}), {
730
+ environment: "browser"
731
+ })))
732
+ persistBrowser();
733
+ } else {
734
+ appendServer(__spreadValues({
735
+ type: "decision",
736
+ meta: decision.meta,
737
+ vector,
738
+ timestampMs
739
+ }, phaseId ? { phaseId } : {}));
740
+ }
741
+ return value;
742
+ }
743
+ export {
744
+ beginBufferedServerEvidence,
745
+ bindCoverageContext,
746
+ coverageCarrier,
747
+ coverageContextEnvironment,
748
+ coverageContextHeaders,
749
+ coverageHit,
750
+ coverageSnapshot,
751
+ defaultEntered,
752
+ defaultSelected,
753
+ enableRuntimeSnapshotEvidence,
754
+ flushBufferedServerEvidence,
755
+ loopBegin,
756
+ loopEnd,
757
+ loopEntered,
758
+ mcdcBegin,
759
+ mcdcCondition,
760
+ mcdcEnd,
761
+ optionalCallBegin,
762
+ optionalCallContinued,
763
+ optionalCallEnd,
764
+ optionalCallReached,
765
+ optionalSelect,
766
+ resetCoverage,
767
+ selectionBegin,
768
+ selectionEnd,
769
+ selectionRight,
770
+ takeNodeAssertionPhases,
771
+ tryBegin,
772
+ tryCatch,
773
+ tryEnd,
774
+ withCoverageCarrier,
775
+ withNodeAssertionPhase,
776
+ withRequestPhase,
777
+ writeExclusiveBackgroundRecord
778
+ };