@specific.dev/spectest 0.121.0 → 0.123.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,373 @@
1
+ import { promises as fs } from "node:fs";
2
+ import path from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ import type { CoverageAdapter } from "../coverage.js";
5
+ import { rawFetch } from "../harness/raw-fetch.js";
6
+
7
+ // Drain all work even on failure: no writes may outlive the capture boundary.
8
+ async function finishAll<T>(pending: Promise<T>[]): Promise<T[]> {
9
+ const results = await Promise.allSettled(pending);
10
+ return results.map(result => {
11
+ if (result.status === "rejected") throw result.reason;
12
+ return result.value;
13
+ });
14
+ }
15
+
16
+ /** The inspector stays on container loopback; only the component's router
17
+ * talks to it. Reports use the existing, runtime-independent V8 wire format. */
18
+ export function supabaseFunctionsCoverage(functionRoot: string): CoverageAdapter {
19
+ const shippedByService = new Map<string, Set<string>>();
20
+ return {
21
+ name: "supabase-functions",
22
+ reports: "delta",
23
+ sourceOptions: { sourceRoot: "." },
24
+ ownsReport: name => name.startsWith("edge-") || name.startsWith("edge-scripts/"),
25
+ async inventory(ctx) {
26
+ // Functions are discovered by directory, not by an import in user code.
27
+ // Changing the catalogue must invalidate selection even for a new file.
28
+ // A removed fingerprint with no executed unit conservatively runs all.
29
+ const prefix = functionRoot + "/";
30
+ const files = await ctx.projectFiles();
31
+ const entries = files.filter(file => {
32
+ if (!file.startsWith(prefix)) return false;
33
+ const parts = file.slice(prefix.length).split("/");
34
+ return parts.length === 2 && !/^[_.]/.test(parts[0]!) && parts[1] === "index.ts";
35
+ }).sort();
36
+ const configNames = new Set(["deno.json", "deno.jsonc", "deno.lock", "import_map.json", "package.json"]);
37
+ const configPaths = files.filter(file => {
38
+ if (!configNames.has(path.posix.basename(file))) return file === path.posix.join(path.posix.dirname(functionRoot), "config.toml");
39
+ const dir = path.posix.dirname(file);
40
+ return dir === "." || file.startsWith(prefix) || functionRoot.startsWith(dir + "/") || dir === functionRoot;
41
+ }).sort();
42
+ const configs = await Promise.all(configPaths.map(async file => [file, await ctx.readProjectFile(file)]));
43
+ const digest = createHash("sha256").update(JSON.stringify({ entries, configs })).digest("hex");
44
+ return [`manifest:edge-functions:${encodeURIComponent(functionRoot)}#${digest}`];
45
+ },
46
+ async capture(ctx) {
47
+ let shipped = shippedByService.get(ctx.service);
48
+ if (!shipped) shippedByService.set(ctx.service, shipped = new Set());
49
+ const response = await rawFetch(`http://${ctx.service}:9000/_spectest/coverage`, {
50
+ method: "POST", signal: ctx.signal,
51
+ });
52
+ if (!response.ok) throw new Error(`edge coverage: ${await response.text()}`);
53
+ const payload = await response.json() as { reports: { name: string; content: string }[] };
54
+ if (!payload || !Array.isArray(payload.reports) || !payload.reports.length) throw new Error("edge coverage returned no reports");
55
+ for (const report of payload.reports) {
56
+ if (!report || !/^(edge-[\w-]+\.json|edge-scripts\/[a-f0-9]+\.json)$/.test(report.name) || typeof report.content !== "string") {
57
+ throw new Error("invalid edge coverage report");
58
+ }
59
+ }
60
+ // State and files both fork with the VM. Remove only reports that this
61
+ // adapter previously shipped, never another adapter's output.
62
+ await finishAll([...shipped].map(name => fs.rm(path.join(ctx.reportDir, name), { force: true })));
63
+ shipped.clear();
64
+ await finishAll(payload.reports.map(async report => {
65
+ // Track attempted writes too, so a failed write is cleaned up next time.
66
+ shipped.add(report.name);
67
+ await ctx.writeReport(report.name, report.content);
68
+ }));
69
+ },
70
+ };
71
+ }
72
+
73
+ /** Runs in the trusted main worker, not in a sandboxed user function. Keep
74
+ * this plain JS so the same module is exercised against the pinned runtime. */
75
+ export const SUPABASE_COVERAGE_COLLECTOR = String.raw`
76
+ const INTERNAL = /^(ext:|node:|internal:)/;
77
+ const COMPILED = /^\/var\/tmp\/sb-compile-[^/]+\//;
78
+ const TIMEOUT = 30000;
79
+ // Keep failed captures fenced until every independent operation has settled.
80
+ const finishAll = async pending => {
81
+ const results = await Promise.allSettled(pending);
82
+ return results.map(result => {
83
+ if (result.status === "rejected") throw result.reason;
84
+ return result.value;
85
+ });
86
+ };
87
+ const hash = async text => Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))), b => b.toString(16).padStart(2, "0")).join("");
88
+ const fileUrl = path => "file://" + path.split("/").map(encodeURIComponent).join("/");
89
+
90
+ export class EdgeCoverage {
91
+ constructor({ inspector = "http://127.0.0.1:9229", projectRoot = "/repo", generatedRoot = "/home/deno/spectest-functions" } = {}) {
92
+ this.inspector = inspector;
93
+ this.projectRoot = projectRoot.replace(/\/$/, "");
94
+ this.generatedRoot = generatedRoot;
95
+ this.entries = new Set();
96
+ this.wrappers = new Map();
97
+ this.mirrors = new Map();
98
+ this.sessions = new Map();
99
+ this.records = new Set();
100
+ this.error = null;
101
+ this.polling = null;
102
+ this.capturing = false;
103
+ this.sequence = 0;
104
+ this.timer = setInterval(() => this.poll().catch(e => this.fail(e)), 100);
105
+ }
106
+ fail(error) { this.error ??= String(error?.stack ?? error); }
107
+ register(entry) { this.entries.add(entry); }
108
+ wrap(entry) {
109
+ if (!this.wrappers.has(entry)) this.wrappers.set(entry, this.writeEntry(entry));
110
+ return this.wrappers.get(entry);
111
+ }
112
+ mirrorDirectory(relative) {
113
+ if (this.mirrors.has(relative)) return this.mirrors.get(relative);
114
+ const pending = (async () => {
115
+ const source = this.projectRoot + (relative ? "/" + relative : "");
116
+ const target = this.generatedRoot + "/project" + (relative ? "/" + relative : "");
117
+ if (relative) {
118
+ await this.mirrorDirectory(relative.includes("/") ? relative.slice(0, relative.lastIndexOf("/")) : "");
119
+ await Deno.remove(target); // replace this directory's link with an overlay
120
+ }
121
+ await Deno.mkdir(target, { recursive: true });
122
+ const items = [];
123
+ for await (const item of Deno.readDir(source)) items.push(item.name);
124
+ await finishAll(items.map(name => Deno.symlink(source + "/" + name, target + "/" + name)));
125
+ return target;
126
+ })();
127
+ this.mirrors.set(relative, pending);
128
+ return pending;
129
+ }
130
+ async writeEntry(entry) {
131
+ const slash = entry.lastIndexOf("/");
132
+ let directory = entry.slice(0, slash);
133
+ if (entry.startsWith(this.projectRoot + "/")) {
134
+ // Keep the complete directory/config layout, including ancestor Deno
135
+ // workspaces, relative import maps and packages. Only directories along
136
+ // the entry's ancestry are materialized; everything else is a symlink.
137
+ directory = await this.mirrorDirectory(directory.slice(this.projectRoot.length + 1));
138
+ }
139
+ const wrapper = directory + "/.spectest-coverage-" + (await hash(entry)).slice(0, 16) + ".mjs";
140
+ const code = [
141
+ "// spectest-generated coverage gate. Do not edit.",
142
+ "const keepAlive = setInterval(() => {}, 25);",
143
+ "const gate = {};",
144
+ "globalThis[Symbol.for('spectest.edgeCoverage')] = gate;",
145
+ "await new Promise(resolve => { gate.release = resolve; });",
146
+ "clearInterval(keepAlive);",
147
+ "const mod = await import(" + JSON.stringify("./" + entry.slice(slash + 1)) + ");",
148
+ "export default ('default' in mod ? mod.default : {});",
149
+ ].join("\n");
150
+ await Deno.writeTextFile(wrapper, code, { createNew: true });
151
+ this.register(wrapper);
152
+ return fileUrl(wrapper);
153
+ }
154
+ async forgetUnstarted(entry) {
155
+ // Compilation can reject the shared graph before an isolate exists. That
156
+ // is a normal reason for the component to retry in per-function mode.
157
+ const wrapper = await this.wrappers.get(entry);
158
+ if (!wrapper) return;
159
+ const original = decodeURIComponent(new URL(wrapper).pathname);
160
+ if (![...this.sessions.values()].some(s => s.entry === original)) this.entries.delete(original);
161
+ }
162
+ async ready() {
163
+ const deadline = Date.now() + TIMEOUT;
164
+ while (true) {
165
+ await this.poll();
166
+ if (this.error) throw new Error(this.error);
167
+ const attached = new Set([...this.sessions.values()].map(s => s.entry));
168
+ if ([...this.entries].every(entry => attached.has(entry))) {
169
+ await Promise.all([...this.sessions.values()].map(s => s.ready));
170
+ return;
171
+ }
172
+ if (Date.now() >= deadline) throw new Error("edge coverage did not attach to every warmed worker");
173
+ await new Promise(resolve => setTimeout(resolve, 25));
174
+ }
175
+ }
176
+ async poll() {
177
+ if (this.polling) return this.polling;
178
+ this.polling = this.discover();
179
+ try { await this.polling; } finally { this.polling = null; }
180
+ }
181
+ async discover() {
182
+ const response = await fetch(this.inspector + "/json/list", { signal: AbortSignal.timeout(TIMEOUT) });
183
+ if (!response.ok) throw new Error("edge inspector discovery failed: " + response.status);
184
+ const targets = await response.json();
185
+ if (!Array.isArray(targets)) throw new Error("invalid edge inspector target list");
186
+ const live = new Set(targets.map(t => t.id));
187
+ for (const [id] of this.sessions) if (!live.has(id)) throw new Error("edge coverage lost worker " + id);
188
+ for (const target of targets) {
189
+ if (this.sessions.has(target.id)) continue;
190
+ const session = this.connect(target);
191
+ this.sessions.set(target.id, session);
192
+ // Discover all isolates while their sessions initialize. ready() joins
193
+ // initialization separately; one worker never blocks discovery of others.
194
+ session.ready.catch(e => this.fail(e));
195
+ }
196
+ }
197
+ connect(target) {
198
+ const url = new URL(target.url);
199
+ if (url.protocol !== "file:") throw new Error("unexpected edge worker entry: " + target.url);
200
+ const compiledPath = decodeURIComponent(url.pathname);
201
+ const relative = compiledPath.replace(COMPILED, "");
202
+ // The runtime relocates the entire module graph under sb-compile-*/.
203
+ // Its registered entrypoint and our exact original entrypoint establish
204
+ // the relocation, independently for every isolate. Never guess a source
205
+ // file by basename or by a repository suffix.
206
+ const candidates = [...this.entries].filter(entry => compiledPath === entry || entry.endsWith("/" + relative));
207
+ if (candidates.length !== 1) throw new Error("ambiguous edge worker entry: " + target.url);
208
+ const original = candidates[0];
209
+ const base = COMPILED.test(compiledPath) ? original.slice(0, -relative.length) : "/";
210
+ const prefix = COMPILED.exec(compiledPath)?.[0] ?? "/";
211
+ const socketUrl = new URL(target.webSocketDebuggerUrl);
212
+ const inspector = new URL(this.inspector);
213
+ socketUrl.host = inspector.host;
214
+ const ws = new WebSocket(socketUrl);
215
+ const session = { ws, base, prefix, entry: original, scripts: new Map(), descriptions: new Map(), nextId: 0, pending: new Map() };
216
+ session.post = (method, params = {}) => new Promise((resolve, reject) => {
217
+ const id = ++session.nextId;
218
+ const timer = setTimeout(() => { session.pending.delete(id); reject(new Error("edge inspector timeout: " + method)); }, TIMEOUT);
219
+ session.pending.set(id, { resolve, reject, timer });
220
+ ws.send(JSON.stringify({ id, method, params }));
221
+ });
222
+ ws.onmessage = event => {
223
+ try {
224
+ const message = JSON.parse(event.data);
225
+ if (message.id) {
226
+ const pending = session.pending.get(message.id);
227
+ if (!pending) return;
228
+ clearTimeout(pending.timer);
229
+ session.pending.delete(message.id);
230
+ if (message.error) pending.reject(new Error(JSON.stringify(message.error)));
231
+ else pending.resolve(message.result);
232
+ } else if (message.method === "Debugger.scriptParsed") {
233
+ session.scripts.set(message.params.scriptId, message.params);
234
+ } else if (message.method === "Debugger.paused") {
235
+ session.post("Debugger.resume").catch(e => this.fail(e));
236
+ }
237
+ } catch (e) { this.fail(e); }
238
+ };
239
+ ws.onclose = () => {
240
+ const error = new Error("edge coverage inspector disconnected: " + target.id);
241
+ for (const p of session.pending.values()) { clearTimeout(p.timer); p.reject(error); }
242
+ session.pending.clear();
243
+ this.fail(error);
244
+ };
245
+ session.ready = (async () => {
246
+ await new Promise((resolve, reject) => {
247
+ const timer = setTimeout(() => reject(new Error("edge inspector connection timeout")), TIMEOUT);
248
+ ws.onopen = () => { clearTimeout(timer); resolve(); };
249
+ ws.onerror = () => { clearTimeout(timer); reject(new Error("edge inspector connection failed")); };
250
+ });
251
+ await session.post("Debugger.enable", { maxScriptsCacheSize: 16 * 1024 * 1024 });
252
+ await session.post("Profiler.enable");
253
+ await session.post("Profiler.startPreciseCoverage", { callCount: true, detailed: true });
254
+ // --inspect-brk can park inside the pinned runtime's inspector before
255
+ // its pending session handshake is polled. Use a live JS gate instead:
256
+ // no project module executes until precise coverage is acknowledged.
257
+ const released = await session.post("Runtime.evaluate", {
258
+ expression: "(async () => { const key = Symbol.for('spectest.edgeCoverage'); while (!globalThis[key]?.release) await new Promise(resolve => setTimeout(resolve, 10)); globalThis[key].release(); await new Promise(resolve => setTimeout(resolve, 0)); })()\n//# sourceURL=spectest:edge-coverage-bootstrap",
259
+ awaitPromise: true,
260
+ });
261
+ if (released.exceptionDetails) throw new Error("edge coverage gate failed: " + JSON.stringify(released.exceptionDetails));
262
+ })();
263
+ return session;
264
+ }
265
+ originalPath(session, url) {
266
+ const parsed = new URL(url);
267
+ if (parsed.protocol !== "file:") return null;
268
+ const pathname = decodeURIComponent(parsed.pathname);
269
+ if (!pathname.startsWith(session.prefix)) throw new Error("unknown edge source root: " + url);
270
+ return session.base + pathname.slice(session.prefix.length);
271
+ }
272
+ sourcePath(file) {
273
+ const mirror = this.generatedRoot + "/project/";
274
+ return file.startsWith(mirror) ? this.projectRoot + "/" + file.slice(mirror.length) : file;
275
+ }
276
+ async describe(session, script, original) {
277
+ if (session.descriptions.has(script.scriptId)) return session.descriptions.get(script.scriptId);
278
+ const { scriptSource: text } = await session.post("Debugger.getScriptSource", { scriptId: script.scriptId });
279
+ if (typeof text !== "string") throw new Error("missing edge source: " + script.url);
280
+ const metadata = session.scripts.get(script.scriptId);
281
+ const mapUrl = metadata?.sourceMapURL;
282
+ let sourceMap = null;
283
+ if (mapUrl) {
284
+ if (!mapUrl.startsWith("data:")) throw new Error("unsupported edge source map: " + mapUrl);
285
+ const comma = mapUrl.indexOf(",");
286
+ const encoded = mapUrl.slice(comma + 1);
287
+ const decoded = mapUrl.slice(0, comma).endsWith(";base64")
288
+ ? new TextDecoder().decode(Uint8Array.from(atob(encoded), c => c.charCodeAt(0))) : decodeURIComponent(encoded);
289
+ const data = JSON.parse(decoded);
290
+ if (!Array.isArray(data.sources) || !Array.isArray(data.sourcesContent) || typeof data.mappings !== "string" || data.sections || data.sourceRoot) {
291
+ throw new Error("missing edge source-map identity: " + script.url);
292
+ }
293
+ // Edge Runtime's map sources are relative to the graph root, rather
294
+ // than the script directory. Validate their contents against the actual
295
+ // mounted sources before archiving the normalized identities.
296
+ data.sources = await finishAll(data.sources.map(async (name, i) => {
297
+ const source = new URL(name, fileUrl(session.base));
298
+ if (source.protocol !== "file:") throw new Error("unexpected mapped edge source: " + source.href);
299
+ const file = this.sourcePath(decodeURIComponent(source.pathname));
300
+ if (!file.startsWith(this.projectRoot + "/")) throw new Error("edge map escapes project: " + file);
301
+ if (await Deno.readTextFile(file) !== data.sourcesContent[i]) throw new Error("edge source content mismatch: " + file);
302
+ return fileUrl(file);
303
+ }));
304
+ delete data.sourcesContent;
305
+ delete data.sourceRoot;
306
+ sourceMap = { url: null, data };
307
+ } else {
308
+ // JavaScript may need no transpilation. TypeScript without a map must
309
+ // not silently attribute generated line numbers to authored source.
310
+ if (await Deno.readTextFile(original) !== text) throw new Error("edge source has no usable map: " + original);
311
+ }
312
+ const record = { url: fileUrl(original), sourceHash: await hash(text),
313
+ lineLengths: text.split(/[\n\u2028\u2029]/).map(line => line.length),
314
+ functions: script.functions.map(f => [f.functionName, f.ranges[0].startOffset, f.ranges[0].endOffset]), sourceMap };
315
+ const content = JSON.stringify({ spectestScript: record });
316
+ const descriptor = { id: await hash(content), content };
317
+ session.descriptions.set(script.scriptId, descriptor);
318
+ return descriptor;
319
+ }
320
+ async capture() {
321
+ if (this.capturing) throw new Error("edge coverage capture already in progress");
322
+ this.capturing = true;
323
+ try {
324
+ await this.ready();
325
+ if (this.error) throw new Error(this.error);
326
+ // Each isolate owns its counters. Take all deltas concurrently, and
327
+ // fetch independent script descriptors concurrently within each isolate.
328
+ // Join before merging so ordering/deduplication don't depend on timing.
329
+ const captures = await finishAll([...this.sessions.values()].map(async session => {
330
+ const dump = await session.post("Profiler.takePreciseCoverage");
331
+ return finishAll(dump.result.map(async script => {
332
+ if (!script.functions.some(f => f.ranges.some(r => r.count > 0))) return null;
333
+ if (INTERNAL.test(script.url)) return null;
334
+ if (script.url === "spectest:edge-coverage-bootstrap") return null;
335
+ if (/^(https?:|npm:|jsr:)/.test(script.url)) return { unit: "deno:" + script.url };
336
+ if (!script.url) throw new Error("anonymous executed edge script cannot be mapped");
337
+ const rawPath = this.originalPath(session, script.url);
338
+ if (rawPath === session.entry) return null; // the generated startup gate
339
+ const original = rawPath && this.sourcePath(rawPath);
340
+ if (original?.startsWith(this.generatedRoot + "/")) return null;
341
+ if (original?.includes("/node_modules/")) return { unit: "deno:" + script.url };
342
+ if (!original?.startsWith(this.projectRoot + "/")) throw new Error("unmapped edge script: " + script.url);
343
+ const descriptor = await this.describe(session, script, original);
344
+ return { descriptor, result: { url: fileUrl(original), spectestScript: descriptor.id,
345
+ functions: script.functions.filter(f => f.ranges.some(r => r.count > 0)).map(f => {
346
+ const start = f.ranges[0].startOffset;
347
+ return f.ranges.flatMap((r, i) => [i ? r.startOffset - start : start, r.endOffset - r.startOffset, r.count]);
348
+ }) } };
349
+ }));
350
+ }));
351
+ const reports = [], result = [], units = new Set();
352
+ for (const capture of captures) for (const item of capture) {
353
+ if (!item) continue;
354
+ if (item.unit) { units.add(item.unit); continue; }
355
+ const { descriptor } = item;
356
+ if (!this.records.has(descriptor.id)) {
357
+ reports.push({ name: "edge-scripts/" + descriptor.id + ".json", content: descriptor.content });
358
+ this.records.add(descriptor.id);
359
+ }
360
+ result.push(item.result);
361
+ }
362
+ if (this.error) throw new Error(this.error);
363
+ reports.push({ name: "edge-" + (++this.sequence) + ".json", content: JSON.stringify({ spectestVersion: 2, result, units: [...units] }) });
364
+ return { reports };
365
+ } catch (e) {
366
+ // A take resets V8 counters. If processing fails afterwards, subsequent
367
+ // captures cannot repair that gap. Keep the failure sticky on this fork.
368
+ this.fail(e);
369
+ throw e;
370
+ } finally { this.capturing = false; }
371
+ }
372
+ }
373
+ `;
@@ -75,6 +75,7 @@ import { microsoft } from "./microsoft.js";
75
75
  import { SUPABASE_WEBHOOKS_SQL } from "./supabase-webhooks.js";
