@surea11y/puppeteer 1.3.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`.
@@ -34,21 +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.11.1"`); 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.3.0 this package needs `@surea11y/core` 1.11.1 or later, which npm installs with it. Core's rules and messages change between its releases; see [What changes with `@surea11y/core` 1.11](#what-changes-with-surea11ycore-111) below and 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
- `.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. 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.
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.
44
73
 
45
- `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.
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
+ ```
46
83
 
47
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).
48
85
 
49
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.
50
87
 
51
- **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()` 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.
52
89
 
53
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.
54
91
 
@@ -72,7 +109,20 @@ assert.ok(
72
109
  );
73
110
  ```
74
111
 
75
- `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), 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.
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.
124
+
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).
76
126
 
77
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.
78
128
 
@@ -88,7 +138,7 @@ AssertionError [ERR_ASSERTION]: 1) button-name-present (serious): This button ha
88
138
  at html > body > img
89
139
  Add an alt attribute that says what the image shows, or alt="" if the image is purely decorative.
90
140
 
91
- Scanned with @surea11y/core 1.11.1.
141
+ Scanned with @surea11y/core 1.12.0.
92
142
  ```
93
143
 
94
144
  and a scope that matched nothing prints:
@@ -96,9 +146,11 @@ and a scope that matched nothing prints:
96
146
  ```
97
147
  AssertionError [ERR_ASSERTION]: Nothing was scanned: the scan scope matched no element ("#main").
98
148
 
99
- Scanned with @surea11y/core 1.11.1.
149
+ Scanned with @surea11y/core 1.12.0.
100
150
  ```
101
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
+
102
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.
103
155
 
104
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.
@@ -168,6 +220,52 @@ This resolves the occurrence to an `ElementHandle` instead of leaving you to re-
168
220
 
169
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).
170
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
+
171
269
  ### Registering a custom rule at runtime
172
270
 
173
271
  `@surea11y/core` supports registering additional rules per-scan via `engineOptions.customRules`. Use `.withCustomRules()` to register one:
@@ -200,8 +298,25 @@ const results = await new A11yCoreBuilder({ page })
200
298
 
201
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.
202
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
+
203
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.
204
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
+
205
320
  ### Scanning with packs: standards, checklists and your own rules
206
321
 
207
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.
@@ -259,7 +374,23 @@ try {
259
374
 
260
375
  ## TypeScript
261
376
 
262
- `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`, and so do the types of `withWcag()` (`WcagVersion`, `WcagLevel`) and `withPacks()`, which takes a pack made with `definePack` (`PackLike`). 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.
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`.
263
394
 
264
395
  ## What changes with `@surea11y/core` 1.11
265
396
 
package/package.json CHANGED
@@ -1,16 +1,22 @@
1
1
  {
2
2
  "name": "@surea11y/puppeteer",
3
- "version": "1.3.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,13 +45,14 @@
39
45
  "LICENSE"
40
46
  ],
41
47
  "dependencies": {
42
- "@surea11y/binding-base": "^1.3.1",
43
- "@surea11y/core": "^1.11.1"
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": {
55
+ "@surea11y/core": "^1.12.0",
49
56
  "@types/node": "^20.19.43",
50
57
  "puppeteer": "^25.13.0",
51
58
  "typescript": "^7.0.2"
@@ -30,18 +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
37
  export type {
37
38
  ScanGap,
39
+ ScanNote,
40
+ PlannedCheck,
41
+ PlannedCriterion,
42
+ WcagLevelInput,
38
43
  EngineErrorCode,
39
44
  OccurrenceLocation,
40
45
  PackLike,
41
46
  WcagVersion,
42
47
  WcagLevel
43
48
  } from '@surea11y/binding-base';
44
- import type { PackLike, WcagVersion, WcagLevel } from '@surea11y/binding-base';
49
+ import type { PackLike, WcagVersion, WcagLevelInput, ScanGap, ScanNote, PlannedCheck, PlannedCriterion } from '@surea11y/binding-base';
45
50
 
46
51
  export type Category = Core.RuleMeta['category'];
47
52
  export type LocaleResolutionReason = Core.LocaleResolution['reason'];
@@ -110,6 +115,14 @@ export class A11yCoreBuilder {
110
115
  */
111
116
  constructor(opts: { page: Page; url?: string });
112
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
+
113
126
  /** Scope the scan to one region. Call multiple times for a multi-region union. */
114
127
  include(selector: string): this;
115
128
  /**
@@ -132,9 +145,28 @@ export class A11yCoreBuilder {
132
145
  * runs those of WCAG 2.2's A and AA criteria. withTags()/withRules() add
133
146
  * to them. A later call replaces the target.
134
147
  */
135
- withWcag(version: WcagVersion | 2.0 | 2.1 | 2.2, level?: WcagLevel): this;
148
+ withWcag(version: WcagVersion | 2.0 | 2.1 | 2.2, level?: WcagLevelInput): this;
136
149
  /** Also run the best-practice rules, those that name no WCAG criterion. */
137
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;
138
170
  /** Merge arbitrary engineOptions (locale, contrast.mode, policyContract, ...). */
139
171
  options(partialEngineOptions: Record<string, unknown>): this;
140
172
  /** Register one or more custom rules for just this scan. Call multiple times to accumulate. */
@@ -150,6 +182,10 @@ export class A11yCoreBuilder {
150
182
  frames(enabled?: boolean): this;
151
183
  /** Opt in to resolving each fail/cantTell occurrence's selector to a live ElementHandle. */
152
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[];
153
189
 
154
190
  /**
155
191
  * Runs the scan. Returns { topFrame, frames } instead of a single result
@@ -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') {
@@ -159,7 +175,7 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
159
175
  const result = rethrowEngineError(
160
176
  await frameOrPage.evaluate(inPageScan, frameUrl, frameContextSelector, engineOptions, runOnly)
161
177
  );
162
- warnScanGaps(result);
178
+ this._warnScanGaps(result, '@surea11y/puppeteer');
163
179
  return this._elementRef ? this._attachElementRefs(frameOrPage, result) : result;
164
180
  };
165
181
 
@@ -225,17 +241,6 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
225
241
  }
226
242
  }
227
243
 
228
- // Says on the console what the scan left out (an include() scope that
229
- // matched nothing, a custom rule the engine did not run), one line per gap,
230
- // so a scan that skipped something does not pass unnoticed as clean. Once
231
- // per scanned frame; the gaps also stay readable through getScanGaps().
232
- function warnScanGaps(result) {
233
- for (const gap of getScanGaps(result)) {
234
- const where = result.url ? ` (${result.url})` : '';
235
- console.warn(`@surea11y/puppeteer${where}: ${gap.message}`);
236
- }
237
- }
238
-
239
244
  // The occurrence's element as an ElementHandle, or null when it is gone (or
240
245
  // a shadow host on the way is). A handle to null is disposed, not leaked.
241
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 };