@surea11y/puppeteer 1.0.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -34,12 +34,16 @@ console.log(results.checksResults.filter(r => r.outcome === 'fail'));
34
34
  await browser.close();
35
35
  ```
36
36
 
37
- `results` is `@surea11y/core`'s own native result shape — see its [`OUTPUT_SCHEMA.md`](https://github.com/SureA11y/core/blob/main/docs/OUTPUT_SCHEMA.md) — not the `violations`/`passes`/`incomplete`/`inapplicable` shape used by other popular accessibility testing tools. The builder's *method names* are modeled on common conventions in this space for migration familiarity; the richer result schema is kept as-is.
37
+ `results` is `@surea11y/core`'s own native result shape — see its [`OUTPUT_SCHEMA.md`](https://github.com/SureA11y/core/blob/main/docs/OUTPUT_SCHEMA.md) — not the `violations`/`passes`/`incomplete`/`inapplicable` shape used by other popular accessibility testing tools. The builder's *method names* are modeled on common conventions in this space for migration familiarity; the richer result schema is kept as-is. `results.engine.version` names the `@surea11y/core` release that produced it (such as `"1.10.0"`); quote it in a bug report.
38
+
39
+ From 1.2.0 this package needs `@surea11y/core` 1.10.0 or later, which npm installs with it. Core's rules change between its releases: 1.10.0, for example, added `landmark-role-name-present` (an element with `role="region"` or `role="form"` and no accessible name) and deprecated `label-title-only`, which now reports `notApplicable` because `form-control-programmatic-label-quality` reports the same fields. A `.withRules()`/`.disableRules()` list naming `label-title-only` still works; move it to the new rule. See core's [changelog](https://github.com/SureA11y/core/blob/main/CHANGELOG.md).
38
40
 
39
41
  Also see `examples/basic-scan.js` for a runnable script (`npm run example -- <url>`).
40
42
 
41
43
  `withTags()`/`disableRules()` above have counterparts: `.withRules([...])` (only run these specific rule IDs) and `.disableTags([...])` (never run rules carrying any of these tags). All four compose the same way similar allow/deny-list options do in other accessibility testing tools, with one non-obvious rule worth knowing: a "disable" always wins over a "with" on the same ID/tag (e.g. `.withRules(['a']).disableRules(['a'])` drops `'a'` entirely), and combining `.withRules()` **and** `.withTags()` together requires a rule to satisfy *both* (`@surea11y/core`'s default `includeMode: 'and'` — see [`ENGINE_OPTIONS.md`](https://github.com/SureA11y/core/blob/main/docs/ENGINE_OPTIONS.md)), not either one.
42
44
 
45
+ Each of the four takes a string or an array of strings. Anything else, such as `undefined` from a missing config value or an empty string, throws a `TypeError` with `code: 'INVALID_RUN_ONLY'` at the call. A list that names nothing the engine knows (`.withRules(['img-alt-presnt'])`) makes `analyze()` reject instead; see [Errors](#errors).
46
+
43
47
  `.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.
44
48
 
45
49
  **Create one builder per scan.** `A11yCoreBuilder` is a mutable object with no reset between `.analyze()` calls — `include()`/`exclude()`/`withRules()`/`disableRules()`/`withTags()`/`disableTags()`/`options()`/`withCustomRules()` all push onto or merge into internal state that persists for the instance's lifetime. Calling one of them again before a second `.analyze()` call *accumulates* on top of the first scan's scope rather than replacing it (this is exactly what makes "call `.include()` several times for one scan," above, work — the same accumulation just also applies across separate scans if you reuse an instance). `.reportOnly()`/`.frames()`/`.elementRef()` are the exception: each call replaces the previous value instead of merging with it.
@@ -52,7 +56,7 @@ The pattern above works unchanged inside a real test:
52
56
 
53
57
  ```js
54
58
  const puppeteer = require('puppeteer');
55
- const { A11yCoreBuilder, formatFailures } = require('@surea11y/puppeteer');
59
+ const { A11yCoreBuilder, formatFailures, getScanGaps } = require('@surea11y/puppeteer');
56
60
 
57
61
  const browser = await puppeteer.launch();
58
62
  const page = await browser.newPage();
@@ -60,25 +64,42 @@ await page.goto('https://example.com/');
60
64
 
61
65
  const results = await new A11yCoreBuilder({ page }).reportOnly(['fail']).analyze();
62
66
 
63
- assert.strictEqual(results.checksResults.length, 0, formatFailures(results.checksResults));
67
+ assert.ok(
68
+ results.checksResults.length === 0 && getScanGaps(results).length === 0,
69
+ formatFailures(results)
70
+ );
64
71
  ```
