@surea11y/puppeteer 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jorge Rumoroso
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,185 @@
1
+ # surea11y-puppeteer
2
+
3
+ A Puppeteer binding for [`surea11y`](../surea11y) — scans a real, already-rendered page for accessibility issues using surea11y's DOM-rules engine.
4
+
5
+ This is a **separate project/package** from `surea11y` itself and from its sibling [`surea11y-playwright`](../surea11y-playwright), kept as its own sibling directory rather than a monorepo subfolder — see `ROADMAP.md` §1 for the reasoning (same reasoning `surea11y-playwright` already used).
6
+
7
+ ## Install (local development)
8
+
9
+ `surea11y` isn't published to npm yet, so this package depends on it via a relative `file:` path (see `package.json`):
10
+
11
+ ```json
12
+ "dependencies": { "surea11y": "file:../core" }
13
+ ```
14
+
15
+ That means this project must stay a sibling of `surea11y` (or you update the path) for `npm install` to resolve it.
16
+
17
+ ```bash
18
+ npm install
19
+ npm test
20
+ ```
21
+
22
+ `puppeteer` (not `puppeteer-core`) is a `devDependency` here, which downloads its own bundled Chrome — unlike the Playwright binding, there's no separate `npx playwright install` step needed for `npm test` to work.
23
+
24
+ The cross-browser regression test in `tests/cross-browser.test.js` (proving this works against Firefox too, not just Chrome) additionally needs `npx puppeteer browsers install firefox`.
25
+
26
+ ## Usage
27
+
28
+ ```js
29
+ const puppeteer = require('puppeteer');
30
+ const { A11yCoreBuilder } = require('surea11y-puppeteer');
31
+
32
+ const browser = await puppeteer.launch();
33
+ const page = await browser.newPage();
34
+ await page.goto('https://example.com/');
35
+
36
+ const results = await new A11yCoreBuilder({ page })
37
+ .include('#main') // optional -- call multiple times for multi-region scans
38
+ .exclude('.cookie-banner') // optional
39
+ .withTags(['wcag2a', 'wcag2aa'])
40
+ .disableRules(['meta-refresh-no-exceptions'])
41
+ .options({ contrast: { mode: 'auditorAssist' } })
42
+ .analyze();
43
+
44
+ console.log(results.checksResults.filter(r => r.outcome === 'fail'));
45
+ await browser.close();
46
+ ```
47
+
48
+ `results` is surea11y's own native result shape — see [`../surea11y/docs/OUTPUT_SCHEMA.md`](../surea11y/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.
49
+
50
+ Also see `examples/basic-scan.js` for a runnable script (`npm run example -- <url>`).
51
+
52
+ `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's default `includeMode: 'and'` — see `../surea11y/docs/ENGINE_OPTIONS.md`), not either one.
53
+
54
+ **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.
55
+
56
+ This binding works against both browsers Puppeteer supports — Chrome (the default) and Firefox via `puppeteer.launch({ browser: 'firefox' })` — verified with a real Firefox run, see `tests/cross-browser.test.js`. There's no WebKit option; that's a Playwright-only engine.
57
+
58
+ ### Using it as an E2E accessibility gate
59
+
60
+ The pattern above works unchanged inside a real test:
61
+
62
+ ```js
63
+ const puppeteer = require('puppeteer');
64
+ const { A11yCoreBuilder, formatFailures } = require('surea11y-puppeteer');
65
+
66
+ const browser = await puppeteer.launch();
67
+ const page = await browser.newPage();
68
+ await page.goto('https://example.com/');
69
+
70
+ const results = await new A11yCoreBuilder({ page }).reportOnly(['fail']).analyze();
71
+
72
+ assert.strictEqual(results.checksResults.length, 0, formatFailures(results.checksResults));
73
+ ```
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 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 (see `ROADMAP.md` §6 for the full reasoning, including the other runners considered).
76
+
77
+ ### Readable console/CI output on failure
78
+
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(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:
80
+
81
+ ```
82
+ Error: 1) button-name-present (serious): This button has no accessible name.
83
+ at html > body > button
84
+ Provide visible button text or a programmatic accessible-name mechanism (for example aria-label) so assistive technologies can identify the button.
85
+ 2) img-alt-present (serious): Missing alt attribute on <img>.
86
+ at html > body > img
87
+ Add an alt attribute (use alt="" only for decorative images).
88
+ ```
89
+
90
+ 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 `../surea11y/docs/OUTPUT_SCHEMA.md`) is still surfaced using its `error` message rather than silently dropped.
91
+
92
+ ### Scanning every frame, including cross-origin iframes
93
+
94
+ ```js
95
+ const results = await new A11yCoreBuilder({ page }).frames(true).analyze();
96
+
97
+ console.log(results.topFrame.checksResults.filter(r => r.outcome === 'fail')); // the top-level page
98
+ for (const frame of results.frames) {
99
+ console.log(frame.checksResults.filter(r => r.outcome === 'fail')); // each sub-frame, same result shape
100
+ }
101
+ ```
102
+
103
+ 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 `surea11y` 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 `ROADMAP.md` §2c and `tests/builder.test.js`. Default off, so plain `.analyze()` is unaffected unless you opt in.
104
+
105
+ ### Trimming the result to just violations
106
+
107
+ By default `analyze()` returns every rule's outcome, including `pass`/`notApplicable` — surea11y's own deliberate "not a violations-only list" design (see `../surea11y/docs/OUTPUT_SCHEMA.md`). Use `.reportOnly()` to post-filter down to only the outcomes you care about:
108
+
109
+ ```js
110
+ const results = await new A11yCoreBuilder({ page })
111
+ .reportOnly(['fail', 'cantTell'])
112
+ .analyze();
113
+
114
+ console.log(results.checksResults); // only fail/cantTell entries, pass/notApplicable dropped
115
+ ```
116
+
117
+ Valid outcome values are `'pass'`, `'fail'`, `'cantTell'`, `'notApplicable'`. This is pure binding-layer filtering — surea11y itself still computes every rule; nothing about the scan itself changes. Combines with `.frames(true)`: the filter is applied to `results.topFrame` and each entry of `results.frames` independently.
118
+
119
+ ### Getting a live element handle, not just a selector string
120
+
121
+ By default each occurrence carries a CSS selector + HTML snippet, not a live reference to the element. Opt in to a real Puppeteer `ElementHandle` with `.elementRef(true)`:
122
+
123
+ ```js
124
+ const results = await new A11yCoreBuilder({ page }).elementRef(true).analyze();
125
+
126
+ const [failing] = results.checksResults.filter(r => r.outcome === 'fail');
127
+ await failing.occurrences[0].elementHandle.screenshot({ path: 'flagged.png' });
128
+ await failing.occurrences[0].elementHandle.click();
129
+ ```
130
+
131
+ 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.
132
+
133
+ 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).
134
+
135
+ ### Registering a custom rule at runtime
136
+
137
+ `surea11y` supports registering additional rules per-scan via `engineOptions.customRules`. Use `.withCustomRules()` to register one:
138
+
139
+ ```js
140
+ const results = await new A11yCoreBuilder({ page })
141
+ .withCustomRules({
142
+ id: 'my-org-custom-rule',
143
+ meta: { title: 'My custom rule', tags: ['custom'], defaultSeverity: 'serious' },
144
+ // A real, live function is fine here -- .withCustomRules() converts it
145
+ // to a function-source string for you (see below for why that matters).
146
+ runInPage(ctx) {
147
+ const el = ctx.document.querySelector('.my-widget');
148
+ return el ? { outcome: 'fail', occurrences: [{ __node: el }] } : { outcome: 'notApplicable', occurrences: [] };
149
+ }
150
+ })
151
+ .analyze();
152
+ ```
153
+
154
+ A custom rule descriptor is the same shape as one of surea11y's own internal rule modules (`{ id, meta, runInPage, applicability?, data? }`) — see `../surea11y/docs/ENGINE_OPTIONS.md` for the full contract. Results appear in `checksResults` exactly like a built-in rule's, including automatic `selector`/`html`/`structuralPath` fill-in. Registered per-scan only (nothing persists between calls or shows up in any catalog listing), and a custom rule whose `id` collides with a built-in one overrides it for that scan.
155
+
156
+ Pass an array to register several at once, or call `.withCustomRules()` again to add more — like `.withRules()`/`.withTags()`, it accumulates rather than replacing what was already registered:
157
+
158
+ ```js
159
+ const results = await new A11yCoreBuilder({ page })
160
+ .withCustomRules([firstRule, secondRule])
161
+ .withCustomRules(thirdRule) // adds a third, doesn't replace the first two
162
+ .analyze();
163
+ ```
164
+
165
+ **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 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.
166
+
167
+ 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's own engine-side behavior, which silently skips an invalid descriptor rather than throwing — see `../surea11y/docs/ENGINE_OPTIONS.md`.)
168
+
169
+ ### Element addressing beyond a CSS selector
170
+
171
+ 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 `../surea11y/docs/OUTPUT_SCHEMA.md` for the full field description.
172
+
173
+ ## TypeScript
174
+
175
+ `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's native result shapes (`A11yCoreResult`, `CheckResult`, `Occurrence`, `CompositeResult`, etc.), mirrored from `../surea11y/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.
176
+
177
+ ## Relationship to `surea11y-playwright`
178
+
179
+ This binding's builder API is deliberately identical to [`surea11y-playwright`](../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 drop-in swap of `puppeteer.launch()`/`playwright.chromium.launch()` and nothing else. As of `ROADMAP.md` §8, that's no longer just parallel implementation: `A11yCoreBuilder` here extends `A11yCoreBuilderBase` from [`../surea11y-binding-base`](../surea11y-binding-base), a small shared package every surea11y binding now depends on for the logic that genuinely has nothing to do with any particular driver. The one real implementation difference left is internal: `analyze()`'s injection call is simpler here, since Puppeteer's `page.evaluate()` is genuinely variadic and doesn't need the wrapper/`eval()` trick Playwright's single-argument `evaluate()` requires — see `ROADMAP.md` §2b.
180
+
181
+ Also see [`../surea11y/docs/BINDING_AUTHORS_GUIDE.md`](../surea11y/docs/BINDING_AUTHORS_GUIDE.md) — `surea11y`'s own reference for building a binding like this one, distinguishing what's already engine-level (a generic `.options()`/`runOnly` passthrough, e.g. WCAG-version tag filtering, `structuralPath`) from what every binding has to build itself (element refs, `reportOnly`-style verbosity filtering, the `page.evaluate()`/`frame.evaluate()` serialization-boundary caveat `.withCustomRules()` exists to paper over). It cites this project's `.elementRef()`, `.reportOnly()`, `.frames(true)`, and `.withCustomRules()` by name as worked examples alongside `surea11y-playwright`'s.
182
+
183
+ ## Status and what's next
184
+
185
+ See `ROADMAP.md` — it documents what's built, what's verified, and what's still open.
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@surea11y/puppeteer",
3
+ "version": "0.1.1",
4
+ "description": "Puppeteer binding for surea11y -- scan real, live-rendered pages for accessibility issues.",
5
+ "main": "src/index.js",
6
+ "types": "src/index.d.ts",
7
+ "author": "Jorge Rumoroso",
8
+ "license": "MIT",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/rumoroso/surea11y-core-puppeteer.git"
12
+ },
13
+ "homepage": "https://github.com/rumoroso/surea11y-core-puppeteer#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/rumoroso/surea11y-core-puppeteer/issues"
16
+ },
17
+ "engines": {
18
+ "node": ">=22.12.0"
19
+ },
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "files": [
24
+ "src",
25
+ "README.md",
26
+ "LICENSE"
27
+ ],
28
+ "dependencies": {
29
+ "@surea11y/core": "^1.1.0",
30
+ "@surea11y/binding-base": "^0.1.0"
31
+ },
32
+ "peerDependencies": {
33
+ "puppeteer": ">=22.0.0"
34
+ },
35
+ "devDependencies": {
36
+ "puppeteer": "^25.3.0"
37
+ },
38
+ "scripts": {
39
+ "test": "node --test \"tests/**/*.test.js\"",
40
+ "example": "node examples/basic-scan.js",
41
+ "example:e2e": "node --test examples/e2e-test-example.test.js"
42
+ }
43
+ }
@@ -0,0 +1,206 @@
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
+ };
61
+ /**
62
+ * Only present when `.elementRef(true)` was used. `null` when this
63
+ * occurrence has no single resolvable target element (e.g. `selector` was
64
+ * `""`) -- see A11yCoreBuilder#elementRef.
65
+ */
66
+ elementHandle?: ElementHandle | null;
67
+ }
68
+
69
+ export interface CheckResult {
70
+ ruleId: string;
71
+ outcome: Outcome;
72
+ outcomeNormalized: OutcomeNormalized;
73
+ severity: Severity;
74
+ confidence: Confidence;
75
+ type: RuleType;
76
+ 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
+ }
115
+
116
+ /** 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;
124
+ checksResults: CheckResult[];
125
+ rulesResults: CompositeResult[];
126
+ }
127
+
128
+ /** A sub-frame that couldn't be scanned (detached, navigated away, or sandboxed). */
129
+ export interface A11yCoreFrameError {
130
+ url: string | null;
131
+ error: string;
132
+ }
133
+
134
+ /** Returned by analyze() when .frames(true) is enabled, instead of a single A11yCoreResult. */
135
+ export interface A11yCoreMultiFrameResult {
136
+ topFrame: A11yCoreResult;
137
+ frames: Array<A11yCoreResult | A11yCoreFrameError>;
138
+ }
139
+
140
+ /**
141
+ * A runtime-registered rule descriptor for `.withCustomRules()` -- the same
142
+ * shape as an internal surea11y rule module's own export (see surea11y's
143
+ * docs/ENGINE_OPTIONS.md). `runInPage`/`applicability` may be passed as
144
+ * either a real function or a function-source string -- `.withCustomRules()`
145
+ * converts a live function to its source string for you, since it must
146
+ * cross a page.evaluate() JSON boundary that cannot carry a live Function
147
+ * reference.
148
+ */
149
+ export interface CustomRuleDescriptor {
150
+ id: string;
151
+ meta?: {
152
+ title?: string;
153
+ description?: string;
154
+ tags?: string[];
155
+ defaultSeverity?: Severity;
156
+ defaultConfidence?: Confidence;
157
+ [key: string]: unknown;
158
+ };
159
+ runInPage: ((ctx: unknown) => unknown) | string;
160
+ applicability?: ((ctx: unknown) => boolean) | string;
161
+ data?: Record<string, unknown>;
162
+ }
163
+
164
+ export class A11yCoreBuilder {
165
+ /**
166
+ * @param opts.page A Puppeteer Page, already navigated to and settled at
167
+ * the URL to scan -- this class does not navigate for you.
168
+ */
169
+ constructor(opts: { page: Page; url?: string });
170
+
171
+ /** Scope the scan to one region. Call multiple times for a multi-region union. */
172
+ include(selector: string): this;
173
+ /** Skip elements matching this selector anywhere in the scanned scope. */
174
+ exclude(selector: string): this;
175
+ /** Only run rules carrying at least one of these tags. */
176
+ withTags(tags: string | string[]): this;
177
+ /** Never run rules carrying any of these tags (applied after withTags). */
178
+ disableTags(tags: string | string[]): this;
179
+ /** Only run these specific rule IDs (accepts with or without the prefix). */
180
+ withRules(ruleIds: string | string[]): this;
181
+ /** Never run these specific rule IDs (applied after withRules). */
182
+ disableRules(ruleIds: string | string[]): this;
183
+ /** Merge arbitrary engineOptions (locale, contrast.mode, policyContract, ...). */
184
+ options(partialEngineOptions: Record<string, unknown>): this;
185
+ /** Register one or more custom rules for just this scan. Call multiple times to accumulate. */
186
+ withCustomRules(rules: CustomRuleDescriptor | CustomRuleDescriptor[]): this;
187
+ /** Post-filter checksResults down to only the given outcomes. */
188
+ reportOnly(outcomes: Outcome | Outcome[]): this;
189
+ /** Opt in to also scanning every sub-frame on the page (including cross-origin iframes). */
190
+ frames(enabled?: boolean): this;
191
+ /** Opt in to resolving each fail/cantTell occurrence's selector to a live ElementHandle. */
192
+ elementRef(enabled?: boolean): this;
193
+
194
+ /** Runs the scan. Returns { topFrame, frames } instead of a single result when .frames(true) was used. */
195
+ analyze(): Promise<A11yCoreResult | A11yCoreMultiFrameResult>;
196
+ }
197
+
198
+ /**
199
+ * Formats a checksResults array into a short, human-readable block -- one
200
+ * entry per occurrence, not per rule. Meant for an assertion library's
201
+ * failure-message parameter, e.g.
202
+ * `assert.strictEqual(results.checksResults.length, 0, formatFailures(results.checksResults))`.
203
+ * Deliberately framework-agnostic -- no dependency on any particular
204
+ * `expect` implementation.
205
+ */
206
+ export function formatFailures(checksResults: CheckResult[], opts?: { outcomes?: Outcome[] }): string;
@@ -0,0 +1,197 @@
1
+ 'use strict';
2
+
3
+ const { runa11yCoreInPage } = require('@surea11y/core');
4
+ const { A11yCoreBuilderBase } = require('@surea11y/binding-base');
5
+
6
+ /**
7
+ * Puppeteer binding for surea11y -- scans a real, already-rendered page.
8
+ *
9
+ * const results = await new A11yCoreBuilder({ page })
10
+ * .include('#main')
11
+ * .exclude('.cookie-banner')
12
+ * .withTags(['wcag2a', 'wcag2aa'])
13
+ * .disableRules(['meta-refresh-no-exceptions'])
14
+ * .options({ contrast: { mode: 'auditorAssist' } })
15
+ * .analyze();
16
+ *
17
+ * `results` is surea11y's own native result shape (checksResults /
18
+ * rulesResults -- see surea11y's docs/OUTPUT_SCHEMA.md), not the
19
+ * violations/passes/incomplete/inapplicable shape used by other tools in
20
+ * this space. Method names are modeled on common conventions in this space
21
+ * for migration ease, but the richer native schema (severity, confidence,
22
+ * occurrences, policy contract, WCAG SC mappings) is kept as-is rather than
23
+ * reshaped to match.
24
+ *
25
+ * Extends `A11yCoreBuilderBase` (from `surea11y-binding-base`), which owns
26
+ * every method with no driver-specific work at all -- `include()`/
27
+ * `exclude()`/`withTags()`/`disableTags()`/`withRules()`/`disableRules()`/
28
+ * `options()`/`reportOnly()`/`elementRef()`/`frames()`/`withCustomRules()`'s
29
+ * validation (including the default customRules stringification, correct
30
+ * here since Puppeteer's `page.evaluate()` crosses a real serialization
31
+ * boundary), and `_buildEngineArgs()`. This class adds exactly the parts
32
+ * that are genuinely Puppeteer-specific: `analyze()`'s injection mechanics,
33
+ * frame traversal, and `_attachElementRefs()`. See
34
+ * `../surea11y-binding-base/README.md` for what's shared and why.
35
+ *
36
+ * Opt in to scanning every frame on the page (including cross-origin
37
+ * iframes) via .frames(true):
38
+ *
39
+ * const results = await new A11yCoreBuilder({ page }).frames(true).analyze();
40
+ * // results.topFrame -- same shape as the single-frame case above
41
+ * // results.frames -- array of the same native result shape, one per sub-frame
42
+ *
43
+ * Unlike script-injection-based accessibility engines (which need a
44
+ * postMessage-based protocol, runPartial/finishRun, to reach cross-origin
45
+ * iframes, since they're injected as a plain <script> and are fully subject
46
+ * to the browser's same-origin policy), this doesn't need any surea11y
47
+ * engine support: Puppeteer drives every frame
48
+ * via CDP at the automation-process level, not as in-page script, so
49
+ * cross-origin frame.evaluate() already just works -- verified empirically
50
+ * against a real cross-origin iframe, see ../ROADMAP.md and
51
+ * tests/builder.test.js. Default off, so plain .analyze() keeps returning
52
+ * the single native result object it always has.
53
+ *
54
+ * By default `analyze()` returns every rule's outcome, including
55
+ * `pass`/`notApplicable` -- surea11y's own deliberate "not a
56
+ * violations-only list" design (see surea11y's docs/OUTPUT_SCHEMA.md).
57
+ * Opt in to a lighter payload with `.reportOnly(['fail', 'cantTell'])`,
58
+ * which post-filters `checksResults` by `outcome` (applied per-frame when
59
+ * combined with `.frames(true)`, since `checksResults` lives at
60
+ * `results.topFrame` / each `results.frames[i]` in that shape, not at the
61
+ * top level):
62
+ *
63
+ * const results = await new A11yCoreBuilder({ page })
64
+ * .reportOnly(['fail', 'cantTell'])
65
+ * .analyze();
66
+ *
67
+ * Opt in to a live `ElementHandle` per occurrence (instead of just a CSS
68
+ * selector string) with `.elementRef(true)`, so you can act on the flagged
69
+ * element directly rather than re-resolving its selector yourself:
70
+ *
71
+ * const results = await new A11yCoreBuilder({ page }).elementRef(true).analyze();
72
+ * const [firstFail] = results.checksResults.filter(r => r.outcome === 'fail');
73
+ * await firstFail.occurrences[0].elementHandle.screenshot({ path: 'flagged.png' });
74
+ *
75
+ * Register your own rule(s) for just this scan with
76
+ * `.withCustomRules([...])` (surea11y's `engineOptions.customRules`
77
+ * escape hatch -- see surea11y's docs/ENGINE_OPTIONS.md). Pass a real,
78
+ * live `runInPage`/
79
+ * `applicability` function -- unlike the raw `.options({ customRules })`
80
+ * passthrough, this method converts them to the function-source string
81
+ * surea11y needs on this side of the page.evaluate() JSON boundary for
82
+ * you, so you don't have to remember to call .toString() yourself:
83
+ *
84
+ * const results = await new A11yCoreBuilder({ page })
85
+ * .withCustomRules({
86
+ * id: 'my-org-custom-rule',
87
+ * meta: { title: 'My custom rule', tags: ['custom'] },
88
+ * runInPage(ctx) {
89
+ * const el = ctx.document.querySelector('.my-widget');
90
+ * return el ? { outcome: 'fail', occurrences: [{ __node: el }] } : { outcome: 'notApplicable', occurrences: [] };
91
+ * }
92
+ * })
93
+ * .analyze();
94
+ *
95
+ * Create one builder per scan. This is a mutable object with no reset
96
+ * between analyze() calls: include()/exclude()/withRules()/disableRules()/
97
+ * withTags()/disableTags()/options()/withCustomRules() all push onto or
98
+ * merge into internal state that persists for the instance's lifetime, so
99
+ * calling one of them again before a second analyze() call accumulates on
100
+ * top of the first scan's scope rather than replacing it (intentional for
101
+ * "call include() several times for one scan" -- see above -- but a footgun
102
+ * if you hold one instance across multiple assertions).
103
+ * reportOnly()/frames()/elementRef() are the exception: each call replaces
104
+ * the previous value rather than merging with it.
105
+ */
106
+ class A11yCoreBuilder extends A11yCoreBuilderBase {
107
+ /**
108
+ * @param {{ page: import('puppeteer').Page, url?: string }} opts
109
+ * `page` must already be navigated to and settled at the URL to scan --
110
+ * this class does not navigate for you.
111
+ */
112
+ constructor({ page, url } = {}) {
113
+ super({ url });
114
+ if (!page || typeof page.evaluate !== 'function') {
115
+ throw new Error('A11yCoreBuilder requires { page } (a Puppeteer Page, with an .evaluate() method).');
116
+ }
117
+ this._page = page;
118
+ }
119
+
120
+ /**
121
+ * Runs the scan and returns surea11y's native result object.
122
+ * @returns {Promise<object>} see surea11y's docs/OUTPUT_SCHEMA.md
123
+ */
124
+ async analyze() {
125
+ const { contextSelector, engineOptions, runOnly } = this._buildEngineArgs();
126
+
127
+ // Unlike Playwright's page.evaluate(fn, arg), which only accepts a
128
+ // SINGLE argument (forcing a hand-built single-arg wrapper there --
129
+ // see surea11y-playwright's own A11yCoreBuilder.js for the full
130
+ // story), Puppeteer's page.evaluate()/frame.evaluate() is genuinely
131
+ // variadic: evaluate<Params extends unknown[], Func>(pageFunction: Func
132
+ // | string, ...args: Params) (confirmed against a real Puppeteer 25.x
133
+ // 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 surea11y's own
137
+ // docs/INTEGRATION.md for the documented example this mirrors.
138
+ const runInFrame = async (frameOrPage) => {
139
+ const frameUrl = this._url || (typeof frameOrPage.url === 'function' ? frameOrPage.url() : null);
140
+ const result = await frameOrPage.evaluate(runa11yCoreInPage, frameUrl, contextSelector, engineOptions, runOnly);
141
+ return this._elementRef ? this._attachElementRefs(frameOrPage, result) : result;
142
+ };
143
+
144
+ if (!this._scanFrames) {
145
+ return this._applyReportOnly(await runInFrame(this._page));
146
+ }
147
+
148
+ const mainFrame = this._page.mainFrame();
149
+ const topFrame = this._applyReportOnly(await runInFrame(mainFrame));
150
+
151
+ // page.frames() includes the main frame itself -- exclude it here since
152
+ // it's already covered by topFrame above, so callers don't have to
153
+ // de-duplicate it themselves out of the frames array.
154
+ const subFrames = this._page.frames().filter((f) => f !== mainFrame);
155
+ const frames = [];
156
+ for (const frame of subFrames) {
157
+ try {
158
+ frames.push(this._applyReportOnly(await runInFrame(frame)));
159
+ } catch (e) {
160
+ // A frame can detach/navigate away mid-scan, or be a sandboxed
161
+ // frame the browser blocks scripting in -- don't let one bad frame
162
+ // abort the whole multi-frame scan; report it and keep going.
163
+ frames.push({
164
+ url: (typeof frame.url === 'function' ? frame.url() : null),
165
+ error: (e && e.message) || String(e)
166
+ });
167
+ }
168
+ }
169
+
170
+ return { topFrame, frames };
171
+ }
172
+
173
+ /**
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).
177
+ * Mutates and returns the same result object -- it's a fresh object from
178
+ * this scan, not shared external state.
179
+ */
180
+ async _attachElementRefs(frameOrPage, result) {
181
+ if (!Array.isArray(result.checksResults)) return result;
182
+ for (const check of result.checksResults) {
183
+ if (!Array.isArray(check.occurrences) || !check.occurrences.length) continue;
184
+ for (const occurrence of check.occurrences) {
185
+ // Most occurrences carry a concrete element selector, but a page-wide
186
+ // finding with no single target element (e.g. some `manual`/cantTell
187
+ // 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;
191
+ }
192
+ }
193
+ return result;
194
+ }
195
+ }
196
+
197
+ module.exports = { A11yCoreBuilder };
@@ -0,0 +1,12 @@
1
+ 'use strict';
2
+
3
+ // Re-exported from surea11y-binding-base, which now holds the single
4
+ // canonical copy shared across every surea11y binding -- see
5
+ // ../ROADMAP.md's note on the shared-package extraction, and
6
+ // ../surea11y-binding-base/README.md for the full rationale. Kept as a
7
+ // real file here (not just re-exporting straight from src/index.js) so
8
+ // `require('surea11y-puppeteer/src/formatFailures')` keeps working for
9
+ // anyone importing the submodule path directly.
10
+ const { formatFailures } = require('@surea11y/binding-base');
11
+
12
+ module.exports = { formatFailures };
package/src/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './A11yCoreBuilder';
package/src/index.js ADDED
@@ -0,0 +1,6 @@
1
+ 'use strict';
2
+
3
+ const { A11yCoreBuilder } = require('./A11yCoreBuilder');
4
+ const { formatFailures } = require('./formatFailures');
5
+
6
+ module.exports = { A11yCoreBuilder, formatFailures };