@surea11y/playwright 1.3.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,6 +9,10 @@ npm install @surea11y/playwright playwright
9
9
  npx playwright install chromium # every test launches a real browser -- npm install alone doesn't fetch it
10
10
  ```
11
11
 
12
+ `@surea11y/core` 1.12.0 or later, the engine, comes with it as a regular dependency, so the line above is all you need, whatever your package manager.
13
+
14
+ If your project uses core directly too, to write a SARIF log or an HTML report (`@surea11y/core/sarif`, `/report`), read the rule catalogue, or keep a baseline, keep one copy of it, so those read results with the same core that produced them. A compatible range in your own `package.json` (`"@surea11y/core": "^1.12.0"`) is enough: npm installs core once. When yours 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, and the binding uses your copy, which needs to be 1.12.0 or later. 1.4.0 made core a peer dependency instead; 1.4.1 undoes that, because Yarn, npm 6 and npm with `legacy-peer-deps` don't install peers, and a project with an older core pinned couldn't install the binding at all.
15
+
12
16
  `npm test` (in this repo) only needs Chromium. The cross-browser regression tests in `tests/cross-browser.test.js` (proving this works against Firefox/WebKit too, not just Chromium) additionally need `npx playwright install firefox webkit`. `npm test` also compiles `tests/types/usage.ts` with TypeScript against the shipped types (`typescript` is a dev dependency only).
13
17
 
14
18
  ## Usage
@@ -35,19 +39,52 @@ await browser.close();
35
39
 
36
40
  `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.
37
41
 
38
- Every result says which `@surea11y/core` release produced it, in `results.engine.version` (for example `"1.11.1"`): quote it in a bug report, and compare it when two runs disagree.
42
+ Every result says which `@surea11y/core` release produced it, in `results.engine.version` (for example `"1.12.0"`): quote it in a bug report, and compare it when two runs disagree. From 1.4.0 this package needs `@surea11y/core` 1.12.0 or later; see [What changes with `@surea11y/core` 1.12](#what-changes-with-surea11ycore-112).
39
43
 
40
44
  Also see `examples/basic-scan.js` for a runnable script (`npm run example -- <url>`).
41
45
 
42
- `.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.
46
+ `.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.
47
+
48
+ `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'`), not either one, unless you ask for that with `.includeMode('or')` (below).
49
+
50
+ `.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:
51
+
52
+ ```js
53
+ const results = await new A11yCoreBuilder({ page })
54
+ .withTags('forms')
55
+ .withRules('contrast-computable')
56
+ .includeMode('or') // every forms rule, plus the contrast check
57
+ .analyze();
58
+ ```
59
+
60
+ 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.
61
+
62
+ `.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):
63
+
64
+ ```js
65
+ const results = await new A11yCoreBuilder({ page })
66
+ .withRules('contrast-computable')
67
+ .wcagLevel('AA') // report 1.4.3, not the AAA 1.4.6
68
+ .analyze();
69
+ ```
70
+
71
+ 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.
43
72
 
44
- `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'`), not either one.
73
+ `.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:
74
+
75
+ ```js
76
+ const builder = new A11yCoreBuilder({ page }).withTags('forms').withRules('contrast-computable');
77
+ if (builder.plannedChecks().length === 0) {
78
+ throw new Error('This selection runs no rule. Did you mean .includeMode("or")?');
79
+ }
80
+ const results = await builder.analyze();
81
+ ```
45
82
 
46
83
  The four take a string or an array of strings. `undefined` (a missing config value) or an empty string throws a `TypeError` with `code: 'INVALID_RUN_ONLY'` at the call. A rule ID or tag the engine doesn't know is ignored, with a warning in the page's console, as long as another one in the list is known; when none is, `.analyze()` rejects with an `EngineError` (below), so a typo such as `.withTags(['wcag2.2aa'])` can't run no rules and pass.
47
84
 
48
85
  `.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.
49
86
 
50
- **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.
87
+ **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.
51
88
 
52
89
  ### When `.include()` matches nothing, or doesn't parse
53
90
 
@@ -62,10 +99,23 @@ const gaps = getScanGaps(results);
62
99
  // message: 'Nothing was scanned: the scan scope matched no element ("#main").' }]
