@surea11y/playwright 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,184 @@
1
+ # surea11y-playwright
2
+
3
+ A Playwright 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, kept as a sibling directory (`../surea11y`) rather than a monorepo subfolder — see `ROADMAP.md` for the reasoning behind that split and everything else about this project's status.
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
+ npx playwright install chromium # every test launches a real browser -- npm install alone doesn't fetch it
20
+ npm test
21
+ ```
22
+
23
+ `npm test` 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`.
24
+
25
+ ## Usage
26
+
27
+ ```js
28
+ const { chromium } = require('playwright');
29
+ const { A11yCoreBuilder } = require('surea11y-playwright');
30
+
31
+ const browser = await chromium.launch();
32
+ const page = await browser.newPage();
33
+ await page.goto('https://example.com/');
34
+
35
+ const results = await new A11yCoreBuilder({ page })
36
+ .include('#main') // optional -- call multiple times for multi-region scans
37
+ .exclude('.cookie-banner') // optional
38
+ .withTags(['wcag2a', 'wcag2aa'])
39
+ .disableRules(['meta-refresh-no-exceptions'])
40
+ .options({ contrast: { mode: 'auditorAssist' } })
41
+ .analyze();
42
+
43
+ console.log(results.checksResults.filter(r => r.outcome === 'fail'));
44
+ await browser.close();
45
+ ```
46
+
47
+ `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.
48
+
49
+ Also see `examples/basic-scan.js` for a runnable script (`npm run example -- <url>`).
50
+
51
+ `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.
52
+
53
+ **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.
54
+
55
+ This binding works against all three Playwright engines, not just Chromium — verified with real Firefox and WebKit runs, see `tests/cross-browser.test.js`.
56
+
57
+ ### Using it as an E2E accessibility gate
58
+
59
+ The pattern above works unchanged inside a real `@playwright/test` test (this is the pattern that actually matters for a CI/E2E suite, not just an ad hoc script):
60
+
61
+ ```js
62
+ const { test, expect } = require('@playwright/test');
63
+ const { A11yCoreBuilder, formatFailures } = require('surea11y-playwright');
64
+
65
+ test('page has no accessibility violations', async ({ page }) => {
66
+ await page.goto('https://example.com/');
67
+
68
+ const results = await new A11yCoreBuilder({ page }).reportOnly(['fail']).analyze();
69
+
70
+ expect(results.checksResults, formatFailures(results.checksResults)).toEqual([]);
71
+ });
72
+ ```
73
+
74
+ See `examples/playwright-test-example.spec.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.
75
+
76
+ ### Readable console/CI output on failure
77
+
78
+ `expect(x).toEqual([])` 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
+
80
+ ```
81
+ Error: 1) button-name-present (serious): This button has no accessible name.
82
+ at html > body > button
83
+ Provide visible button text or a programmatic accessible-name mechanism (for example aria-label) so assistive technologies can identify the button.
84
+ 2) img-alt-present (serious): Missing alt attribute on <img>.
85
+ at html > body > img
86
+ Add an alt attribute (use alt="" only for decorative images).
87
+ ```
88
+
89
+ ...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 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.
90
+
91
+ ### Scanning every frame, including cross-origin iframes
92
+
93
+ ```js
94
+ const results = await new A11yCoreBuilder({ page }).frames(true).analyze();
95
+
96
+ console.log(results.topFrame.checksResults.filter(r => r.outcome === 'fail')); // the top-level page
97
+ for (const frame of results.frames) {
98
+ console.log(frame.checksResults.filter(r => r.outcome === 'fail')); // each sub-frame, same result shape
99
+ }
100
+ ```
101
+
102
+ 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 — Playwright 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` gap #1 and `tests/builder.test.js`. Default off, so plain `.analyze()` is unaffected unless you opt in.
103
+
104
+ ### Trimming the result to just violations
105
+
106
+ 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:
107
+
108
+ ```js
109
+ const results = await new A11yCoreBuilder({ page })
110
+ .reportOnly(['fail', 'cantTell'])
111
+ .analyze();
112
+
113
+ console.log(results.checksResults); // only fail/cantTell entries, pass/notApplicable dropped
114
+ ```
115
+
116
+ 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.
117
+
118
+ ### Getting a live element handle, not just a selector string
119
+
120
+ By default each occurrence carries a CSS selector + HTML snippet, not a live reference to the element. Opt in to a real Playwright `ElementHandle` with `.elementRef(true)`:
121
+
122
+ ```js
123
+ const results = await new A11yCoreBuilder({ page }).elementRef(true).analyze();
124
+
125
+ const [failing] = results.checksResults.filter(r => r.outcome === 'fail');
126
+ await failing.occurrences[0].elementHandle.screenshot({ path: 'flagged.png' });
127
+ await failing.occurrences[0].elementHandle.click();
128
+ ```
129
+
130
+ 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.
131
+
132
+ 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).
133
+
134
+ ### Registering a custom rule at runtime
135
+
136
+ `surea11y` supports registering additional rules per-scan via `engineOptions.customRules`. Use `.withCustomRules()` to register one:
137
+
138
+ ```js
139
+ const results = await new A11yCoreBuilder({ page })
140
+ .withCustomRules({
141
+ id: 'my-org-custom-rule',
142
+ meta: { title: 'My custom rule', tags: ['custom'], defaultSeverity: 'serious' },
143
+ // A real, live function is fine here -- .withCustomRules() converts it
144
+ // to a function-source string for you (see below for why that matters).
145
+ runInPage(ctx) {
146
+ const el = ctx.document.querySelector('.my-widget');
147
+ return el ? { outcome: 'fail', occurrences: [{ __node: el }] } : { outcome: 'notApplicable', occurrences: [] };
148
+ }
149
+ })
150
+ .analyze();
151
+ ```
152
+
153
+ 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.
154
+
155
+ 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:
156
+
157
+ ```js
158
+ const results = await new A11yCoreBuilder({ page })
159
+ .withCustomRules([firstRule, secondRule])
160
+ .withCustomRules(thirdRule) // adds a third, doesn't replace the first two
161
+ .analyze();
162
+ ```
163
+
164
+ **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 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.
165
+
166
+ 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`.)
167
+
168
+ ### Element addressing beyond a CSS selector
169
+
170
+ 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.
171
+
172
+ ## TypeScript
173
+
174
+ `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. `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.
175
+
176
+ ## Building another framework binding?
177
+
178
+ See [`../surea11y/docs/BINDING_AUTHORS_GUIDE.md`](../surea11y/docs/BINDING_AUTHORS_GUIDE.md) — a reference for building the *next* binding (Puppeteer, Cypress, ...), written from what this project already worked out: which parity features are engine-level (work through a generic `.options()`/`runOnly` passthrough with zero binding code, including WCAG-version tag filtering) vs. binding-layer (element refs, `reportOnly`-style verbosity filtering, the `page.evaluate()` serialization-boundary caveat that `.withCustomRules()` exists to paper over). It cites this project's `.elementRef()`, `.reportOnly()`, `.frames(true)`, and `.withCustomRules()` by name as the worked examples.
179
+
180
+ Four more bindings have since been built this way (Puppeteer, Selenium, WebdriverIO, Cypress), each copying this project's own scaffolding as a starting point. As of `ROADMAP.md` §5, that scaffolding is no longer duplicated per-project: `A11yCoreBuilder` here (and every sibling's own) extends `A11yCoreBuilderBase` from [`../surea11y-binding-base`](../surea11y-binding-base), a small shared package holding everything that has nothing to do with any particular driver. A *new* binding should depend on that package from the start rather than re-copying this project's `include()`/`exclude()`/etc. by hand.
181
+
182
+ ## Status and what's next
183
+
184
+ See `ROADMAP.md` — it documents what's built, what's verified, the known gaps vs. other accessibility testing tools (prioritized, with reasoning), and exactly what to pick up next. Read it before starting new work here, especially in a fresh chat session that hasn't seen how this project came to exist.
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@surea11y/playwright",
3
+ "version": "0.1.1",
4
+ "description": "Playwright 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-playwright.git"
12
+ },
13
+ "homepage": "https://github.com/rumoroso/surea11y-core-playwright#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/rumoroso/surea11y-core-playwright/issues"
16
+ },
17
+ "engines": {
18
+ "node": ">=18.13.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
+ "playwright": ">=1.0.0"
34
+ },
35
+ "devDependencies": {
36
+ "playwright": "^1.61.1"
37
+ },
38
+ "scripts": {
39
+ "test": "node --test \"tests/**/*.test.js\"",
40
+ "example": "node examples/basic-scan.js",
41
+ "example:e2e": "playwright test examples/playwright-test-example.spec.js"
42
+ }
43
+ }
@@ -0,0 +1,206 @@
1
+ import type { Page, ElementHandle } from 'playwright';
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 Playwright 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
+ * `expect(results.checksResults, formatFailures(results.checksResults)).toEqual([])`.
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,213 @@
1
+ 'use strict';
2
+
3
+ const { runa11yCoreInPage } = require('@surea11y/core');
4
+ const { A11yCoreBuilderBase } = require('@surea11y/binding-base');
5
+
6
+ /**
7
+ * Playwright 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 Playwright's `page.evaluate()` crosses a real serialization
31
+ * boundary), and `_buildEngineArgs()`. This class adds exactly the parts
32
+ * that are genuinely Playwright-specific: `analyze()`'s injection mechanics
33
+ * (including the single-argument `page.evaluate()` wrapper below), frame
34
+ * traversal, and `_attachElementRefs()`. See
35
+ * `../surea11y-binding-base/README.md` for what's shared and why.
36
+ *
37
+ * Opt in to scanning every frame on the page (including cross-origin
38
+ * iframes) via .frames(true):
39
+ *
40
+ * const results = await new A11yCoreBuilder({ page }).frames(true).analyze();
41
+ * // results.topFrame -- same shape as the single-frame case above
42
+ * // results.frames -- array of the same native result shape, one per sub-frame
43
+ *
44
+ * Unlike script-injection-based accessibility engines (which need a
45
+ * postMessage-based protocol, runPartial/finishRun, to reach cross-origin
46
+ * iframes, since they're injected as a plain <script> and are fully subject
47
+ * to the browser's same-origin policy), this doesn't need any surea11y
48
+ * engine support: Playwright
49
+ * drives every frame via CDP at the automation-process level, not as
50
+ * in-page script, so cross-origin frame.evaluate() already just works --
51
+ * verified empirically, see ../ROADMAP.md gap #1 for the full story.
52
+ * Default off, so plain .analyze() keeps returning the single native result
53
+ * object it always has.
54
+ *
55
+ * By default `analyze()` returns every rule's outcome, including
56
+ * `pass`/`notApplicable` -- surea11y's own deliberate "not a
57
+ * violations-only list" design (see surea11y's docs/OUTPUT_SCHEMA.md).
58
+ * Opt in to a lighter payload with `.reportOnly(['fail', 'cantTell'])`,
59
+ * which post-filters `checksResults` by `outcome` (applied per-frame when
60
+ * combined with `.frames(true)`, since `checksResults` lives at
61
+ * `results.topFrame` / each `results.frames[i]` in that shape, not at the
62
+ * top level):
63
+ *
64
+ * const results = await new A11yCoreBuilder({ page })
65
+ * .reportOnly(['fail', 'cantTell'])
66
+ * .analyze();
67
+ *
68
+ * Opt in to a live `ElementHandle` per occurrence (instead of just a CSS
69
+ * selector string) with `.elementRef(true)`, so you can act on the flagged
70
+ * element directly rather than re-resolving its selector yourself:
71
+ *
72
+ * const results = await new A11yCoreBuilder({ page }).elementRef(true).analyze();
73
+ * const [firstFail] = results.checksResults.filter(r => r.outcome === 'fail');
74
+ * await firstFail.occurrences[0].elementHandle.screenshot({ path: 'flagged.png' });
75
+ *
76
+ * Register your own rule(s) for just this scan with
77
+ * `.withCustomRules([...])` (surea11y's `engineOptions.customRules`
78
+ * escape hatch -- see surea11y's docs/ENGINE_OPTIONS.md). Pass a real,
79
+ * live `runInPage`/
80
+ * `applicability` function -- unlike the raw `.options({ customRules })`
81
+ * passthrough, this method converts them to the function-source string
82
+ * surea11y needs on this side of the page.evaluate() JSON boundary for
83
+ * you, so you don't have to remember to call .toString() yourself:
84
+ *
85
+ * const results = await new A11yCoreBuilder({ page })
86
+ * .withCustomRules({
87
+ * id: 'my-org-custom-rule',
88
+ * meta: { title: 'My custom rule', tags: ['custom'] },
89
+ * runInPage(ctx) {
90
+ * const el = ctx.document.querySelector('.my-widget');
91
+ * return el ? { outcome: 'fail', occurrences: [{ __node: el }] } : { outcome: 'notApplicable', occurrences: [] };
92
+ * }
93
+ * })
94
+ * .analyze();
95
+ *
96
+ * Create one builder per scan. This is a mutable object with no reset
97
+ * between analyze() calls: include()/exclude()/withRules()/disableRules()/
98
+ * withTags()/disableTags()/options()/withCustomRules() all push onto or
99
+ * merge into internal state that persists for the instance's lifetime, so
100
+ * calling one of them again before a second analyze() call accumulates on
101
+ * top of the first scan's scope rather than replacing it (intentional for
102
+ * "call include() several times for one scan" -- see above -- but a footgun
103
+ * if you hold one instance across multiple assertions).
104
+ * reportOnly()/frames()/elementRef() are the exception: each call replaces
105
+ * the previous value rather than merging with it.
106
+ */
107
+ class A11yCoreBuilder extends A11yCoreBuilderBase {
108
+ /**
109
+ * @param {{ page: import('playwright').Page, url?: string }} opts
110
+ * `page` must already be navigated to and settled at the URL to scan --
111
+ * this class does not navigate for you.
112
+ */
113
+ constructor({ page, url } = {}) {
114
+ super({ url });
115
+ if (!page || typeof page.evaluate !== 'function') {
116
+ throw new Error('A11yCoreBuilder requires { page } (a Playwright Page, with an .evaluate() method).');
117
+ }
118
+ this._page = page;
119
+ }
120
+
121
+ /**
122
+ * Runs the scan and returns surea11y's native result object.
123
+ * @returns {Promise<object>} see surea11y's docs/OUTPUT_SCHEMA.md
124
+ */
125
+ async analyze() {
126
+ const { contextSelector, engineOptions, runOnly } = this._buildEngineArgs();
127
+
128
+ // Playwright's page.evaluate(fn, arg) (and frame.evaluate(fn, arg), same
129
+ // signature) only accepts ONE arg value -- page.evaluate(fn, a, b, c, d)
130
+ // throws "Too many arguments. If you need to pass more than 1 argument
131
+ // to the function wrap them in an object." (confirmed against a real
132
+ // Playwright page -- see surea11y's own docs/INTEGRATION.md for the
133
+ // full story, including why this differs from Puppeteer's variadic
134
+ // form). runa11yCoreInPage itself takes 4 positional args, so wrap it in
135
+ // a single-arg function that destructures one options object, embedding
136
+ // runa11yCoreInPage's own source via .toString() so the wrapper stays
137
+ // fully self-contained once serialized into the page (it has zero free
138
+ // vars of its own -- see surea11y's docs/RULE_AUTHORING.md for why that
139
+ // matters).
140
+ const wrapperSource = `(args) => {
141
+ const runa11yCoreInPage = ${runa11yCoreInPage.toString()};
142
+ return runa11yCoreInPage(args.url, args.contextSelector, args.engineOptions, args.runOnly);
143
+ }`;
144
+ // eslint-disable-next-line no-eval
145
+ const wrapperFn = eval(wrapperSource);
146
+
147
+ // A Playwright Page and a Frame both expose the same .evaluate(fn, arg)
148
+ // and .url() shape, so this works unchanged for either.
149
+ const runInFrame = async (frameOrPage) => {
150
+ const frameUrl = this._url || (typeof frameOrPage.url === 'function' ? frameOrPage.url() : null);
151
+ const result = await frameOrPage.evaluate(wrapperFn, {
152
+ url: frameUrl,
153
+ contextSelector,
154
+ engineOptions,
155
+ runOnly
156
+ });
157
+ return this._elementRef ? this._attachElementRefs(frameOrPage, result) : result;
158
+ };
159
+
160
+ if (!this._scanFrames) {
161
+ return this._applyReportOnly(await runInFrame(this._page));
162
+ }
163
+
164
+ const mainFrame = this._page.mainFrame();
165
+ const topFrame = this._applyReportOnly(await runInFrame(mainFrame));
166
+
167
+ // page.frames() includes the main frame itself -- exclude it here since
168
+ // it's already covered by topFrame above, so callers don't have to
169
+ // de-duplicate it themselves out of the frames array.
170
+ const subFrames = this._page.frames().filter((f) => f !== mainFrame);
171
+ const frames = [];
172
+ for (const frame of subFrames) {
173
+ try {
174
+ frames.push(this._applyReportOnly(await runInFrame(frame)));
175
+ } catch (e) {
176
+ // A frame can detach/navigate away mid-scan, or be a sandboxed
177
+ // frame the browser blocks scripting in -- don't let one bad frame
178
+ // abort the whole multi-frame scan; report it and keep going.
179
+ frames.push({
180
+ url: (typeof frame.url === 'function' ? frame.url() : null),
181
+ error: (e && e.message) || String(e)
182
+ });
183
+ }
184
+ }
185
+
186
+ return { topFrame, frames };
187
+ }
188
+
189
+ /**
190
+ * Resolves occurrence.selector to a live ElementHandle for every
191
+ * fail/cantTell occurrence, scoped to frameOrPage's own document (a
192
+ * Playwright Page and Frame both expose the same .$(selector) shape).
193
+ * Mutates and returns the same result object -- it's a fresh object from
194
+ * this scan, not shared external state.
195
+ */
196
+ async _attachElementRefs(frameOrPage, result) {
197
+ if (!Array.isArray(result.checksResults)) return result;
198
+ for (const check of result.checksResults) {
199
+ if (!Array.isArray(check.occurrences) || !check.occurrences.length) continue;
200
+ for (const occurrence of check.occurrences) {
201
+ // Most occurrences carry a concrete element selector, but a page-wide
202
+ // finding with no single target element (e.g. some `manual`/cantTell
203
+ // rules) can carry "" -- not every occurrence resolves to one element,
204
+ // so leave elementHandle null rather than passing "" to .$() (which
205
+ // throws, it's not a valid CSS selector).
206
+ occurrence.elementHandle = occurrence.selector ? await frameOrPage.$(occurrence.selector) : null;
207
+ }
208
+ }
209
+ return result;
210
+ }
211
+ }
212
+
213
+ 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-playwright/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 };