76
76
  import { postgresTls } from "./postgres-tls.js";
77
77
  import { supabasePoolerService } from "./supabase-pooler.js";
78
+ import { SUPABASE_COVERAGE_COLLECTOR, supabaseFunctionsCoverage } from "./supabase-coverage.js";
78
79
  import {
79
80
  mapSupabaseConfig,
80
81
  parseSupabaseConfigFile,
@@ -1065,6 +1066,8 @@ services:
1065
1066
  // ──────────────────────────────────────────────────────────────────────────
1066
1067
 
1067
1068
  const FUNCTIONS_MAIN_TS = String.raw`// spectest-generated edge-functions router. Do not edit.
1069
+ import { EdgeCoverage } from "./coverage.js";
1070
+ const edgeCoverage = new EdgeCoverage();
1068
1071
  const FUNCTIONS_DIR = Deno.env.get("FUNCTIONS_DIR") ?? "/repo/supabase/functions";
1069
1072
  const JWT_SECRET = Deno.env.get("JWT_SECRET") ?? "";
1070
1073
  const VERIFY_JWT = Deno.env.get("VERIFY_JWT") === "true";
@@ -1129,8 +1132,10 @@ const WORKER_TIMEOUT_MS = 24 * 60 * 60 * 1000;
1129
1132
  * isolates, and an isolate reaped for idleness is rebooted by the next
1130
1133
  * test that calls the function — a boot's worth of dirtied memory in that
1131
1134
  * test's own snapshot diff. */
1132
- function workerFor(name: string) {
1135
+ async function workerFor(name: string) {
1136
+ const maybeEntrypoint = await edgeCoverage.wrap(FUNCTIONS_DIR + "/" + name + "/index.ts");
1133
1137
  return EdgeRuntime.userWorkers.create({
1138
+ maybeEntrypoint,
1134
1139
  servicePath: FUNCTIONS_DIR + "/" + name,
1135
1140
  memoryLimitMb: 256,
1136
1141
  workerTimeoutMs: WORKER_TIMEOUT_MS,
@@ -1353,6 +1358,7 @@ async function sharedWorker(): Promise<any | null> {
1353
1358
  try {
1354
1359
  await createShared();
1355
1360
  } catch (e) {
1361
+ await edgeCoverage.forgetUnstarted(SHARED_DIR + "/index.ts");
1356
1362
  reason = "the shared isolate failed to boot: " + String(e);
1357
1363
  }
1358
1364
  }
@@ -1364,8 +1370,10 @@ async function sharedWorker(): Promise<any | null> {
1364
1370
  return spec.reason === null ? createShared() : null;
1365
1371
  }
1366
1372
 
1367
- function createShared() {
1373
+ async function createShared() {
1374
+ const maybeEntrypoint = await edgeCoverage.wrap(SHARED_DIR + "/index.ts");
1368
1375
  return EdgeRuntime.userWorkers.create({
1376
+ maybeEntrypoint,
1369
1377
  servicePath: SHARED_DIR,
1370
1378
  // A cap on the one isolate that holds every function, not a reservation.
1371
1379
  memoryLimitMb: 2048,
@@ -1393,8 +1401,8 @@ function createShared() {
1393
1401
  async function warmAll(): Promise<{ mode: "shared" | "per-function"; warmed: string[]; failed: Record<string, string> }> {
1394
1402
  const names = await functionNames();
1395
1403
  if ((await sharedWorker()) !== null) return { mode: "shared", warmed: names, failed: {} };
1396
- // All at once: each boot is mostly module loading, and the isolates come
1397
- // up concurrently.
1404
+ // Each worker starts behind a generated gate; attach and initialize them
1405
+ // concurrently, then release each only after precise coverage has started.
1398
1406
  const results = await Promise.allSettled(names.map((name) => workerFor(name)));
1399
1407
  const warmed: string[] = [];
1400
1408
  const failed: Record<string, string> = {};
@@ -1411,8 +1419,16 @@ Deno.serve(async (req: Request) => {
1411
1419
  // Ready probe — answered before any auth check, so bring-up never needs a
1412
1420
  // token, and never treated as a function name.
1413
1421
  if (pathname === "/_spectest/health") return new Response("ok");
1422
+ if (pathname === "/_spectest/coverage" && req.method === "POST") {
1423
+ try { return json(await edgeCoverage.capture()); }
1424
+ catch (error) { return json({ error: String(error) }, 500); }
1425
+ }
1414
1426
  // Setup-time warm-up (see warmAll); never treated as a function name.
1415
- if (pathname === "/_spectest/warm") return json(await warmAll());
1427
+ if (pathname === "/_spectest/warm") {
1428
+ const warmed = await warmAll();
1429
+ await edgeCoverage.ready();
1430
+ return json(warmed);
1431
+ }
1416
1432
 
1417
1433
  const name = pathname.split("/")[1] ?? "";
1418
1434
  if (name === "") return json({ msg: "missing function name in request" }, 400);
@@ -2286,8 +2302,15 @@ CREATE SCHEMA IF NOT EXISTS _supavisor AUTHORIZATION supabase_admin;
2286
2302
  volumes: [{ source: projectRootPath(), target: REPO_MOUNT, readOnly: true, reachExempt: true }],
2287
2303
  // Our router (see FUNCTIONS_MAIN_TS) sits outside that mount, so
2288
2304
  // the project never has to carry a `main/` function of ours.
2289
- files: [{ path: "/home/deno/main/index.ts", content: FUNCTIONS_MAIN_TS }],
2290
- args: ["start", "--main-service", "/home/deno/main", "--port", "9000"],
2305
+ files: [
2306
+ { path: "/home/deno/main/index.ts", content: FUNCTIONS_MAIN_TS },
2307
+ { path: "/home/deno/main/coverage.js", content: SUPABASE_COVERAGE_COLLECTOR },
2308
+ ],
2309
+ // Generated entry gates hold project imports until coverage starts;
2310
+ // the inspector stays live and is not exposed to peer containers.
2311
+ args: ["start", "--main-service", "/home/deno/main", "--port", "9000", "--inspect=127.0.0.1:9229"],
2312
+ workdir: REPO_MOUNT,
2313
+ coverage: { adapters: [supabaseFunctionsCoverage(fnRelPath)] },
2291
2314
  env: {
2292
2315
  JWT_SECRET: jwtSecret,
2293
2316
  // Where the router looks for `<name>/`, inside the repo mount.