@ai-ecoverse/slicc-shared-web 1.23.2 → 1.23.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -187,7 +187,7 @@ test('boots', async (t) => {
187
187
  | `roots` | `[urlPrefix, directory]` pairs the local server serves, first match wins | `[['/', 'src/']]` |
188
188
  | `aliases` | Extra `[urlPrefix, directory]` pairs used only to map coverage and profiles back to files, for scripts that something else serves, such as a service worker | none |
189
189
  | `isolated` | Send COOP, COEP and CORP on every response, so pages are cross-origin isolated | `false` |
190
- | `coverage` | URL prefixes whose `.js`/`.mjs` scripts count for coverage. `node_modules/` never does. A `.map` next to a file is used | `['/']` |
190
+ | `coverage` | URL prefixes whose `.js`/`.mjs` scripts count for coverage. `node_modules/` never does. A `.map` next to a file is used. `[]` collects nothing: without profiling, no target gets the debugger, the profiler, exit breakpoints or a `beforeunload` pause, and workers don't wait for the harness to start | `['/']` |
191
191
  | `exits` | `{ urlPath: [regex, ...] }`: a breakpoint on the first line matching each pattern in that worker script, where the harness takes the worker's coverage and profile before it closes itself | none |
192
192
  | `intercept` | Remote URL prefixes answered from a disk cache in `node_modules/.cache/`. Registry documents (anything on a `registry.*` host but a `/-/….tgz` tarball: packuments, abbreviated or full, and dist-tags) are fetched fresh once per test process and only served from the disk cache when the registry can't be reached (a `4xx` is passed on) | none |
193
193
  | `extensions` | Unpacked extension directories to load. They are loaded with `Extensions.loadUnpacked` (behind `--enable-unsafe-extension-debugging`) once the harness is attached, so their service workers start paused like every other target. Their scripts are covered and profiled like the repo's own, and tests then run in the default browser context, closing their tabs when they end, because Chrome does not run extensions in the per-test contexts | none |
@@ -217,7 +217,7 @@ test('boots', async (t) => {
217
217
  - the summary runs in the test process, which also serves the page's files and talks CDP, so it is linear in the trace's events: a busy page's half-million-event trace takes well under a second, and the page's fetches keep getting answers meanwhile;
218
218
  - it adds a line for every debugger pause still held in the browser, in any target, with its id, URL, start time, reason and top call frames.
219
219
 
220
- A pause in one target blocks every page in the same renderer process, so those pause lines name the culprit even when it isn't the page under test. The harness resumes its own coverage pauses (`beforeunload`, worker exits) within 10 s, even when collecting coverage fails. Downloads of intercepted URLs time out after 60 s and are tried up to three times; a `4xx` is not retried. `chrome.requests` lists the paths the server saw in this test, `chrome.overrides` is a `Map` of paths to bodies served instead of files, and `chrome.cdn` takes `status` (answer every intercepted request with it), `corrupt` (flip the last byte) and lists the intercepted `requests`. All of them reset with each test. `serve(options)` starts the same server on its own, for an `npm start`.
220
+ Coverage is kept as one entry per script URL, each worker's counts summed into it as the worker's coverage is taken, so a run of thousands of workers keeps no more than its distinct scripts. A worker paused at its exit breakpoint is resumed as soon as its coverage and profile are taken; the profile is written to disk after. A pause in one target blocks every page in the same renderer process, so those pause lines name the culprit even when it isn't the page under test. The harness resumes its own coverage pauses (`beforeunload`, worker exits) within 10 s, even when collecting coverage fails. Downloads of intercepted URLs time out after 60 s and are tried up to three times; a `4xx` is not retried. `chrome.requests` lists the paths the server saw in this test, `chrome.overrides` is a `Map` of paths to bodies served instead of files, and `chrome.cdn` takes `status` (answer every intercepted request with it), `corrupt` (flip the last byte) and lists the intercepted `requests`. All of them reset with each test. `serve(options)` starts the same server on its own, for an `npm start`.
221
221
 
222
222
  Why it works the way it does:
223
223
 
@@ -2,12 +2,12 @@ import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
2
  import { basename, relative } from 'node:path';
3
3
  import { cwd } from 'node:process';
4
4
  import { pathToFileURL } from 'node:url';
5
+ import Util from 'monocart-coverage-reports/util';
5
6
  import { CRASHED } from './cdp.mjs';
6
7
  import { trace } from './trace.mjs';
7
8
  import { bounded, ignore, raw, samples, sleep, TIMED_OUT } from './util.mjs';
8
9
 
9
10
  const profiled = new Set(['page', 'worker', 'service_worker', 'shared_worker']);
10
- const nested = { autoAttach: true, waitForDebuggerOnStart: true, flatten: true };
11
11
  const sampling = [['Profiler.setSamplingInterval', { interval: 100 }], ['Profiler.start']];
12
12
  const unload = "addEventListener('beforeunload', () => { debugger; })";
13
13
 
@@ -91,13 +91,13 @@ async function sample(cdp, pauses, [sessionId, target], dir, tag, profiling) {
91
91
  return `${label(target)}: ${state}, profile ${name}`;
92
92
  }
93
93
 
94
- function collect(send, profiling) {
95
- const stop = profiling ? send('Profiler.stop') : {};
96
- const taken = Promise.all([send('Profiler.takePreciseCoverage'), stop]);
97
- return Promise.race([taken, sleep(3000)]).then(
98
- (answer) => answer ?? [{}, {}],
99
- () => [{}, {}]
100
- );
94
+ function collect(send, profiling, collecting) {
95
+ const asked = (on, method) => (on ? send(method).catch(() => ({})) : {});
96
+ const taken = Promise.all([
97
+ asked(collecting, 'Profiler.takePreciseCoverage'),
98
+ asked(profiling, 'Profiler.stop'),
99
+ ]);
100
+ return Promise.race([taken, sleep(3000)]).then((answer) => answer ?? [{}, {}]);
101
101
  }
102
102
 
103
103
  function held(pauses) {
@@ -131,7 +131,48 @@ function contextOf(sessions, parents, sessionId) {
131
131
  return undefined;
132
132
  }
133
133
 
134
+ export function retain(scripts, result) {
135
+ for (const script of result) {
136
+ const prev = scripts.get(script.url);
137
+ const functions = prev ? Util.mergeV8Coverage([prev, script]).functions : script.functions;
138
+ scripts.set(script.url, { ...(prev ?? script), functions });
139
+ }
140
+ return scripts;
141
+ }
142
+
143
+ export function commands({ type, url }, { coverage = ['/'], exits = new Map(), profiling } = {}) {
144
+ const collecting = coverage.length > 0;
145
+ const watching = collecting || Boolean(profiling);
146
+ const nested = { autoAttach: true, waitForDebuggerOnStart: watching, flatten: true };
147
+ const list = [];
148
+ if (profiled.has(type)) {
149
+ list.push(['Runtime.enable']);
150
+ if (watching) list.push(['Profiler.enable']);
151
+ if (collecting) {
152
+ list.push(['Profiler.startPreciseCoverage', { callCount: true, detailed: true }]);
153
+ }
154
+ list.push(['Target.setAutoAttach', nested]);
155
+ if (profiling) list.push(...sampling);
156
+ }
157
+ const lines = type === 'worker' && watching ? exits.get(pathOf(url)) : undefined;
158
+ if (lines) {
159
+ list.push(
160
+ ['Debugger.enable'],
161
+ ...lines.map((lineNumber) => ['Debugger.setBreakpointByUrl', { url, lineNumber }])
162
+ );
163
+ }
164
+ if (type === 'page') {
165
+ list.push(['Network.enable'], ['Page.enable']);
166
+ if (watching) {
167
+ list.push(['Debugger.enable'], ['Page.addScriptToEvaluateOnNewDocument', { source: unload }]);
168
+ }
169
+ }
170
+ return list;
171
+ }
172
+
134
173
  export function recorder(cdp, server, { coverage = ['/'], exits = new Map(), profiling } = {}) {
174
+ const collecting = coverage.length > 0;
175
+ const watching = collecting || Boolean(profiling);
135
176
  const sessions = new Map();
136
177
  const pauses = new Map();
137
178
  const parents = new Map();
@@ -143,18 +184,21 @@ export function recorder(cdp, server, { coverage = ['/'], exits = new Map(), pro
143
184
  async function dump(sessionId, target, restart) {
144
185
  const current = run;
145
186
  const send = (method) => cdp.send(method, {}, sessionId);
146
- const [{ result }, { profile }] = await collect(send, profiling);
147
- if (!(result && current)) return;
148
- current.scripts.push(...result.filter(ours));
187
+ const [{ result }, { profile }] = await collect(send, profiling, collecting);
188
+ if (!current) return;
189
+ retain(current.scripts, (result ?? []).filter(ours));
149
190
  if (!profile) return;
150
191
  if (restart) send('Profiler.start').catch(ignore);
151
192
  current.profiles += 1;
152
193
  selfTimes(profile, server, current.self);
153
194
  const name = `${String(current.profiles).padStart(3, '0')}-${label(target)}.cpuprofile`;
154
- await writeFile(new URL(name, current.dir), JSON.stringify(profile));
195
+ current.writes.push(
196
+ writeFile(new URL(name, current.dir), JSON.stringify(profile)).catch(ignore)
197
+ );
155
198
  }
156
199
 
157
200
  async function checkpoint() {
201
+ if (!watching) return;
158
202
  const current = [...sessions].filter(([, target]) => target.browserContextId === run?.context);
159
203
  await Promise.all(current.map(([sessionId, target]) => dump(sessionId, target, true)));
160
204
  }
@@ -170,38 +214,9 @@ export function recorder(cdp, server, { coverage = ['/'], exits = new Map(), pro
170
214
  return tabs.get(targetId);
171
215
  }
172
216
 
173
- function commands({ type, url }) {
174
- const list = [];
175
- if (profiled.has(type)) {
176
- list.push(
177
- ['Runtime.enable'],
178
- ['Profiler.enable'],
179
- ['Profiler.startPreciseCoverage', { callCount: true, detailed: true }],
180
- ['Target.setAutoAttach', nested]
181
- );
182
- if (profiling) list.push(...sampling);
183
- }
184
- const lines = type === 'worker' ? exits.get(pathOf(url)) : undefined;
185
- if (lines) {
186
- list.push(
187
- ['Debugger.enable'],
188
- ...lines.map((lineNumber) => ['Debugger.setBreakpointByUrl', { url, lineNumber }])
189
- );
190
- }
191
- if (type === 'page') {
192
- list.push(
193
- ['Network.enable'],
194
- ['Debugger.enable'],
195
- ['Page.enable'],
196
- ['Page.addScriptToEvaluateOnNewDocument', { source: unload }]
197
- );
198
- }
199
- return list;
200
- }
201
-
202
217
  function attach({ sessionId, targetInfo, waitingForDebugger }) {
203
218
  if (profiled.has(targetInfo.type)) sessions.set(sessionId, targetInfo);
204
- const list = commands(targetInfo);
219
+ const list = commands(targetInfo, { coverage, exits, profiling });
205
220
  if (waitingForDebugger) list.push(['Runtime.runIfWaitingForDebugger']);
206
221
  const ready = Promise.all(
207
222
  list.map(([method, params]) => cdp.send(method, params, sessionId).catch(ignore))
@@ -283,14 +298,25 @@ export function recorder(cdp, server, { coverage = ['/'], exits = new Map(), pro
283
298
  }
284
299
 
285
300
  function begin(context, dir, name) {
286
- run = { context, dir, name, scripts: [], console: early.splice(0), profiles: 0, self: {} };
301
+ run = {
302
+ context,
303
+ dir,
304
+ name,
305
+ scripts: new Map(),
306
+ writes: [],
307
+ console: early.splice(0),
308
+ profiles: 0,
309
+ self: {},
310
+ };
287
311
  }
288
312
 
289
313
  async function end() {
290
314
  await checkpoint();
291
315
  const current = run;
292
316
  run = null;
293
- const entries = await Promise.all(current.scripts.map((script) => entry(server, script)));
317
+ await Promise.all(current.writes);
318
+ const scripts = [...current.scripts.values()];
319
+ const entries = await Promise.all(scripts.map((script) => entry(server, script)));
294
320
  const found = { profiles: current.profiles, self: current.self };
295
321
  await mkdir(raw, { recursive: true });
296
322
  await mkdir(samples, { recursive: true });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-ecoverse/slicc-shared-web",
3
- "version": "1.23.2",
3
+ "version": "1.23.3",
4
4
  "description": "Shared Renovate, Biome, TypeScript, lefthook and GitHub Actions configuration, plus the CDP integration-test harness, for SLICC's web repos",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",