63
100
  ```
64
101
 
65
- Each gap has a `kind`: `'context-not-found'` (nothing was scanned), `'context-partly-not-found'` (some of several selectors matched nothing), `'custom-rule-skipped'` (a custom rule the engine could not run, one per rule, from `results.skippedCustomRules`), or `'pack-skipped'` (a pack that did not run, one per pack, from `results.skippedPacks`; see [Scanning with packs](#scanning-with-packs-standards-checklists-and-your-own-rules)).
102
+ Each gap has a `kind`: `'context-not-found'` (nothing was scanned), `'context-partly-not-found'` (some of several selectors matched nothing), `'custom-rule-skipped'` (a custom rule the engine could not run, one per rule, from `results.skippedCustomRules`; one you excluded yourself with `.disableRules()` is not a gap), or `'pack-skipped'` (a pack that did not run, one per pack, from `results.skippedPacks`; see [Scanning with packs](#scanning-with-packs-standards-checklists-and-your-own-rules)).
66
103
 
67
104
  `.analyze()` also prints each gap with `console.warn`, once per scanned frame, prefixed with the frame's URL, for example `@surea11y/playwright (https://example.com/): Nothing was scanned: the scan scope matched no element ("#main").` The engine warns too, but in the page's console, which a Playwright run doesn't show. The warning doesn't fail anything: to fail a test on a gap, assert on `getScanGaps(results)` as below.
68
105
 
106
+ 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:
107
+
108
+ ```js
109
+ const results = await new A11yCoreBuilder({ page })
110
+ .include('#checkout')
111
+ .logger((gap, frame) => log.warn({ url: frame.url, kind: gap.kind }, gap.message))
112
+ .analyze();
113
+ ```
114
+
115
+ 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.
116
+
117
+ `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).
118
+
69
119
  ### Errors from the engine
70
120
 
71
121
  When the engine refuses its input, `.analyze()` rejects with an `EngineError` (exported from this package) carrying the engine's `code`:
@@ -127,10 +177,10 @@ Error: 1) button-name-present (serious): This button has no accessible name.
127
177
 
128
178
  Part of the scan scope was not scanned: no element matched "#sidebar".
129
179
 
130
- Scanned with @surea11y/core 1.11.1.
180
+ Scanned with @surea11y/core 1.12.0.
131
181
  ```
132
182
 
133
- Given the whole result, as here, it also lists what the scan left out (see `getScanGaps()` above; a scan whose `.include()` matched nothing never reads as "No accessibility violations found.") and ends with the core release that produced the result. It still accepts `results.checksResults` alone, without those two parts. A finding inside a shadow tree is located through its shadow hosts, as `my-app >>> my-card >>> img` (`formatOccurrenceLocation(occurrence)` gives that line on its own); that notation is for reading, not a selector `document.querySelector()` takes. For a `.frames(true)` scan, format `results.topFrame` and each frame on its own: both functions throw a `TypeError` for the `{ topFrame, frames }` shape rather than report it as clean.
183
+ Given the whole result, as here, it also lists what the scan left out (see `getScanGaps()` above; a scan whose `.include()` matched nothing never reads as "No accessibility violations found.") and its notes (`getScanNotes()`, such as a page shown in forced colors), and ends with the core release that produced the result. It still accepts `results.checksResults` alone, without those two parts. A finding inside a shadow tree is located through its shadow hosts, as `my-app >>> my-card >>> img` (`formatOccurrenceLocation(occurrence)` gives that line on its own); that notation is for reading, not a selector `document.querySelector()` takes. For a `.frames(true)` scan, format `results.topFrame` and each frame on its own: both functions throw a `TypeError` for the `{ topFrame, frames }` shape rather than report it as clean.
134
184
 
135
185
  ...with Playwright's own raw diff still printed underneath (unavoidable — `toEqual` always includes it), but the readable summary now comes first, where it's actually useful. Deliberately a plain function, not a custom `expect` matcher — no dependency on any particular assertion library, so it works the same with Playwright's `expect`, Jest, Vitest, or a hand-rolled `if`/`throw`. Defaults to `fail`/`cantTell` outcomes (the ones that report findings; a `notApplicable` rule can carry one occurrence saying why it had nothing to judge, which is left out); pass `{ outcomes: [...] }` to narrow further. A thrown rule (`occurrences: []`, `error` set) is still surfaced using its `error` message rather than silently dropped.
136
186
 
@@ -193,6 +243,55 @@ This resolves each occurrence to an `ElementHandle` in its own frame instead of
193
243
 
194
244
  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 [Playwright's own `ElementHandle` guidance](https://playwright.dev/docs/api/class-elementhandle).
195
245
 
246
+ ### Web components: the internals hook
247
+
248
+ Many web components keep their `ElementInternals` in a private field and name themselves, set their states or give themselves a role through it:
249
+
250
+ ```js
251
+ class SubscribeCheckbox extends HTMLElement {
252
+ #internals = this.attachInternals();
253
+ constructor() {
254
+ super();
255
+ this.#internals.ariaLabel = 'Subscribe';
256
+ this.#internals.ariaChecked = 'false';
257
+ }
258
+ }
259
+ ```
260
+
261
+ 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.
262
+
263
+ `A11yCoreBuilder.installInternalsHook(pageOrContext)` installs `@surea11y/core`'s opt-in hook, which records each component's internals for the scan to read. Call it **before** `page.goto()`, on the page, or on its browser context to cover every page the context opens:
264
+
265
+ ```js
266
+ const context = await browser.newContext();
267
+ await A11yCoreBuilder.installInternalsHook(context); // before any page navigates
268
+ const page = await context.newPage();
269
+ await page.goto('https://example.com/');
270
+
271
+ const results = await new A11yCoreBuilder({ page }).analyze();
272
+ results.engine.environment.internalsHook; // 'early': the hook ran before the page's scripts
273
+ ```
274
+
275
+ With `@playwright/test`, install it in a `beforeEach` on the `context` fixture, or on `page` before the test navigates.
276
+
277
+ 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. Playwright runs init scripts (`addInitScript()`) before the page's own scripts in every frame, and again after each navigation, so one call covers a page or context for its lifetime. It works in Chromium, Firefox and WebKit.
278
+
279
+ - **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`.
280
+ - **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.
281
+ - **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'`.
282
+
283
+ ### Forced colors
284
+
285
+ 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, in Chromium, Firefox or WebKit:
286
+
287
+ ```js
288
+ await page.emulateMedia({ forcedColors: 'active' });
289
+ const results = await new A11yCoreBuilder({ page }).analyze();
290
+ results.engine.environment.forcedColors; // 'active'
291
+ ```
292
+
293
+ `browser.newContext({ forcedColors: 'active' })` does the same for a whole context, and `@playwright/test` takes it as a `use` option. 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.
294
+
196
295
  ### Registering a custom rule at runtime
197
296
 
198
297
  `@surea11y/core` supports registering additional rules per-scan via `engineOptions.customRules`. Use `.withCustomRules()` to register one:
@@ -225,8 +324,25 @@ const results = await new A11yCoreBuilder({ page })
225
324
 
226
325
  **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 Playwright `page.evaluate()` argument crosses a JSON 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.
227
326
 
327
+ 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).
328
+
228
329
  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 silently-skipped rule deep inside the page — easier to catch during development. (Note: a *raw* `.options({ customRules })` call bypasses this check entirely and defers to `@surea11y/core`'s own engine-side behavior, which skips an invalid descriptor rather than throwing, and lists it in `results.skippedCustomRules`.)
229
330
 
331
+ ### Checking against EN 301 549
332
+
333
+ 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):
334
+
335
+ ```js
336
+ // 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)
337
+ const results = await new A11yCoreBuilder({ page })
338
+ .options({ profile: 'en301549-v4.1.1' })
339
+ .analyze();
340
+
341
+ results.engine.profile; // 'en301549-v4.1.1'
342
+ ```
343
+
344
+ `.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.
345
+
230
346
  ### Scanning with packs: standards, checklists and your own rules
231
347
 
232
348
  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.
@@ -260,7 +376,23 @@ Every occurrence already carries `selector` and (with `.elementRef(true)`, above
260
376
 
261
377
  ## TypeScript
262
378
 
263
- `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 and the result (`A11yCoreResult`, `CheckResult`, `Occurrence`, `CompositeResult`, etc.). The result types are built on the ones `@surea11y/core` ships, so they carry every field the engine returns (`engine.version`, `engine.environment`, `contextMatch`, `skippedCustomRules`, `shadowHostSelectors`, `margin`, ...); this package adds `elementHandle` and the `.frames(true)` shape. `EngineError`/`EngineErrorCode`, `getScanGaps()`/`ScanGap` and `formatOccurrenceLocation()` are typed too, and so are `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. `playwright` is a `peerDependencies` entry (not just `devDependencies`) since the class's `page` argument and `Occurrence#elementHandle` both come from it — consumers need their own `playwright` install for the types to resolve, same as they already do to construct a `Page` in the first place.
379
+ `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 and the result (`A11yCoreResult`, `CheckResult`, `Occurrence`, `CompositeResult`, etc.). The result types are built on the ones `@surea11y/core` ships, so they carry every field the engine returns (`engine.version`, `engine.environment`, `contextMatch`, `skippedCustomRules`, `shadowHostSelectors`, `margin`, ...); this package adds `elementHandle` and the `.frames(true)` shape. `EngineError`/`EngineErrorCode`, `getScanGaps()`/`ScanGap`, `getScanNotes()`/`ScanNote` and `formatOccurrenceLocation()` are typed too, and so are `withWcag()` and `wcagLevel()` (`WcagVersion`, `WcagLevelInput`), `plannedChecks()`/`plannedCriteria()` (`PlannedCheck`, `PlannedCriterion`), the static `installInternalsHook()`, 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. `playwright` is a `peerDependencies` entry (not just `devDependencies`) since the class's `page` argument and `Occurrence#elementHandle` both come from it — consumers need their own `playwright` install for the types to resolve, same as they already do to construct a `Page` in the first place.
380
+
381
+ ## What changes with `@surea11y/core` 1.12
382
+
383
+ 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):
384
+
385
+ - **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.
386
+ - **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.
387
+ - **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.
388
+ - **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.
389
+ - **`engine.wcagLevel`** records the level a scan was gated by, and [`.wcagLevel()`](#usage) sets it.
390
+ - **`engine.environment.forcedColors`** records whether the page was in [forced colors](#forced-colors).
391
+ - **A custom rule you exclude** isn't a scan gap any more, so `.disableRules()` of one prints no warning.
392
+ - **Rule IDs in another case select their rule**: `.withRules('IMG-ALT-PRESENT')` used to throw `INVALID_RUN_ONLY` or be ignored.
393
+ - **`runOnly.optInTags` on its own throws** `INVALID_RUN_ONLY`; it was accepted and did nothing. Opt-in rules are unlocked with `.options({ optInRules })`.
394
+ - **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.
395
+ - **An inline `policyContract`** with an unknown value in `allowedOutcomes` or `allowedConfidence` drops that value with a warning, where it turned every check into `cantTell`.
264
396
 
265
397
  ## What changes with `@surea11y/core` 1.11
266
398
 
package/package.json CHANGED
@@ -1,16 +1,23 @@
1
1
  {
2
2
  "name": "@surea11y/playwright",
3
- "version": "1.3.0",
4
- "description": "Playwright binding for surea11y -- scan real, live-rendered pages for accessibility issues.",
3
+ "version": "1.4.1",
4
+ "description": "Accessibility (a11y, WCAG) checks for Playwright 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
  "playwright",
17
+ "playwright-test",
12
18
  "e2e",
13
19
  "e2e-testing",
20
+ "end-to-end",
14
21
  "audit",
15
22
  "aria",
16
23
  "surea11y"
@@ -39,8 +46,8 @@
39
46
  "LICENSE"
40
47
  ],
41
48
  "dependencies": {
42
- "@surea11y/binding-base": "^1.3.1",
43
- "@surea11y/core": "^1.11.1"
49
+ "@surea11y/binding-base": "^1.4.0",
50
+ "@surea11y/core": "^1.12.0"
44
51
  },
45
52
  "peerDependencies": {
46
53
  "playwright": ">=1.0.0"
@@ -1,4 +1,4 @@
1
- import type { Page, ElementHandle } from 'playwright';
1
+ import type { Page, BrowserContext, ElementHandle } from 'playwright';
2
2
  import type * as Core from '@surea11y/core';
3
3
 
4
4
  // The result shapes are @surea11y/core's own types (shipped with it since
@@ -55,8 +55,8 @@ export type {
55
55
  * page's scripts broke a JavaScript built-in the engine relies on).
56
56
  */
57
57
  export { EngineError } from '@surea11y/binding-base';
58
- export type { EngineErrorCode, PackLike, WcagVersion, WcagLevel } from '@surea11y/binding-base';
59
- import type { PackLike, WcagVersion, WcagLevel } from '@surea11y/binding-base';
58
+ export type { EngineErrorCode, PackLike, WcagVersion, WcagLevel, WcagLevelInput, PlannedCheck, PlannedCriterion } from '@surea11y/binding-base';
59
+ import type { PackLike, WcagVersion, WcagLevelInput, ScanGap, ScanNote, PlannedCheck, PlannedCriterion } from '@surea11y/binding-base';
60
60
 
61
61
  export type Category = Core.RuleMeta['category'];
62
62
  export type LocaleResolutionReason = Core.LocaleResolution['reason'];
@@ -124,6 +124,15 @@ export class A11yCoreBuilder {
124
124
  */
125
125
  constructor(opts: { page: Page; url?: string });
126
126
 
127
+ /**
128
+ * Installs @surea11y/core's opt-in internals hook on a Page, or on a
129
+ * BrowserContext for every page it opens, so a scan can read names,
130
+ * states and roles web components set through a private ElementInternals.
131
+ * Call it before page.goto(): it runs before the page's scripts in every
132
+ * frame and after each navigation.
133
+ */
134
+ static installInternalsHook(pageOrContext: Page | BrowserContext): Promise<void>;
135
+
127
136
  /** Scope the scan to one region. Call multiple times for a multi-region union. */
128
137
  include(selector: string): this;
129
138
  /**
@@ -146,9 +155,28 @@ export class A11yCoreBuilder {
146
155
  * runs those of WCAG 2.2's A and AA criteria. withTags()/withRules() add
147
156
  * to them. A later call replaces the target.
148
157
  */
149
- withWcag(version: WcagVersion | 2.0 | 2.1 | 2.2, level?: WcagLevel): this;
158
+ withWcag(version: WcagVersion | 2.0 | 2.1 | 2.2, level?: WcagLevelInput): this;
150
159
  /** Also run the best-practice rules, those that name no WCAG criterion. */
151
160
  withBestPractices(enabled?: boolean): this;
161
+ /**
162
+ * How withRules() and withTags() combine when both are given: 'and' (the
163
+ * default) runs the rules matching both, 'or' those matching either. A
164
+ * later call replaces the mode.
165
+ */
166
+ includeMode(mode: 'and' | 'or'): this;
167
+ /**
168
+ * The WCAG level of the criteria the scan reports, without changing which
169
+ * rules run: `.withRules('contrast-computable').wcagLevel('AA')` reports
170
+ * 1.4.3 and not 1.4.6. Any case; null clears it. A later call replaces it.
171
+ */
172
+ wcagLevel(level: WcagLevelInput | null): this;
173
+ /**
174
+ * Where analyze() sends each scan gap instead of console.warn: called once
175
+ * per gap, with the result of the frame it came from, and once per scan
176
+ * for the internals-hook note (tell them apart by `kind`). `() => {}`
177
+ * silences them, `null` goes back to console.warn. A later call replaces it.
178
+ */
179
+ logger(fn: ((entry: ScanGap | ScanNote, result: A11yCoreResult) => void) | null): this;
152
180
  /** Merge arbitrary engineOptions (locale, contrast.mode, policyContract, ...). */
153
181
  options(partialEngineOptions: Record<string, unknown>): this;
154
182
  /** Register one or more custom rules for just this scan. Call multiple times to accumulate. */
@@ -164,6 +192,10 @@ export class A11yCoreBuilder {
164
192
  frames(enabled?: boolean): this;
165
193
  /** Opt in to resolving each fail/cantTell occurrence's selector to a live ElementHandle. */
166
194
  elementRef(enabled?: boolean): this;
195
+ /** The rules this scan will run, worked out in Node with no page (@surea11y/core 1.12.0 and later). */
196
+ plannedChecks(): PlannedCheck[];
197
+ /** The criteria this scan will report in rulesResults, worked out in Node with no page. */
198
+ plannedCriteria(): PlannedCriterion[];
167
199
 
168
200
  /**
169
201
  * Runs the scan. Returns { topFrame, frames } instead of a single result
@@ -202,3 +234,11 @@ export function formatFailures(
202
234
  */
203
235
  export { getScanGaps, formatOccurrenceLocation } from '@surea11y/binding-base';
204
236
  export type { ScanGap, OccurrenceLocation } from '@surea11y/binding-base';
237
+
238
+ /**
239
+ * How the page was scanned, which a gap doesn't cover: `forced-colors` when
240
+ * the page was shown in forced colors, and `internals-hook` when the scan
241
+ * asked about web components it could have read with the internals hook.
242
+ */
243
+ export { getScanNotes } from '@surea11y/binding-base';
244
+ export type { ScanNote } from '@surea11y/binding-base';
@@ -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
  // Playwright's page.evaluate(fn, arg) (and frame.evaluate(fn, arg), same
@@ -147,6 +146,23 @@ const findOccurrenceElement = eval(`(args) => {
147
146
  * the previous value rather than merging with it.
148
147
  */
149
148
  class A11yCoreBuilder extends A11yCoreBuilderBase {
149
+ /**
150
+ * Installs @surea11y/core's opt-in internals hook, so a scan can read the
151
+ * names, states and roles web components set through a private
152
+ * ElementInternals. Takes a Page, or a BrowserContext to cover every page
153
+ * it opens. Call it before page.goto(): Playwright runs init scripts
154
+ * before the page's own scripts in every frame, and again after each
155
+ * navigation (addInitScript()). The page already loaded when it is called
156
+ * doesn't get it until it navigates. Resolves when the script is added.
157
+ * @param {import('playwright').Page | import('playwright').BrowserContext} pageOrContext
158
+ */
159
+ static installInternalsHook(pageOrContext) {
160
+ if (!pageOrContext || typeof pageOrContext.addInitScript !== 'function') {
161
+ throw new TypeError('A11yCoreBuilder.installInternalsHook() requires a Playwright Page or BrowserContext (with an .addInitScript() method).');
162
+ }
163
+ return pageOrContext.addInitScript({ content: internalsHookScript() });
164
+ }
165
+
150
166
  /**
151
167
  * @param {{ page: import('playwright').Page, url?: string }} opts
152
168
  * `page` must already be navigated to and settled at the URL to scan --
@@ -188,7 +204,7 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
188
204
  engineOptions,
189
205
  runOnly
190
206
  }));
191
- this._warnScanGaps(result);
207
+ this._warnScanGaps(result, '@surea11y/playwright');
192
208
  return this._elementRef ? this._attachElementRefs(frameOrPage, result) : result;
193
209
  };
194
210
 
@@ -250,27 +266,6 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
250
266
  return result;
251
267
  }
252
268
 
253
- /**
254
- * Prints what the scan left out (getScanGaps(): an include() scope that
255
- * matched nothing, a custom rule that did not run) with console.warn,
256
- * once per scanned frame. @surea11y/core warns about these too, but in
257
- * the page's console, which a Playwright run does not show; a result
258
- * whose checksResults alone look clean would otherwise pass without a
259
- * word.
260
- */
261
- _warnScanGaps(result) {
262
- let gaps;
263
- try {
264
- gaps = getScanGaps(result);
265
- } catch (e) {
266
- return; // not a scan result; nothing to say about it here
267
- }
268
- const where = result.url ? ` (${result.url})` : '';
269
- for (const gap of gaps) {
270
- console.warn(`@surea11y/playwright${where}: ${gap.message}`);
271
- }
272
- }
273
-
274
269
  async _findElement(frameOrPage, occurrence) {
275
270
  const handle = await frameOrPage.evaluateHandle(findOccurrenceElement, {
276
271
  selector: occurrence.selector,
package/src/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- const { EngineError, getScanGaps, formatOccurrenceLocation } = require('@surea11y/binding-base');
3
+ const { EngineError, getScanGaps, getScanNotes, formatOccurrenceLocation } = require('@surea11y/binding-base');
4
4
  const { A11yCoreBuilder } = require('./A11yCoreBuilder');
5
5
  const { formatFailures } = require('./formatFailures');
6
6
 
7
- module.exports = { A11yCoreBuilder, EngineError, formatFailures, formatOccurrenceLocation, getScanGaps };
7
+ module.exports = { A11yCoreBuilder, EngineError, formatFailures, formatOccurrenceLocation, getScanGaps, getScanNotes };