@ai-ecoverse/slicc-shared-web 1.22.1 → 1.23.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
@@ -136,7 +136,8 @@ The committed public CLI integration regressions use real git repositories and a
136
136
 
137
137
  The diff-coverage hook, `slicc-unit-cover`, runs only the unit tests that cover the staged change, then `slicc-diff-cover` on their `coverage/unit/lcov.info`, so every staged line in `src/` still has to run:
138
138
 
139
- - **What counts as changed:** the staged files (`git diff --cached --name-only`). Since `test/unit/` is gitignored, files in it count as changed when they were modified after HEAD last moved (the last commit, checkout or pull).
139
+ - **What counts as changed:** the staged files (`git diff --cached --name-only`), and nothing else. `test/unit/` is gitignored, and repos that keep their unit tests in a store outside git sync the whole store into it before a commit, which brings in tests for code that is on other branches; so a unit test that is new or edited runs only when its imports reach a staged file, like any other. One that reaches nothing staged adds no coverage to the staged lines.
140
+ - **A unit test for code this tree doesn't have:** a test whose imports reach a staged file but also a repo file that doesn't exist and isn't a staged deletion (a store test for a module on another branch) is skipped, and the hook names it in one line before the count.
140
141
  - **Which tests run:** every `*.test.*` file in `test/unit/` that is changed, or whose static imports reach a changed file. The import graph is parsed with [acorn](https://github.com/acornjs/acorn), TypeScript after Node's type stripping. It follows `import`, `export … from`, `import()`, `require()` and `new URL(…, import.meta.url)` with literal paths, relative or through the `paths` of `tsconfig.json` (and the files it extends). A path may leave out its extension or name `index`, and `.js` also finds `.ts`. Type-only imports don't count, and nothing is followed into `node_modules/`.
141
142
  - **Barrels are followed by name:** a test that imports `{ a, b }` from a module follows only what provides `a` and `b`: `export { a } from`, `export { default as a } from`, an imported binding exported again, and `export * from`, by the target's own exports. `const { a, b } = await import('…')` with a literal path is followed by name too. A name the module declares itself follows all of that module's imports. A namespace import (`import * as`), any other `import()` (bound to a namespace, with `.then`, or destructured with a computed key or a rest element), a `require()`, and an `export *` that leads outside the repo or into CommonJS (any `.cjs` or `.cts` file) all count as the whole module.
142
143
  - **No code staged** (only docs, YAML, JSON or lockfiles): no unit tests and no diff coverage; the hook passes.
@@ -198,7 +199,7 @@ test('boots', async (t) => {
198
199
  | `profile` | Record a CPU profile of every target, sampled every 100 µs | `true` if `SLICC_PROFILE=1`, else `false` |
199
200
  | `realistic` | Run Chrome as a user would: headed, and without `--disable-background-timer-throttling`, `--disable-backgrounding-occluded-windows` and `--disable-renderer-backgrounding`, so a tab behind another one is hidden and throttled. For measuring background tabs. It needs a display: on CI, run the tests under `xvfb-run -a` | `false` |
200
201
 
201
- `chrome.page(t)` opens a tab and returns the page API: `goto(path)`, `reload()`, `evaluate(fn, ...args)`, `until(fn, ...args)`, `press(key, ...modifiers)` (a key name like `Enter` or `F5`, or a single character typed with its US-layout key code), `type(text)`, `insert(text)`, `enter()`, `init(fn)` (runs in every new document), `expose(name, handler)` (a binding the page calls with a JSON string), `screenshot(file)`, `tab()` (another tab in the same context), `close()`, `send(method, params, ms)` (a raw CDP call in the tab's session), `errors`, `responses` and `dir` (the test's artifact directory). `chrome.pid` is the browser's process id and `chrome.profile` its `slicc-harness-*` profile directory in `$TMPDIR`. `goto` and `reload` wait until the new document is complete and no longer `about:blank`, and retry the navigation once if that never happens. `until` polls until the function returns a truthy value (not only strict `true`) and resolves with that value; the timeout error names the last result. `within(ms, fn, ...args)` is `until` with its own deadline, for a stage that should take a known time. Both stop at the deadline even if one evaluation never answers. Every CDP call has a deadline: `connect(url).send(method, params, sessionId, ms)` rejects with `<method>: no answer in <ms> ms` (60 s unless given), so a stuck page fails its test instead of hanging the run. A crash fails it at once instead:
202
+ `chrome.page(t)` opens a tab and returns the page API: `goto(path)`, `reload()`, `evaluate(fn, ...args)`, `until(fn, ...args)`, `press(key, ...modifiers)` (a key name like `Enter` or `F5`, or a single character typed with its US-layout key code), `type(text)`, `insert(text)`, `enter()`, `init(fn)` (runs in every new document), `expose(name, handler)` (a binding the page calls with a JSON string), `screenshot(file)`, `tab()` (another tab in the same context), `close()`, `send(method, params, ms)` (a raw CDP call in the tab's session), `errors`, `responses` and `dir` (the test's artifact directory). `chrome.pid` is the browser's process id and `chrome.profile` its `slicc-harness-*` profile directory in `$TMPDIR`. `goto` and `reload` wait until the new document is complete and no longer `about:blank`, and retry the navigation once if that never happens. `until` polls until the function returns a truthy value (not only strict `true`) and resolves with that value; the timeout error names the last result. `within(ms, fn, ...args)` is `until` with its own deadline, for a stage that should take a known time. `run(fn, ...args)` or `run(options, fn, ...args)` is for a job that may outlast the `timeout`: it starts `fn` in the page without holding a `Runtime.evaluate` open, then polls it every `everyMs` (1 s) with short evaluates, and resolves or rejects with the job's own result. It decides slow from hung by progress, not by the clock. Progress is a change in `marker` (a function run in the page at each poll, such as `() => window.done`) or in what `progress` returns (an async function run in Node, such as a probe of a process tree's CPU time). With either one set, a job whose progress stays the same for `quietMs` (60 s) fails with `<label>: no progress for N s after M s`, the last marker and progress values, and the page's pending requests and navigations. `maxMs` (30 min) is the outer bound for a job that keeps moving but never ends. Without a `marker` or `progress` only `maxMs` applies. `label` defaults to the start of `fn`'s source. The job's value must survive `returnByValue`, as with `evaluate`. Both stop at the deadline even if one evaluation never answers. Every CDP call has a deadline: `connect(url).send(method, params, sessionId, ms)` rejects with `<method>: no answer in <ms> ms` (60 s unless given), so a stuck page fails its test instead of hanging the run. A crash fails it at once instead:
202
203
  - when the browser dies, every pending and later call rejects with `<method>: browser exited with <signal>` (or `with code <n>`);
203
204
  - when a renderer crashes, every pending and later call to that target, and to the dedicated workers it started, rejects with `<method>: page renderer crashed (<status>, code <n>) at <url>` (or `worker`, `shared worker`, `service worker`), and `console.log` gets the same line;
204
205
  - `until`, `within`, `goto` and `reload` stop retrying and rethrow it;
@@ -14,13 +14,6 @@ function git(...args) {
14
14
  return run.status === 0 ? run.stdout : undefined;
15
15
  }
16
16
 
17
- function since() {
18
- const moved = git('log', '-g', '-1', '--format=%gd', '--date=unix', 'HEAD')?.match(/\{(\d+)\}/);
19
- const committed = git('log', '-1', '--format=%ct', 'HEAD')?.trim();
20
- const seconds = Math.max(Number(moved?.[1] ?? 0), Number(committed || 0));
21
- return seconds > 0 ? seconds * 1000 : undefined;
22
- }
23
-
24
17
  function run(command, args, env) {
25
18
  const result = spawnSync(command, args, { cwd: root, env, stdio: 'inherit' });
26
19
  if (result.error) throw result.error;
@@ -30,7 +23,12 @@ function run(command, args, env) {
30
23
  function selection(staged) {
31
24
  if (process.env.SLICC_UNIT_ALL === '1') return undefined;
32
25
  try {
33
- const { tests, total } = select({ root, changed: staged, since: since() });
26
+ const { tests, elsewhere, total } = select({ root, changed: staged });
27
+ if (elsewhere.length > 0) {
28
+ say(
29
+ `skipping ${elsewhere.length} that import a module this tree lacks: ${elsewhere.join(' ')}`
30
+ );
31
+ }
34
32
  say(`running ${tests.length} of ${total} unit test files`);
35
33
  return tests;
36
34
  } catch (error) {
package/harness/page.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { writeFile } from 'node:fs/promises';
2
2
  import { flights } from './flight.mjs';
3
+ import { runner } from './run.mjs';
3
4
  import { sleep } from './util.mjs';
4
5
 
5
6
  const masks = { alt: 1, ctrl: 2, meta: 4, shift: 8 };
@@ -153,6 +154,23 @@ export function page(
153
154
  return run(fn, args, timeout);
154
155
  }
155
156
 
157
+ async function expression(source, ms) {
158
+ const { result, exceptionDetails } = await send(
159
+ 'Runtime.evaluate',
160
+ { expression: source, awaitPromise: true, returnByValue: true },
161
+ ms
162
+ );
163
+ if (exceptionDetails) throw new Error(exceptionDetails.exception?.description);
164
+ return decoded(result);
165
+ }
166
+
167
+ const job = runner({
168
+ expression,
169
+ timeout,
170
+ pending: () => flying.pending(),
171
+ capture: stall ? capture : undefined,
172
+ });
173
+
156
174
  async function within(ms, fn, ...args) {
157
175
  const deadline = Date.now() + ms;
158
176
  let last;
@@ -208,6 +226,7 @@ export function page(
208
226
  dispose,
209
227
  send,
210
228
  evaluate,
229
+ run: job,
211
230
  until,
212
231
  within,
213
232
  probed: () => Promise.all(probes),
@@ -0,0 +1,114 @@
1
+ import { sleep } from './util.mjs';
2
+
3
+ const RUN_EVERY = 1000;
4
+ const RUN_POLL = 10000;
5
+ const RUN_QUIET = 60000;
6
+ const RUN_MAX = 30 * 60 * 1000;
7
+
8
+ const unanswered = (error) => /: no answer in \d+ ms$/.test(error.message);
9
+ const seconds = (ms) => `${Math.round(ms / 1000)} s`;
10
+
11
+ export function started(source, args) {
12
+ return `(() => {
13
+ const runs = (globalThis.sliccHarnessRuns ??= []);
14
+ const slot = { done: false };
15
+ runs.push(slot);
16
+ Promise.resolve()
17
+ .then(() => (${source})(...${JSON.stringify(args)}))
18
+ .then(
19
+ (value) => Object.assign(slot, { done: true, value }),
20
+ (error) => Object.assign(slot, { done: true, error: String(error?.stack ?? error) })
21
+ );
22
+ return runs.length - 1;
23
+ })()`;
24
+ }
25
+
26
+ export function polled(id, marker) {
27
+ const mark = marker
28
+ ? `(() => { try { return (${marker})(); } catch (error) { return 'marker threw ' + error; } })()`
29
+ : 'null';
30
+ return `(() => {
31
+ const slot = globalThis.sliccHarnessRuns?.[${id}];
32
+ if (!slot) throw new Error('the page lost the run (it navigated or reloaded)');
33
+ if (slot.done) globalThis.sliccHarnessRuns[${id}] = { done: true };
34
+ return { ...slot, mark: ${mark} };
35
+ })()`;
36
+ }
37
+
38
+ function settings(first, rest) {
39
+ const direct = typeof first === 'function';
40
+ const options = direct ? {} : first;
41
+ const [fn, ...args] = direct ? [first, ...rest] : rest;
42
+ return {
43
+ fn,
44
+ args,
45
+ marker: options.marker,
46
+ progress: options.progress,
47
+ everyMs: options.everyMs ?? RUN_EVERY,
48
+ quietMs: options.quietMs ?? RUN_QUIET,
49
+ maxMs: options.maxMs ?? RUN_MAX,
50
+ label: options.label ?? String(fn).replace(/\s+/g, ' ').slice(0, 60),
51
+ };
52
+ }
53
+
54
+ async function poll(expression, source) {
55
+ try {
56
+ return await expression(source, RUN_POLL);
57
+ } catch (error) {
58
+ if (error.fatal || !unanswered(error)) throw error;
59
+ return undefined;
60
+ }
61
+ }
62
+
63
+ async function probed(progress) {
64
+ if (!progress) return null;
65
+ try {
66
+ return await progress();
67
+ } catch (error) {
68
+ return `threw ${error}`;
69
+ }
70
+ }
71
+
72
+ export function runner({ expression, timeout, pending, capture }) {
73
+ async function failure(run, last, why) {
74
+ if (capture) await capture().catch(() => undefined);
75
+ const lines = [`${run.label}: ${why}`];
76
+ if (run.marker !== undefined) lines.push(`last marker: ${JSON.stringify(last.mark)}`);
77
+ if (run.progress !== undefined) lines.push(`last progress: ${JSON.stringify(last.probe)}`);
78
+ const flying = pending();
79
+ lines.push(...(flying.length ? flying : ['nothing in flight']));
80
+ return new Error(lines.join('\n'));
81
+ }
82
+
83
+ return async function run(first, ...rest) {
84
+ const job = settings(first, rest);
85
+ const watched = job.marker !== undefined || job.progress !== undefined;
86
+ const id = await expression(started(String(job.fn), job.args), timeout);
87
+ const source = polled(id, job.marker && String(job.marker));
88
+ const begun = Date.now();
89
+ const at = { seen: undefined, moved: begun, last: {} };
90
+ for (;;) {
91
+ await sleep(job.everyMs);
92
+ const state = await poll(expression, source);
93
+ if (state?.done) {
94
+ if (state.error !== undefined) throw new Error(state.error);
95
+ return state.value;
96
+ }
97
+ at.last = { mark: state ? state.mark : at.last.mark, probe: await probed(job.progress) };
98
+ const signature = JSON.stringify([at.last.mark, at.last.probe]);
99
+ const now = Date.now();
100
+ if (signature !== at.seen) Object.assign(at, { seen: signature, moved: now });
101
+ if (watched && now - at.moved >= job.quietMs) {
102
+ const why = `no progress for ${seconds(now - at.moved)} after ${seconds(now - begun)}`;
103
+ throw await failure(job, at.last, why);
104
+ }
105
+ if (now - begun >= job.maxMs) {
106
+ throw await failure(
107
+ job,
108
+ at.last,
109
+ `still running after ${seconds(now - begun)}, the outer bound`
110
+ );
111
+ }
112
+ }
113
+ };
114
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-ecoverse/slicc-shared-web",
3
- "version": "1.22.1",
3
+ "version": "1.23.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",
@@ -66,7 +66,7 @@
66
66
  "@biomejs/biome": "2.5.15",
67
67
  "monocart-coverage-reports": "2.13.2",
68
68
  "playwright-core": "1.64.0",
69
- "pnpm": "12.11.1",
69
+ "pnpm": "12.11.2",
70
70
  "semantic-release": "25.0.9"
71
71
  },
72
72
  "peerDependencies": {
package/unit/graph.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { readdirSync, readFileSync, statSync } from 'node:fs';
1
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
2
2
  import { stripTypeScriptTypes } from 'node:module';
3
3
  import { dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
4
  import { parse } from 'acorn';
@@ -243,12 +243,16 @@ function reacher(graph) {
243
243
  const context = { find, provides: provider(graph) };
244
244
  return (start) => {
245
245
  const touched = new Set();
246
+ const absent = [];
246
247
  const seen = new Set();
247
248
  const queue = [[start, BODY]];
248
249
  const go = (file, spec, name) => {
249
250
  const found = find(file, spec);
250
251
  if (found?.hit) queue.push([found.hit, name]);
251
- else if (found) for (const path of found.missing) touched.add(path);
252
+ else if (found) {
253
+ for (const path of found.missing) touched.add(path);
254
+ if (found.missing.length > 0) absent.push(found.missing);
255
+ }
252
256
  };
253
257
  while (queue.length > 0) {
254
258
  const [file, name] = queue.pop();
@@ -263,7 +267,7 @@ function reacher(graph) {
263
267
  else go(next, spec, wanted);
264
268
  }
265
269
  }
266
- return touched;
270
+ return { touched, absent };
267
271
  };
268
272
  }
269
273
 
@@ -298,20 +302,23 @@ function step(info, name, file, context) {
298
302
  return starred(file, info, name, context);
299
303
  }
300
304
 
301
- export function select({ root, changed, since }) {
302
- const unit = join(root, 'test', 'unit');
303
- const files = walk(unit);
304
- const all = files.filter((file) => tests.test(file));
305
- const fresh = files.filter((file) => since === undefined || statSync(file).mtimeMs > since);
306
- const touched = new Set([...changed.map((file) => resolve(root, file)), ...fresh]);
305
+ export function select({ root, changed }) {
306
+ const all = walk(join(root, 'test', 'unit')).filter((file) => tests.test(file));
307
+ const staged = new Set(changed.map((file) => resolve(root, file)));
307
308
  const reach = reacher(modules(root));
308
- const reached = new Set(all.filter((test) => [...reach(test)].some((file) => touched.has(file))));
309
309
  const posix = (file) => relative(root, file).split(sep).join('/');
310
- return {
311
- tests: all
312
- .filter((file) => reached.has(file))
313
- .map(posix)
314
- .sort(),
315
- total: all.length,
316
- };
310
+ const lacks = ([target, ...rest]) =>
311
+ !relative(root, target).startsWith('..') &&
312
+ !target.includes(`${sep}node_modules${sep}`) &&
313
+ !existsSync(target) &&
314
+ ![target, ...rest].some((path) => staged.has(path));
315
+ const reached = [];
316
+ const elsewhere = [];
317
+ for (const test of all) {
318
+ const { touched, absent } = reach(test);
319
+ if (![...touched].some((file) => staged.has(file))) continue;
320
+ const lacking = absent.some(lacks);
321
+ (lacking ? elsewhere : reached).push(posix(test));
322
+ }
323
+ return { tests: reached.sort(), elsewhere: elsewhere.sort(), total: all.length };
317
324
  }