@surea11y/puppeteer 1.4.2 → 1.6.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 +189 -11
- package/package.json +3 -3
- package/src/A11yCoreBuilder.d.ts +71 -4
- package/src/A11yCoreBuilder.js +219 -18
- package/src/index.js +5 -5
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@ A Puppeteer binding for [`@surea11y/core`](https://github.com/SureA11y/core) —
|
|
|
8
8
|
npm install @surea11y/core @surea11y/puppeteer puppeteer
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
`@surea11y/core` 1.
|
|
11
|
+
`@surea11y/core` 1.15.0 or later, the engine, comes with the binding as a regular dependency, so a project that doesn't list it still works. List it in your own `package.json` too, as the line above does: your project and the binding then share one copy, so whatever you do with core directly, writing a SARIF log or an HTML report (`@surea11y/core/sarif`, `/report`), reading the rule catalogue or keeping a baseline, reads results with the same core that produced them. When your core can't match the binding's range, as with a linked checkout (`file:../core`) or a fork, add `"overrides": { "@surea11y/core": "$@surea11y/core" }` beside it.
|
|
12
12
|
|
|
13
13
|
**Coming in 2.0:** core becomes a peer dependency, so the binding will no longer install it for you, and the `overrides` entry is no longer needed. Add `@surea11y/core` to your `package.json` now and 2.0 needs no change.
|
|
14
14
|
|
|
@@ -40,7 +40,7 @@ await browser.close();
|
|
|
40
40
|
|
|
41
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.
|
|
42
42
|
|
|
43
|
-
From 1.
|
|
43
|
+
From 1.6.0 this package needs `@surea11y/core` 1.15.0 or later, which it installs with it (see [Install](#install)). Core's rules and messages change between its releases; see [What changes with `@surea11y/core` 1.15](#what-changes-with-surea11ycore-115) below and core's [changelog](https://github.com/SureA11y/core/blob/main/CHANGELOG.md).
|
|
44
44
|
|
|
45
45
|
Also see `examples/basic-scan.js` for a runnable script (`npm run example -- <url>`).
|
|
46
46
|
|
|
@@ -109,7 +109,7 @@ assert.ok(
|
|
|
109
109
|
);
|
|
110
110
|
```
|
|
111
111
|
|
|
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),
|
|
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), 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)), and each profile a scan of several did not run (`'profile-not-run'`, from `results.engine.profilesNotRun`, `@surea11y/core` 1.15 and later; 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
113
|
|
|
114
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
115
|
|
|
@@ -122,13 +122,27 @@ const results = await new A11yCoreBuilder({ page })
|
|
|
122
122
|
|
|
123
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
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),
|
|
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), `'internals-hook'` when the scan asked about web components it could have read with the [internals hook](#web-components-the-internals-hook), and `'listener-hook'` or `'live-region-hook'` when findings that the [listener hook](#click-handlers-added-from-script-the-listener-hook) or the [live-region hook](#live-regions-the-live-region-hook-and-announcements) would have decided were judged without it (with `findingCount` and the `rules`). `analyze()` also prints each hook note, once per scan, and a `.logger()` receives it (check `kind` to tell a note from a gap).
|
|
126
126
|
|
|
127
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.
|
|
128
128
|
|
|
129
|
+
### Failing only on serious problems
|
|
130
|
+
|
|
131
|
+
Every rule result has a severity: `critical`, `serious`, `moderate` or `minor` (a profile can set its own). To start by blocking on serious problems while the rest are still reported, gate on `getGatingFailures(results, { failOnSeverity })` (`@surea11y/binding-base` 1.6.0 and later): the failing rules at that level or above, the same ones `surea11y scan --fail-on-severity` counts for the page. `formatFailures()` takes the same option and still lists the failures below the level, marked as ones that don't fail the test.
|
|
132
|
+
|
|
133
|
+
```js
|
|
134
|
+
const { A11yCoreBuilder, formatFailures, getGatingFailures } = require('@surea11y/puppeteer');
|
|
135
|
+
|
|
136
|
+
const results = await new A11yCoreBuilder({ page }).analyze();
|
|
137
|
+
const gate = { failOnSeverity: 'serious' };
|
|
138
|
+
assert.deepStrictEqual(getGatingFailures(results, gate), [], formatFailures(results, gate));
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
`fail` keeps its meaning, a definite violation; the level only picks which failures stop the test, and every failure stays in `results`. A level that isn't one of the four throws a `TypeError`. `SEVERITIES` lists them, least to most severe.
|
|
142
|
+
|
|
129
143
|
### Readable console/CI output on failure
|
|
130
144
|
|
|
131
|
-
A bare length/equality assertion alone gets you a *working* gate, but the failure message is a raw, deeply-nested object diff — hundreds of lines for a handful of violations. `formatFailures(results)` turns that into a short, scannable block (one entry per occurrence, numbered, with rule ID/severity/location/hint), followed by the result's scan gaps and the `@surea11y/core` release that produced it, that you hand to your assertion library's own failure-message parameter, as above. A real failure then prints:
|
|
145
|
+
A bare length/equality assertion alone gets you a *working* gate, but the failure message is a raw, deeply-nested object diff — hundreds of lines for a handful of violations. `formatFailures(results)` turns that into a short, scannable block (one entry per occurrence, numbered, with rule ID/severity/location/hint), followed by the result's scan gaps and the `@surea11y/core` release that produced it, that you hand to your assertion library's own failure-message parameter, as above. Each occurrence is read by its own outcome, and the list follows the order a review takes: failures first, then the [questions](#findings-that-need-review-leans-and-how-to-check) that likely fail, those that likely pass, and those only a person can answer. A real failure then prints:
|
|
132
146
|
|
|
133
147
|
```
|
|
134
148
|
AssertionError [ERR_ASSERTION]: 1) button-name-present (serious): This button has no accessible name.
|
|
@@ -153,7 +167,7 @@ Before the version line, it also prints the result's notes (`getScanNotes()`, ab
|
|
|
153
167
|
|
|
154
168
|
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.
|
|
155
169
|
|
|
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.
|
|
170
|
+
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, by outcome or by review group (`'leanFail'`, `'leanPass'`, `'open'`), and `{ howToCheck: true }` to list each question's steps (see [below](#findings-that-need-review-leans-and-how-to-check)). An outcome it doesn't know throws a `TypeError`. 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.
|
|
157
171
|
|
|
158
172
|
### Scanning every frame, including cross-origin iframes
|
|
159
173
|
|
|
@@ -174,9 +188,11 @@ const messages = [results.topFrame, ...results.frames].map((frame) =>
|
|
|
174
188
|
);
|
|
175
189
|
```
|
|
176
190
|
|
|
177
|
-
`.include()` scopes the top frame only: each sub-frame is scanned whole, as `@surea11y/core`'s own `runa11yCoreAcrossFrames` does. The selectors are written against the top document, and since core 1.10.0 a selector that matches nothing scans nothing, so passing them on would leave most frames unscanned. `.exclude()` and every other option apply in every frame. A sub-frame that can't be scanned (detached, navigated away, sandboxed) becomes a `{ url, error }` entry; an [engine error](#errors) rejects the whole `analyze()` from the top frame instead, since it would fail in every frame.
|
|
191
|
+
`.include()` scopes the top frame only: each sub-frame inside its roots is scanned whole, as `@surea11y/core`'s own `runa11yCoreAcrossFrames` does. The selectors are written against the top document, and since core 1.10.0 a selector that matches nothing scans nothing, so passing them on would leave most frames unscanned. `.exclude()` and every other option apply in every frame. Sub-frames are scanned up to four at a time, each result in its frame's place in `page.frames()`; with `.screenshots()` they go one at a time, since taking an element's picture scrolls the page. A sub-frame that can't be scanned (detached, navigated away, sandboxed) becomes a `{ url, error }` entry; an [engine error](#errors) rejects the whole `analyze()` from the top frame instead, since it would fail in every frame.
|
|
192
|
+
|
|
193
|
+
Which frames are scanned, and how, also follows `runa11yCoreAcrossFrames` (`@surea11y/binding-base` 1.7.0 and later). A frame the page doesn't show, or that an open modal dialog covers, unless `.options({ includeHiddenElements: true })`, a frame in content `.exclude()` leaves out, a frame of the top page outside the `.include()` roots, a frame in a shadow root with `.options({ includeShadowDom: false })`, and a frame whose document shows nothing (an empty `about:blank`) are left out of `results.frames`, with the frames inside them. A frame under `aria-hidden="true"` is scanned as aria-hidden content, where names and roles don't apply and contrast, focus and keyboard still do, and one under `inert` only for how it looks; a frame inside one is read the same way (`@surea11y/core` 1.15 and later). The elements around a frame are read through slots and shadow hosts, as the accessibility tree reads them. Each sub-frame's result is named by its own `url`; a `url` given to the constructor names the top frame only.
|
|
178
194
|
|
|
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
|
|
195
|
+
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 from the automation process (CDP in Chrome, WebDriver BiDi in Firefox), 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.
|
|
180
196
|
|
|
181
197
|
`@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
198
|
|
|
@@ -251,6 +267,40 @@ first.occurrences[0].screenshot;
|
|
|
251
267
|
|
|
252
268
|
The pictures are taken right after each frame's scan, before `.reportOnly()` trims the result, and combine with `.elementRef(true)`. Focus, hover, animations or content that loads late can still differ from what the scan saw. An option it can't use throws a `TypeError` with `code: 'INVALID_ENGINE_OPTIONS'` at the call, and so does `.analyze()` with `options({ output: { includeSelector: false } })`, since each element is found by its selector. Works in Chrome and Firefox.
|
|
253
269
|
|
|
270
|
+
### Findings that need review: leans and how to check
|
|
271
|
+
|
|
272
|
+
A `cantTell` is a question for a person: the engine couldn't prove the answer from the page. With `@surea11y/core` 1.14, a question says more:
|
|
273
|
+
|
|
274
|
+
- **Which way it leans.** Where the page's evidence points one way, the occurrence has a `lean`: `toward` (`'fail'` or `'pass'`), `why`, and sometimes a `caution` saying what could make it wrong. A skipped heading level leans fail; `aria-checked` on a native checkbox leans pass. A lean counted against the W3C ACT test cases on five cases or more also says how often it was right (`measured`). The outcome stays `cantTell` either way. See core's [`LEANS.md`](https://github.com/SureA11y/core/blob/main/docs/LEANS.md).
|
|
275
|
+
- **How to check it.** Each question of a core rule carries `howToCheck`: `steps` starting from the element it names, and what a person sees if it passes (`passWhen`) or fails (`failWhen`), in the scan's locale. The engine in the page leaves them out; `analyze()` adds them, with the steps of your packs' rules too.
|
|
276
|
+
|
|
277
|
+
`formatFailures()` shows both: each question says beside its severity whether it likely fails, likely passes or needs review, then why, the caution, and with `{ howToCheck: true }` the steps:
|
|
278
|
+
|
|
279
|
+
```
|
|
280
|
+
2) heading-order (minor, likely fails): This heading jumps from level 1 to level 3, skipping a level.
|
|
281
|
+
at html > body > main > h3
|
|
282
|
+
Go down one level at a time, so an <h2> is followed by an <h3> rather than an <h4>, and the outline of the page stays easy to follow.
|
|
283
|
+
Why it likely fails: The heading skips a level after the one before it.
|
|
284
|
+
How to check:
|
|
285
|
+
1. Find the heading the report names and note its level and the previous heading's level (from the report or the Accessibility pane).
|
|
286
|
+
...
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
To gate a test on the questions that likely fail as well as the failures, use `@surea11y/core`'s `leaningFailures(results)`, which works on this binding's results (a `.frames(true)` tree included). It leaves out the rules whose criteria are outside the scan's target, and with `{ wcagOnly: true }` the best-practice rules too:
|
|
290
|
+
|
|
291
|
+
```js
|
|
292
|
+
const { leaningFailures } = require('@surea11y/core');
|
|
293
|
+
|
|
294
|
+
const results = await new A11yCoreBuilder({ page }).analyze();
|
|
295
|
+
const failures = results.checksResults.filter((r) => r.outcome === 'fail');
|
|
296
|
+
assert.ok(
|
|
297
|
+
failures.length === 0 && leaningFailures(results).length === 0,
|
|
298
|
+
formatFailures(results, { outcomes: ['fail', 'leanFail'] })
|
|
299
|
+
);
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
Don't trim such a result with `.reportOnly(['fail'])` first: it drops the `cantTell` rules, and their leans with them. `.reportOnly()` filters whole rules by their outcome, while a rule's occurrences can sit in different tiers (`occurrenceOutcome`), which `formatFailures()` reads one by one. For CI reports, core's `renderJunitReport(results, { leanFailAs: 'failure' })` and `renderSarifReport(results, { leanFailAs: 'error' })` gate on the same findings, and both carry the steps.
|
|
303
|
+
|
|
254
304
|
### Web components: the internals hook
|
|
255
305
|
|
|
256
306
|
Many web components keep their `ElementInternals` in a private field and name themselves, set their states or give themselves a role through it:
|
|
@@ -285,6 +335,63 @@ With it, the checkbox above passes, an unnamed component that attaches internals
|
|
|
285
335
|
- **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.
|
|
286
336
|
- **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'`.
|
|
287
337
|
|
|
338
|
+
### Click handlers added from script: the listener hook
|
|
339
|
+
|
|
340
|
+
Most pages add their click handlers from script, where no page script can list them afterwards:
|
|
341
|
+
|
|
342
|
+
```html
|
|
343
|
+
<div class="save" role="button" tabindex="0">Save</div>
|
|
344
|
+
<script>
|
|
345
|
+
document.querySelector('.save').addEventListener('click', save);
|
|
346
|
+
</script>
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
Enter and Space don't fire `click` on a `<div>`, so this button does nothing from the keyboard. Without help the scan can't see the listener, so `click-handler-keyboard-operable` doesn't report the element at all. `A11yCoreBuilder.installListenerHook(page)` installs `@surea11y/core`'s opt-in listener hook (core 1.14.0 and later), which records the click, key, focus and mouse listeners a page adds, so the keyboard rules judge them. Call it **before** `page.goto()`, as the internals hook:
|
|
350
|
+
|
|
351
|
+
```js
|
|
352
|
+
const page = await browser.newPage();
|
|
353
|
+
await A11yCoreBuilder.installListenerHook(page); // before goto
|
|
354
|
+
await page.goto('https://example.com/');
|
|
355
|
+
|
|
356
|
+
const results = await new A11yCoreBuilder({ page }).analyze();
|
|
357
|
+
results.engine.environment.listenerHook; // 'early'
|
|
358
|
+
```
|
|
359
|
+
|
|
360
|
+
With it:
|
|
361
|
+
|
|
362
|
+
- **The button above fails** `click-handler-keyboard-operable` (`CLICK_HANDLER_NO_KEY_LISTENER`): it's a focusable control with no key listener on it, inside it, above it, on the document or on the window. Once it listens for `keydown`, it passes.
|
|
363
|
+
- **A key listener only above the element** (on an ancestor, the document or the window) is asked about: it may handle this element's keys, or only others'.
|
|
364
|
+
- **A click listener on a container**, as a framework that delegates events from its root adds, makes no element inside it a candidate, so delegated handlers never fail.
|
|
365
|
+
- **Pointer listeners** added from script are asked about by `mouse-only-event-handlers`, unless the element also has a keyboard equivalent.
|
|
366
|
+
- **`widget-keyboard-focusable`** counts the listeners too when it asks about a widget Tab never reaches.
|
|
367
|
+
|
|
368
|
+
It works in Chrome and Firefox.
|
|
369
|
+
|
|
370
|
+
- **Before the page loads.** Only a hook that ran before the page's scripts proves an element has no key listener. Called after `page.goto()`, it has no effect until the next navigation, and a new tab the page opens itself doesn't get it.
|
|
371
|
+
- **For test and audit runs.** The hook wraps `addEventListener`, `removeEventListener` and the `on…` property setters (listeners themselves aren't wrapped, and run as before), and keeps its record under a global symbol. That's why it's opt-in.
|
|
372
|
+
- **Without it**, `analyze()` says once per scan when findings the hook would have decided were judged without it (`1 finding (click-handler-keyboard-operable) was judged without seeing the listeners the page adds from script...`), and `getScanNotes()` gives that note as `kind: 'listener-hook'`, with `findingCount` and the `rules`.
|
|
373
|
+
|
|
374
|
+
Core's [`INTEGRATION.md`](https://github.com/SureA11y/core/blob/main/docs/INTEGRATION.md#seeing-listeners-added-from-script-the-listener-hook) has the details, and its binding authors' guide the reason codes each hook decides.
|
|
375
|
+
|
|
376
|
+
### Live regions: the live-region hook and announcements()
|
|
377
|
+
|
|
378
|
+
`A11yCoreBuilder.installLiveRegionHook(page)` installs `@surea11y/core`'s opt-in live-region hook (core 1.14.0 and later), which records what the page's live regions are given while it runs. The scan then asks about a region added with its text already in it, and one shown and filled at once, which screen readers commonly don't announce. And `A11yCoreBuilder.announcements(page)` returns what the page made available to announce, so a test can check that an action told the user something:
|
|
379
|
+
|
|
380
|
+
```js
|
|
381
|
+
const page = await browser.newPage();
|
|
382
|
+
await A11yCoreBuilder.installLiveRegionHook(page); // before goto
|
|
383
|
+
await page.goto('https://example.com/settings');
|
|
384
|
+
|
|
385
|
+
await page.click('#save');
|
|
386
|
+
const said = await A11yCoreBuilder.announcements(page);
|
|
387
|
+
// [{ text: 'Saved', politeness: 'polite', time: 1234.5, order: 7, behindModal: false, selector: '#status' }]
|
|
388
|
+
assert.ok(said.some((a) => a.text === 'Saved'));
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
Each entry names its region by `selector` (and `shadowHostSelectors` inside a shadow root; `null` for a region that has since left the page, such as a toast). It's `null` without the hook. A text given to a region behind an open modal dialog, which assistive technology did not get, is left out unless you pass `{ includeBehindModal: true }`, and comes marked `behindModal: true`. This is what the page made available to announce, not what a screen reader said. The hook only observes, with one `MutationObserver`; see core's [`INTEGRATION.md`](https://github.com/SureA11y/core/blob/main/docs/INTEGRATION.md#seeing-what-live-regions-are-given-the-live-region-hook).
|
|
392
|
+
|
|
393
|
+
With it, `live-region-announcements` also asks about a region the page added with its text already in it (`LIVE_REGION_INSERTED_WITH_CONTENT`; `role="alert"` is left out, since an alert added that way is announced) and a hidden region shown and filled at once (`LIVE_REGION_SHOWN_AND_FILLED`), even if it has left the page since, like a toast. The result records the hook in `engine.environment.liveRegionHook`, and without it `getScanNotes()` gives a `'live-region-hook'` note when findings it would have decided were judged without it.
|
|
394
|
+
|
|
288
395
|
### Forced colors
|
|
289
396
|
|
|
290
397
|
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:
|
|
@@ -297,6 +404,24 @@ results.engine.environment.forcedColors; // 'active'
|
|
|
297
404
|
|
|
298
405
|
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.
|
|
299
406
|
|
|
407
|
+
### Dark mode and phone width: scans under conditions
|
|
408
|
+
|
|
409
|
+
A page can fail differently in dark mode or at phone width: text that reads well on white fails contrast on a dark background, and a target big enough at 1280 pixels shrinks at 320. `.conditions()` scans the page as it is, then under each condition, and returns one result:
|
|
410
|
+
|
|
411
|
+
```js
|
|
412
|
+
const results = await new A11yCoreBuilder({ page })
|
|
413
|
+
.conditions([{ colorScheme: 'dark' }, { width: 320 }, { colorScheme: 'dark', width: 320 }])
|
|
414
|
+
.analyze();
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
A condition sets a color scheme (`'light'` or `'dark'`, with `page.emulateMediaFeatures()`), a viewport width in CSS pixels (with `page.setViewport()`, keeping the rest of the viewport), or both. The viewport and color scheme are put back after the last scan, even when one throws. In Firefox, widths work; a color scheme needs the DevTools protocol, which Puppeteer has only in Chrome, so `.analyze()` rejects before any scan when a condition sets one there.
|
|
418
|
+
|
|
419
|
+
- A rule's outcome is its worst across the scans, so a contrast failure only in dark mode fails the rule.
|
|
420
|
+
- An occurrence is listed once per element, rule and reason code, with the `conditions` it appeared under (`['default', 'dark']`); `formatFailures()` prints them as `seen in: default, dark`.
|
|
421
|
+
- `results.conditionRuns` lists each scan's condition and `engine.environment`.
|
|
422
|
+
|
|
423
|
+
Each condition is a full scan, so three conditions take about four times as long as one scan. `.frames(true)` can't be combined with `.conditions()` yet. A picture taken with `.screenshots()` under a condition has the condition in its file name.
|
|
424
|
+
|
|
300
425
|
### Registering a custom rule at runtime
|
|
301
426
|
|
|
302
427
|
`@surea11y/core` supports registering additional rules per-scan via `engineOptions.customRules`. Use `.withCustomRules()` to register one:
|
|
@@ -377,12 +502,38 @@ results.engine.profile; // 'acme-web-2026'
|
|
|
377
502
|
results.rulesResults.filter((r) => r.meta && r.meta.standard === 'Acme web policy');
|
|
378
503
|
```
|
|
379
504
|
|
|
505
|
+
**Several profiles at once.** `.options({ profile })` also takes a list, a pack's profile beside WCAG's or another pack's (`@surea11y/core` 1.15 and later). Each profile judges the page as it would alone, and the result reads as one profile with the rules of all, in the top frame and in each frame with `.frames(true)`:
|
|
506
|
+
|
|
507
|
+
```js
|
|
508
|
+
const waiAria = require('@surea11y/pack-wai-aria');
|
|
509
|
+
|
|
510
|
+
const results = await new A11yCoreBuilder({ page })
|
|
511
|
+
.withPacks(waiAria)
|
|
512
|
+
.options({ profile: ['wcag22-aa', 'wai-aria-1.2'] })
|
|
513
|
+
.analyze();
|
|
514
|
+
|
|
515
|
+
results.engine.profiles; // ['wcag22-aa', 'wai-aria-1.2']
|
|
516
|
+
// A rule both run is one check: its outcome is the worst, and its verdicts
|
|
517
|
+
// say what each profile makes of it.
|
|
518
|
+
results.checksResults.find((c) => c.ruleId === 'aria-allowed-attr').verdicts;
|
|
519
|
+
```
|
|
520
|
+
|
|
521
|
+
A profile that didn't run is in `results.engine.profilesNotRun`, with why, and `getScanGaps()` reports it as `'profile-not-run'`. Core's [`OUTPUT_SCHEMA.md`](https://github.com/SureA11y/core/blob/main/docs/OUTPUT_SCHEMA.md#several-profiles) has the whole result.
|
|
522
|
+
|
|
380
523
|
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.
|
|
381
524
|
|
|
382
525
|
**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.
|
|
383
526
|
|
|
384
527
|
**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.
|
|
385
528
|
|
|
529
|
+
### Style sheets from another origin
|
|
530
|
+
|
|
531
|
+
A page's script can't read the rules of a style sheet served from another origin (a CDN, a fonts service), so a check that reads the CSS, such as `css-orientation-lock`, can't tell whether it holds an orientation lock and asks about it. With `@surea11y/core` 1.14.0 or later, `.analyze()` asks the page which sheets it can't read, fetches them from Node (without the browser's cookies), and gives core their text, which it then checks. It's on by default; each request is given up after five seconds, and a sheet that can't be fetched leaves the check asking as before. To send no request but the page's own:
|
|
532
|
+
|
|
533
|
+
```js
|
|
534
|
+
await new A11yCoreBuilder({ page }).fetchStyleSheets(false).analyze();
|
|
535
|
+
```
|
|
536
|
+
|
|
386
537
|
### Element addressing beyond a CSS selector
|
|
387
538
|
|
|
388
539
|
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.
|
|
@@ -413,11 +564,38 @@ try {
|
|
|
413
564
|
|
|
414
565
|
## TypeScript
|
|
415
566
|
|
|
416
|
-
`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`) of `withPacks()`, which takes a pack made with `definePack` (`PackLike`), and of `.screenshots()` (`ScreenshotOptions`, and `OccurrenceScreenshot` for an occurrence's `screenshot`). `A11yCoreBuilder.installInternalsHook(page)`
|
|
567
|
+
`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`), of `withPacks()`, which takes a pack made with `definePack` (`PackLike`), and of `.screenshots()` (`ScreenshotOptions`, and `OccurrenceScreenshot` for an occurrence's `screenshot`). `A11yCoreBuilder.installInternalsHook(page)`, `installListenerHook(page)`, `installLiveRegionHook(page)` and `announcements(page)` are typed as static methods, the last resolving to `LocatedAnnouncement[] | null` (from `@surea11y/binding-base`). 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`, and one for `'profile-not-run'`, which carries `profile`. `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.
|
|
568
|
+
|
|
569
|
+
## What changes with `@surea11y/core` 1.15
|
|
570
|
+
|
|
571
|
+
With `@surea11y/core` 1.15.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):
|
|
572
|
+
|
|
573
|
+
- **WCAG fails only where WCAG fails.** Where only WAI-ARIA or the HTML content model is broken (an attribute the role doesn't support, an unnamed grid or dialog, a heading in a list), the ARIA and HTML structure rules now ask (`cantTell`, uncertainty `spec-only`) instead of failing. The findings keep their reason codes, so baselines still match, and a gate on `fail` no longer fails on them.
|
|
574
|
+
- **Frames are read as the browser reads them.** A framed document is no page of its own, so its title, language, viewport and landmark rules are `notApplicable`; a frame under `aria-hidden` or `inert` is read as such, one behind an open modal dialog is left out, and one in a shadow root is read through its host ([more](#scanning-every-frame-including-cross-origin-iframes)).
|
|
575
|
+
- **Several profiles at once.** `.options({ profile: ['wcag22-aa', 'wai-aria-1.2'] })`, with the packs that bring them, judges the page by each; a profile that can't run is a `profile-not-run` gap ([more](#scanning-with-packs-standards-checklists-and-your-own-rules)).
|
|
576
|
+
- **A picture in the state the finding was made in.** A `text-spacing-content-loss` finding is also pictured with the spacing applied ([more](#a-picture-of-each-failing-element)).
|
|
577
|
+
- **How to check by hand.** Core's procedures say how a person assesses each criterion, and its HTML report lists what a scan leaves to a person.
|
|
578
|
+
- **Roles follow WAI-ARIA more closely:** `role="text"` names no role, and an image with a presentational role and a global ARIA attribute keeps its role, so it fails without `alt`.
|
|
579
|
+
|
|
580
|
+
## What changes with `@surea11y/core` 1.14
|
|
581
|
+
|
|
582
|
+
With `@surea11y/core` 1.14.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):
|
|
583
|
+
|
|
584
|
+
- **Status messages.** `live-region-announcements` (4.1.3) asks about a live region hidden with `aria-hidden` or `inert`, or left `aria-busy`. With [`installLiveRegionHook()`](#live-regions-the-live-region-hook-and-announcements) it also asks about one added with its text or shown and filled at once, and `announcements()` reads what the page made available to announce, each region named by its selector.
|
|
585
|
+
- **Listeners added from script.** With [`installListenerHook()`](#click-handlers-added-from-script-the-listener-hook), `click-handler-keyboard-operable` judges a click listener added with `addEventListener` as an inline `onclick`, and fails a focusable control that no key listener can reach (`CLICK_HANDLER_NO_KEY_LISTENER`); `mouse-only-event-handlers` asks about pointer listeners added from script. Both rules' messages now say "click handler" rather than "onclick handler".
|
|
586
|
+
- **Roles that depend on context.** `aria-allowed-attr` no longer fails `aria-expanded` on a text input whose `list` names a `<datalist>` (a combobox), and now judges `<td>`: `cell` in a table, `gridcell` in a grid. `label-in-name` checks a `<td>` in a grid. `heading-order` and `page-has-heading-one` count a heading marked `role="none"` that can take focus or has a global ARIA attribute, as browsers do.
|
|
587
|
+
- **Style sheets from another origin are checked.** `.analyze()` fetches, from Node, the style sheets the page can't read and core checks them, so `css-orientation-lock` finds a lock in a CDN's CSS instead of asking (`.fetchStyleSheets(false)` turns it off). [More](#style-sheets-from-another-origin).
|
|
588
|
+
- **No WCAG criterion passes on its rules alone.** A rollup passes only for a criterion whose rules check all it asks, and none is listed as checked in full yet, so where its rules all pass it is `cantTell` (`composite.rollup.cantTell.partialCheck`). A rollup whose rules all found nothing is `notApplicable` only for 2.4.3, 2.4.4, 2.4.7, 2.4.9, 2.5.3 and 4.1.1, whose rules find every case, and `cantTell` otherwise (`composite.rollup.cantTell.partialCoverage`). `page-title-patterns` asks about every page title, so 2.4.2 is `cantTell` on a page with one. A gate that asserted a criterion `pass` or `notApplicable` now sees `cantTell`; gate on failures (`getGatingFailures()`, or `outcome === 'fail'`) instead.
|
|
589
|
+
- **New checks.** `click-handler-keyboard-operable` (2.1.1, 2.1.3) fails a button-like role with a click handler the keyboard can't reach, and asks about one with no key handler. `focus-not-removed-by-script` (2.1.1, 2.4.7) fails an element whose `onfocus` only blurs it. `aria-owns-valid` (1.3.1, 4.1.2) fails an element owned twice. These ask, and never fail: `widget-keyboard-focusable` (a widget Tab never reaches), `invalid-field-error-message` (3.3.1), `live-region-announcements` (4.1.3), `aria-expanded-state-mismatch`, `moving-content-pausable` (2.2.2), `image-of-text` (1.4.5), and the best practices `label-for-valid` and `control-name-title-only`.
|
|
590
|
+
- **Placeholders below the contrast ratio fail** when the page chose their colours; in the browser's own colours they pass. They used to be questions.
|
|
591
|
+
- **More questions in some places**, fewer in others: `css-hidden-focus` asks about a link in a closed off-canvas menu or a container clipped to nothing; contrast is measured over solid backgrounds, empty background layers, `::before` strips and drop shadows it used to ask about; `link-name-quality` knows more French generic phrases.
|
|
592
|
+
- **Questions lean, and say how to answer them.** A `cantTell` occurrence can carry a `lean` (which way the evidence points, and why) and carries `howToCheck` (the steps to answer it), which `analyze()` adds. `formatFailures()` lists findings in the order a review takes and shows both. [More](#findings-that-need-review-leans-and-how-to-check).
|
|
593
|
+
- **Two more opt-in hooks.** `A11yCoreBuilder.installListenerHook(page)` lets the keyboard rules see click handlers added from script, and `A11yCoreBuilder.installLiveRegionHook(page)` records what live regions are given, which `A11yCoreBuilder.announcements(page)` returns. [More](#click-handlers-added-from-script-the-listener-hook).
|
|
594
|
+
- **Some reason codes are split by cause** (`LIST_ITEM_ROLE_OVERRIDDEN`, `LIST_ROLE_OVERRIDDEN`, `DUPLICATE_ID_IN_SHADOW_TREE`, `DEFAULT_LANG_INVALID`, `IMAGE_ONLY_CONTROL_CONTENT`, `HEADING_LIKE_NUMBER`, `HEADING_LIKE_LINK`). Core's baselines still match a 1.13 entry to its finding under the new code, and `migrateBaselineEntries()` rewrites a baseline; see core's [`BASELINE.md`](https://github.com/SureA11y/core/blob/main/docs/BASELINE.md#upgrading).
|
|
417
595
|
|
|
418
596
|
## What changes with `@surea11y/core` 1.12
|
|
419
597
|
|
|
420
|
-
|
|
598
|
+
From 1.4.0 this package 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):
|
|
421
599
|
|
|
422
600
|
- **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.
|
|
423
601
|
- **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.
|
|
@@ -443,7 +621,7 @@ The binding passes rule IDs, tags and options through to the engine, so these sh
|
|
|
443
621
|
|
|
444
622
|
## Relationship to `@surea11y/playwright`
|
|
445
623
|
|
|
446
|
-
This binding's builder API is deliberately identical to `@surea11y/playwright`'s — same method names, same mutability contract, same result shapes — so switching between the two (or running the same accessibility gate logic against both) is a
|
|
624
|
+
This binding's builder API is deliberately identical to `@surea11y/playwright`'s — same method names, same mutability contract, same result shapes — so switching between the two (or running the same accessibility gate logic against both) is mostly a swap of `puppeteer.launch()`/`playwright.chromium.launch()`. The differences follow the drivers: the hooks are installed on a page, since Puppeteer runs a script before a page's own only through `page.evaluateOnNewDocument()`, style sheets from another origin are fetched without the browser's cookies, in Firefox Puppeteer can't emulate forced colors or a color scheme, and `.frames(true)` scans up to four sub-frames at a time. `analyze()`'s injection call is also simpler here, since Puppeteer's `page.evaluate()` is genuinely variadic and doesn't need the wrapper/`eval()` trick Playwright's single-argument `evaluate()` requires.
|
|
447
625
|
|
|
448
626
|
## Building another framework binding?
|
|
449
627
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@surea11y/puppeteer",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.0",
|
|
4
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",
|
|
@@ -45,8 +45,8 @@
|
|
|
45
45
|
"LICENSE"
|
|
46
46
|
],
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"@surea11y/binding-base": "^1.
|
|
49
|
-
"@surea11y/core": "^1.
|
|
48
|
+
"@surea11y/binding-base": "^1.7.0",
|
|
49
|
+
"@surea11y/core": "^1.15.0"
|
|
50
50
|
},
|
|
51
51
|
"peerDependencies": {
|
|
52
52
|
"puppeteer": ">=22.0.0"
|
package/src/A11yCoreBuilder.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Page, ElementHandle } from 'puppeteer';
|
|
1
|
+
import type { Page, ElementHandle, Frame } from 'puppeteer';
|
|
2
2
|
import type * as Core from '@surea11y/core';
|
|
3
3
|
|
|
4
4
|
// The result shapes are @surea11y/core's own types (shipped since core
|
|
@@ -49,9 +49,12 @@ export type {
|
|
|
49
49
|
ScreenshotOptions,
|
|
50
50
|
ScreenshotSkip,
|
|
51
51
|
ScreenshotBox,
|
|
52
|
-
OccurrenceScreenshot
|
|
52
|
+
OccurrenceScreenshot,
|
|
53
|
+
LocatedAnnouncement,
|
|
54
|
+
ReviewGroup
|
|
53
55
|
} from '@surea11y/binding-base';
|
|
54
56
|
import type {
|
|
57
|
+
LocatedAnnouncement,
|
|
55
58
|
PackLike,
|
|
56
59
|
WcagVersion,
|
|
57
60
|
WcagLevelInput,
|
|
@@ -69,6 +72,8 @@ export type CheckResultMeta = Core.RuleMeta;
|
|
|
69
72
|
export type CompositeResultDetails = Core.CompositeResult['data']['details'];
|
|
70
73
|
|
|
71
74
|
export interface Occurrence extends Core.Occurrence {
|
|
75
|
+
/** With .conditions(): the conditions it was found under, 'default' for the page as it was. */
|
|
76
|
+
conditions?: string[];
|
|
72
77
|
/**
|
|
73
78
|
* Only present when `.elementRef(true)` was used. `null` when this
|
|
74
79
|
* occurrence has no single resolvable target element (e.g. `selector` was
|
|
@@ -90,6 +95,8 @@ export interface CheckResult extends Omit<Core.CheckResult, 'occurrences'> {
|
|
|
90
95
|
|
|
91
96
|
/** surea11y's native top-level result shape -- see docs/OUTPUT_SCHEMA.md. */
|
|
92
97
|
export interface A11yCoreResult extends Omit<Core.ScanResult, 'checksResults'> {
|
|
98
|
+
/** With .conditions(): each scan's condition ('default' first) and environment. */
|
|
99
|
+
conditionRuns?: Array<{ condition: string; environment: Record<string, unknown> | null }>;
|
|
93
100
|
checksResults: CheckResult[];
|
|
94
101
|
}
|
|
95
102
|
|
|
@@ -144,6 +151,28 @@ export class A11yCoreBuilder {
|
|
|
144
151
|
*/
|
|
145
152
|
static installInternalsHook(page: Page): ReturnType<Page['evaluateOnNewDocument']>;
|
|
146
153
|
|
|
154
|
+
/**
|
|
155
|
+
* Installs @surea11y/core's opt-in listener hook in `page`, so the keyboard
|
|
156
|
+
* rules see the event listeners the page adds from script. Call it before
|
|
157
|
+
* page.goto(). Needs @surea11y/core 1.14.0 or later.
|
|
158
|
+
*/
|
|
159
|
+
static installListenerHook(page: Page): ReturnType<Page['evaluateOnNewDocument']>;
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Installs @surea11y/core's opt-in live-region hook in `page`, which
|
|
163
|
+
* records what its live regions are given. Call it before page.goto().
|
|
164
|
+
* Needs @surea11y/core 1.14.0 or later.
|
|
165
|
+
*/
|
|
166
|
+
static installLiveRegionHook(page: Page): ReturnType<Page['evaluateOnNewDocument']>;
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* What `page`'s live regions were given since it loaded, in order, each
|
|
170
|
+
* region named by its selector; null without the live-region hook. Texts
|
|
171
|
+
* given to a region behind an open modal dialog only with
|
|
172
|
+
* `includeBehindModal: true`.
|
|
173
|
+
*/
|
|
174
|
+
static announcements(page: Page, options?: { includeBehindModal?: boolean }): Promise<LocatedAnnouncement[] | null>;
|
|
175
|
+
|
|
147
176
|
/** Scope the scan to one region. Call multiple times for a multi-region union. */
|
|
148
177
|
include(selector: string): this;
|
|
149
178
|
/**
|
|
@@ -184,7 +213,8 @@ export class A11yCoreBuilder {
|
|
|
184
213
|
/**
|
|
185
214
|
* Where analyze() sends each scan gap instead of console.warn: called once
|
|
186
215
|
* per gap, with the result of the frame it came from, and once per scan
|
|
187
|
-
* for the internals-hook
|
|
216
|
+
* for each of the internals-hook and listener-hook notes (tell them apart
|
|
217
|
+
* by `kind`). `() => {}`
|
|
188
218
|
* silences them, `null` goes back to console.warn. A later call replaces it.
|
|
189
219
|
*/
|
|
190
220
|
logger(fn: ((entry: ScanGap | ScanNote, result: A11yCoreResult) => void) | null): this;
|
|
@@ -201,6 +231,15 @@ export class A11yCoreBuilder {
|
|
|
201
231
|
reportOnly(outcomes: Core.Outcome | Core.Outcome[]): this;
|
|
202
232
|
/** Opt in to also scanning every sub-frame on the page (including cross-origin iframes). */
|
|
203
233
|
frames(enabled?: boolean): this;
|
|
234
|
+
/**
|
|
235
|
+
* Also scan the page under each condition after scanning it as it is
|
|
236
|
+
* (@surea11y/binding-base 1.6.0): a color scheme, a viewport width, or
|
|
237
|
+
* both. analyze() returns one merged result: a rule's outcome is its worst
|
|
238
|
+
* across the scans, each occurrence lists the `conditions` it appeared
|
|
239
|
+
* under, and `conditionRuns` gives each scan's environment. The viewport
|
|
240
|
+
* and scheme are put back afterwards. Not combined with frames(true) yet.
|
|
241
|
+
*/
|
|
242
|
+
conditions(list: ReadonlyArray<ScanCondition> | null): this;
|
|
204
243
|
/** Opt in to resolving each fail/cantTell occurrence's selector to a live ElementHandle. */
|
|
205
244
|
elementRef(enabled?: boolean): this;
|
|
206
245
|
/**
|
|
@@ -210,6 +249,12 @@ export class A11yCoreBuilder {
|
|
|
210
249
|
* it can't use.
|
|
211
250
|
*/
|
|
212
251
|
screenshots(options?: ScreenshotOptions | boolean): this;
|
|
252
|
+
/**
|
|
253
|
+
* Fetch, from Node, the style sheets the page can't read (another origin's)
|
|
254
|
+
* and give core their text, so checks that read the CSS can check them. On
|
|
255
|
+
* by default; needs @surea11y/core 1.14.0 or later.
|
|
256
|
+
*/
|
|
257
|
+
fetchStyleSheets(enabled?: boolean): this;
|
|
213
258
|
/** The rules this scan will run, worked out in Node with no page (@surea11y/core 1.12.0 and later). */
|
|
214
259
|
plannedChecks(): PlannedCheck[];
|
|
215
260
|
/** The criteria this scan will report in rulesResults, worked out in Node with no page. */
|
|
@@ -218,7 +263,7 @@ export class A11yCoreBuilder {
|
|
|
218
263
|
/**
|
|
219
264
|
* Runs the scan. Returns { topFrame, frames } instead of a single result
|
|
220
265
|
* when .frames(true) was used; include() then scopes the top frame only,
|
|
221
|
-
* and each sub-frame is scanned whole. Rejects with an EngineError for
|
|
266
|
+
* and each sub-frame inside its roots is scanned whole. Rejects with an EngineError for
|
|
222
267
|
* input the engine cannot use, with its `code`: 'INVALID_RUN_ONLY'
|
|
223
268
|
* (withRules()/withTags() named no rule or tag it knows),
|
|
224
269
|
* 'INVALID_CONTEXT_SELECTOR' (an include() selector the browser can't
|
|
@@ -228,3 +273,25 @@ export class A11yCoreBuilder {
|
|
|
228
273
|
*/
|
|
229
274
|
analyze(): Promise<A11yCoreResult | A11yCoreMultiFrameResult>;
|
|
230
275
|
}
|
|
276
|
+
|
|
277
|
+
/** The four severities, least to most severe (@surea11y/binding-base 1.6.0 and later). */
|
|
278
|
+
export const SEVERITIES: ReadonlyArray<Core.Severity>;
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* The failing rule results that should fail a test: every `fail`, or with
|
|
282
|
+
* `failOnSeverity` only those whose severity is that level or above, as
|
|
283
|
+
* `surea11y scan --fail-on-severity` counts them. `fail` keeps its meaning;
|
|
284
|
+
* the level only picks which failures stop the test. Throws a TypeError for
|
|
285
|
+
* a level that is not a severity. From @surea11y/binding-base 1.6.0.
|
|
286
|
+
*/
|
|
287
|
+
export function getGatingFailures(
|
|
288
|
+
input: A11yCoreResult | ReadonlyArray<CheckResult>,
|
|
289
|
+
opts?: { failOnSeverity?: Core.Severity }
|
|
290
|
+
): CheckResult[];
|
|
291
|
+
|
|
292
|
+
/** A condition to scan the page under with .conditions(). */
|
|
293
|
+
export interface ScanCondition {
|
|
294
|
+
colorScheme?: 'light' | 'dark';
|
|
295
|
+
/** The viewport's width in CSS pixels; its height is kept. */
|
|
296
|
+
width?: number;
|
|
297
|
+
}
|
package/src/A11yCoreBuilder.js
CHANGED
|
@@ -1,18 +1,50 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const
|
|
3
|
+
const core = require('@surea11y/core');
|
|
4
|
+
|
|
5
|
+
const { runa11yCoreInPage, internalsHookScript } = core;
|
|
6
|
+
const bindingBase = require('@surea11y/binding-base');
|
|
4
7
|
const {
|
|
5
8
|
A11yCoreBuilderBase,
|
|
6
9
|
createInPageScan,
|
|
7
10
|
rethrowEngineError,
|
|
8
|
-
queryOccurrenceElement
|
|
9
|
-
|
|
11
|
+
queryOccurrenceElement,
|
|
12
|
+
// How .frames(true) reads each frame (binding-base 1.7 and later).
|
|
13
|
+
readFrameElement,
|
|
14
|
+
isFrameDocumentEmpty,
|
|
15
|
+
frameReadingOptions
|
|
16
|
+
} = bindingBase;
|
|
17
|
+
const frameEngineOptions = bindingBase.frameEngineOptions || ((engineOptions) => engineOptions);
|
|
18
|
+
// What a frame is under, with what the frames around it are under
|
|
19
|
+
// (binding-base 1.7 and later; aria-hidden and inert alike).
|
|
20
|
+
const inheritFrameReading = bindingBase.inheritFrameReading || ((above, reading) => ({
|
|
21
|
+
ariaHidden: !!((above && above.ariaHidden) || (reading && reading.ariaHidden)),
|
|
22
|
+
inert: !!((above && above.inert) || (reading && reading.inert))
|
|
23
|
+
}));
|
|
10
24
|
|
|
11
25
|
// core's scan, wrapped so an engine error keeps its `code` across
|
|
12
26
|
// page.evaluate(), which keeps only an error's message. Built once; it is
|
|
13
27
|
// self-contained, so Puppeteer serializes it as it did runa11yCoreInPage.
|
|
14
28
|
const inPageScan = createInPageScan(runa11yCoreInPage);
|
|
15
29
|
|
|
30
|
+
// How many sub-frames a .frames(true) scan runs at once.
|
|
31
|
+
const FRAME_CONCURRENCY = 4;
|
|
32
|
+
|
|
33
|
+
/** Maps `items` through async `fn`, at most `limit` at a time, keeping their order. */
|
|
34
|
+
async function mapInBatches(items, limit, fn) {
|
|
35
|
+
const out = new Array(items.length);
|
|
36
|
+
let next = 0;
|
|
37
|
+
const worker = async () => {
|
|
38
|
+
while (next < items.length) {
|
|
39
|
+
const i = next;
|
|
40
|
+
next += 1;
|
|
41
|
+
out[i] = await fn(items[i]);
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
|
|
16
48
|
/**
|
|
17
49
|
* Puppeteer binding for surea11y -- scans a real, already-rendered page.
|
|
18
50
|
*
|
|
@@ -51,7 +83,7 @@ const inPageScan = createInPageScan(runa11yCoreInPage);
|
|
|
51
83
|
* // results.frames -- array of the same native result shape, one per sub-frame
|
|
52
84
|
*
|
|
53
85
|
* Unlike script-injection-based accessibility engines (which need a
|
|
54
|
-
* postMessage-based protocol
|
|
86
|
+
* postMessage-based protocol to reach cross-origin
|
|
55
87
|
* iframes, since they're injected as a plain <script> and are fully subject
|
|
56
88
|
* to the browser's same-origin policy), this doesn't need any @surea11y/core
|
|
57
89
|
* engine support: Puppeteer drives every frame
|
|
@@ -149,6 +181,53 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
|
|
|
149
181
|
return page.evaluateOnNewDocument(internalsHookScript());
|
|
150
182
|
}
|
|
151
183
|
|
|
184
|
+
/**
|
|
185
|
+
* Installs @surea11y/core's opt-in listener hook in `page`, so the
|
|
186
|
+
* keyboard rules see the event listeners the page adds from script
|
|
187
|
+
* (`addEventListener`, `el.onclick = fn`), which no page script can list.
|
|
188
|
+
* Without it a `<div role="button">` given a click listener from script
|
|
189
|
+
* goes unjudged. Call it before page.goto(), as installInternalsHook():
|
|
190
|
+
* Puppeteer runs it before the page's own scripts in every frame and
|
|
191
|
+
* after each navigation. Needs @surea11y/core 1.14.0 or later. Resolves
|
|
192
|
+
* to what evaluateOnNewDocument() resolves to.
|
|
193
|
+
* @param {import('puppeteer').Page} page
|
|
194
|
+
*/
|
|
195
|
+
static installListenerHook(page) {
|
|
196
|
+
return installHook(page, 'installListenerHook', 'listenerHookScript');
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Installs @surea11y/core's opt-in live-region hook in `page`, which
|
|
201
|
+
* records what the page's live regions are given while it runs: the
|
|
202
|
+
* scan then asks about a region added with its text already in it, and
|
|
203
|
+
* A11yCoreBuilder.announcements(page) returns what the page made
|
|
204
|
+
* available to announce. Call it before page.goto(), as
|
|
205
|
+
* installInternalsHook(). Needs @surea11y/core 1.14.0 or later.
|
|
206
|
+
* @param {import('puppeteer').Page} page
|
|
207
|
+
*/
|
|
208
|
+
static installLiveRegionHook(page) {
|
|
209
|
+
return installHook(page, 'installLiveRegionHook', 'liveRegionHookScript');
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* What `page`'s live regions were given since it loaded, as the
|
|
214
|
+
* live-region hook recorded it, in order: `[{ text, politeness, time,
|
|
215
|
+
* order, behindModal, selector }]`, each region named by its selector (and
|
|
216
|
+
* `shadowHostSelectors` inside a shadow root; null for a region that has
|
|
217
|
+
* since left the page). null where installLiveRegionHook(page) wasn't
|
|
218
|
+
* called before the page loaded. What the page made available to
|
|
219
|
+
* announce, not what a screen reader said. A text given to a region
|
|
220
|
+
* behind an open modal dialog, which assistive technology did not get, is
|
|
221
|
+
* listed only with `{ includeBehindModal: true }`, marked `behindModal`.
|
|
222
|
+
* Needs @surea11y/core 1.14.0 or later.
|
|
223
|
+
* @param {import('puppeteer').Page} page
|
|
224
|
+
* @param {{ includeBehindModal?: boolean }} [options]
|
|
225
|
+
* @returns {Promise<Array<object>|null>}
|
|
226
|
+
*/
|
|
227
|
+
static announcements(page, options) {
|
|
228
|
+
return new A11yCoreBuilder({ page })._announcementsIn(page, options);
|
|
229
|
+
}
|
|
230
|
+
|
|
152
231
|
constructor({ page, url } = {}) {
|
|
153
232
|
super({ url });
|
|
154
233
|
if (!page || typeof page.evaluate !== 'function') {
|
|
@@ -182,11 +261,21 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
|
|
|
182
261
|
// An engine error (INVALID_RUN_ONLY, INVALID_CONTEXT_SELECTOR) comes
|
|
183
262
|
// back as a plain object and is thrown here as an EngineError with its
|
|
184
263
|
// `code`; any other error in the page rejects evaluate() as before.
|
|
185
|
-
|
|
186
|
-
|
|
264
|
+
// url() names the top page only; a frame is named by its own address.
|
|
265
|
+
const top = this._page.mainFrame ? this._page.mainFrame() : null;
|
|
266
|
+
const runInFrame = async (frameOrPage, frameContextSelector, frameOptions = engineOptions) => {
|
|
267
|
+
const isTop = frameOrPage === this._page || frameOrPage === top;
|
|
268
|
+
const ownUrl = typeof frameOrPage.url === 'function' ? frameOrPage.url() : null;
|
|
269
|
+
const frameUrl = isTop ? this._url || ownUrl : ownUrl;
|
|
187
270
|
if (packScript) await frameOrPage.evaluate(packScript);
|
|
271
|
+
// The text of the style sheets the frame can't read, fetched from Node
|
|
272
|
+
// (binding-base 1.6.0 and core 1.14.0; nothing with older ones).
|
|
273
|
+
const scanOptions =
|
|
274
|
+
typeof this._styleSheetEngineOptions === 'function'
|
|
275
|
+
? await this._styleSheetEngineOptions(frameOrPage, frameOptions)
|
|
276
|
+
: frameOptions;
|
|
188
277
|
const result = rethrowEngineError(
|
|
189
|
-
await frameOrPage.evaluate(inPageScan, frameUrl, frameContextSelector,
|
|
278
|
+
await frameOrPage.evaluate(inPageScan, frameUrl, frameContextSelector, scanOptions, runOnly)
|
|
190
279
|
);
|
|
191
280
|
this._warnScanGaps(result, '@surea11y/puppeteer');
|
|
192
281
|
// Right after the frame's scan, before reportOnly(): nothing unless
|
|
@@ -195,6 +284,14 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
|
|
|
195
284
|
return this._elementRef ? this._attachElementRefs(frameOrPage, result) : result;
|
|
196
285
|
};
|
|
197
286
|
|
|
287
|
+
// .conditions() (binding-base 1.6.0): the page as it is, then under each
|
|
288
|
+
// condition, merged into one result.
|
|
289
|
+
if (this._conditions) {
|
|
290
|
+
return this._applyReportOnly(
|
|
291
|
+
await this._scanUnderConditions(() => runInFrame(this._page, contextSelector), this._conditionDriver())
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
|
|
198
295
|
if (!this._scanFrames) {
|
|
199
296
|
return this._applyReportOnly(await runInFrame(this._page, contextSelector));
|
|
200
297
|
}
|
|
@@ -206,29 +303,69 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
|
|
|
206
303
|
// it's already covered by topFrame above, so callers don't have to
|
|
207
304
|
// de-duplicate it themselves out of the frames array.
|
|
208
305
|
const subFrames = this._page.frames().filter((f) => f !== mainFrame);
|
|
209
|
-
|
|
210
|
-
|
|
306
|
+
// include() scopes the top frame only: each sub-frame is scanned whole,
|
|
307
|
+
// as core's own runa11yCoreAcrossFrames does. The selectors were written
|
|
308
|
+
// against the top document, and since core 1.10.0 a selector that
|
|
309
|
+
// matches nothing scans nothing, so passing them on would leave most
|
|
310
|
+
// frames unscanned.
|
|
311
|
+
// Each frame read as core's own scan across frames reads it
|
|
312
|
+
// (binding-base's frames helpers, 1.7 and later): one the page doesn't
|
|
313
|
+
// show, that is excluded or outside include()'s roots, or that shows
|
|
314
|
+
// nothing is left out; one under aria-hidden is scanned as aria-hidden.
|
|
315
|
+
// A frame inside one inherits how it is read.
|
|
316
|
+
const readings = new Map();
|
|
317
|
+
const readingOf = (frame) => {
|
|
318
|
+
if (!readings.has(frame)) readings.set(frame, this._readFrame(frame, mainFrame, readingOf, engineOptions, contextSelector));
|
|
319
|
+
return readings.get(frame);
|
|
320
|
+
};
|
|
321
|
+
const scanFrame = async (frame) => {
|
|
211
322
|
try {
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
// selector that matches nothing scans nothing, so passing them on
|
|
216
|
-
// would leave most frames unscanned.
|
|
217
|
-
frames.push(this._applyReportOnly(await runInFrame(frame, null)));
|
|
323
|
+
const reading = await readingOf(frame);
|
|
324
|
+
if (reading.skipped) return null;
|
|
325
|
+
return this._applyReportOnly(await runInFrame(frame, null, frameEngineOptions(engineOptions, reading)));
|
|
218
326
|
} catch (e) {
|
|
219
327
|
// A frame can detach/navigate away mid-scan, or be a sandboxed
|
|
220
328
|
// frame the browser blocks scripting in -- don't let one bad frame
|
|
221
329
|
// abort the whole multi-frame scan; report it and keep going.
|
|
222
|
-
|
|
330
|
+
return {
|
|
223
331
|
url: (typeof frame.url === 'function' ? frame.url() : null),
|
|
224
332
|
error: (e && e.message) || String(e)
|
|
225
|
-
}
|
|
333
|
+
};
|
|
226
334
|
}
|
|
227
|
-
}
|
|
335
|
+
};
|
|
336
|
+
// Frames are scanned a few at a time, each result in the frame's place
|
|
337
|
+
// in page.frames(): a page of 50 small frames took 18 s one by one.
|
|
338
|
+
// Element pictures scroll the page, so with .screenshots() they go one
|
|
339
|
+
// at a time, as before.
|
|
340
|
+
const frames = (await mapInBatches(subFrames, this._screenshots ? 1 : FRAME_CONCURRENCY, scanFrame))
|
|
341
|
+
.filter(Boolean);
|
|
228
342
|
|
|
229
343
|
return { topFrame, frames };
|
|
230
344
|
}
|
|
231
345
|
|
|
346
|
+
/**
|
|
347
|
+
* How a sub-frame is read: `{ skipped }`, `{ ariaHidden }` or `{}`, from
|
|
348
|
+
* its element in its parent frame and its own document, as core's scan
|
|
349
|
+
* across frames reads it. Without binding-base's frames helpers, every
|
|
350
|
+
* frame is scanned as before.
|
|
351
|
+
*/
|
|
352
|
+
async _readFrame(frame, mainFrame, readingOf, engineOptions, contextSelector) {
|
|
353
|
+
if (typeof readFrameElement !== 'function') return {};
|
|
354
|
+
const parent = frame.parentFrame && frame.parentFrame();
|
|
355
|
+
const above = parent && parent !== mainFrame ? await readingOf(parent) : {};
|
|
356
|
+
if (above.skipped) return above;
|
|
357
|
+
let own = {};
|
|
358
|
+
try {
|
|
359
|
+
const handle = await frame.frameElement();
|
|
360
|
+
own = await handle.evaluate(readFrameElement, frameReadingOptions(engineOptions, contextSelector, parent === mainFrame));
|
|
361
|
+
await handle.dispose().catch(() => {});
|
|
362
|
+
if (!own.skipped && (await frame.evaluate(isFrameDocumentEmpty))) own = { skipped: 'empty' };
|
|
363
|
+
} catch (e) {
|
|
364
|
+
own = {};
|
|
365
|
+
}
|
|
366
|
+
return own.skipped ? own : inheritFrameReading(above, own);
|
|
367
|
+
}
|
|
368
|
+
|
|
232
369
|
/**
|
|
233
370
|
* Resolves each fail/cantTell occurrence to a live ElementHandle, scoped
|
|
234
371
|
* to frameOrPage's own document (a Puppeteer Page and Frame both expose
|
|
@@ -278,6 +415,58 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
|
|
|
278
415
|
});
|
|
279
416
|
}
|
|
280
417
|
|
|
418
|
+
/**
|
|
419
|
+
* The driver steps .conditions() scans need: the viewport's width with
|
|
420
|
+
* page.setViewport() (the rest of the viewport kept) and the color scheme
|
|
421
|
+
* with page.emulateMediaFeatures(). Each condition sets both, from the
|
|
422
|
+
* page as it was, so one condition's width or scheme doesn't carry into
|
|
423
|
+
* the next; at the end the viewport goes back, and the page is left dark
|
|
424
|
+
* if it was dark before (a scheme emulated by the caller, or the
|
|
425
|
+
* system's), or with the scheme no longer emulated.
|
|
426
|
+
*/
|
|
427
|
+
_conditionDriver() {
|
|
428
|
+
const page = this._page;
|
|
429
|
+
let viewport = null;
|
|
430
|
+
// The scheme a condition without one goes back to: the one the page was
|
|
431
|
+
// in, named, since clearing the emulation would give the system's, which
|
|
432
|
+
// a caller may have emulated away from.
|
|
433
|
+
let baseScheme = 'light';
|
|
434
|
+
// The scheme is emulated, and put back, only when a condition sets one:
|
|
435
|
+
// page.emulateMediaFeatures() needs the DevTools protocol, which Firefox
|
|
436
|
+
// over WebDriver BiDi doesn't have, where setViewport() works.
|
|
437
|
+
const usesScheme = this._conditions.some((c) => c.colorScheme);
|
|
438
|
+
const scheme = (value) => page.emulateMediaFeatures([{ name: 'prefers-color-scheme', value }]);
|
|
439
|
+
return {
|
|
440
|
+
save: async () => {
|
|
441
|
+
const browser = typeof page.browser === 'function' ? page.browser() : null;
|
|
442
|
+
if (usesScheme && browser && browser.cdpSupported === false) {
|
|
443
|
+
throw new Error(
|
|
444
|
+
'A11yCoreBuilder.conditions(): a colorScheme needs the DevTools protocol (Chrome), which this browser does not offer to Puppeteer; ' +
|
|
445
|
+
'scan the widths alone here, or the color schemes in Chrome.'
|
|
446
|
+
);
|
|
447
|
+
}
|
|
448
|
+
const before = await page.evaluate(() => ({
|
|
449
|
+
width: innerWidth,
|
|
450
|
+
height: innerHeight,
|
|
451
|
+
deviceScaleFactor: devicePixelRatio,
|
|
452
|
+
dark: matchMedia('(prefers-color-scheme: dark)').matches
|
|
453
|
+
}));
|
|
454
|
+
viewport = page.viewport() || { width: before.width, height: before.height, deviceScaleFactor: before.deviceScaleFactor };
|
|
455
|
+
baseScheme = before.dark ? 'dark' : 'light';
|
|
456
|
+
return { viewport };
|
|
457
|
+
},
|
|
458
|
+
apply: async (condition) => {
|
|
459
|
+
await page.setViewport({ ...viewport, width: condition.width || viewport.width });
|
|
460
|
+
if (usesScheme) await scheme(condition.colorScheme || baseScheme);
|
|
461
|
+
},
|
|
462
|
+
restore: async (state) => {
|
|
463
|
+
if (!state) return;
|
|
464
|
+
await page.setViewport(state.viewport);
|
|
465
|
+
if (usesScheme) await scheme(baseScheme);
|
|
466
|
+
}
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
|
|
281
470
|
async _attachElementRefs(frameOrPage, result) {
|
|
282
471
|
if (!Array.isArray(result.checksResults)) return result;
|
|
283
472
|
for (const check of result.checksResults) {
|
|
@@ -296,6 +485,18 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
|
|
|
296
485
|
}
|
|
297
486
|
}
|
|
298
487
|
|
|
488
|
+
// One of core's hook scripts (1.14.0 and later for the listener and
|
|
489
|
+
// live-region hooks), registered to run before the page's own scripts.
|
|
490
|
+
function installHook(page, method, scriptName) {
|
|
491
|
+
if (!page || typeof page.evaluateOnNewDocument !== 'function') {
|
|
492
|
+
throw new TypeError(`A11yCoreBuilder.${method}() requires a Puppeteer Page (with an .evaluateOnNewDocument() method).`);
|
|
493
|
+
}
|
|
494
|
+
if (typeof core[scriptName] !== 'function') {
|
|
495
|
+
throw new Error(`A11yCoreBuilder.${method}() needs @surea11y/core 1.14.0 or later, which has ${scriptName}().`);
|
|
496
|
+
}
|
|
497
|
+
return page.evaluateOnNewDocument(core[scriptName]());
|
|
498
|
+
}
|
|
499
|
+
|
|
299
500
|
// The occurrence's element as an ElementHandle, or null when it is gone (or
|
|
300
501
|
// a shadow host on the way is). A handle to null is disposed, not leaked.
|
|
301
502
|
async function resolveElementHandle(frameOrPage, occurrence) {
|
package/src/index.js
CHANGED
|
@@ -5,9 +5,9 @@ const { formatFailures } = require('./formatFailures');
|
|
|
5
5
|
|
|
6
6
|
// Re-exported from @surea11y/binding-base, as formatFailures is, so a test
|
|
7
7
|
// needs only this package: what a result says it left out, how the page was
|
|
8
|
-
// scanned (forced colors, the
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
const { getScanGaps, getScanNotes, formatOccurrenceLocation, EngineError } = require('@surea11y/binding-base');
|
|
8
|
+
// scanned (forced colors, the hooks), an occurrence's location as text, the
|
|
9
|
+
// error analyze() throws for input the engine cannot use, and the failures
|
|
10
|
+
// that fail a test at a severity.
|
|
11
|
+
const { getScanGaps, getScanNotes, formatOccurrenceLocation, EngineError, getGatingFailures, SEVERITIES } = require('@surea11y/binding-base');
|
|
12
12
|
|
|
13
|
-
module.exports = { A11yCoreBuilder, formatFailures, getScanGaps, getScanNotes, formatOccurrenceLocation, EngineError };
|
|
13
|
+
module.exports = { A11yCoreBuilder, formatFailures, getScanGaps, getScanNotes, formatOccurrenceLocation, EngineError, getGatingFailures, SEVERITIES };
|