@ai-ecoverse/slicc-shared-web 1.24.2 → 1.25.1

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
@@ -191,6 +191,7 @@ test('boots', async (t) => {
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 |
194
+ | `extension` | Load the [harness extension](#harness-extension). `false`, or `SLICC_HARNESS_EXTENSION=0` in the environment, leaves it out; any other value of either is an error | `true` |
194
195
  | `persistent` | Run every test in the default browser context, on the launch's on-disk `slicc-harness-*` profile, instead of a fresh off-the-record context per test. Off-the-record contexts keep OPFS in memory, with a far smaller real budget than `navigator.storage.estimate()` reports, so a suite that stores hundreds of MB there needs this. When a test ends, its tabs are closed and `Storage.clearDataForOrigin` (`storageTypes: 'all'`) clears the server's origin, every origin a page in the context showed (popups the app opened included) and every origin the harness's tabs got a response from, so nothing leaks into the next test. If clearing fails, the test fails | `false` |
195
196
  | `executable` | The Chromium binary. Without it, `$CHROME_PATH`, then slicc-cdp's `findBrowser()`, then playwright-core (see above) | found |
196
197
  | `args` | Extra Chromium flags, such as `--host-resolver-rules` or `--ignore-certificate-errors` | none |
@@ -229,11 +230,23 @@ Why it works the way it does:
229
230
  - Coverage of a script served from `chrome.overrides` would be mapped onto the file on disk, so a path overridden during a test is left out of that test's coverage.
230
231
  - A CI cache restored with a prefix key kept packuments from before a release, so pnpm in the page saw an outdated `latest` and failed with `ERR_PNPM_NO_MATCHING_VERSION`. Tarballs and versioned CDN files never change and stay cached forever; registry documents do change, so the disk copy is only the offline fallback.
231
232
  - An unscoped packument cached at `registry.npmjs.org/<name>` sat where the tarball directory `registry.npmjs.org/<name>/-/` goes, so saving one after the other failed with `EISDIR` and pnpm in the page saw `ECONNREFUSED`. Registry documents are now cached as `<path>/index.json`; a file left at the old place is a miss and is removed when something needs its place.
232
- - `--disable-extensions --disable-component-extensions-with-background-pages` keeps a Hangouts service worker out of every run.
233
+ - `--disable-component-extensions-with-background-pages` keeps a Hangouts service worker out of every run, and the fresh profile has no other extension. A launch with no extension at all keeps `--disable-extensions`. No extension goes on the command line (`--load-extension`, `--disable-extensions-except`): every extension, the harness's and a test's, loads once, through `Extensions.loadUnpacked`, because a second load gives an extension two service workers and drops its first runtime port. Once they are loaded, `launch()` fails if any target belongs to an extension it did not load.
233
234
  - The attach event can arrive before `Target.createTarget` returns, so new tabs wait on a slot keyed by target id.
234
235
  - A worker blocked in `Atomics.wait`, or one that is already gone, may never answer; snapshots give up after 3 s, and closing a context or the browser after 10 s. A call to a target that detaches or crashes fails instead of waiting forever, and a new tab that never attaches fails after 10 s.
235
236
  - A WebSocket that has closed takes new messages without an error, and a crashed target never answers, so after a crash every call used to wait out its own deadline: a browser that died 4 s in showed up as `no answer` 15 minutes later. The harness now remembers the crash or the exit and fails each call with it.
236
237
 
238
+ ## Harness extension
239
+
240
+ Real users run content-script extensions, such as password managers and Grammarly, and each one adds an isolated JavaScript world with origin `chrome-extension://<id>` to every frame of every page. Over raw CDP, `Runtime.executionContextCreated` reports it as `{ origin: 'chrome-extension://<id>', auxData: { isDefault: false, type: 'isolated' } }`. slicc-cdp#377: bios's guard took that world for a protected page and refused everything, and CI never saw it because the harness's Chrome had no extension. So every browser `launch()` starts now carries one by default.
241
+
242
+ `harness/extension/` is an MV3 extension with no permissions, only a content script on `<all_urls>`, in all frames, at `document_start`. It sets `data-slicc-harness-extension="<id>"` on `document.documentElement`. On a page whose URL has the query flag `slicc-extension-frame` (`/?slicc-extension-frame`), it also adds a hidden `<iframe>` of its own `chrome-extension://<id>/frame.html` to the top frame, for testing extension-origin frames. Its manifest has a fixed `key`, so its id is always `ankmbodmgimjemnojmeddfcdlbocolob`, exported as `EXTENSION_ID` (and its directory as `EXTENSION_PATH`) from the harness. `chrome.extension` is `{ id, path }` for a launch that loaded it and `null` for one that didn't, so a test can assert either.
243
+
244
+ Chrome gets `--headless=new`, which runs extensions, and `--enable-unsafe-extension-debugging`. Once attached, the harness loads the extension directory with `Extensions.loadUnpacked` and `enableInIncognito: true`, so it runs in the default context and in the off-the-record context each test gets, and tests stay in their own contexts. If it loads with any other id, or not at all, `launch()` fails rather than going on without it. Its script is not counted for coverage.
245
+
246
+ A lane that can't have it opts out explicitly, in one of two ways:
247
+ - `launch({ extension: false })`, for one launch;
248
+ - `SLICC_HARNESS_EXTENSION=0` in the test process's environment, for every launch. `1` or unset loads it; any other value is an error, so a typo never turns it off.
249
+
237
250
  ## Cleanup
238
251
 
239
252
  `close()` stops Chrome and removes its profile. It asks Chrome to close, waits up to 10 s for the exit, sends `SIGKILL`, waits up to 5 s more and then moves on with a warning, so a browser that ignores `Browser.close` or a missed exit never hangs teardown. A test process that ends without `close()` still leaves nothing running:
@@ -9,14 +9,21 @@ import { executablePath, explicit } from './browser.mjs';
9
9
  import { cdn } from './cdn.mjs';
10
10
  import { CRASHED, connect, pipe } from './cdp.mjs';
11
11
  import { crashpad } from './dumps.mjs';
12
- import { extensionSource, install, unpacked } from './extensions.mjs';
12
+ import {
13
+ builtinWanted,
14
+ exclusive,
15
+ extensionSource,
16
+ install,
17
+ installBuiltin,
18
+ unpacked,
19
+ } from './extensions.mjs';
13
20
  import { page } from './page.mjs';
14
21
  import { breakpoints, recorder } from './recorder.mjs';
15
22
  import { serve } from './server.mjs';
16
23
  import { artifacts, bounded, ignore, sleep, slug, TIMED_OUT } from './util.mjs';
17
24
 
18
25
  export const flags = [
19
- '--headless',
26
+ '--headless=new',
20
27
  '--remote-debugging-port=0',
21
28
  '--remote-debugging-pipe',
22
29
  '--no-first-run',
@@ -33,14 +40,20 @@ export const flags = [
33
40
  ];
34
41
 
35
42
  export const unrealistic = [
36
- '--headless',
43
+ '--headless=new',
37
44
  '--disable-background-timer-throttling',
38
45
  '--disable-backgrounding-occluded-windows',
39
46
  '--disable-renderer-backgrounding',
40
47
  ];
41
48
 
42
- export function commandLine(profile, extensions = [], extra = [], realistic = false) {
43
- const loaded = extensions.length > 0;
49
+ export function commandLine(
50
+ profile,
51
+ extensions = [],
52
+ extra = [],
53
+ realistic = false,
54
+ builtin = false
55
+ ) {
56
+ const loaded = builtin || extensions.length > 0;
44
57
  const dropped = new Set([
45
58
  ...(loaded ? ['--disable-extensions'] : []),
46
59
  ...(realistic ? unrealistic : []),
@@ -293,6 +306,7 @@ export async function launch({
293
306
  exits = {},
294
307
  intercept = [],
295
308
  extensions = [],
309
+ extension = true,
296
310
  args = [],
297
311
  timeout,
298
312
  stallAfter,
@@ -301,6 +315,7 @@ export async function launch({
301
315
  persistent = false,
302
316
  executable,
303
317
  } = {}) {
318
+ const builtin = builtinWanted(extension, inherited);
304
319
  const browser = executable === undefined ? await executablePath() : explicit(executable);
305
320
  pruning ??= prune();
306
321
  await pruning;
@@ -314,7 +329,7 @@ export async function launch({
314
329
  const dumps = await crashpad();
315
330
  const { child, exited, stderr } = await start(
316
331
  userData,
317
- commandLine(userData, loaded, args, realistic),
332
+ commandLine(userData, loaded, args, realistic, builtin),
318
333
  browser,
319
334
  dumps.env
320
335
  ).catch(async (error) => {
@@ -351,7 +366,18 @@ export async function launch({
351
366
  waitForDebuggerOnStart: true,
352
367
  flatten: true,
353
368
  });
354
- await install(cdp, found);
369
+ const harnessExtension = await (async () => {
370
+ const own = builtin ? await installBuiltin(cdp) : null;
371
+ await install(cdp, found);
372
+ await exclusive(cdp, [...(own ? [own.id] : []), ...found.keys()]);
373
+ return own;
374
+ })().catch(async (error) => {
375
+ await stop(cdp, child);
376
+ untrack();
377
+ await rm(userData, { recursive: true, force: true });
378
+ await Promise.all([dumps.remove(), server.close()]);
379
+ throw error;
380
+ });
355
381
 
356
382
  async function tabs() {
357
383
  const { targetInfos } = await cdp.send('Target.getTargets');
@@ -411,6 +437,7 @@ export async function launch({
411
437
  url: server.url,
412
438
  pid: child.pid,
413
439
  profile: userData,
440
+ extension: harnessExtension,
414
441
  cdn: remote.state,
415
442
  requests: server.requests,
416
443
  overrides: server.overrides,
@@ -0,0 +1,15 @@
1
+ const root = document.documentElement;
2
+ if (root) root.dataset.sliccHarnessExtension = chrome.runtime.id;
3
+ const wanted = new URLSearchParams(location.search).has('slicc-extension-frame');
4
+ if (wanted && window === window.top) {
5
+ const frame = document.createElement('iframe');
6
+ frame.src = chrome.runtime.getURL('frame.html');
7
+ frame.dataset.sliccHarnessExtension = chrome.runtime.id;
8
+ frame.hidden = true;
9
+ const attach = () => (document.body ?? document.documentElement).append(frame);
10
+ if (document.readyState === 'loading') {
11
+ document.addEventListener('DOMContentLoaded', attach, { once: true });
12
+ } else {
13
+ attach();
14
+ }
15
+ }
@@ -0,0 +1,8 @@
1
+ <!doctype html>
2
+ <html>
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>slicc harness extension frame</title>
6
+ </head>
7
+ <body></body>
8
+ </html>
@@ -0,0 +1,15 @@
1
+ {
2
+ "manifest_version": 3,
3
+ "name": "slicc harness content script",
4
+ "version": "1.0.0",
5
+ "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtijyxGxZi2jKhXS+8Le/kCpxmybs7P7tulmwdGG4pERze0UAJ1d95NwzZ3vXoND/sC+BdxPdstIBg7RvBFdFZKSOZFPqBTDHNiE40HHo+jpxjT3o1sFZQGtUIQpY9PFblnfWs0mhD0tslY4a3TVDusoMlnhZ49TWLumeShEiSgUcwDYzAaWx/PYhfl6WrvbRh4KbYPjcyVhjzvazxU+4QThzqgNr1GI/zcIBAGySiJv9P0VfJ7yg+iR/Yjmmoxz0XIZlp2vhqqICcSl884pUDYjbO9np10+887iMM0g0z9+X3CmxXNLLwIu3CVdV5ZvgEh6eOrwfRjczXlEoZkR+UwIDAQAB",
6
+ "content_scripts": [
7
+ {
8
+ "matches": ["<all_urls>"],
9
+ "js": ["content.js"],
10
+ "all_frames": true,
11
+ "run_at": "document_start"
12
+ }
13
+ ],
14
+ "web_accessible_resources": [{ "resources": ["frame.html"], "matches": ["<all_urls>"] }]
15
+ }
@@ -1,6 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { readFile, realpath } from 'node:fs/promises';
3
3
  import { join, normalize, sep } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
4
5
 
5
6
  export function extensionId(input) {
6
7
  const hex = createHash('sha256').update(input).digest('hex').slice(0, 32);
@@ -33,3 +34,45 @@ export async function install(cdp, found) {
33
34
  if (id !== expected) found.set(id, root);
34
35
  }
35
36
  }
37
+
38
+ export const BUILTIN_PATH = fileURLToPath(new URL('./extension', import.meta.url));
39
+ export const BUILTIN_ID = 'ankmbodmgimjemnojmeddfcdlbocolob';
40
+ export const OPT_OUT = 'SLICC_HARNESS_EXTENSION';
41
+
42
+ export function builtinWanted(option, env) {
43
+ const value = env[OPT_OUT];
44
+ if (value !== undefined && value !== '0' && value !== '1') {
45
+ throw new Error(
46
+ `${OPT_OUT} is ${JSON.stringify(value)}; set it to 0 to leave the harness extension out, or 1 (or unset) to load it`
47
+ );
48
+ }
49
+ if (option !== true && option !== false) {
50
+ throw new Error(
51
+ `launch({ extension }) is ${JSON.stringify(option)}; pass false to leave the harness extension out`
52
+ );
53
+ }
54
+ return option && value !== '0';
55
+ }
56
+
57
+ export async function installBuiltin(cdp) {
58
+ const { id } = await cdp.send('Extensions.loadUnpacked', {
59
+ path: BUILTIN_PATH,
60
+ enableInIncognito: true,
61
+ });
62
+ if (id !== BUILTIN_ID) {
63
+ throw new Error(`the harness extension loaded as ${id}, not ${BUILTIN_ID}`);
64
+ }
65
+ return { id, path: BUILTIN_PATH };
66
+ }
67
+
68
+ export async function exclusive(cdp, allowed) {
69
+ const { targetInfos } = await cdp.send('Target.getTargets');
70
+ const hosts = targetInfos
71
+ .map(({ url }) => url)
72
+ .filter((url) => url.startsWith('chrome-extension://'))
73
+ .map((url) => new URL(url).host);
74
+ const foreign = [...new Set(hosts)].filter((host) => !allowed.includes(host));
75
+ if (foreign.length > 0) {
76
+ throw new Error(`Chrome loaded extensions the harness did not ask for: ${foreign.join(', ')}`);
77
+ }
78
+ }
package/harness/index.mjs CHANGED
@@ -1,4 +1,9 @@
1
1
  export { connect } from './cdp.mjs';
2
2
  export { launch } from './chrome.mjs';
3
+ export {
4
+ BUILTIN_ID as EXTENSION_ID,
5
+ BUILTIN_PATH as EXTENSION_PATH,
6
+ OPT_OUT as EXTENSION_OPT_OUT,
7
+ } from './extensions.mjs';
3
8
  export { isolation, serve } from './server.mjs';
4
9
  export { slug } from './util.mjs';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-ecoverse/slicc-shared-web",
3
- "version": "1.24.2",
3
+ "version": "1.25.1",
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",
@@ -62,7 +62,7 @@
62
62
  "release": "semantic-release"
63
63
  },
64
64
  "devDependencies": {
65
- "@ai-ecoverse/slicc-browsers": "1.8.4",
65
+ "@ai-ecoverse/slicc-browsers": "1.8.5",
66
66
  "@biomejs/biome": "2.5.15",
67
67
  "monocart-coverage-reports": "2.13.2",
68
68
  "playwright-core": "1.64.0",