65
72
 
66
- 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 well-formed page passes cleanly. It uses `node:test` directly rather than a dedicated test-runner package: Puppeteer has no first-party test runner the way `@playwright/test` is the default for Playwright, and `node:test` is a zero-new-dependency choice that already matches this project's own test suite.
73
+ `getScanGaps(results)` lists what the scan left out, which `checksResults` alone would pass over as clean: an `.include()` scope that matched nothing (`kind: 'context-not-found'`; nothing was scanned, so every rule reports `notApplicable`), some of several `.include()` selectors that matched nothing (`'context-partly-not-found'`), and each custom rule the engine did not run (`'custom-rule-skipped'`, with the engine's reason). Each gap has a `message`. Checking it is what keeps a mistyped scope from passing the gate. `analyze()` also prints each gap's message with `console.warn` (as `@surea11y/puppeteer (<frame url>): <message>`, once per scanned frame under `.frames(true)`), so a scan that left something out shows in the log even where nothing asserts on it.
74
+
75
+ See `examples/e2e-test-example.test.js` for a fuller, runnable version (`npm run example:e2e`) — one test proving real violations get caught (unlabeled button, missing `alt`), one proving a mistyped `.include()` scope is caught rather than passed, one proving a well-formed page passes cleanly. It uses `node:test` directly rather than a dedicated test-runner package: Puppeteer has no first-party test runner the way `@playwright/test` is the default for Playwright, and `node:test` is a zero-new-dependency choice that already matches this project's own test suite.
67
76
 
68
77
  ### Readable console/CI output on failure
69
78
 
70
- 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(checksResults)` turns that into a short, scannable block (one entry per occurrence, numbered, with rule ID/severity/selector/hint) that you hand to your assertion library's own failure-message parameter, as above. A real failure then prints:
79
+ 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:
71
80
 
72
81
  ```
73
- Error: 1) button-name-present (serious): This button has no accessible name.
82
+ AssertionError [ERR_ASSERTION]: 1) button-name-present (serious): This button has no accessible name.
74
83
  at html > body > button
75
84
  Provide visible button text or a programmatic accessible-name mechanism (for example aria-label) so assistive technologies can identify the button.
76
85
  2) img-alt-present (serious): Missing alt attribute on <img>.
77
86
  at html > body > img
78
87
  Add an alt attribute (use alt="" only for decorative images).
88
+
89
+ Scanned with @surea11y/core 1.10.0.
90
+ ```
91
+
92
+ and a scope that matched nothing prints:
93
+
94
+ ```
95
+ AssertionError [ERR_ASSERTION]: Nothing was scanned: the scan scope matched no element ("#main").
96
+
97
+ Scanned with @surea11y/core 1.10.0.
79
98
  ```
80
99
 
81
- 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 only two that ever carry occurrences); pass `{ outcomes: [...] }` to narrow further. 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.
100
+ An element inside a shadow tree is located through its shadow hosts, as `my-app >>> my-card >>> img`; `formatOccurrenceLocation(occurrence)` gives that line on its own. Passing `results.checksResults` instead of `results` still works and lists the findings alone.
101
+
102
+ 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.
82
103
 
83
104
  ### Scanning every frame, including cross-origin iframes
84
105
 
@@ -91,6 +112,16 @@ for (const frame of results.frames) {
91
112
  }
92
113
  ```
93
114
 
115
+ Format a `.frames(true)` result one frame at a time:
116
+
117
+ ```js
118
+ const messages = [results.topFrame, ...results.frames].map((frame) =>
119
+ 'error' in frame ? `${frame.url}: not scanned (${frame.error})` : formatFailures(frame)
120
+ );
121
+ ```
122
+
123
+ `.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.
124
+
94
125
  Unlike script-injection-based accessibility tools (which need a `postMessage`-based protocol to reach cross-origin iframes, since they're injected as a plain `<script>` fully subject to the browser's same-origin policy), this needs no extra `@surea11y/core` engine support at all — Puppeteer drives every frame via CDP at the automation-process level, so cross-origin `frame.evaluate()` already just works. Verified against a real cross-origin page (`example.org` embedded in an unrelated origin) — see `tests/builder.test.js`. Default off, so plain `.analyze()` is unaffected unless you opt in.
95
126
 
96
127
  ### Trimming the result to just violations
@@ -119,7 +150,7 @@ await failing.occurrences[0].elementHandle.screenshot({ path: 'flagged.png' });
119
150
  await failing.occurrences[0].elementHandle.click();
120
151
  ```
