@surea11y/puppeteer 1.2.0 → 1.4.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.
package/README.md CHANGED
@@ -8,6 +8,10 @@ A Puppeteer binding for [`@surea11y/core`](https://github.com/SureA11y/core) —
8
8
  npm install @surea11y/puppeteer puppeteer
9
9
  ```
10
10
 
11
+ `@surea11y/core` 1.12.0 or later comes with it as a peer dependency, as Puppeteer does: npm 7 and later, and pnpm 8 and later, install it for you, so the line above is all you need. With Yarn 1 or npm 6, which don't install peers, add `@surea11y/core` to that line.
12
+
13
+ Being a peer means your project and this binding share one copy of core. That matters as soon as your project uses core directly, to write a SARIF log or an HTML report (`@surea11y/core/sarif`, `/report`), read the rule catalogue, or keep a baseline: those read results with the same core that produced them, so a report never labels a finding with another release's rules. It holds when you bring your own core too: a linked checkout (`file:../core`), a monorepo, a fork, or a pinned release. Before 1.4.0, core was a regular dependency, and a project whose core differed from the binding's got a second copy without a word; such a project needed `"overrides": { "@surea11y/core": "$@surea11y/core" }` in its `package.json`, which it can now drop.
14
+
11
15
  Puppeteer downloads its own bundled Chrome as part of `npm install` — unlike the Playwright binding, there's no separate browser-install step needed for `npm test` to work.
12
16
 
13
17
  The cross-browser regression test in `tests/cross-browser.test.js` (proving this works against Firefox too, not just Chrome) additionally needs `npx puppeteer browsers install firefox`.
@@ -25,7 +29,7 @@ await page.goto('https://example.com/');
25
29
  const results = await new A11yCoreBuilder({ page })
26
30
  .include('#main') // optional -- call multiple times for multi-region scans
27
31
  .exclude('.cookie-banner') // optional
28
- .withTags(['wcag2a', 'wcag2aa'])
32
+ .withWcag('2.2', 'AA') // the rules for WCAG 2.2's A and AA criteria
29
33
  .disableRules(['meta-refresh-no-exceptions'])
30
34
  .options({ contrast: { mode: 'auditorAssist' } })
31
35
  .analyze();
@@ -34,19 +38,54 @@ console.log(results.checksResults.filter(r => r.outcome === 'fail'));
34
38
  await browser.close();
35
39
  ```
36
40
 
37
- `results` is `@surea11y/core`'s own native result shape — see its [`OUTPUT_SCHEMA.md`](https://github.com/SureA11y/core/blob/main/docs/OUTPUT_SCHEMA.md) — not the `violations`/`passes`/`incomplete`/`inapplicable` shape used by other popular accessibility testing tools. The builder's *method names* are modeled on common conventions in this space for migration familiarity; the richer result schema is kept as-is. `results.engine.version` names the `@surea11y/core` release that produced it (such as `"1.10.0"`); quote it in a bug report.
41
+ `results` is `@surea11y/core`'s own native result shape — see its [`OUTPUT_SCHEMA.md`](https://github.com/SureA11y/core/blob/main/docs/OUTPUT_SCHEMA.md) — not the `violations`/`passes`/`incomplete`/`inapplicable` shape used by other popular accessibility testing tools. The builder's *method names* are modeled on common conventions in this space for migration familiarity; the richer result schema is kept as-is. `results.engine.version` names the `@surea11y/core` release that produced it (such as `"1.12.0"`); quote it in a bug report.
38
42
 
39
- From 1.2.0 this package needs `@surea11y/core` 1.10.0 or later, which npm installs with it. Core's rules change between its releases: 1.10.0, for example, added `landmark-role-name-present` (an element with `role="region"` or `role="form"` and no accessible name) and deprecated `label-title-only`, which now reports `notApplicable` because `form-control-programmatic-label-quality` reports the same fields. A `.withRules()`/`.disableRules()` list naming `label-title-only` still works; move it to the new rule. See core's [changelog](https://github.com/SureA11y/core/blob/main/CHANGELOG.md).
43
+ From 1.4.0 this package needs `@surea11y/core` 1.12.0 or later, which npm installs with it as a peer (see [Install](#install)). Core's rules and messages change between its releases; see [What changes with `@surea11y/core` 1.12](#what-changes-with-surea11ycore-112) below and core's [changelog](https://github.com/SureA11y/core/blob/main/CHANGELOG.md).
40
44
 
41
45
  Also see `examples/basic-scan.js` for a runnable script (`npm run example -- <url>`).
42
46
 
43
- `withTags()`/`disableRules()` above have counterparts: `.withRules([...])` (only run these specific rule IDs) and `.disableTags([...])` (never run rules carrying any of these tags). All four compose the same way similar allow/deny-list options do in other accessibility testing tools, with one non-obvious rule worth knowing: a "disable" always wins over a "with" on the same ID/tag (e.g. `.withRules(['a']).disableRules(['a'])` drops `'a'` entirely), and combining `.withRules()` **and** `.withTags()` together requires a rule to satisfy *both* (`@surea11y/core`'s default `includeMode: 'and'` — see [`ENGINE_OPTIONS.md`](https://github.com/SureA11y/core/blob/main/docs/ENGINE_OPTIONS.md)), not either one.
47
+ `.withWcag(version, level)` selects by conformance target: `.withWcag('2.2', 'AA')` runs the rules for WCAG 2.2's Level A and AA criteria, by the level each criterion has in that version (4.1.1 Parsing, which 2.2 removed, is part of a `'2.1'` target and not of a `'2.2'` one). `.withBestPractices()` adds the rules that name no WCAG criterion, such as `region` and `heading-order`; on its own it runs only those. `.withRules()` and `.withTags()` add to a target's rules, and the disable methods apply after. The level is read in any case (`'aa'` is `'AA'`). A version other than `'2.0'`, `'2.1'` or `'2.2'`, or a level other than A, AA or AAA, throws a `TypeError` with `code: 'INVALID_RUN_ONLY'` at the call. Both need `@surea11y/core` 1.11 or later.
48
+
49
+ `withTags()`/`disableRules()` have counterparts: `.withRules([...])` (only run these specific rule IDs) and `.disableTags([...])` (never run rules carrying any of these tags). All four compose the same way similar allow/deny-list options do in other accessibility testing tools, with one non-obvious rule worth knowing: a "disable" always wins over a "with" on the same ID/tag (e.g. `.withRules(['a']).disableRules(['a'])` drops `'a'` entirely), and combining `.withRules()` **and** `.withTags()` together requires a rule to satisfy *both* (`@surea11y/core`'s default `includeMode: 'and'` — see [`ENGINE_OPTIONS.md`](https://github.com/SureA11y/core/blob/main/docs/ENGINE_OPTIONS.md)), not either one, unless you ask for that with `.includeMode('or')` (below).
50
+
51
+ `.includeMode(mode)` decides how `.withRules()` and `.withTags()` combine when both are given: `'and'`, the default, runs only the rules that match both, and `'or'` runs those that match either. That's what lets a scan say "this area, plus these checks". A team that owns a design system's form components, say, can run every rule about forms and the contrast check too, in one scan:
52
+
53
+ ```js
54
+ const results = await new A11yCoreBuilder({ page })
55
+ .withTags('forms')
56
+ .withRules('contrast-computable')
57
+ .includeMode('or') // every forms rule, plus the contrast check
58
+ .analyze();
59
+ ```
60
+
61
+ Without `.includeMode('or')`, the same lines run no rule at all, since `contrast-computable` isn't tagged `forms`, and a scan of no rules looks clean. The same goes for a WCAG level tag beside a best practice: `.withTags('wcag2a').withRules('region')` runs nothing, and with `'or'` runs the `wcag2a` rules plus `region`. On its own, with no other selection, it changes nothing. A value other than `'and'` or `'or'` throws a `TypeError` with `code: 'INVALID_RUN_ONLY'` at the call. A `.withWcag()` target doesn't need it: its rules are always added to what tags and rules select.
62
+
63
+ `.wcagLevel(level)` sets the WCAG level of the criteria a scan reports, without changing which rules run: criteria above it are left out of `results.rulesResults`, while every selected rule still runs and reports in `results.checksResults`. It's what lets a scan that names a few checks say it is meant as WCAG AA. A team that gates each pull request on colour contrast alone, say, runs one check, which covers both 1.4.3 (AA) and 1.4.6 (AAA):
64
+
65
+ ```js
66
+ const results = await new A11yCoreBuilder({ page })
67
+ .withRules('contrast-computable')
68
+ .wcagLevel('AA') // report 1.4.3, not the AAA 1.4.6
69
+ .analyze();
70
+ ```
71
+
72
+ Without `.wcagLevel('AA')`, that scan reports 1.4.6 as well, so a site that meets AA can show a failing AAA criterion it never aimed for. With it, the scan reports 1.4.3 alone, and `results.engine.wcagLevel` says `'AA'`. A `.withWcag()` target already implies its level; `.wcagLevel()` is for selections that don't, and wins when both are given, as it does over a level given through `.options()`. `'A'`, `'AA'` or `'AAA'` in any case is accepted. Anything else throws a `TypeError` with `code: 'INVALID_ENGINE_OPTIONS'` at the call, and `null` clears it. Needs `@surea11y/core` 1.12.0 or later.
73
+
74
+ `.plannedChecks()` and `.plannedCriteria()` say what a scan *will* check before you run it: the rules it runs (entries with `ruleId`) and the criteria it reports in `rulesResults` (entries with `id`), worked out in Node from the same selection and options, with no page. Use them to record what a run covered next to its result, or to catch a selection that runs nothing, which would otherwise look like a clean scan:
75
+
76
+ ```js
77
+ const builder = new A11yCoreBuilder({ page }).withTags('forms').withRules('contrast-computable');
78
+ if (builder.plannedChecks().length === 0) {
79
+ throw new Error('This selection runs no rule. Did you mean .includeMode("or")?');
80
+ }
81
+ const results = await builder.analyze();
82
+ ```
44
83
 
45
84
  Each of the four takes a string or an array of strings. Anything else, such as `undefined` from a missing config value or an empty string, throws a `TypeError` with `code: 'INVALID_RUN_ONLY'` at the call. A list that names nothing the engine knows (`.withRules(['img-alt-presnt'])`) makes `analyze()` reject instead; see [Errors](#errors).
46
85
 
47
86
  `.exclude(selector)` above excludes globally. Pass a second argument to scope it to specific rule IDs instead: `.exclude('.mat-select', { rules: ['aria-required-children'] })` skips `.mat-select` for that rule only — every other rule still sees it. Global and rule-scoped `.exclude()` calls compose freely.
48
87
 
49
- **Create one builder per scan.** `A11yCoreBuilder` is a mutable object with no reset between `.analyze()` calls — `include()`/`exclude()`/`withRules()`/`disableRules()`/`withTags()`/`disableTags()`/`options()`/`withCustomRules()` all push onto or merge into internal state that persists for the instance's lifetime. Calling one of them again before a second `.analyze()` call *accumulates* on top of the first scan's scope rather than replacing it (this is exactly what makes "call `.include()` several times for one scan," above, work — the same accumulation just also applies across separate scans if you reuse an instance). `.reportOnly()`/`.frames()`/`.elementRef()` are the exception: each call replaces the previous value instead of merging with it.
88
+ **Create one builder per scan.** `A11yCoreBuilder` is a mutable object with no reset between `.analyze()` calls — `include()`/`exclude()`/`withRules()`/`disableRules()`/`withTags()`/`disableTags()`/`options()`/`withCustomRules()`/`withPacks()` all push onto or merge into internal state that persists for the instance's lifetime. Calling one of them again before a second `.analyze()` call *accumulates* on top of the first scan's scope rather than replacing it (this is exactly what makes "call `.include()` several times for one scan," above, work — the same accumulation just also applies across separate scans if you reuse an instance). `.reportOnly()`/`.frames()`/`.elementRef()`/`.withWcag()`/`.withBestPractices()`/`.includeMode()`/`.wcagLevel()`/`.logger()` are the exception: each call replaces the previous value instead of merging with it.
50
89
 
51
90
  This binding works against both browsers Puppeteer supports — Chrome (the default) and Firefox via `puppeteer.launch({ browser: 'firefox' })` — verified with a real Firefox run, see `tests/cross-browser.test.js`. There's no WebKit option; that's a Playwright-only engine.
52
91
 
@@ -70,9 +109,22 @@ assert.ok(
70
109
  );
71
110
  ```
72
111
 
73
- `getScanGaps(results)` lists what the scan left out, which `checksResults` alone would pass over as clean: an `.include()` scope that matched nothing (`kind: 'context-not-found'`; nothing was scanned, so every rule reports `notApplicable`), some of several `.include()` selectors that matched nothing (`'context-partly-not-found'`), and each custom rule the engine did not run (`'custom-rule-skipped'`, with the engine's reason). Each gap has a `message`. Checking it is what keeps a mistyped scope from passing the gate. `analyze()` also prints each gap's message with `console.warn` (as `@surea11y/puppeteer (<frame url>): <message>`, once per scanned frame under `.frames(true)`), so a scan that left something out shows in the log even where nothing asserts on it.
112
+ `getScanGaps(results)` lists what the scan left out, which `checksResults` alone would pass over as clean: an `.include()` scope that matched nothing (`kind: 'context-not-found'`; nothing was scanned, so every rule reports `notApplicable`), some of several `.include()` selectors that matched nothing (`'context-partly-not-found'`), each custom rule the engine did not run (`'custom-rule-skipped'`, with the engine's reason; a custom rule you excluded yourself with `.disableRules()` is not a gap), and each pack the page did not run (`'pack-skipped'`, from `results.skippedPacks`; see [Scanning with packs](#scanning-with-packs-standards-checklists-and-your-own-rules)). Each gap has a `message`. Checking it is what keeps a mistyped scope from passing the gate. `analyze()` also prints each gap's message with `console.warn` (as `@surea11y/puppeteer (<frame url>): <message>`, once per scanned frame under `.frames(true)`), so a scan that left something out shows in the log even where nothing asserts on it.
113
+
114
+ That warning is the right default for a test run. A project that already handles gaps itself can take them over with `.logger(fn)`: `fn(gap, result)` is called once per gap, with the gap as `getScanGaps()` gives it and the result of the frame it came from, instead of `console.warn`. A scanning service that shows gaps to its users, say, can send them once to its own structured log, rather than also printing a loose line on the server's console for every scan:
115
+
116
+ ```js
117
+ const results = await new A11yCoreBuilder({ page })
118
+ .include('#checkout')
119
+ .logger((gap, frame) => log.warn({ url: frame.url, kind: gap.kind }, gap.message))
120
+ .analyze();
121
+ ```
122
+
123
+ A batch job that writes `getScanGaps(results)` into its own report can pass `.logger(() => {})` to keep its output to the report, and `.logger(null)` brings `console.warn` back. Anything other than a function or `null` throws a `TypeError` at the call, and a later call replaces the logger. Either way, `getScanGaps(results)` still lists every gap.
74
124
 
75
- See `examples/e2e-test-example.test.js` for a fuller, runnable version (`npm run example:e2e`) — one test proving real violations get caught (unlabeled button, missing `alt`), one proving a mistyped `.include()` scope is caught rather than passed, one proving a well-formed page passes cleanly. It uses `node:test` directly rather than a dedicated test-runner package: Puppeteer has no first-party test runner the way `@playwright/test` is the default for Playwright, and `node:test` is a zero-new-dependency choice that already matches this project's own test suite.
125
+ `getScanNotes(results)` says how the page was scanned, which a gap doesn't cover, and nothing was left out: `'forced-colors'` when the page was shown in [forced colors](#forced-colors), and `'internals-hook'` when the scan asked about web components it could have read with the [internals hook](#web-components-the-internals-hook). `analyze()` also prints the internals note, once per scan, and a `.logger()` receives it (check `kind` to tell a note from a gap).
126
+
127
+ See `examples/e2e-test-example.test.js` for a fuller, runnable version (`npm run example:e2e`) — one test proving real violations get caught (unlabeled button, missing `alt`), one proving a mistyped `.include()` scope is caught rather than passed, one proving a well-formed page passes cleanly, and one gating a page on a pack's checklist. It uses `node:test` directly rather than a dedicated test-runner package: Puppeteer has no first-party test runner the way `@playwright/test` is the default for Playwright, and `node:test` is a zero-new-dependency choice that already matches this project's own test suite.
76
128
 
77
129
  ### Readable console/CI output on failure
78
130
 
@@ -81,12 +133,12 @@ A bare length/equality assertion alone gets you a *working* gate, but the failur
81
133
  ```
82
134
  AssertionError [ERR_ASSERTION]: 1) button-name-present (serious): This button has no accessible name.
83
135
  at html > body > button
84
- Provide visible button text or a programmatic accessible-name mechanism (for example aria-label) so assistive technologies can identify the button.
85
- 2) img-alt-present (serious): Missing alt attribute on <img>.
136
+ Give the button visible text, or name it with aria-label, so screen reader users know what it does.
137
+ 2) img-alt-present (serious): This <img> has no alt attribute.
86
138
  at html > body > img
87
- Add an alt attribute (use alt="" only for decorative images).
139
+ Add an alt attribute that says what the image shows, or alt="" if the image is purely decorative.
88
140
 
89
- Scanned with @surea11y/core 1.10.0.
141
+ Scanned with @surea11y/core 1.12.0.
90
142
  ```
91
143
 
92
144
  and a scope that matched nothing prints:
@@ -94,9 +146,11 @@ and a scope that matched nothing prints:
94
146
  ```
95
147
  AssertionError [ERR_ASSERTION]: Nothing was scanned: the scan scope matched no element ("#main").
96
148
 
97
- Scanned with @surea11y/core 1.10.0.
149
+ Scanned with @surea11y/core 1.12.0.
98
150
  ```
99
151
 
152
+ Before the version line, it also prints the result's notes (`getScanNotes()`, above), such as `The page was shown in forced colors (high contrast); contrast findings may differ with forced colors off.`
153
+
100
154
  An element inside a shadow tree is located through its shadow hosts, as `my-app >>> my-card >>> img`; `formatOccurrenceLocation(occurrence)` gives that line on its own. Passing `results.checksResults` instead of `results` still works and lists the findings alone.
101
155
 
102
156
  Deliberately a plain function, not a custom `expect` matcher — no dependency on any particular assertion library, so it works the same with `node:assert`, Jest, Vitest, or a hand-rolled `if`/`throw`. Defaults to `fail`/`cantTell` outcomes (the ones that report something found); pass `{ outcomes: [...] }` to narrow further. It throws a `TypeError` for the `{ topFrame, frames }` result of a `.frames(true)` scan: format `topFrame` and each frame on its own (below). A thrown rule (`occurrences: []`, `error` set — see [`OUTPUT_SCHEMA.md`](https://github.com/SureA11y/core/blob/main/docs/OUTPUT_SCHEMA.md)) is still surfaced using its `error` message rather than silently dropped.
@@ -124,6 +178,16 @@ const messages = [results.topFrame, ...results.frames].map((frame) =>
124
178
 
125
179
  Unlike script-injection-based accessibility tools (which need a `postMessage`-based protocol to reach cross-origin iframes, since they're injected as a plain `<script>` fully subject to the browser's same-origin policy), this needs no extra `@surea11y/core` engine support at all — Puppeteer drives every frame via CDP at the automation-process level, so cross-origin `frame.evaluate()` already just works. Verified against a real cross-origin page (`example.org` embedded in an unrelated origin) — see `tests/builder.test.js`. Default off, so plain `.analyze()` is unaffected unless you opt in.
126
180
 
181
+ `@surea11y/core`'s reporters take this result as it is (core 1.11.1 and later): `renderSarifReport(results)`, `renderJunitReport(results)`, `renderHtmlReport(results)` and the baseline functions report every frame's findings, and a frame that couldn't be scanned as not scanned, so it never reads as a pass.
182
+
183
+ ```js
184
+ const fs = require('node:fs');
185
+ const { renderSarifReport } = require('@surea11y/core/sarif');
186
+
187
+ const results = await new A11yCoreBuilder({ page }).frames(true).analyze();
188
+ fs.writeFileSync('a11y.sarif', renderSarifReport(results));
189
+ ```
190
+
127
191
  ### Trimming the result to just violations
128
192
 
129
193
  By default `analyze()` returns every rule's outcome, including `pass`/`notApplicable` — `@surea11y/core`'s own deliberate "not a violations-only list" design (see [`OUTPUT_SCHEMA.md`](https://github.com/SureA11y/core/blob/main/docs/OUTPUT_SCHEMA.md)). Use `.reportOnly()` to post-filter down to only the outcomes you care about:
@@ -138,6 +202,8 @@ console.log(results.checksResults); // only fail/cantTell entries, pass/notAppli
138
202
 
139
203
  Valid outcome values are `'pass'`, `'fail'`, `'cantTell'`, `'notApplicable'`. This is pure binding-layer filtering — the engine itself still computes every rule; nothing about the scan itself changes. Combines with `.frames(true)`: the filter is applied to `results.topFrame` and each entry of `results.frames` independently.
140
204
 
205
+ A result trimmed this way is no longer the whole scan to `@surea11y/core`'s reporters: JUnit counts one test per rule it finds, and EARL makes one assertion per rule. To keep a result small and still hand it to them, ask the engine for a compact one instead, with `.options({ output: { detail: 'findings' } })`: a rule that passed or did not apply keeps only its outcome, and every reporter reads it as the full result. An empty page's result goes from about 238 KB to 82 KB.
206
+
141
207
  ### Getting a live element handle, not just a selector string
142
208
 
143
209
  By default each occurrence carries a CSS selector + HTML snippet, not a live reference to the element. Opt in to a real Puppeteer `ElementHandle` with `.elementRef(true)`:
@@ -154,6 +220,52 @@ This resolves the occurrence to an `ElementHandle` instead of leaving you to re-
154
220
 
155
221
  Each `ElementHandle` holds a browser-side reference until garbage collected or explicitly disposed — for a scan with many violations that you're keeping around a while (rather than using immediately, as above), call `occurrence.elementHandle.dispose()` when you're done with it, per [Puppeteer's own `ElementHandle` guidance](https://pptr.dev/api/puppeteer.elementhandle).
156
222
 
223
+ ### Web components: the internals hook
224
+
225
+ Many web components keep their `ElementInternals` in a private field and name themselves, set their states or give themselves a role through it:
226
+
227
+ ```js
228
+ class SubscribeCheckbox extends HTMLElement {
229
+ #internals = this.attachInternals();
230
+ constructor() {
231
+ super();
232
+ this.#internals.ariaLabel = 'Subscribe';
233
+ this.#internals.ariaChecked = 'false';
234
+ }
235
+ }
236
+ ```
237
+
238
+ The browser exposes that name, but no page script can read it back, so by default the scan asks about such a component (`cantTell`) instead of judging it. A component that's a `switch` only through `this.#internals.role` isn't even asked about: the scan doesn't see its role, so it isn't checked at all.
239
+
240
+ `A11yCoreBuilder.installInternalsHook(page)` installs `@surea11y/core`'s opt-in hook, which records each component's internals for the scan to read. Call it **before** `page.goto()`:
241
+
242
+ ```js
243
+ const page = await browser.newPage();
244
+ await A11yCoreBuilder.installInternalsHook(page); // before goto
245
+ await page.goto('https://example.com/');
246
+
247
+ const results = await new A11yCoreBuilder({ page }).analyze();
248
+ results.engine.environment.internalsHook; // 'early': the hook ran before the page's scripts
249
+ ```
250
+
251
+ With it, the checkbox above passes, an unnamed component that attaches internals fails like any unnamed control, and the switch is checked as a switch, so it fails without a name. Puppeteer runs the hook before the page's own scripts in every frame, and again after each navigation (`page.evaluateOnNewDocument()`), so one call covers the page for its lifetime. It works in Chrome and Firefox.
252
+
253
+ - **Before the page loads.** On a page that's already loaded, the call has no effect until the next navigation (a reload will do), and the result has no `internalsHook`. A new tab the page opens itself doesn't get it either.
254
+ - **For test and audit runs.** The hook wraps `HTMLElement.prototype.attachInternals` (components get the same internals back), adds a stack frame to errors thrown through it, and keeps its record under a global symbol, where any script on the page can read every component's internals. That's why it's opt-in.
255
+ - **Without it**, `analyze()` says so once per scan when it asked about such components (`1 custom element was asked about because the scan could not read...`), and `getScanNotes()` gives that note as `kind: 'internals-hook'`.
256
+
257
+ ### Forced colors
258
+
259
+ A page shown in forced colors (Windows high contrast) draws in the user's colors, not its own. `results.engine.environment.forcedColors` says which it was: `'active'` or `'none'`. To check a page under forced colors on purpose, emulate it before scanning:
260
+
261
+ ```js
262
+ await page.emulateMediaFeatures([{ name: 'forced-colors', value: 'active' }]);
263
+ const results = await new A11yCoreBuilder({ page }).analyze();
264
+ results.engine.environment.forcedColors; // 'active'
265
+ ```
266
+
267
+ This works in Chrome. In Firefox, Puppeteer can't emulate it: `emulateMediaFeatures()` throws, saying it needs CDP. The contrast rules still measure the page's own colors under forced colors, since WCAG judges contrast in those, so results match a scan with forced colors off; a contrast finding the engine couldn't measure that way carries `details.forcedColors: true`. When forced colors were active, `formatFailures()` adds a line saying so, since it's easy to miss on a CI agent with high contrast turned on.
268
+
157
269
  ### Registering a custom rule at runtime
158
270
 
159
271
  `@surea11y/core` supports registering additional rules per-scan via `engineOptions.customRules`. Use `.withCustomRules()` to register one:
@@ -186,8 +298,52 @@ const results = await new A11yCoreBuilder({ page })
186
298
 
187
299
  **Why `.withCustomRules()` instead of the raw `.options({ customRules })` passthrough** (still supported, and composes with this method if you use both): `runInPage`/`applicability` must reach the page as a function-source *string*, not a live `Function` — a Puppeteer `page.evaluate()` argument crosses a serialization boundary that can't carry a live function reference, only a string `@surea11y/core` can reconstruct with `new Function` on the page side. Passing a raw live function via `.options()` directly would silently fail to serialize; `.withCustomRules()` calls `.toString()` on a live function for you, so you can write a normal function and not have to remember that constraint yourself. A string is still accepted as-is if you already have one.
188
300
 
301
+ A custom rule you turn off for one scan (`.withCustomRules(rules).disableRules('org-banner-text')`) is listed in `skippedCustomRules` with `excluded: true` and isn't a scan gap, so it isn't warned about (core 1.12.0 and later).
302
+
189
303
  Invalid input (a missing/empty `id`, or a `runInPage`/`applicability` that's neither a function nor a non-empty string) throws immediately from `.withCustomRules()` itself, rather than surfacing later as a skipped rule deep inside the page — easier to catch during development. A *raw* `.options({ customRules })` call bypasses this check and defers to `@surea11y/core`, which skips a descriptor it can't use without throwing. The result lists each one in `skippedCustomRules` as `{ id, reason }`, and `getScanGaps()`/`formatFailures(results)` report it, so a rule that did not run doesn't look like one that passed.
190
304
 
305
+ ### Checking against EN 301 549
306
+
307
+ EN 301 549, the standard the European Accessibility Act refers to, restates WCAG's Level A and AA criteria in its chapter 9. `.options({ profile })` runs the rules for its version, and each finding carries its EN 301 549 clause beside its WCAG criterion, in `meta.normativeMappings` (WCAG 1.1.1 is clause 9.1.1.1):
308
+
309
+ ```js
310
+ // EN 301 549 V4.1.1 (WCAG 2.2 A and AA); 'en301549-v3.2.1' for V3.2.1 (WCAG 2.1 A and AA)
311
+ const results = await new A11yCoreBuilder({ page })
312
+ .options({ profile: 'en301549-v4.1.1' })
313
+ .analyze();
314
+
315
+ results.engine.profile; // 'en301549-v4.1.1'
316
+ ```
317
+
318
+ `.withWcag()`, `.withRules()` and `.withTags()` select rules instead of a profile, so leave them out when scanning with one. As with any target, a scan with no failures means no rule found a violation, not that the page conforms: most criteria need a person to check them. A profile name core doesn't know is not an error: the scan runs without it, core warns in the page's console, and `results.engine.profile` is left out.
319
+
320
+ ### Scanning with packs: standards, checklists and your own rules
321
+
322
+ A pack brings rules, variants of core's rules, a standard or a checklist, and their profiles and messages, from a package of its own: a national standard such as RGAA, or your organisation's accessibility policy. `@surea11y/core` runs a pack as it runs its own rules and standards, so its results, rollups and report entries look like core's. Packs need `@surea11y/core` 1.11.1 or later.
323
+
324
+ `.withPacks()` registers packs in the page, and in every frame with `.frames(true)`, before the scan; a pack's profile is chosen with `.options({ profile })`:
325
+
326
+ ```js
327
+ const acmePolicy = require('@acme/a11y-policy'); // a pack
328
+
329
+ const results = await new A11yCoreBuilder({ page })
330
+ .withPacks(acmePolicy)
331
+ .options({ profile: 'acme-web-2026' })
332
+ .analyze();
333
+
334
+ results.engine.packs; // ['@acme/a11y-policy@1.0.0']
335
+ results.engine.profile; // 'acme-web-2026'
336
+
337
+ // A checklist's items, each one result, beside core's WCAG rollups:
338
+ results.rulesResults.filter((r) => r.meta && r.meta.standard === 'Acme web policy');
339
+ ```
340
+
341
+ A pack's own rules appear in `checksResults` like core's, with ids that start with its namespace (`acme-no-autoplay`). Without its profile, a pack's rules run only when selected, with `.withRules()` or by a tag. `@surea11y/core`'s HTML, SARIF and JUnit reports show a standard's or a checklist's items in a section of their own. Pass an array, or call `.withPacks()` again, to scan with several packs.
342
+
343
+ **Writing a pack.** A pack is an object made with `definePack` from `@surea11y/core/pack`. [`examples/acme-policy-pack.js`](./examples/acme-policy-pack.js) is a small one: a house rule, a checklist profile (WCAG 2.2 A and AA, `region`, and the house rule) and two checklist items. `npm run example:pack` scans a page with it, and [`examples/e2e-test-example.test.js`](./examples/e2e-test-example.test.js) uses it as a test gate. For a pack of your own, `npx surea11y-pack new <folder>` (from `@surea11y/core`) writes a package that works as generated, with its tests, docs and lint; core's [`PACKS.md`](https://github.com/SureA11y/core/blob/main/docs/PACKS.md) is the guide.
344
+
345
+ **When a pack doesn't run.** `.withPacks()` builds the page's script with the `@surea11y/core` this binding loads, and checks each pack as it does: `.analyze()` throws before scanning for a pack that core can't run, such as one whose `core` range leaves out the installed core, or whose profile names a rule that doesn't exist. A pack the page then doesn't run (one named with a raw `.options({ packs })` and never registered, or a page running another core version, when two copies of core are installed) is listed in `results.skippedPacks` with the reason. `getScanGaps()` reports that as `'pack-skipped'`, and `.analyze()` warns about it, so a test gate that asserts on `getScanGaps(results)` fails rather than passing with the pack's checks never run. Install the pack beside the binding, so npm resolves one core for both.
346
+
191
347
  ### Element addressing beyond a CSS selector
192
348
 
193
349
  Every occurrence already carries `selector` and (with `.elementRef(true)`, above) a live `ElementHandle`. It also carries `structuralPath` — a sibling-index path from the document root down to the flagged element (e.g. `[1, 0, 2]`) — a more robust identity than a selector string alone, since it survives some DOM changes a selector wouldn't (an id/class rename, for instance). No opt-in needed; it's already on every `fail`/`cantTell` occurrence today. See [`OUTPUT_SCHEMA.md`](https://github.com/SureA11y/core/blob/main/docs/OUTPUT_SCHEMA.md) for the full field description.
@@ -198,6 +354,8 @@ Every occurrence already carries `selector` and (with `.elementRef(true)`, above
198
354
 
199
355
  - `'INVALID_RUN_ONLY'`: a `.withRules()`/`.withTags()` list in which no value names a rule or a tag the engine knows, such as a misspelled rule ID. A value that names nothing beside ones that do is ignored, with a `console.warn` in the page.
200
356
  - `'INVALID_CONTEXT_SELECTOR'`: an `.include()` selector the browser can't parse. `error.selector` is that selector.
357
+ - `'INVALID_ENGINE_OPTIONS'`: with `.options({ strictOptions: true })`, an option the engine doesn't read or a value it can't use. The message names each, with the closest known option (`lcoale`: did you mean `locale`?). Without `strictOptions`, a likely typo is only warned about in the page's console.
358
+ - `'PAGE_BUILTINS_BROKEN'`: the page's own scripts broke a JavaScript built-in the engine relies on (`Array.prototype.filter`, `Map`, `JSON.stringify`, ...), so no result it gave could be trusted. The message names each one.
201
359
 
202
360
  ```js
203
361
  const { A11yCoreBuilder, EngineError } = require('@surea11y/puppeteer');
@@ -216,7 +374,33 @@ try {
216
374
 
217
375
  ## TypeScript
218
376
 
219
- `src/A11yCoreBuilder.d.ts` (re-exported from `src/index.d.ts`, wired up via `package.json`'s `types` field) ships types for the whole builder API plus `@surea11y/core`'s native result shapes (`A11yCoreResult`, `CheckResult`, `Occurrence`, `CompositeResult`, etc.). The result shapes are `@surea11y/core`'s own types (its `ScanResult` and the rest), with `elementHandle` added to an occurrence, so they follow the engine: `engine.version`, `contextMatch`, `skippedCustomRules`, `shadowHostSelectors` and `margin` are all declared. `EngineError`, `ScanGap` and `EngineErrorCode` come from `@surea11y/binding-base`. `analyze()` is typed `Promise<A11yCoreResult | A11yCoreMultiFrameResult>` — narrow on `'topFrame' in results` (or cast, if you already know which mode you called) to get the specific shape back, since a fluent builder can't statically track that `.frames(true)` was called earlier in the chain. `puppeteer` is a `peerDependencies` entry (not just `devDependencies`) since the class's `page` argument and `Occurrence#elementHandle` both come from it — consumers need their own `puppeteer` install for the types to resolve, same as they already do to construct a `Page` in the first place.
377
+ `src/A11yCoreBuilder.d.ts` (re-exported from `src/index.d.ts`, wired up via `package.json`'s `types` field) ships types for the whole builder API plus `@surea11y/core`'s native result shapes (`A11yCoreResult`, `CheckResult`, `Occurrence`, `CompositeResult`, etc.). The result shapes are `@surea11y/core`'s own types (its `ScanResult` and the rest), with `elementHandle` added to an occurrence, so they follow the engine: `engine.version`, `contextMatch`, `skippedCustomRules`, `shadowHostSelectors` and `margin` are all declared. `EngineError`, `ScanGap`, `ScanNote` and `EngineErrorCode` come from `@surea11y/binding-base`, and so do the types of `withWcag()` and `wcagLevel()` (`WcagVersion`, `WcagLevelInput`), of `plannedChecks()`/`plannedCriteria()` (`PlannedCheck`, `PlannedCriterion`) and of `withPacks()`, which takes a pack made with `definePack` (`PackLike`). `A11yCoreBuilder.installInternalsHook(page)` is typed as a static method. Code that handles every `ScanGap` kind it knows and treats the rest in an `else` branch needs a branch for `'pack-skipped'`, which carries `pack` rather than `selectors`. `analyze()` is typed `Promise<A11yCoreResult | A11yCoreMultiFrameResult>` — narrow on `'topFrame' in results` (or cast, if you already know which mode you called) to get the specific shape back, since a fluent builder can't statically track that `.frames(true)` was called earlier in the chain. `puppeteer` is a `peerDependencies` entry (not just `devDependencies`) since the class's `page` argument and `Occurrence#elementHandle` both come from it — consumers need their own `puppeteer` install for the types to resolve, same as they already do to construct a `Page` in the first place.
378
+
379
+ ## What changes with `@surea11y/core` 1.12
380
+
381
+ This release needs `@surea11y/core` 1.12.0. What a scan through this binding shows differently (core's [`CHANGELOG.md`](https://github.com/SureA11y/core/blob/main/CHANGELOG.md) has the full list):
382
+
383
+ - **An empty heading now fails an unscoped scan.** `empty-heading` used to ask about a heading with no accessible name; it now fails it. It's a best practice, so it runs in a scan that selects nothing and with `.withBestPractices()`, not under `.withWcag()`, tags or a profile. A gate on a page with `<h2></h2>` that asserted no failures now fails: fix the heading, or scan a WCAG target.
384
+ - **Scans that pick rules report their criteria.** `.withRules('img-alt-present')`, a non-WCAG tag or `.withBestPractices()` now fill `rulesResults` with the WCAG criteria those rules belong to, where it was empty. A criterion whose other rules weren't selected is `cantTell` (`reasonCode` `composite.rollup.cantTell.notSelectedChild`), and each check's `rollupIds` names the criteria it was added for. `.wcagLevel()` keeps those criteria to a level.
385
+ - **Four rules count towards more criteria**, as W3C's ACT rules map them: `input-image-alt-present` adds 4.1.2, `aria-roles-valid` 1.3.1, `link-name-present` 2.4.9 (AAA), and `meta-refresh-timing-absent` 2.2.4 and 3.2.5 (AAA). The findings don't change; the 1.3.1 and 4.1.2 rollups can now fail where they passed.
386
+ - **Unnamed custom elements are questions.** A defined custom element with no visible name may name itself through `ElementInternals`, so it's `cantTell` (`name_internals`) where it used to fail. [`installInternalsHook()`](#web-components-the-internals-hook) lets the engine decide.
387
+ - **`engine.wcagLevel`** records the level a scan was gated by, and [`.wcagLevel()`](#usage) sets it.
388
+ - **`engine.environment.forcedColors`** records whether the page was in [forced colors](#forced-colors).
389
+ - **A custom rule you exclude** isn't a scan gap any more, so `.disableRules()` of one prints no warning.
390
+ - **Rule IDs in another case select their rule**: `.withRules('IMG-ALT-PRESENT')` used to throw `INVALID_RUN_ONLY` or be ignored.
391
+ - **`runOnly.optInTags` on its own throws** `INVALID_RUN_ONLY`; it was accepted and did nothing. Opt-in rules are unlocked with `.options({ optInRules })`.
392
+ - **A finding in a shadow tree is located through its hosts**, as `#card >>> img`, in core's HTML report, SARIF, JUnit and baselines, as `formatFailures()` already did.
393
+ - **An inline `policyContract`** with an unknown value in `allowedOutcomes` or `allowedConfidence` drops that value with a warning, where it turned every check into `cantTell`.
394
+
395
+ ## What changes with `@surea11y/core` 1.11
396
+
397
+ The binding passes rule IDs, tags and options through to the engine, so these show in results without a change here (see core's [`CHANGELOG.md`](https://github.com/SureA11y/core/blob/main/CHANGELOG.md) for the full list):
398
+
399
+ - **Messages are reworded** in all five languages to say plainly what is wrong and what to do (`This <img> has no alt attribute.`). Message keys, rule IDs, reason codes and baselines are unchanged; a test that matches message text needs the new wording.
400
+ - **Contrast and target size measure what is on screen.** In a browser, the contrast rules check only text a reader can see, measure it against what is painted under it, and measure form field values and placeholders. `target-size-minimum` measures the area a pointer can hit, and exempts only links in a sentence. Expect new findings, and some old ones gone.
401
+ - **`aria-hidden-focus` maps to 4.1.2 only**, no longer to 2.4.7 Focus Visible, so `.withTags('wcag2aa')` alone no longer selects it.
402
+ - **A custom rule counts toward its WCAG criterion.** A `.withCustomRules()` rule with `meta.wcagSc` (or a WCAG `normativeMappings` entry) fails that criterion's rollup when it fails, and custom rules run after core's.
403
+ - **On/off options read as meant**: `.options({ perfStats: 'false' })` is off, where it was on. `.options({ strictOptions: true })` rejects any option the engine doesn't read (see [Errors](#errors)).
220
404
 
221
405
  ## Relationship to `@surea11y/playwright`
222
406
 
package/package.json CHANGED
@@ -1,16 +1,22 @@
1
1
  {
2
2
  "name": "@surea11y/puppeteer",
3
- "version": "1.2.0",
4
- "description": "Puppeteer binding for surea11y -- scan real, live-rendered pages for accessibility issues.",
3
+ "version": "1.4.0",
4
+ "description": "Accessibility (a11y, WCAG) checks for Puppeteer scripts and tests: scan the live page with new A11yCoreBuilder({ page }).analyze() and get only proven violations, with findings that need human review listed separately.",
5
5
  "keywords": [
6
6
  "accessibility",
7
7
  "a11y",
8
+ "a11y-testing",
8
9
  "wcag",
10
+ "wcag21",
9
11
  "wcag22",
12
+ "en301549",
13
+ "en-301-549",
14
+ "european-accessibility-act",
10
15
  "accessibility-testing",
11
16
  "puppeteer",
12
17
  "e2e",
13
18
  "e2e-testing",
19
+ "end-to-end",
14
20
  "audit",
15
21
  "aria",
16
22
  "surea11y"
@@ -39,20 +45,22 @@
39
45
  "LICENSE"
40
46
  ],
41
47
  "dependencies": {
42
- "@surea11y/binding-base": "^1.2.0",
43
- "@surea11y/core": "^1.10.0"
48
+ "@surea11y/binding-base": "^1.4.0"
44
49
  },
45
50
  "peerDependencies": {
51
+ "@surea11y/core": ">=1.12.0",
46
52
  "puppeteer": ">=22.0.0"
47
53
  },
48
54
  "devDependencies": {
49
- "@types/node": "^22.20.5",
50
- "puppeteer": "^25.3.0",
51
- "typescript": "^5.9.3"
55
+ "@surea11y/core": "^1.12.0",
56
+ "@types/node": "^20.19.43",
57
+ "puppeteer": "^25.13.0",
58
+ "typescript": "^7.0.2"
52
59
  },
53
60
  "scripts": {
54
61
  "test": "node --test tests/*.test.js",
55
62
  "example": "node examples/basic-scan.js",
56
- "example:e2e": "node --test examples/e2e-test-example.test.js"
63
+ "example:e2e": "node --test examples/e2e-test-example.test.js",
64
+ "example:pack": "node examples/scan-with-pack.js"
57
65
  }
58
66
  }
@@ -30,10 +30,23 @@ export type {
30
30
  export {
31
31
  formatFailures,
32
32
  getScanGaps,
33
+ getScanNotes,
33
34
  formatOccurrenceLocation,
34
35
  EngineError
35
36
  } from '@surea11y/binding-base';
36
- export type { ScanGap, EngineErrorCode, OccurrenceLocation } from '@surea11y/binding-base';
37
+ export type {
38
+ ScanGap,
39
+ ScanNote,
40
+ PlannedCheck,
41
+ PlannedCriterion,
42
+ WcagLevelInput,
43
+ EngineErrorCode,
44
+ OccurrenceLocation,
45
+ PackLike,
46
+ WcagVersion,
47
+ WcagLevel
48
+ } from '@surea11y/binding-base';
49
+ import type { PackLike, WcagVersion, WcagLevelInput, ScanGap, ScanNote, PlannedCheck, PlannedCriterion } from '@surea11y/binding-base';
37
50
 
38
51
  export type Category = Core.RuleMeta['category'];
39
52
  export type LocaleResolutionReason = Core.LocaleResolution['reason'];
@@ -102,6 +115,14 @@ export class A11yCoreBuilder {
102
115
  */
103
116
  constructor(opts: { page: Page; url?: string });
104
117
 
118
+ /**
119
+ * Installs @surea11y/core's opt-in internals hook in `page`, so a scan can
120
+ * read names, states and roles web components set through a private
121
+ * ElementInternals. Call it before page.goto(): it runs before the page's
122
+ * scripts in every frame and after each navigation.
123
+ */
124
+ static installInternalsHook(page: Page): ReturnType<Page['evaluateOnNewDocument']>;
125
+
105
126
  /** Scope the scan to one region. Call multiple times for a multi-region union. */
106
127
  include(selector: string): this;
107
128
  /**
@@ -119,23 +140,63 @@ export class A11yCoreBuilder {
119
140
  withRules(ruleIds: string | string[]): this;
120
141
  /** Never run these specific rule IDs (applied after withRules). */
121
142
  disableRules(ruleIds: string | string[]): this;
143
+ /**
144
+ * Run the rules for a WCAG conformance target: `withWcag('2.2', 'AA')`
145
+ * runs those of WCAG 2.2's A and AA criteria. withTags()/withRules() add
146
+ * to them. A later call replaces the target.
147
+ */
148
+ withWcag(version: WcagVersion | 2.0 | 2.1 | 2.2, level?: WcagLevelInput): this;
149
+ /** Also run the best-practice rules, those that name no WCAG criterion. */
150
+ withBestPractices(enabled?: boolean): this;
151
+ /**
152
+ * How withRules() and withTags() combine when both are given: 'and' (the
153
+ * default) runs the rules matching both, 'or' those matching either. A
154
+ * later call replaces the mode.
155
+ */
156
+ includeMode(mode: 'and' | 'or'): this;
157
+ /**
158
+ * The WCAG level of the criteria the scan reports, without changing which
159
+ * rules run: `.withRules('contrast-computable').wcagLevel('AA')` reports
160
+ * 1.4.3 and not 1.4.6. Any case; null clears it. A later call replaces it.
161
+ */
162
+ wcagLevel(level: WcagLevelInput | null): this;
163
+ /**
164
+ * Where analyze() sends each scan gap instead of console.warn: called once
165
+ * per gap, with the result of the frame it came from, and once per scan
166
+ * for the internals-hook note (tell them apart by `kind`). `() => {}`
167
+ * silences them, `null` goes back to console.warn. A later call replaces it.
168
+ */
169
+ logger(fn: ((entry: ScanGap | ScanNote, result: A11yCoreResult) => void) | null): this;
122
170
  /** Merge arbitrary engineOptions (locale, contrast.mode, policyContract, ...). */
123
171
  options(partialEngineOptions: Record<string, unknown>): this;
124
172
  /** Register one or more custom rules for just this scan. Call multiple times to accumulate. */
125
173
  withCustomRules(rules: CustomRuleDescriptor | CustomRuleDescriptor[]): this;
174
+ /**
175
+ * Packs from `@surea11y/core/pack` (core 1.11 or later): registered in each
176
+ * frame before the scan, and named in `engineOptions.packs`.
177
+ */
178
+ withPacks(packs: PackLike | PackLike[]): this;
126
179
  /** Post-filter checksResults down to only the given outcomes. */
127
180
  reportOnly(outcomes: Core.Outcome | Core.Outcome[]): this;
128
181
  /** Opt in to also scanning every sub-frame on the page (including cross-origin iframes). */
129
182
  frames(enabled?: boolean): this;
130
183
  /** Opt in to resolving each fail/cantTell occurrence's selector to a live ElementHandle. */
131
184
  elementRef(enabled?: boolean): this;
185
+ /** The rules this scan will run, worked out in Node with no page (@surea11y/core 1.12.0 and later). */
186
+ plannedChecks(): PlannedCheck[];
187
+ /** The criteria this scan will report in rulesResults, worked out in Node with no page. */
188
+ plannedCriteria(): PlannedCriterion[];
132
189
 
133
190
  /**
134
191
  * Runs the scan. Returns { topFrame, frames } instead of a single result
135
192
  * when .frames(true) was used; include() then scopes the top frame only,
136
- * and each sub-frame is scanned whole. Rejects with an EngineError
137
- * (`code` 'INVALID_RUN_ONLY' or 'INVALID_CONTEXT_SELECTOR') for input the
138
- * engine cannot use.
193
+ * and each sub-frame is scanned whole. Rejects with an EngineError for
194
+ * input the engine cannot use, with its `code`: 'INVALID_RUN_ONLY'
195
+ * (withRules()/withTags() named no rule or tag it knows),
196
+ * 'INVALID_CONTEXT_SELECTOR' (an include() selector the browser can't
197
+ * parse), 'INVALID_ENGINE_OPTIONS' (an option `strictOptions: true`
198
+ * rejects) or 'PAGE_BUILTINS_BROKEN' (the page's scripts broke a
199
+ * JavaScript built-in the engine relies on).
139
200
  */
140
201
  analyze(): Promise<A11yCoreResult | A11yCoreMultiFrameResult>;
141
202
  }
@@ -1,12 +1,11 @@
1
1
  'use strict';
2
2
 
3
- const { runa11yCoreInPage } = require('@surea11y/core');
3
+ const { runa11yCoreInPage, internalsHookScript } = require('@surea11y/core');
4
4
  const {
5
5
  A11yCoreBuilderBase,
6
6
  createInPageScan,
7
7
  rethrowEngineError,
8
- queryOccurrenceElement,
9
- getScanGaps
8
+ queryOccurrenceElement
10
9
  } = require('@surea11y/binding-base');
11
10
 
12
11
  // core's scan, wrapped so an engine error keeps its `code` across
@@ -120,6 +119,23 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
120
119
  * `page` must already be navigated to and settled at the URL to scan --
121
120
  * this class does not navigate for you.
122
121
  */
122
+ /**
123
+ * Installs @surea11y/core's opt-in internals hook in `page`, so a scan can
124
+ * read the names, states and roles web components set through a private
125
+ * ElementInternals. Call it before page.goto(): Puppeteer runs the script
126
+ * before the page's own scripts in every frame, and again after each
127
+ * navigation (page.evaluateOnNewDocument()). The page already loaded when
128
+ * it is called doesn't get it, nor does a tab the page opens itself.
129
+ * Resolves to what evaluateOnNewDocument() resolves to.
130
+ * @param {import('puppeteer').Page} page
131
+ */
132
+ static installInternalsHook(page) {
133
+ if (!page || typeof page.evaluateOnNewDocument !== 'function') {
134
+ throw new TypeError('A11yCoreBuilder.installInternalsHook() requires a Puppeteer Page (with an .evaluateOnNewDocument() method).');
135
+ }
136
+ return page.evaluateOnNewDocument(internalsHookScript());
137
+ }
138
+
123
139
  constructor({ page, url } = {}) {
124
140
  super({ url });
125
141
  if (!page || typeof page.evaluate !== 'function') {
@@ -134,6 +150,9 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
134
150
  */
135
151
  async analyze() {
136
152
  const { contextSelector, engineOptions, runOnly } = this._buildEngineArgs();
153
+ // The script that registers withPacks()'s packs in a frame, which the
154
+ // scan names in engineOptions.packs; null without packs.
155
+ const packScript = this._packScript();
137
156
 
138
157
  // Unlike Playwright's page.evaluate(fn, arg), which only accepts a
139
158
  // SINGLE argument (forcing a hand-built single-arg wrapper there --
@@ -152,10 +171,11 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
152
171
  // `code`; any other error in the page rejects evaluate() as before.
153
172
  const runInFrame = async (frameOrPage, frameContextSelector) => {
154
173
  const frameUrl = this._url || (typeof frameOrPage.url === 'function' ? frameOrPage.url() : null);
174
+ if (packScript) await frameOrPage.evaluate(packScript);
155
175
  const result = rethrowEngineError(
156
176
  await frameOrPage.evaluate(inPageScan, frameUrl, frameContextSelector, engineOptions, runOnly)
157
177
  );
158
- warnScanGaps(result);
178
+ this._warnScanGaps(result, '@surea11y/puppeteer');
159
179
  return this._elementRef ? this._attachElementRefs(frameOrPage, result) : result;
160
180
  };
161
181
 
@@ -221,17 +241,6 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
221
241
  }
222
242
  }
223
243
 
224
- // Says on the console what the scan left out (an include() scope that
225
- // matched nothing, a custom rule the engine did not run), one line per gap,
226
- // so a scan that skipped something does not pass unnoticed as clean. Once
227
- // per scanned frame; the gaps also stay readable through getScanGaps().
228
- function warnScanGaps(result) {
229
- for (const gap of getScanGaps(result)) {
230
- const where = result.url ? ` (${result.url})` : '';
231
- console.warn(`@surea11y/puppeteer${where}: ${gap.message}`);
232
- }
233
- }
234
-
235
244
  // The occurrence's element as an ElementHandle, or null when it is gone (or
236
245
  // a shadow host on the way is). A handle to null is disposed, not leaked.
237
246
  async function resolveElementHandle(frameOrPage, occurrence) {
package/src/index.js CHANGED
@@ -4,9 +4,10 @@ const { A11yCoreBuilder } = require('./A11yCoreBuilder');
4
4
  const { formatFailures } = require('./formatFailures');
5
5
 
6
6
  // Re-exported from @surea11y/binding-base, as formatFailures is, so a test
7
- // needs only this package: what a result says it left out, an occurrence's
7
+ // needs only this package: what a result says it left out, how the page was
8
+ // scanned (forced colors, the internals hook), an occurrence's
8
9
  // location as text, and the error analyze() throws for input the engine
9
10
  // cannot use.
10
- const { getScanGaps, formatOccurrenceLocation, EngineError } = require('@surea11y/binding-base');
11
+ const { getScanGaps, getScanNotes, formatOccurrenceLocation, EngineError } = require('@surea11y/binding-base');
11
12
 
12
- module.exports = { A11yCoreBuilder, formatFailures, getScanGaps, formatOccurrenceLocation, EngineError };
13
+ module.exports = { A11yCoreBuilder, formatFailures, getScanGaps, getScanNotes, formatOccurrenceLocation, EngineError };