@specific.dev/spectest 0.57.0 → 0.59.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,192 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { spawn, type ChildProcess } from "node:child_process";
3
+ import { promises as fs } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import {
7
+ NODE_COVERAGE_HOOK,
8
+ NODE_COVERAGE_HOOK_PATH,
9
+ NODE_COVERAGE_SOCKET,
10
+ applyCoverageAdapters,
11
+ appendEnvFlag,
12
+ browser,
13
+ command,
14
+ node,
15
+ validateCoverage,
16
+ type CoverageCaptureContext,
17
+ } from "./coverage.js";
18
+ import type { ServiceConfig } from "./index.js";
19
+
20
+ const base: ServiceConfig = {
21
+ image: { type: "registry", reference: "node:20" },
22
+ command: "node server.js",
23
+ env: { NODE_OPTIONS: "--max-old-space-size=512" },
24
+ };
25
+
26
+ describe("validateCoverage", () => {
27
+ test("accepts true, a list of adapters, nothing else", () => {
28
+ validateCoverage("a", undefined);
29
+ validateCoverage("a", true);
30
+ validateCoverage("a", { adapters: [node(), { name: "x" }] });
31
+ expect(() => validateCoverage("a", false)).toThrow(/invalid `coverage` value/);
32
+ expect(() => validateCoverage("a", { command: "x" })).toThrow(/invalid `coverage` value/);
33
+ expect(() => validateCoverage("a", [node()])).toThrow(/invalid `coverage` value/);
34
+ expect(() => validateCoverage("a", { adapters: [{ name: "" }] })).toThrow(/invalid coverage adapter/);
35
+ expect(() => validateCoverage("a", { adapters: [{ name: "x", capture: 1 }] })).toThrow(/invalid coverage adapter/);
36
+ });
37
+ });
38
+
39
+ describe("applyCoverageAdapters", () => {
40
+ test("node: appends NODE_OPTIONS, sets NODE_V8_COVERAGE, mounts the hook", () => {
41
+ const out = applyCoverageAdapters("api", { ...base, coverage: { adapters: [node()] } });
42
+ expect(out.env?.NODE_OPTIONS).toBe(`--max-old-space-size=512 --require ${NODE_COVERAGE_HOOK_PATH}`);
43
+ expect(out.env?.NODE_V8_COVERAGE).toBe("/spectest/coverage");
44
+ expect(out.files?.map((f) => f.path)).toEqual([NODE_COVERAGE_HOOK_PATH]);
45
+ expect(out.files?.[0]?.content).toBe(NODE_COVERAGE_HOOK);
46
+ });
47
+ test("the adapters stay on the config for the harness, and serialize as names", () => {
48
+ const out = applyCoverageAdapters("api", { ...base, coverage: { adapters: [node(), browser()] } });
49
+ const list = (out.coverage as { adapters: readonly { name: string; capture?: unknown; load?: unknown }[] }).adapters;
50
+ expect(list.map((a) => a.name)).toEqual(["node", "browser"]);
51
+ expect(typeof list[0]?.capture).toBe("function");
52
+ expect(typeof list[1]?.load).toBe("function");
53
+ expect(JSON.parse(JSON.stringify(out)).coverage).toEqual({
54
+ adapters: [{ adapter: "node" }, { adapter: "browser" }],
55
+ });
56
+ });
57
+ test("true and undefined pass through untouched", () => {
58
+ const t = { ...base, coverage: true as const };
59
+ expect(applyCoverageAdapters("api", t)).toBe(t);
60
+ expect(applyCoverageAdapters("api", base)).toBe(base);
61
+ });
62
+ test("appendEnvFlag sets when absent", () => {
63
+ expect(appendEnvFlag(undefined, "X", "a")).toEqual({ X: "a" });
64
+ expect(appendEnvFlag({ X: " b " }, "X", "a")).toEqual({ X: "b a" });
65
+ });
66
+ test("coverage.command refuses an empty command", () => {
67
+ expect(() => command(" ")).toThrow(/non-empty/);
68
+ });
69
+ });
70
+
71
+ /** A capture context over a real directory, no container. */
72
+ function fakeCtx(dir: string, signal = new AbortController().signal): CoverageCaptureContext {
73
+ return {
74
+ service: "api",
75
+ reportDir: dir,
76
+ signal,
77
+ async exec() {
78
+ throw new Error("no container");
79
+ },
80
+ async writeReport(name, content) {
81
+ await fs.writeFile(path.join(dir, name), content);
82
+ },
83
+ };
84
+ }
85
+
86
+ describe("browserCoverage", () => {
87
+ test("writes an empty lcov when nothing ran for the service", async () => {
88
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), "spectest-cov-"));
89
+ await browser().capture!(fakeCtx(dir));
90
+ expect(await fs.readFile(path.join(dir, "browser.lcov"), "utf8")).toBe("TN:\n");
91
+ });
92
+ });
93
+
94
+ // The node hook against a real `node` (the box has one; skipped where it
95
+ // does not). A long-lived process armed with the hook must answer the
96
+ // socket with a fresh V8 report; a second process must stay a bystander
97
+ // and exit on its own; the socket path must work across a bind mount —
98
+ // which is what a plain directory path stands in for here.
99
+ const hasNode = await new Promise<boolean>((resolve) => {
100
+ const p = spawn("node", ["--version"]);
101
+ p.on("error", () => resolve(false));
102
+ p.on("exit", (code) => resolve(code === 0));
103
+ });
104
+
105
+ describe.if(hasNode)("nodeCoverage hook (real node)", () => {
106
+ async function startServer(dir: string): Promise<ChildProcess> {
107
+ const hook = path.join(dir, "hook.cjs");
108
+ await fs.writeFile(hook, NODE_COVERAGE_HOOK);
109
+ const server = path.join(dir, "server.js");
110
+ await fs.writeFile(server, "setInterval(() => {}, 1000); process.stdout.write('up\\n');\n");
111
+ const child = spawn("node", ["--require", hook, server], {
112
+ env: { ...process.env, NODE_V8_COVERAGE: dir },
113
+ stdio: ["ignore", "pipe", "inherit"],
114
+ });
115
+ await new Promise<void>((resolve) => child.stdout!.once("data", () => resolve()));
116
+ // The socket is bound after the module graph runs; wait for it.
117
+ const sock = path.join(dir, NODE_COVERAGE_SOCKET);
118
+ for (let i = 0; i < 100; i++) {
119
+ try {
120
+ await fs.stat(sock);
121
+ break;
122
+ } catch {
123
+ await new Promise((r) => setTimeout(r, 20));
124
+ }
125
+ }
126
+ return child;
127
+ }
128
+
129
+ test("capture asks the live server for a dump; a bystander exits on its own", async () => {
130
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), "spectest-covhook-"));
131
+ const server = await startServer(dir);
132
+ try {
133
+ const reportsBefore = (await fs.readdir(dir)).filter((n) => n.startsWith("coverage-"));
134
+ expect(reportsBefore).toEqual([]);
135
+ await node().capture!(fakeCtx(dir));
136
+ const reports = (await fs.readdir(dir)).filter((n) => n.startsWith("coverage-"));
137
+ expect(reports.length).toBe(1);
138
+ const doc = JSON.parse(await fs.readFile(path.join(dir, reports[0]!), "utf8")) as {
139
+ result: { url: string }[];
140
+ };
141
+ expect(doc.result.some((s) => s.url.endsWith("/server.js"))).toBe(true);
142
+
143
+ // A second process with the same env: the socket is held, so it must
144
+ // not try to serve, and it must exit (the server's socket is unref'd,
145
+ // so a bystander is never kept alive by it).
146
+ const bystander = spawn("node", ["--require", path.join(dir, "hook.cjs"), "-e", "1"], {
147
+ env: { ...process.env, NODE_V8_COVERAGE: dir },
148
+ stdio: "ignore",
149
+ });
150
+ const code = await new Promise<number | null>((resolve) => bystander.on("exit", resolve));
151
+ expect(code).toBe(0);
152
+ // …and it wrote its own exit-time report, as every node process does.
153
+ const after = (await fs.readdir(dir)).filter((n) => n.startsWith("coverage-"));
154
+ expect(after.length).toBe(2);
155
+
156
+ // The live server still answers.
157
+ await node().capture!(fakeCtx(dir));
158
+ expect((await fs.readdir(dir)).filter((n) => n.startsWith("coverage-")).length).toBe(3);
159
+ } finally {
160
+ server.kill("SIGKILL");
161
+ }
162
+ });
163
+
164
+ test("a stale socket left by a dead process is reclaimed", async () => {
165
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), "spectest-covhook-"));
166
+ const first = await startServer(dir);
167
+ first.kill("SIGKILL");
168
+ await new Promise<void>((resolve) => first.on("exit", () => resolve()));
169
+ expect(await fs.stat(path.join(dir, NODE_COVERAGE_SOCKET))).toBeTruthy(); // stale file
170
+ const second = await startServer(dir);
171
+ try {
172
+ // Give the EADDRINUSE → probe → unlink → listen dance a moment.
173
+ let ok = false;
174
+ for (let i = 0; i < 50 && !ok; i++) {
175
+ try {
176
+ await node().capture!(fakeCtx(dir));
177
+ ok = true;
178
+ } catch {
179
+ await new Promise((r) => setTimeout(r, 50));
180
+ }
181
+ }
182
+ expect(ok).toBe(true);
183
+ } finally {
184
+ second.kill("SIGKILL");
185
+ }
186
+ });
187
+
188
+ test("no server: capture fails naming the socket", async () => {
189
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), "spectest-covhook-"));
190
+ await expect(node().capture!(fakeCtx(dir))).rejects.toThrow(/no node process is serving/);
191
+ });
192
+ });
@@ -0,0 +1,327 @@
1
+ // Coverage adapters — how spectest gets a coverage report out of a service.
2
+ //
3
+ // A service opts in with `coverage: true` (the program writes its own
4
+ // reports into `/spectest/coverage/`) or `coverage: { adapters: [...] }`
5
+ // (spectest gets the reports out). An adapter has three optional moments:
6
+ //
7
+ // configure — config time, inside `defineEnvironment`. Rewrites the
8
+ // service (env, files, command). Pure: its output is part
9
+ // of the wire config and of the warm-template hash.
10
+ // load — harness, at /load. Asks the harness for capabilities a
11
+ // container cannot supply itself (browser scripts).
12
+ // capture — harness, after bring-up and after every test. Must leave
13
+ // a report in the directory.
14
+ //
15
+ // After every adapter ran, the harness reads the directory the same way
16
+ // it does for `coverage: true`: at least one well-formed report (lcov or
17
+ // V8 JSON), shipped verbatim. Adapters convert nothing — the control
18
+ // plane derives what it needs from the stored bytes.
19
+ //
20
+ // Imported from `@specific.dev/spectest/coverage`. The three shipped
21
+ // adapters: `node()` (V8 JSON through a hook spectest mounts), `browser()`
22
+ // (scripts the guest browser loads from the service), `command(cmd)` (run
23
+ // a command, then read). A project writes its own with `defineAdapter`.
24
+ //
25
+ // import * as coverage from "@specific.dev/spectest/coverage";
26
+ // coverage: { adapters: [coverage.node(), coverage.browser()] }
27
+
28
+ import type { ServiceConfig } from "./index.js";
29
+ import { browserCoverageReports } from "./browser-coverage.js";
30
+
31
+ import { COVERAGE_CONTAINER_DIR } from "./harness/coverage.js";
32
+ export { COVERAGE_CONTAINER_DIR };
33
+
34
+ /** Where `node()` mounts its hook inside the container. */
35
+ export const NODE_COVERAGE_HOOK_PATH = "/spectest/coverage-hook.cjs";
36
+
37
+ /** The socket the node hook answers on, relative to the coverage dir. */
38
+ export const NODE_COVERAGE_SOCKET = ".ctl";
39
+
40
+ /** What `configure` learns about the service it rewrites. */
41
+ export interface CoverageConfigureInfo {
42
+ /** The services-map key. */
43
+ key: string;
44
+ }
45
+
46
+ /** The harness capabilities an adapter can ask for at `/load`. */
47
+ export interface CoverageLoadContext {
48
+ /** The services-map key. */
49
+ service: string;
50
+ /**
51
+ * Collect V8 coverage for every script the guest browser
52
+ * (`ctx.browser()` / `ctx.mobile()`) loads from this service's origins:
53
+ * its key, `<key>.internal`, its `hostnames`/`dnsName` aliases, its
54
+ * `tls`/`proxy` hostnames and any service-targeted wildcard. The
55
+ * harness maps each script back to source through the served source
56
+ * map and keeps per-service totals in memory (they fork with the
57
+ * environment). `browser()` calls this and writes the totals
58
+ * at capture.
59
+ */
60
+ collectBrowserScripts(): void;
61
+ }
62
+
63
+ /** What one adapter's `capture` runs against. */
64
+ export interface CoverageCaptureContext {
65
+ /** The services-map key. */
66
+ service: string;
67
+ /**
68
+ * The coverage directory, seen from the harness. It is the same
69
+ * directory the container sees at `/spectest/coverage/` (a bind
70
+ * mount), so a file written here is in the container and a socket the
71
+ * container bound here is reachable.
72
+ */
73
+ reportDir: string;
74
+ /** Run a shell command (`sh -c`) inside the container. Rejects on a
75
+ * non-zero exit with the command's output in the message. */
76
+ exec(command: string): Promise<{ stdout: string; stderr: string }>;
77
+ /** Write one report file (name relative to the directory). */
78
+ writeReport(name: string, content: string): Promise<void>;
79
+ /** Aborts when the per-service capture budget runs out. */
80
+ signal: AbortSignal;
81
+ }
82
+
83
+ export interface CoverageAdapter {
84
+ /** Names the adapter in errors (`coverage adapter "node" on service …`). */
85
+ name: string;
86
+ /**
87
+ * Rewrite the service at config time. Must be pure and deterministic
88
+ * (the result is hashed into the warm-template key) and must **append**
89
+ * to `env` values like `NODE_OPTIONS` rather than replace them.
90
+ */
91
+ configure?(service: ServiceConfig, info: CoverageConfigureInfo): ServiceConfig;
92
+ /** Ask the harness for capabilities, at `/load`. */
93
+ load?(ctx: CoverageLoadContext): void | Promise<void>;
94
+ /** Make the report appear in the directory. A throw fails the test. */
95
+ capture?(ctx: CoverageCaptureContext): void | Promise<void>;
96
+ }
97
+
98
+ /** `ServiceConfig.coverage`: the program writes its own reports, or a
99
+ * list of adapters gets them out. */
100
+ export type ServiceCoverage = true | { adapters: readonly CoverageAdapter[] };
101
+
102
+ /** Type an inline adapter. Identity at runtime. */
103
+ export function defineAdapter(adapter: CoverageAdapter): CoverageAdapter {
104
+ return adapter;
105
+ }
106
+
107
+ /** Check one service's `coverage` field. Exported so the daemon applies
108
+ * the same rule to a runtime `startService` spec. */
109
+ export function validateCoverage(service: string, cov: unknown): void {
110
+ if (cov === undefined || cov === true) return;
111
+ const adapters = (cov as { adapters?: unknown } | null)?.adapters;
112
+ if (typeof cov === "object" && cov !== null && Array.isArray(adapters)) {
113
+ for (const a of adapters) {
114
+ const ok =
115
+ typeof a === "object" &&
116
+ a !== null &&
117
+ typeof (a as CoverageAdapter).name === "string" &&
118
+ (a as CoverageAdapter).name.length > 0 &&
119
+ ["configure", "load", "capture"].every(
120
+ (k) =>
121
+ (a as Record<string, unknown>)[k] === undefined ||
122
+ typeof (a as Record<string, unknown>)[k] === "function",
123
+ );
124
+ if (!ok) {
125
+ throw new Error(
126
+ `service "${service}" has an invalid coverage adapter — an adapter is \`{ name, configure?, load?, capture? }\` (see \`defineAdapter\` in @specific.dev/spectest/coverage)`,
127
+ );
128
+ }
129
+ }
130
+ return;
131
+ }
132
+ throw new Error(
133
+ `service "${service}" has an invalid \`coverage\` value — use \`true\` (the program writes its own reports) or \`{ adapters: [...] }\` from @specific.dev/spectest/coverage (\`node()\`, \`browser()\`, \`command("…")\`)`,
134
+ );
135
+ }
136
+
137
+ /** The adapters of a `coverage` value (`true` has none). */
138
+ export function coverageAdapters(cov: ServiceCoverage | undefined): readonly CoverageAdapter[] {
139
+ return typeof cov === "object" && cov !== null ? cov.adapters : [];
140
+ }
141
+
142
+ /**
143
+ * Apply every adapter's `configure` to a service, in list order. Called by
144
+ * `defineEnvironment` (after group expansion, before validation) and by
145
+ * the daemon for a runtime `startService` spec. The adapter list stays on
146
+ * the returned config for the harness; on the wire it serializes as the
147
+ * adapter names (`toJSON`), never as functions.
148
+ */
149
+ export function applyCoverageAdapters<S extends ServiceConfig>(key: string, svc: S): S {
150
+ validateCoverage(key, svc.coverage);
151
+ const adapters = coverageAdapters(svc.coverage);
152
+ if (adapters.length === 0) return svc;
153
+ let out: ServiceConfig = svc;
154
+ for (const a of adapters) {
155
+ if (a.configure) out = a.configure(out, { key });
156
+ }
157
+ const wire = { adapters: adapters.map((a) => withWireName(a)) };
158
+ return { ...out, coverage: wire } as unknown as S;
159
+ }
160
+
161
+ function withWireName(a: CoverageAdapter): CoverageAdapter {
162
+ if (Object.prototype.hasOwnProperty.call(a, "toJSON")) return a;
163
+ return Object.assign(Object.create(Object.getPrototypeOf(a) as object | null), a, {
164
+ toJSON: () => ({ adapter: a.name }),
165
+ }) as CoverageAdapter;
166
+ }
167
+
168
+ /** `env` with `value` appended to `name` (space-separated), or set. */
169
+ export function appendEnvFlag(
170
+ env: Readonly<Record<string, string>> | undefined,
171
+ name: string,
172
+ value: string,
173
+ ): Record<string, string> {
174
+ const prior = env?.[name]?.trim();
175
+ return { ...env, [name]: prior ? `${prior} ${value}` : value };
176
+ }
177
+
178
+ // ── node ──────────────────────────────────────────────────────────
179
+
180
+ /**
181
+ * The hook `node()` mounts and `--require`s into every node
182
+ * process of the container. Node writes V8 coverage JSON into
183
+ * `NODE_V8_COVERAGE` when a process exits; a long-lived server never
184
+ * exits, so the hook binds a Unix socket in the coverage directory and
185
+ * calls `v8.takeCoverage()` for each connection. The first process to
186
+ * start owns the socket (a stale socket left by a dead process is
187
+ * reclaimed); a later process — a CLI run by `ctx.exec` — leaves it
188
+ * alone and writes at its own exit. No signal is used: signals are
189
+ * claimed by frameworks (SIGUSR2 stops a Temporal worker, restarts
190
+ * nodemon), a socket is nobody's.
191
+ */
192
+ export const NODE_COVERAGE_HOOK = `"use strict";
193
+ // spectest coverage hook (coverage.node() adapter). See \`spectest docs /services/coverage\`.
194
+ if (process.env.NODE_V8_COVERAGE) {
195
+ const net = require("node:net");
196
+ const fs = require("node:fs");
197
+ const v8 = require("node:v8");
198
+ const SOCK = require("node:path").join(process.env.NODE_V8_COVERAGE, ${JSON.stringify(NODE_COVERAGE_SOCKET)});
199
+ const server = net.createServer((conn) => {
200
+ // A dump is taken only on an explicit "dump" request: a bystander's
201
+ // liveness probe connects and closes without one.
202
+ let buf = "";
203
+ conn.on("data", (chunk) => {
204
+ buf += chunk;
205
+ if (!buf.includes("\\n")) return;
206
+ let reply;
207
+ try {
208
+ if (!buf.startsWith("dump")) throw new Error("unknown request");
209
+ v8.takeCoverage();
210
+ reply = "ok\\n";
211
+ } catch (err) {
212
+ reply = "error " + (err && err.message ? err.message : String(err)) + "\\n";
213
+ }
214
+ conn.end(reply);
215
+ });
216
+ });
217
+ server.unref();
218
+ server.on("error", (err) => {
219
+ if (err.code !== "EADDRINUSE") return;
220
+ // Someone holds the socket. If it answers, it is the live server and
221
+ // this process is a bystander; if not, it is a stale file.
222
+ const probe = net.connect(SOCK);
223
+ probe.on("connect", () => probe.destroy());
224
+ probe.on("error", () => {
225
+ try { fs.unlinkSync(SOCK); } catch {}
226
+ server.listen(SOCK);
227
+ });
228
+ });
229
+ server.listen(SOCK);
230
+ }
231
+ `;
232
+
233
+ /**
234
+ * Coverage for a Node service. Sets `NODE_V8_COVERAGE` to the coverage
235
+ * directory (every node process in the container then writes V8
236
+ * coverage JSON when it exits) and `--require`s a hook that lets spectest
237
+ * ask the long-lived server process for a dump at capture time. Nothing
238
+ * for the app to write. Source maps: with `--enable-source-maps` (or a
239
+ * `sourceMappingURL` next to the file) Node records the map in the
240
+ * report, which is what maps a TypeScript service back to its sources.
241
+ */
242
+ export function node(): CoverageAdapter {
243
+ return {
244
+ name: "node",
245
+ configure(svc) {
246
+ const env = appendEnvFlag(svc.env, "NODE_OPTIONS", `--require ${NODE_COVERAGE_HOOK_PATH}`);
247
+ env.NODE_V8_COVERAGE = COVERAGE_CONTAINER_DIR;
248
+ return {
249
+ ...svc,
250
+ env,
251
+ files: [...(svc.files ?? []), { path: NODE_COVERAGE_HOOK_PATH, content: NODE_COVERAGE_HOOK }],
252
+ };
253
+ },
254
+ async capture(ctx) {
255
+ const { connect } = await import("node:net");
256
+ const path = await import("node:path");
257
+ const sock = path.join(ctx.reportDir, NODE_COVERAGE_SOCKET);
258
+ const reply = await new Promise<string>((resolve, reject) => {
259
+ const chunks: Buffer[] = [];
260
+ const c = connect(sock, () => c.write("dump\n"));
261
+ const onAbort = (): void => {
262
+ c.destroy();
263
+ reject(new Error("timed out waiting for the node hook to write a report"));
264
+ };
265
+ ctx.signal.addEventListener("abort", onAbort, { once: true });
266
+ c.on("data", (b: Buffer) => chunks.push(b));
267
+ c.on("error", (err: NodeJS.ErrnoException) => {
268
+ ctx.signal.removeEventListener("abort", onAbort);
269
+ reject(
270
+ new Error(
271
+ err.code === "ENOENT" || err.code === "ECONNREFUSED"
272
+ ? `no node process is serving ${COVERAGE_CONTAINER_DIR}/${NODE_COVERAGE_SOCKET} — is the service's main process node, and does it run with the service's env (NODE_OPTIONS)?`
273
+ : err.message,
274
+ ),
275
+ );
276
+ });
277
+ c.on("close", () => {
278
+ ctx.signal.removeEventListener("abort", onAbort);
279
+ resolve(Buffer.concat(chunks).toString("utf8").trim());
280
+ });
281
+ });
282
+ if (reply !== "ok") throw new Error(`the node hook answered: ${reply || "(nothing)"}`);
283
+ },
284
+ };
285
+ }
286
+
287
+ // ── browser ───────────────────────────────────────────────────────
288
+
289
+ /**
290
+ * Coverage for the frontend a service serves. The code runs in the guest
291
+ * browser — spectest's own process — so no report can be written by the
292
+ * container; spectest collects V8 coverage for every script the browser
293
+ * loads from this service's origins, maps it back to source through the
294
+ * served source map, and writes one lcov per capture. Nothing ran yet on
295
+ * this branch ⇒ an lcov with no records, which is a report saying so.
296
+ */
297
+ export function browser(): CoverageAdapter {
298
+ return {
299
+ name: "browser",
300
+ load(ctx) {
301
+ ctx.collectBrowserScripts();
302
+ },
303
+ async capture(ctx) {
304
+ const lcov = browserCoverageReports().get(ctx.service) ?? "TN:\n";
305
+ await ctx.writeReport("browser.lcov", lcov);
306
+ },
307
+ };
308
+ }
309
+
310
+ // ── command ───────────────────────────────────────────────────────
311
+
312
+ /**
313
+ * Run `command` (via `sh -c`) in the container at every capture, so the
314
+ * service writes a fresh report into `/spectest/coverage/`. The escape
315
+ * hatch for a runtime with no shipped adapter.
316
+ */
317
+ export function command(command: string): CoverageAdapter {
318
+ if (typeof command !== "string" || command.trim().length === 0) {
319
+ throw new Error("coverage.command: `command` must be a non-empty shell command");
320
+ }
321
+ return {
322
+ name: "command",
323
+ async capture(ctx) {
324
+ await ctx.exec(command);
325
+ },
326
+ };
327
+ }