121
152
 
122
- This resolves `occurrence.selector` to an `ElementHandle` (via `page.$()`/`frame.$()`) instead of leaving you to re-resolve a possibly-stale selector string yourself. Default off — resolving a handle per occurrence is a real page query per occurrence, so it costs more than a plain `.analyze()`. Combines with `.frames(true)`: each frame's occurrences resolve against that frame's own document. Not every occurrence has one target element — a page-wide finding (some `manual`/`cantTell` rules) can carry `selector: ""`, in which case `occurrence.elementHandle` is `null` rather than a handle.
153
+ This resolves the occurrence to an `ElementHandle` instead of leaving you to re-resolve a possibly-stale selector string yourself. An occurrence inside a shadow tree carries `shadowHostSelectors` (the shadow hosts leading to it, outermost first), and its `selector` holds only inside the last host's shadow root, so `page.$(occurrence.selector)` would find another element or none; `.elementRef(true)` goes through the hosts and finds the right one. `elementHandle` is `null` when the element is no longer in the page. Default off — resolving a handle per occurrence is a real page query per occurrence, so it costs more than a plain `.analyze()`. Combines with `.frames(true)`: each frame's occurrences resolve against that frame's own document. Not every occurrence has one target element — a page-wide finding (some `manual`/`cantTell` rules) can carry `selector: ""`, in which case `occurrence.elementHandle` is `null` rather than a handle.
123
154
 
124
155
  Each `ElementHandle` holds a browser-side reference until garbage collected or explicitly disposed — for a scan with many violations that you're keeping around a while (rather than using immediately, as above), call `occurrence.elementHandle.dispose()` when you're done with it, per [Puppeteer's own `ElementHandle` guidance](https://pptr.dev/api/puppeteer.elementhandle).
125
156
 
@@ -155,15 +186,37 @@ const results = await new A11yCoreBuilder({ page })
155
186
 
156
187
  **Why `.withCustomRules()` instead of the raw `.options({ customRules })` passthrough** (still supported, and composes with this method if you use both): `runInPage`/`applicability` must reach the page as a function-source *string*, not a live `Function` — a Puppeteer `page.evaluate()` argument crosses a serialization boundary that can't carry a live function reference, only a string `@surea11y/core` can reconstruct with `new Function` on the page side. Passing a raw live function via `.options()` directly would silently fail to serialize; `.withCustomRules()` calls `.toString()` on a live function for you, so you can write a normal function and not have to remember that constraint yourself. A string is still accepted as-is if you already have one.
157
188
 
158
- 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 silently skips an invalid descriptor rather than throwing.)
189
+ Invalid input (a missing/empty `id`, or a `runInPage`/`applicability` that's neither a function nor a non-empty string) throws immediately from `.withCustomRules()` itself, rather than surfacing later as a skipped rule deep inside the page — easier to catch during development. A *raw* `.options({ customRules })` call bypasses this check and defers to `@surea11y/core`, which skips a descriptor it can't use without throwing. The result lists each one in `skippedCustomRules` as `{ id, reason }`, and `getScanGaps()`/`formatFailures(results)` report it, so a rule that did not run doesn't look like one that passed.
159
190
 
160
191
  ### Element addressing beyond a CSS selector
161
192
 
162
193
  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.
163
194
 
195
+ ## Errors
196
+
197
+ `analyze()` rejects with an `EngineError` (exported from this package) when `@surea11y/core` can't use what it was given. Its `code` says why:
198
+
199
+ - `'INVALID_RUN_ONLY'`: a `.withRules()`/`.withTags()` list in which no value names a rule or a tag the engine knows, such as a misspelled rule ID. A value that names nothing beside ones that do is ignored, with a `console.warn` in the page.
200
+ - `'INVALID_CONTEXT_SELECTOR'`: an `.include()` selector the browser can't parse. `error.selector` is that selector.
201
+
202
+ ```js
203
+ const { A11yCoreBuilder, EngineError } = require('@surea11y/puppeteer');
204
+
205
+ try {
206
+ await new A11yCoreBuilder({ page }).withRules(['img-alt-presnt']).analyze();
207
+ } catch (e) {
208
+ if (e instanceof EngineError && e.code === 'INVALID_RUN_ONLY') {
209
+ // e.message: 'runOnly.includeRuleIds: no rule named "img-alt-presnt".'
210
+ }
211
+ throw e;
212
+ }
213
+ ```
214
+
215
+ `page.evaluate()` keeps only an error's message; the binding brings the `code` back. Any other error in the page rejects `analyze()` as Puppeteer reports it. An `.include()` that parses but matches nothing is not an error: see `getScanGaps()` [above](#using-it-as-an-e2e-accessibility-gate).
216
+
164
217
  ## TypeScript
165
218
 
166
- `src/A11yCoreBuilder.d.ts` (re-exported from `src/index.d.ts`, wired up via `package.json`'s `types` field) ships hand-written types for the whole builder API plus `@surea11y/core`'s native result shapes (`A11yCoreResult`, `CheckResult`, `Occurrence`, `CompositeResult`, etc.), mirrored from [`OUTPUT_SCHEMA.md`](https://github.com/SureA11y/core/blob/main/docs/OUTPUT_SCHEMA.md). `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.
219
+ `src/A11yCoreBuilder.d.ts` (re-exported from `src/index.d.ts`, wired up via `package.json`'s `types` field) ships types for the whole builder API plus `@surea11y/core`'s native result shapes (`A11yCoreResult`, `CheckResult`, `Occurrence`, `CompositeResult`, etc.). The result shapes are `@surea11y/core`'s own types (its `ScanResult` and the rest), with `elementHandle` added to an occurrence, so they follow the engine: `engine.version`, `contextMatch`, `skippedCustomRules`, `shadowHostSelectors` and `margin` are all declared. `EngineError`, `ScanGap` and `EngineErrorCode` come from `@surea11y/binding-base`. `analyze()` is typed `Promise<A11yCoreResult | A11yCoreMultiFrameResult>` — narrow on `'topFrame' in results` (or cast, if you already know which mode you called) to get the specific shape back, since a fluent builder can't statically track that `.frames(true)` was called earlier in the chain. `puppeteer` is a `peerDependencies` entry (not just `devDependencies`) since the class's `page` argument and `Occurrence#elementHandle` both come from it — consumers need their own `puppeteer` install for the types to resolve, same as they already do to construct a `Page` in the first place.
167
220
 
168
221
  ## Relationship to `@surea11y/playwright`
169
222
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@surea11y/puppeteer",
3
- "version": "1.0.2",
3
+ "version": "1.2.0",
4
4
  "description": "Puppeteer binding for surea11y -- scan real, live-rendered pages for accessibility issues.",
5
5
  "keywords": [
6
6
  "accessibility",
@@ -39,14 +39,16 @@
39
39
  "LICENSE"
40
40
  ],
41
41
  "dependencies": {
42
- "@surea11y/core": "^1.1.0",
43
- "@surea11y/binding-base": "^1.1.0"
42
+ "@surea11y/binding-base": "^1.2.0",
43
+ "@surea11y/core": "^1.10.0"
44
44
  },
45
45
  "peerDependencies": {
46
46
  "puppeteer": ">=22.0.0"
47
47
  },
48
48
  "devDependencies": {
49
- "puppeteer": "^25.3.0"
49
+ "@types/node": "^22.20.5",
50
+ "puppeteer": "^25.3.0",
51
+ "typescript": "^5.9.3"
50
52
  },
51
53
  "scripts": {
52
54
  "test": "node --test tests/*.test.js",
@@ -1,128 +1,62 @@
1
1
  import type { Page, ElementHandle } from 'puppeteer';
2
-
3
- // See surea11y's docs/OUTPUT_SCHEMA.md -- this file mirrors that document's
4
- // shapes exactly (plus the elementHandle field this binding adds on top when
5
- // .elementRef(true) is used). Keep in sync with that doc, not the other way
6
- // around -- it's the source of truth for what the engine actually returns.
7
-
8
- export type Outcome = 'pass' | 'fail' | 'cantTell' | 'notApplicable';
9
- export type OutcomeNormalized = 'pass' | 'fail' | 'cantTell' | 'inapplicable';
10
- export type Severity = 'minor' | 'moderate' | 'serious' | 'critical';
11
- export type Confidence = 'high' | 'medium' | 'low';
12
- export type RuleType = 'automatic' | 'manual';
13
- export type Category = 'perceivable' | 'operable' | 'understandable' | 'robust' | null;
14
-
15
- export interface EngineInfo {
16
- tag: string;
17
- schemaVersion: string;
18
- }
19
-
20
- export interface NormativeMapping {
21
- standard: string;
22
- version: string;
23
- requirement: string;
24
- title: string;
25
- conformanceLevel: string;
26
- }
27
-
28
- export interface CheckResultMeta {
29
- ruleId: string;
30
- ruleInterfaceVersion: string;
31
- ruleVersion: string;
32
- normative: boolean;
33
- atomic: boolean;
34
- category: Category;
35
- normativeMappings: NormativeMapping[];
36
- standard: string | null;
37
- applicability: string;
38
- expectation: string;
39
- references: string[];
40
- requirements: Record<string, unknown> | null;
41
- mappings: Record<string, unknown> | null;
42
- }
43
-
44
- export interface VisibilityFilter {
45
- targetSet: string;
46
- accEligible: boolean | null;
47
- reasons: string[];
48
- }
49
-
50
- export interface Occurrence {
51
- selector: string;
52
- html: string;
53
- structuralPath: number[] | null;
54
- summary: string;
55
- hint: string;
56
- i18n: { summaryKey: string; hintKey: string; params: Record<string, unknown> } | null;
57
- data: {
58
- visibilityFilter?: VisibilityFilter;
59
- details?: Record<string, unknown>;
60
- };
2
+ import type * as Core from '@surea11y/core';
3
+
4
+ // The result shapes are @surea11y/core's own types (shipped since core
5
+ // 1.9.0, checked there against real scan results), re-exported under the
6
+ // names this file has always used. The binding adds `elementHandle` to an
7
+ // occurrence when .elementRef(true) is used, and the { topFrame, frames }
8
+ // shape of a .frames(true) scan. See core's docs/OUTPUT_SCHEMA.md for what
9
+ // each field means.
10
+
11
+ export type {
12
+ Outcome,
13
+ OutcomeNormalized,
14
+ Severity,
15
+ Confidence,
16
+ RuleType,
17
+ LocaleResolution,
18
+ EngineInfo,
19
+ RenderingEnvironment,
20
+ NormativeMapping,
21
+ VisibilityFilter,
22
+ Uncertainty,
23
+ Margin,
24
+ ContextMatch,
25
+ CompositeResult
26
+ } from '@surea11y/core';
27
+
28
+ // Re-exported from @surea11y/binding-base with the functions src/index.js
29
+ // re-exports from it.
30
+ export {
31
+ formatFailures,
32
+ getScanGaps,
33
+ formatOccurrenceLocation,
34
+ EngineError
35
+ } from '@surea11y/binding-base';
36
+ export type { ScanGap, EngineErrorCode, OccurrenceLocation } from '@surea11y/binding-base';
37
+
38
+ export type Category = Core.RuleMeta['category'];
39
+ export type LocaleResolutionReason = Core.LocaleResolution['reason'];
40
+ export type CheckResultMeta = Core.RuleMeta;
41
+ export type CompositeResultDetails = Core.CompositeResult['data']['details'];
42
+
43
+ export interface Occurrence extends Core.Occurrence {
61
44
  /**
62
45
  * Only present when `.elementRef(true)` was used. `null` when this
63
46
  * occurrence has no single resolvable target element (e.g. `selector` was
64
- * `""`) -- see A11yCoreBuilder#elementRef.
47
+ * `""`), or the element is no longer in the page -- see
48
+ * A11yCoreBuilder#elementRef.
65
49
  */
66
50
  elementHandle?: ElementHandle | null;
67
51
  }
68
52
 
69
- export interface CheckResult {
70
- ruleId: string;
71
- outcome: Outcome;
72
- outcomeNormalized: OutcomeNormalized;
73
- severity: Severity;
74
- confidence: Confidence;
75
- type: RuleType;
53
+ export interface CheckResult extends Omit<Core.CheckResult, 'occurrences'> {
76
54
  occurrences: Occurrence[];
77
- title: string;
78
- description: string;
79
- i18n: { titleKey: string; descriptionKey: string } | null;
80
- meta: CheckResultMeta;
81
- engineOptions: Record<string, unknown>;
82
- schemaVersion: string;
83
- /** Present only if the rule threw, or the manual-fail-to-cantTell coercion fired. */
84
- error?: string;
85
- }
86
-
87
- export interface CompositeResultDetails {
88
- reasonCode: string;
89
- checksIds: string[];
90
- contributors: Array<{ testId: string; outcome: string; severity: string | null }>;
91
- metrics: {
92
- failCount: number;
93
- cantTellCount: number;
94
- notApplicableCount: number;
95
- passCount: number;
96
- missingCount: number;
97
- };
98
- }
99
-
100
- export interface CompositeResult {
101
- ruleId: string;
102
- outcome: Outcome;
103
- severity: Severity;
104
- confidence: Confidence;
105
- type: RuleType;
106
- title: string;
107
- description: string;
108
- meta: CheckResultMeta;
109
- engineOptions: Record<string, unknown>;
110
- schemaVersion: string;
111
- /** Always empty -- composites are rollups, not element-level findings. */
112
- occurrences: [];
113
- data: { details: CompositeResultDetails };
114
55
  }
115
56
 
116
57
  /** surea11y's native top-level result shape -- see docs/OUTPUT_SCHEMA.md. */
117
- export interface A11yCoreResult {
118
- engine: EngineInfo;
119
- url: string | null;
120
- title: string | null;
121
- timestamp: string | null;
122
- perfStats: Record<string, unknown> | null;
123
- contextSelector: string | string[] | null;
58
+ export interface A11yCoreResult extends Omit<Core.ScanResult, 'checksResults'> {
124
59
  checksResults: CheckResult[];
125
- rulesResults: CompositeResult[];
126
60
  }
127
61
 
128
62
  /** A sub-frame that couldn't be scanned (detached, navigated away, or sandboxed). */
@@ -152,8 +86,8 @@ export interface CustomRuleDescriptor {
152
86
  title?: string;
153
87
  description?: string;
154
88
  tags?: string[];
155
- defaultSeverity?: Severity;
156
- defaultConfidence?: Confidence;
89
+ defaultSeverity?: Core.Severity;
90
+ defaultConfidence?: Core.Confidence;
157
91
  [key: string]: unknown;
158
92
  };
159
93
  runInPage: ((ctx: unknown) => unknown) | string;
@@ -181,7 +115,7 @@ export class A11yCoreBuilder {
181
115
  withTags(tags: string | string[]): this;
182
116
  /** Never run rules carrying any of these tags (applied after withTags). */
183
117
  disableTags(tags: string | string[]): this;
184
- /** Only run these specific rule IDs (accepts with or without the prefix). */
118
+ /** Only run these specific rule IDs (accepts with or without the `a11ycore-` prefix). */
185
119
  withRules(ruleIds: string | string[]): this;
186
120
  /** Never run these specific rule IDs (applied after withRules). */
187
121
  disableRules(ruleIds: string | string[]): this;
@@ -190,22 +124,18 @@ export class A11yCoreBuilder {
190
124
  /** Register one or more custom rules for just this scan. Call multiple times to accumulate. */
191
125
  withCustomRules(rules: CustomRuleDescriptor | CustomRuleDescriptor[]): this;
192
126
  /** Post-filter checksResults down to only the given outcomes. */
193
- reportOnly(outcomes: Outcome | Outcome[]): this;
127
+ reportOnly(outcomes: Core.Outcome | Core.Outcome[]): this;
194
128
  /** Opt in to also scanning every sub-frame on the page (including cross-origin iframes). */
195
129
  frames(enabled?: boolean): this;
196
130
  /** Opt in to resolving each fail/cantTell occurrence's selector to a live ElementHandle. */
197
131
  elementRef(enabled?: boolean): this;
198
132
 
199
- /** Runs the scan. Returns { topFrame, frames } instead of a single result when .frames(true) was used. */
133
+ /**
134
+ * Runs the scan. Returns { topFrame, frames } instead of a single result
135
+ * when .frames(true) was used; include() then scopes the top frame only,
136
+ * and each sub-frame is scanned whole. Rejects with an EngineError
137
+ * (`code` 'INVALID_RUN_ONLY' or 'INVALID_CONTEXT_SELECTOR') for input the
138
+ * engine cannot use.
139
+ */
200
140
  analyze(): Promise<A11yCoreResult | A11yCoreMultiFrameResult>;
201
141
  }
202
-
203
- /**
204
- * Formats a checksResults array into a short, human-readable block -- one
205
- * entry per occurrence, not per rule. Meant for an assertion library's
206
- * failure-message parameter, e.g.
207
- * `assert.strictEqual(results.checksResults.length, 0, formatFailures(results.checksResults))`.
208
- * Deliberately framework-agnostic -- no dependency on any particular
209
- * `expect` implementation.
210
- */
211
- export function formatFailures(checksResults: CheckResult[], opts?: { outcomes?: Outcome[] }): string;
@@ -1,7 +1,18 @@
1
1
  'use strict';
2
2
 
3
3
  const { runa11yCoreInPage } = require('@surea11y/core');
4
- const { A11yCoreBuilderBase } = require('@surea11y/binding-base');
4
+ const {
5
+ A11yCoreBuilderBase,
6
+ createInPageScan,
7
+ rethrowEngineError,
8
+ queryOccurrenceElement,
9
+ getScanGaps
10
+ } = require('@surea11y/binding-base');
11
+
12
+ // core's scan, wrapped so an engine error keeps its `code` across
13
+ // page.evaluate(), which keeps only an error's message. Built once; it is
14
+ // self-contained, so Puppeteer serializes it as it did runa11yCoreInPage.
15
+ const inPageScan = createInPageScan(runa11yCoreInPage);
5
16
 
6
17
  /**
7
18
  * Puppeteer binding for surea11y -- scans a real, already-rendered page.
@@ -131,22 +142,29 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
131
142
  // variadic: evaluate<Params extends unknown[], Func>(pageFunction: Func
132
143
  // | string, ...args: Params) (confirmed against a real Puppeteer 25.x
133
144
  // install's own puppeteer-core/lib/types.d.ts, on the shared abstract
134
- // Realm class both Page and Frame implement). That means
135
- // runa11yCoreInPage's own 4 positional args can be passed straight
136
- // through with no wrapper/eval() trick needed -- see
137
- // ../core/docs/INTEGRATION.md for the documented example this mirrors.
138
- const runInFrame = async (frameOrPage) => {
145
+ // Realm class both Page and Frame implement). That means the scan's
146
+ // own 4 positional args can be passed straight through with no
147
+ // wrapper/eval() trick needed -- see ../core/docs/INTEGRATION.md for
148
+ // the documented example this mirrors.
149
+ //
150
+ // An engine error (INVALID_RUN_ONLY, INVALID_CONTEXT_SELECTOR) comes
151
+ // back as a plain object and is thrown here as an EngineError with its
152
+ // `code`; any other error in the page rejects evaluate() as before.
153
+ const runInFrame = async (frameOrPage, frameContextSelector) => {
139
154
  const frameUrl = this._url || (typeof frameOrPage.url === 'function' ? frameOrPage.url() : null);
140
- const result = await frameOrPage.evaluate(runa11yCoreInPage, frameUrl, contextSelector, engineOptions, runOnly);
155
+ const result = rethrowEngineError(
156
+ await frameOrPage.evaluate(inPageScan, frameUrl, frameContextSelector, engineOptions, runOnly)
157
+ );
158
+ warnScanGaps(result);
141
159
  return this._elementRef ? this._attachElementRefs(frameOrPage, result) : result;
142
160
  };
143
161
 
144
162
  if (!this._scanFrames) {
145
- return this._applyReportOnly(await runInFrame(this._page));
163
+ return this._applyReportOnly(await runInFrame(this._page, contextSelector));
146
164
  }
147
165
 
148
166
  const mainFrame = this._page.mainFrame();
149
- const topFrame = this._applyReportOnly(await runInFrame(mainFrame));
167
+ const topFrame = this._applyReportOnly(await runInFrame(mainFrame, contextSelector));
150
168
 
151
169
  // page.frames() includes the main frame itself -- exclude it here since
152
170
  // it's already covered by topFrame above, so callers don't have to
@@ -155,7 +173,12 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
155
173
  const frames = [];
156
174
  for (const frame of subFrames) {
157
175
  try {
158
- frames.push(this._applyReportOnly(await runInFrame(frame)));
176
+ // include() scopes the top frame only: each sub-frame is scanned
177
+ // whole, as core's own runa11yCoreAcrossFrames does. The selectors
178
+ // were written against the top document, and since core 1.10.0 a
179
+ // selector that matches nothing scans nothing, so passing them on
180
+ // would leave most frames unscanned.
181
+ frames.push(this._applyReportOnly(await runInFrame(frame, null)));
159
182
  } catch (e) {
160
183
  // A frame can detach/navigate away mid-scan, or be a sandboxed
161
184
  // frame the browser blocks scripting in -- don't let one bad frame
@@ -171,9 +194,12 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
171
194
  }
172
195
 
173
196
  /**
174
- * Resolves occurrence.selector to a live ElementHandle for every
175
- * fail/cantTell occurrence, scoped to frameOrPage's own document (a
176
- * Puppeteer Page and Frame both expose the same .$(selector) shape).
197
+ * Resolves each fail/cantTell occurrence to a live ElementHandle, scoped
198
+ * to frameOrPage's own document (a Puppeteer Page and Frame both expose
199
+ * evaluateHandle()). An occurrence inside a shadow tree is found through
200
+ * its `shadowHostSelectors` (core 1.10.0 and later): its `selector` holds
201
+ * only inside the last host's shadow root, so `frameOrPage.$(selector)`
202
+ * would find another element, or none.
177
203
  * Mutates and returns the same result object -- it's a fresh object from
178
204
  * this scan, not shared external state.
179
205
  */
@@ -185,13 +211,38 @@ class A11yCoreBuilder extends A11yCoreBuilderBase {
185
211
  // Most occurrences carry a concrete element selector, but a page-wide
186
212
  // finding with no single target element (e.g. some `manual`/cantTell
187
213
  // rules) can carry "" -- not every occurrence resolves to one element,
188
- // so leave elementHandle null rather than passing "" to .$() (which
189
- // throws, it's not a valid CSS selector).
190
- occurrence.elementHandle = occurrence.selector ? await frameOrPage.$(occurrence.selector) : null;
214
+ // so leave elementHandle null without a round trip to the page.
215
+ occurrence.elementHandle = occurrence.selector
216
+ ? await resolveElementHandle(frameOrPage, occurrence)
217
+ : null;
191
218
  }
192
219
  }
193
220
  return result;
194
221
  }
195
222
  }
196
223
 
224
+ // Says on the console what the scan left out (an include() scope that
225
+ // matched nothing, a custom rule the engine did not run), one line per gap,
226
+ // so a scan that skipped something does not pass unnoticed as clean. Once
227
+ // per scanned frame; the gaps also stay readable through getScanGaps().
228
+ function warnScanGaps(result) {
229
+ for (const gap of getScanGaps(result)) {
230
+ const where = result.url ? ` (${result.url})` : '';
231
+ console.warn(`@surea11y/puppeteer${where}: ${gap.message}`);
232
+ }
233
+ }
234
+
235
+ // The occurrence's element as an ElementHandle, or null when it is gone (or
236
+ // a shadow host on the way is). A handle to null is disposed, not leaked.
237
+ async function resolveElementHandle(frameOrPage, occurrence) {
238
+ const handle = await frameOrPage.evaluateHandle(
239
+ queryOccurrenceElement,
240
+ occurrence.selector,
241
+ occurrence.shadowHostSelectors || null
242
+ );
243
+ const element = handle.asElement();
244
+ if (!element) await handle.dispose();
245
+ return element;
246
+ }
247
+
197
248
  module.exports = { A11yCoreBuilder };
package/src/index.js CHANGED
@@ -3,4 +3,10 @@
3
3
  const { A11yCoreBuilder } = require('./A11yCoreBuilder');
4
4
  const { formatFailures } = require('./formatFailures');
5
5
 
6
- module.exports = { A11yCoreBuilder, formatFailures };
6
+ // Re-exported from @surea11y/binding-base, as formatFailures is, so a test
7
+ // needs only this package: what a result says it left out, an occurrence's
8
+ // location as text, and the error analyze() throws for input the engine
9
+ // cannot use.
10
+ const { getScanGaps, formatOccurrenceLocation, EngineError } = require('@surea11y/binding-base');
11
+
12
+ module.exports = { A11yCoreBuilder, formatFailures, getScanGaps, formatOccurrenceLocation, EngineError };