@surea11y/core 1.3.0 → 1.4.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.
Files changed (163) hide show
  1. package/CHANGELOG.md +46 -2
  2. package/README.md +109 -35
  3. package/bin/surea11y-core.js +20 -0
  4. package/docs/API_STABILITY.md +26 -0
  5. package/docs/CI_INTEGRATIONS.md +7 -7
  6. package/docs/ENGINE_OPTIONS.md +1 -1
  7. package/docs/I18N.md +12 -9
  8. package/docs/INTEGRATION.md +1 -1
  9. package/docs/LIMITATIONS.md +1 -1
  10. package/docs/REPORT.md +1 -1
  11. package/package.json +50 -16
  12. package/src/baseline.js +0 -0
  13. package/src/checks/automatic/area-alt-present.js +4 -6
  14. package/src/checks/automatic/aria-allowed-attr.js +15 -51
  15. package/src/checks/automatic/aria-allowed-role.js +2 -0
  16. package/src/checks/automatic/aria-braille-equivalent.js +2 -0
  17. package/src/checks/automatic/aria-conditional-attr.js +8 -7
  18. package/src/checks/automatic/aria-deprecated-role.js +4 -3
  19. package/src/checks/automatic/aria-hidden-body.js +6 -4
  20. package/src/checks/automatic/aria-hidden-focus.js +12 -13
  21. package/src/checks/automatic/aria-prohibited-attr.js +98 -105
  22. package/src/checks/automatic/aria-prohibited-children.js +56 -87
  23. package/src/checks/automatic/aria-required-attr.js +6 -7
  24. package/src/checks/automatic/aria-required-children.js +7 -10
  25. package/src/checks/automatic/aria-required-parent.js +20 -25
  26. package/src/checks/automatic/aria-role-name-present.js +2 -0
  27. package/src/checks/automatic/aria-roles-valid.js +2 -0
  28. package/src/checks/automatic/aria-valid-attr-value.js +18 -15
  29. package/src/checks/automatic/aria-valid-attr.js +2 -0
  30. package/src/checks/automatic/autocomplete-valid.js +2 -0
  31. package/src/checks/automatic/avoid-inline-spacing.js +3 -2
  32. package/src/checks/automatic/binary-control-name-present.js +2 -0
  33. package/src/checks/automatic/button-name-present.js +7 -7
  34. package/src/checks/automatic/bypass-blocks-present.js +9 -7
  35. package/src/checks/automatic/canvas-text-alternative-present.js +2 -0
  36. package/src/checks/automatic/combobox-name-present.js +2 -0
  37. package/src/checks/automatic/contrast-computable.js +2 -0
  38. package/src/checks/automatic/contrast-enhanced.js +2 -0
  39. package/src/checks/automatic/contrast-minimum.js +2 -0
  40. package/src/checks/automatic/css-orientation-lock.js +21 -27
  41. package/src/checks/automatic/definition-list-children-valid.js +6 -6
  42. package/src/checks/automatic/deprecated-elements-not-used.js +4 -2
  43. package/src/checks/automatic/dialog-name-present.js +10 -10
  44. package/src/checks/automatic/dlitem-parent-valid.js +2 -0
  45. package/src/checks/automatic/duplicate-id-aria.js +4 -3
  46. package/src/checks/automatic/embed-text-alternative-present.js +2 -0
  47. package/src/checks/automatic/form-control-programmatic-label-present.js +2 -0
  48. package/src/checks/automatic/form-control-single-label.js +6 -7
  49. package/src/checks/automatic/html-xml-lang-mismatch.js +2 -0
  50. package/src/checks/automatic/iframe-focusable-content.js +246 -18
  51. package/src/checks/automatic/iframe-name-present.js +2 -0
  52. package/src/checks/automatic/iframe-title-unique.js +3 -1
  53. package/src/checks/automatic/img-alt-present.js +7 -9
  54. package/src/checks/automatic/input-image-alt-present.js +4 -6
  55. package/src/checks/automatic/label-in-name.js +15 -19
  56. package/src/checks/automatic/language-page-present.js +2 -0
  57. package/src/checks/automatic/link-in-text-block.js +2 -0
  58. package/src/checks/automatic/link-name-present.js +2 -0
  59. package/src/checks/automatic/list-children-valid.js +14 -24
  60. package/src/checks/automatic/listbox-name-present.js +2 -0
  61. package/src/checks/automatic/listitem-parent-valid.js +30 -7
  62. package/src/checks/automatic/menuitem-name-present.js +2 -0
  63. package/src/checks/automatic/meta-refresh-no-exceptions.js +4 -4
  64. package/src/checks/automatic/meta-refresh-timing-absent.js +2 -0
  65. package/src/checks/automatic/meta-viewport-zoom-enabled.js +2 -0
  66. package/src/checks/automatic/meter-name-present.js +4 -3
  67. package/src/checks/automatic/nested-interactive-controls-absent.js +27 -5
  68. package/src/checks/automatic/object-text-alternative-present.js +2 -0
  69. package/src/checks/automatic/option-name-present.js +2 -0
  70. package/src/checks/automatic/page-title-present.js +2 -0
  71. package/src/checks/automatic/progressbar-name-present.js +8 -10
  72. package/src/checks/automatic/role-img-alt-present.js +4 -4
  73. package/src/checks/automatic/searchbox-name-present.js +2 -0
  74. package/src/checks/automatic/server-side-image-map-absent.js +4 -3
  75. package/src/checks/automatic/slider-name-present.js +2 -0
  76. package/src/checks/automatic/spinbutton-name-present.js +2 -0
  77. package/src/checks/automatic/summary-name-present.js +2 -0
  78. package/src/checks/automatic/svg-image-text-alternative-present.js +2 -0
  79. package/src/checks/automatic/svg-text-alternative-present.js +17 -5
  80. package/src/checks/automatic/tab-name-present.js +2 -0
  81. package/src/checks/automatic/table-headers-attr-valid.js +3 -2
  82. package/src/checks/automatic/table-th-has-data-cells.js +2 -0
  83. package/src/checks/automatic/target-size-minimum.js +5 -0
  84. package/src/checks/automatic/td-has-header.js +24 -1
  85. package/src/checks/automatic/textbox-name-present.js +2 -0
  86. package/src/checks/automatic/tooltip-name-present.js +2 -0
  87. package/src/checks/automatic/treeitem-name-present.js +2 -0
  88. package/src/checks/automatic/valid-lang.js +2 -0
  89. package/src/checks/automatic/video-poster-text-alternative-present.js +2 -0
  90. package/src/checks/manual/accesskeys-manual.js +3 -1
  91. package/src/checks/manual/area-alt-decorative-manual.js +2 -0
  92. package/src/checks/manual/area-alt-quality-manual.js +2 -0
  93. package/src/checks/manual/aria-checked-state-mismatch-manual.js +14 -23
  94. package/src/checks/manual/aria-text-manual.js +6 -5
  95. package/src/checks/manual/canvas-text-alternative-quality-manual.js +2 -0
  96. package/src/checks/manual/css-hidden-focus.js +184 -9
  97. package/src/checks/manual/embed-text-alternative-quality-manual.js +18 -13
  98. package/src/checks/manual/empty-heading-manual.js +17 -17
  99. package/src/checks/manual/empty-table-header-manual.js +52 -25
  100. package/src/checks/manual/focus-order-semantics-manual.js +16 -4
  101. package/src/checks/manual/form-control-programmatic-label-quality-manual.js +2 -0
  102. package/src/checks/manual/heading-order-manual.js +28 -1
  103. package/src/checks/manual/identical-links-same-purpose-manual.js +2 -0
  104. package/src/checks/manual/image-redundant-alt-manual.js +21 -1
  105. package/src/checks/manual/img-alt-decorative-manual.js +2 -0
  106. package/src/checks/manual/img-alt-quality-manual.js +2 -0
  107. package/src/checks/manual/input-image-alt-decorative-manual.js +2 -0
  108. package/src/checks/manual/input-image-alt-quality-manual.js +2 -0
  109. package/src/checks/manual/label-title-only-manual.js +29 -22
  110. package/src/checks/manual/landmark-banner-is-top-level-manual.js +54 -47
  111. package/src/checks/manual/landmark-contentinfo-is-top-level-manual.js +42 -26
  112. package/src/checks/manual/landmark-main-is-top-level-manual.js +41 -24
  113. package/src/checks/manual/landmark-no-duplicate-banner-manual.js +16 -23
  114. package/src/checks/manual/landmark-no-duplicate-contentinfo-manual.js +14 -21
  115. package/src/checks/manual/landmark-no-duplicate-main-manual.js +10 -13
  116. package/src/checks/manual/landmark-one-main-manual.js +12 -23
  117. package/src/checks/manual/landmark-unique-manual.js +37 -52
  118. package/src/checks/manual/link-name-quality-manual.js +2 -0
  119. package/src/checks/manual/media-transcript-present-manual.js +2 -0
  120. package/src/checks/manual/meta-viewport-large-manual.js +3 -1
  121. package/src/checks/manual/mouse-only-event-handlers-manual.js +2 -0
  122. package/src/checks/manual/no-autoplay-audio-manual.js +2 -0
  123. package/src/checks/manual/object-text-alternative-quality-manual.js +2 -0
  124. package/src/checks/manual/p-as-heading-manual.js +2 -0
  125. package/src/checks/manual/page-has-heading-one-manual.js +12 -11
  126. package/src/checks/manual/page-title-patterns-manual.js +2 -0
  127. package/src/checks/manual/presentation-role-conflict-manual.js +51 -37
  128. package/src/checks/manual/region-manual.js +27 -36
  129. package/src/checks/manual/scope-attr-valid-manual.js +3 -1
  130. package/src/checks/manual/scrollable-region-focusable-manual.js +2 -0
  131. package/src/checks/manual/skip-link-manual.js +7 -6
  132. package/src/checks/manual/svg-text-alternative-quality-manual.js +2 -0
  133. package/src/checks/manual/tabindex-manual.js +3 -1
  134. package/src/checks/manual/table-duplicate-name-manual.js +5 -4
  135. package/src/checks/manual/table-fake-caption-manual.js +24 -3
  136. package/src/checks/manual/video-caption-manual.js +2 -0
  137. package/src/checks/manual-review.js +2 -0
  138. package/src/core.js +6772 -2158
  139. package/src/index.js +2 -0
  140. package/src/report.js +51 -9
  141. package/src/sarif.js +18 -3
  142. package/surea11y.browser.js +2731 -999
  143. package/bin/core.js +0 -473
  144. package/docs/CLI.md +0 -128
  145. package/src/catalogs/composites.wcag.js +0 -454
  146. package/src/checks/rules-and-tags.full.csv +0 -19
  147. package/src/checks/rules-and-tags.full.json +0 -259
  148. package/src/core/aria-helpers.js +0 -1211
  149. package/src/core/contrast-helpers.js +0 -1302
  150. package/src/core/dom-helpers.js +0 -4493
  151. package/src/core/dom-runner.js +0 -787
  152. package/src/core/frame-messaging.js +0 -261
  153. package/src/core/frame-scan.js +0 -190
  154. package/src/core/rollup-composites.js +0 -127
  155. package/src/core/rule-meta.js +0 -176
  156. package/src/coverage/wcag-facets.js +0 -1079
  157. package/src/coverage/wcag-version-map.js +0 -84
  158. package/src/i18n/en.js +0 -1228
  159. package/src/i18n/fr.js +0 -1185
  160. package/src/policy/contracts.js +0 -18
  161. package/src/policy/resolvePolicy.js +0 -59
  162. package/src/policy/schemas/engine-options.schema.json +0 -103
  163. package/src/policy/schemas/policy-contract.schema.json +0 -40
@@ -1,787 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * DOM runner implementation.
5
- *
6
- * IMPORTANT:
7
- * - This function is inlined into generated core.js (Node + in-page runner).
8
- * - It intentionally references shared runtime helpers that core.js defines:
9
- * resolvePolicy, POLICY_CONTRACTS, resolveRuleDefI18n, ruleMatchesRunOnly,
10
- * normalizeRuleResult, normalizeLocale, createDomHelpers, normalizeSelectorList,
11
- * resolveContextRoots (src/core/dom-helpers.js -- also used by frame-scan.js),
12
- * normalizeRuleMeta (src/core/rule-meta.js -- used for engineOptions.customRules).
13
- */
14
-
15
- /* global resolvePolicy, POLICY_CONTRACTS, resolveRuleDefI18n, ruleMatchesRunOnly,
16
- normalizeRuleResult, normalizeLocale, createDomHelpers, normalizeSelectorList,
17
- resolveContextRoots, normalizeRuleMeta */
18
-
19
- function runCore(
20
- pageUrl,
21
- contextSelector,
22
- engineOptions,
23
- runOnly,
24
- CHECK_DEFS,
25
- RULE_IMPLS,
26
- ENGINE_TAG,
27
- SCHEMA_VERSION,
28
- COMPOSITE_RULES
29
- ) {
30
- // Normalize contrast options without mutating caller-provided engineOptions.
31
- function __normalizeContrastOptions(engineOptions2) {
32
- const eo = engineOptions2 && typeof engineOptions2 === 'object' ? engineOptions2 : {};
33
- const c = eo.contrast && typeof eo.contrast === 'object' ? eo.contrast : {};
34
- const mode = c.mode === 'auditorAssist' ? 'auditorAssist' : 'strictConformance';
35
- const rootCanvasFallback =
36
- typeof c.rootCanvasFallback === 'string' && c.rootCanvasFallback.trim()
37
- ? c.rootCanvasFallback.trim()
38
- : '#ffffff';
39
- return { mode, rootCanvasFallback };
40
- }
41
-
42
- const engineOptionsResolved =
43
- engineOptions && typeof engineOptions === 'object'
44
- ? { ...engineOptions, contrast: __normalizeContrastOptions(engineOptions) }
45
- : { contrast: __normalizeContrastOptions(null) };
46
-
47
- const policy = resolvePolicy(POLICY_CONTRACTS, engineOptionsResolved);
48
-
49
- // contextSelector accepts a single selector string (which may itself be a
50
- // comma-separated selector list -- ordinary CSS union semantics) OR an
51
- // array of selector strings for scanning multiple, possibly disjoint
52
- // regions in one run (a widely-used reference engine's multi-.include()
53
- // capability has no equivalent here otherwise). Both forms resolve via querySelectorAll,
54
- // not querySelector -- previously a single string only ever scanned its
55
- // FIRST match, silently ignoring the rest if it happened to match more
56
- // than one element. That was a real gap, not a deliberate "one region
57
- // only" design: switched to querySelectorAll for both forms so
58
- // "matches this selector" actually means all matches, consistently.
59
- // Shared with frame-scan.js (same resolution used to discover which
60
- // child <iframe>/<frame> elements fall within the same scan scope).
61
- const { ctxSelector, roots } = resolveContextRoots(document, contextSelector);
62
-
63
- // Default on: opt OUT with `includeShadowDom: false`, not opt in.
64
- const includeShadowDom = !(
65
- engineOptionsResolved && engineOptionsResolved.includeShadowDom === false
66
- );
67
- // Default off: hidden/collapsed content is excluded from rule evaluation
68
- // unless the caller explicitly opts in.
69
- const includeHiddenElements = !!(
70
- engineOptionsResolved && engineOptionsResolved.includeHiddenElements === true
71
- );
72
- const excludeSelectors = normalizeSelectorList(
73
- engineOptionsResolved && engineOptionsResolved.excludeSelectors
74
- );
75
- // Default off: explicit opt-in for "this scan target was never meant to
76
- // represent a real page" -- see helpers.isWholeDocumentScope().
77
- const fragment = !!(engineOptionsResolved && engineOptionsResolved.fragment === true);
78
-
79
- const url = pageUrl || (document.location && document.location.href) || null;
80
- const title = document.title || null;
81
- // Deterministic timestamp: only use host-provided value (no time-based logic).
82
- const timestamp =
83
- engineOptionsResolved &&
84
- typeof engineOptionsResolved.timestamp === 'string' &&
85
- engineOptionsResolved.timestamp.trim()
86
- ? engineOptionsResolved.timestamp.trim()
87
- : null;
88
-
89
- // createDomHelpers()/createContrastHelpers() persist their element-keyed
90
- // caches (outerHtmlCache, selectorCache, etc.) on window.__a11ycoreSharedCache
91
- // so multiple helper instances created *within this run* can share them
92
- // deterministically. But a window/document is frequently reused across
93
- // SEPARATE runs -- e.g. Jest's jsdom environment creates one window per
94
- // test file, and mutating document.body between it() blocks is standard.
95
- // Those caches are keyed by element reference, not content, so a run that
96
- // reuses an already-cached element (document.body never changes identity)
97
- // would otherwise read stale data cached by an earlier, unrelated run on
98
- // the same window. Clearing at the start of every run keeps sharing scoped
99
- // to "this run" as intended, without leaking across runs.
100
- try {
101
- if (window && window.__a11ycoreSharedCache) window.__a11ycoreSharedCache = {};
102
- } catch {}
103
-
104
- const sharedHelpers = createDomHelpers({
105
- document,
106
- window,
107
- root: roots,
108
- includeShadowDom,
109
- includeHiddenElements,
110
- excludeSelectors,
111
- fragment,
112
- // Optional perf counters (bench/debug only). Deterministic and per-run.
113
- perfStats: !!(engineOptionsResolved && engineOptionsResolved.perfStats)
114
- });
115
-
116
- const profileRules = !!(engineOptionsResolved && engineOptionsResolved.profileRules);
117
- const ruleTimings = profileRules ? Object.create(null) : null;
118
-
119
- function nowMs() {
120
- // performance.now() if available, else Date.now()
121
- try {
122
- if (
123
- typeof performance !== 'undefined' &&
124
- performance &&
125
- typeof performance.now === 'function'
126
- ) {
127
- return performance.now();
128
- }
129
- } catch (e) {}
130
- return Date.now();
131
- }
132
-
133
- // =========================
134
- // Probes (optional evidence fed by the host app)
135
- // Keep deterministic + serializable + no-throws.
136
- // =========================
137
- function sanitizeProbeValue(v, depth) {
138
- // depth-bounded, JSON-safe sanitizer
139
- if (depth <= 0) return null;
140
- if (v == null) return null;
141
-
142
- const t = typeof v;
143
- if (t === 'string') return v.length > 2000 ? v.slice(0, 2000) : v;
144
- if (t === 'number') return Number.isFinite(v) ? v : null;
145
- if (t === 'boolean') return v;
146
- if (t === 'function') return null;
147
-
148
- if (Array.isArray(v)) {
149
- // cap arrays to avoid huge payloads
150
- const out = [];
151
- const n = Math.min(v.length, 200);
152
- for (let i = 0; i < n; i++) out.push(sanitizeProbeValue(v[i], depth - 1));
153
- return out;
154
- }
155
-
156
- if (t === 'object') {
157
- const out = {};
158
- const keys = Object.keys(v).sort();
159
- // cap object keys
160
- const n = Math.min(keys.length, 50);
161
- for (let i = 0; i < n; i++) {
162
- const k = keys[i];
163
- // only allow string keys
164
- if (typeof k !== 'string') continue;
165
- out[k] = sanitizeProbeValue(v[k], depth - 1);
166
- }
167
- return out;
168
- }
169
-
170
- return null;
171
- }
172
-
173
- let probes;
174
- try {
175
- const rawProbes =
176
- engineOptionsResolved && typeof engineOptionsResolved.probes === 'object'
177
- ? engineOptionsResolved.probes
178
- : null;
179
- probes = rawProbes ? sanitizeProbeValue(rawProbes, 6) : null;
180
- if (!probes || typeof probes !== 'object' || Array.isArray(probes)) probes = null;
181
- } catch (e) {
182
- probes = null;
183
- }
184
-
185
- // =========================
186
- // Runtime custom rules (engineOptions.customRules)
187
- // =========================
188
- // Same module shape as an internal rule file: { id, meta, runInPage, applicability?, data? }.
189
- // runInPage/applicability may be a real function (fine for same-realm/Node/jsdom callers)
190
- // or a function-source string (required for cross-realm callers, e.g. a Playwright
191
- // page.evaluate(runa11yCoreInPage, { engineOptions }) call -- engineOptions crosses a
192
- // structured-clone/JSON boundary there, so a live Function reference can't survive it,
193
- // but a string can). Reconstructed via `new Function`, matching exactly how build-core.js
194
- // already embeds each built-in rule's own runInPage source into the in-page runner.
195
- // Scan-scoped only (not added to the static CHECK_DEFS/getRulesCatalog() catalog) --
196
- // matches surea11y's existing "fresh engineOptions per call, no mutable global config"
197
- // design (see ROADMAP.md), rather than a widely-used reference engine's stateful global configure().
198
- let effectiveCheckDefs = CHECK_DEFS;
199
- let effectiveRuleImpls = RULE_IMPLS;
200
- let overriddenBuiltinIds = [];
201
- const rawCustomRules = Array.isArray(engineOptionsResolved.customRules)
202
- ? engineOptionsResolved.customRules
203
- : [];
204
- if (rawCustomRules.length) {
205
- function reviveRuleFn(value) {
206
- if (typeof value === 'function') return value;
207
- if (typeof value === 'string' && value.trim()) {
208
- try {
209
- const fn = new Function('return (' + value + ')')();
210
- if (typeof fn === 'function') return fn;
211
- } catch (e) {
212
- return null;
213
- }
214
- }
215
- return null;
216
- }
217
-
218
- const extraDefsById = new Map();
219
- const extraImpls = {};
220
- for (const c of rawCustomRules) {
221
- if (!c || typeof c !== 'object') continue;
222
- const ruleId = typeof c.id === 'string' ? c.id.trim() : '';
223
- if (!ruleId) continue;
224
- const runFn = reviveRuleFn(c.runInPage);
225
- if (typeof runFn !== 'function') continue; // invalid custom rule: skipped, not a crash
226
-
227
- const applicabilityFn = reviveRuleFn(c.applicability);
228
- const normalizedMeta = normalizeRuleMeta(ruleId, ruleId, c.meta, ENGINE_TAG);
229
-
230
- // Overriding a built-in rule id is supported (see docs/ENGINE_OPTIONS.md),
231
- // but a same-named custom rule is just as likely to be an accidental
232
- // collision (a generic name like "region" or "tabindex" picked without
233
- // realizing it's already a built-in id) as a deliberate override -- so
234
- // surface it either way rather than silently swapping the rule out.
235
- if (CHECK_DEFS.some((d) => d && d.ruleId === ruleId)) {
236
- overriddenBuiltinIds.push(ruleId);
237
- }
238
-
239
- extraDefsById.set(ruleId, {
240
- ruleId,
241
- title: normalizedMeta.title,
242
- description: normalizedMeta.description,
243
- i18n: normalizedMeta.i18n,
244
- helpUrl: normalizedMeta.helpUrl,
245
- tags: normalizedMeta.tags,
246
- wcagSc: normalizedMeta.wcagSc,
247
- normativeMappings: normalizedMeta.normativeMappings,
248
- defaultSeverity: normalizedMeta.defaultSeverity,
249
- defaultConfidence: normalizedMeta.defaultConfidence,
250
- type: normalizedMeta.type,
251
- coverage: normalizedMeta.coverage,
252
- data: c.data === undefined ? null : c.data,
253
- ruleInterfaceVersion: normalizedMeta.ruleInterfaceVersion,
254
- ruleVersion: normalizedMeta.ruleVersion,
255
- normative: normalizedMeta.normative,
256
- atomic: normalizedMeta.atomic,
257
- deprecated: normalizedMeta.deprecated,
258
- deprecation: normalizedMeta.deprecation,
259
- category: normalizedMeta.category,
260
- standard: normalizedMeta.standard,
261
- applicability: normalizedMeta.applicability,
262
- expectation: normalizedMeta.expectation,
263
- references: normalizedMeta.references,
264
- requirements: normalizedMeta.requirements,
265
- mappings: normalizedMeta.mappings
266
- });
267
- extraImpls[ruleId] = { run: runFn, applicability: applicabilityFn || null };
268
- }
269
-
270
- if (extraDefsById.size) {
271
- effectiveCheckDefs = CHECK_DEFS.filter((d) => !extraDefsById.has(d.ruleId)).concat(
272
- Array.from(extraDefsById.values())
273
- );
274
- effectiveRuleImpls = { ...RULE_IMPLS, ...extraImpls };
275
- }
276
-
277
- if (overriddenBuiltinIds.length) {
278
- try {
279
- console.warn(
280
- '[surea11y] customRules overriding built-in rule id(s) for this scan: ' +
281
- overriddenBuiltinIds.join(', ')
282
- );
283
- } catch (e) {}
284
- }
285
- }
286
-
287
- const checksResults = [];
288
-
289
- for (const def of effectiveCheckDefs) {
290
- const t0 = ruleTimings ? nowMs() : 0;
291
- const defResolved = resolveRuleDefI18n(def, engineOptionsResolved);
292
- if (!ruleMatchesRunOnly(defResolved, runOnly, ENGINE_TAG)) continue;
293
-
294
- const implEntry = effectiveRuleImpls[defResolved.ruleId];
295
- const impl = implEntry && typeof implEntry.run === 'function' ? implEntry.run : null;
296
- const applicabilityFn =
297
- implEntry && typeof implEntry.applicability === 'function' ? implEntry.applicability : null;
298
- if (typeof impl !== 'function') continue;
299
-
300
- const ruleConfig =
301
- engineOptionsResolved &&
302
- engineOptionsResolved.rules &&
303
- engineOptionsResolved.rules[defResolved.ruleId]
304
- ? engineOptionsResolved.rules[defResolved.ruleId]
305
- : null;
306
-
307
- // Rule-scoped excludeSelectors (engineOptions.rules[ruleId].excludeSelectors)
308
- // apply on top of the global excludeSelectors for exactly this rule's
309
- // applicability check + run, then are cleared once this rule is done.
310
- // Safe because rule execution below is synchronous and one rule at a
311
- // time -- sharedHelpers is reused across all rules in this loop.
312
- if (typeof sharedHelpers.__setActiveRuleExcludeSelectors === 'function') {
313
- sharedHelpers.__setActiveRuleExcludeSelectors(ruleConfig && ruleConfig.excludeSelectors);
314
- }
315
-
316
- const ctx = {
317
- document,
318
- window,
319
- root: roots,
320
- rule: defResolved,
321
- config: ruleConfig,
322
- helpers: sharedHelpers,
323
- engineTag: ENGINE_TAG,
324
- contextSelector: ctxSelector,
325
- engineOptions:
326
- engineOptionsResolved && typeof engineOptionsResolved === 'object'
327
- ? engineOptionsResolved
328
- : {},
329
-
330
- // Optional evidence channel provided by host app
331
- inputs: {
332
- probes
333
- }
334
- };
335
-
336
- if (typeof applicabilityFn === 'function') {
337
- let applicable = true;
338
- try {
339
- const res = applicabilityFn(ctx);
340
- if (typeof res === 'boolean') applicable = res;
341
- else if (res && typeof res === 'object' && typeof res.applicable === 'boolean')
342
- applicable = res.applicable;
343
- } catch (err) {
344
- const raw = {
345
- outcome: 'cantTell',
346
- occurrences: [],
347
- error: String(err && err.message ? err.message : err),
348
- engineOptions: {
349
- ...(ctx.engineOptions || {}),
350
- locale: normalizeLocale(engineOptionsResolved && engineOptionsResolved.locale)
351
- }
352
- };
353
- checksResults.push(
354
- normalizeRuleResult(defResolved, raw, SCHEMA_VERSION, policy, sharedHelpers)
355
- );
356
- if (ruleTimings)
357
- ruleTimings[defResolved.ruleId] = (ruleTimings[defResolved.ruleId] || 0) + (nowMs() - t0);
358
- continue;
359
- }
360
-
361
- if (!applicable) {
362
- const raw = {
363
- outcome: 'notApplicable',
364
- occurrences: [],
365
- engineOptions: {
366
- ...(ctx.engineOptions || {}),
367
- locale: normalizeLocale(engineOptionsResolved && engineOptionsResolved.locale)
368
- }
369
- };
370
- checksResults.push(
371
- normalizeRuleResult(defResolved, raw, SCHEMA_VERSION, policy, sharedHelpers)
372
- );
373
- if (ruleTimings)
374
- ruleTimings[defResolved.ruleId] = (ruleTimings[defResolved.ruleId] || 0) + (nowMs() - t0);
375
- continue;
376
- }
377
- }
378
-
379
- let result;
380
- try {
381
- result = impl(ctx);
382
- } catch (err) {
383
- result = {
384
- outcome: 'cantTell',
385
- occurrences: [],
386
- error: String(err && err.message ? err.message : err),
387
- engineOptions: {
388
- ...(ctx.engineOptions || {}),
389
- locale: normalizeLocale(engineOptionsResolved && engineOptionsResolved.locale)
390
- }
391
- };
392
- }
393
-
394
- if (!result || typeof result !== 'object') {
395
- if (ruleTimings)
396
- ruleTimings[defResolved.ruleId] = (ruleTimings[defResolved.ruleId] || 0) + (nowMs() - t0);
397
- continue;
398
- }
399
- if (!result.engineOptions) {
400
- result.engineOptions = {
401
- ...(ctx.engineOptions || {}),
402
- locale: normalizeLocale(engineOptionsResolved && engineOptionsResolved.locale)
403
- };
404
- }
405
- checksResults.push(
406
- normalizeRuleResult(defResolved, result, SCHEMA_VERSION, policy, sharedHelpers)
407
- );
408
- if (ruleTimings)
409
- ruleTimings[defResolved.ruleId] = (ruleTimings[defResolved.ruleId] || 0) + (nowMs() - t0);
410
- }
411
-
412
- // Composite rollups below carry no occurrences/nodes of their own, so
413
- // they never exercise rule-scoped excludes -- but clear the "active
414
- // rule" state on sharedHelpers regardless, so nothing after this point
415
- // (composite aggregation, perf stats) can observe a stale rule's excludes.
416
- if (typeof sharedHelpers.__setActiveRuleExcludeSelectors === 'function') {
417
- sharedHelpers.__setActiveRuleExcludeSelectors(null);
418
- }
419
-
420
- // =========================
421
- // Composite rule aggregation (data-only rollups)
422
- // =========================
423
- const rulesResults = [];
424
- try {
425
- const composites = Array.isArray(COMPOSITE_RULES) ? COMPOSITE_RULES : [];
426
-
427
- // Determine target conformance level from runOnly.tags (already normalized by caller)
428
- const LEVEL_RANK = { A: 1, AA: 2, AAA: 3 };
429
-
430
- function inferTargetLevelFromRunOnly(runOnly2) {
431
- const tags = runOnly2 && Array.isArray(runOnly2.tags) ? runOnly2.tags : [];
432
- // tags are already lowercase
433
- if (tags.includes('wcag2aaa') || tags.includes('wcag22aaa') || tags.includes('wcag21aaa'))
434
- return 'AAA';
435
- if (tags.includes('wcag2aa') || tags.includes('wcag22aa') || tags.includes('wcag21aa'))
436
- return 'AA';
437
- if (tags.includes('wcag2a') || tags.includes('wcag22a') || tags.includes('wcag21a'))
438
- return 'A';
439
- return null; // if not specified, don't filter composites (back-compat)
440
- }
441
-
442
- function normalizeLevel(s) {
443
- const v = typeof s === 'string' ? s.trim().toUpperCase() : '';
444
- return v === 'A' || v === 'AA' || v === 'AAA' ? v : null;
445
- }
446
-
447
- function isAllowedByTargetLevel(compositeLevel, targetLevel) {
448
- if (!targetLevel) return true;
449
- const c = LEVEL_RANK[compositeLevel];
450
- const t = LEVEL_RANK[targetLevel];
451
- if (!c || !t) return false; // unknown level => safest: exclude
452
- return c <= t;
453
- }
454
-
455
- const targetLevel = inferTargetLevelFromRunOnly(runOnly);
456
-
457
- // Severity rollup (deterministic)
458
- const SEVERITY_RANK = { minor: 1, moderate: 2, serious: 3, critical: 4 };
459
-
460
- function normalizeSeverity(s) {
461
- const v = typeof s === 'string' ? s.trim().toLowerCase() : '';
462
- return SEVERITY_RANK[v] ? v : null;
463
- }
464
-
465
- function maxSeverity(a, b) {
466
- if (!a) return b || null;
467
- if (!b) return a || null;
468
- return SEVERITY_RANK[b] > SEVERITY_RANK[a] ? b : a;
469
- }
470
-
471
- // Index atomic results by ruleId (deterministic)
472
- const byRuleId = Object.create(null);
473
- for (const rr of checksResults) {
474
- if (rr && typeof rr === 'object' && typeof rr.ruleId === 'string' && rr.ruleId) {
475
- byRuleId[rr.ruleId] = rr;
476
- }
477
- }
478
-
479
- function isNonEmptyString(s) {
480
- return typeof s === 'string' && !!s.trim();
481
- }
482
-
483
- function buildCompositeDef(entry) {
484
- if (!entry || typeof entry !== 'object') return null;
485
-
486
- const ruleId = isNonEmptyString(entry.id) ? entry.id.trim() : String(entry.id || '').trim();
487
- if (!ruleId) return null;
488
-
489
- const metaIn =
490
- entry.meta && typeof entry.meta === 'object' && !Array.isArray(entry.meta)
491
- ? entry.meta
492
- : {};
493
-
494
- const titleKey =
495
- typeof metaIn.titleKey === 'string' && metaIn.titleKey.trim() ? metaIn.titleKey.trim() : '';
496
- const descriptionKey =
497
- typeof metaIn.descriptionKey === 'string' && metaIn.descriptionKey.trim()
498
- ? metaIn.descriptionKey.trim()
499
- : '';
500
-
501
- const wcagSc = Array.isArray(metaIn.wcagSc)
502
- ? metaIn.wcagSc
503
- .map(String)
504
- .map((s) => s.trim())
505
- .filter(Boolean)
506
- : [];
507
-
508
- const tags = [];
509
- tags.push(String(ENGINE_TAG || 'a11ycore').toLowerCase());
510
- tags.push('composite');
511
-
512
- // Fixed WCAG-version-introduction lists (2.1 and 2.2 additions only -- every other
513
- // SC, including all pre-2.1 ones, is WCAG 2.0 baseline). Keep in sync with
514
- // src/coverage/wcag-version-map.js (the canonical copy the rule-authoring
515
- // consistency test checks against) -- this one has to stay a self-contained
516
- // literal since runCore is inlined via .toString() with no module access at runtime.
517
- const WCAG21_NEW_SCS = [
518
- '1.3.4',
519
- '1.3.5',
520
- '1.3.6',
521
- '1.4.10',
522
- '1.4.11',
523
- '1.4.12',
524
- '1.4.13',
525
- '2.1.4',
526
- '2.2.6',
527
- '2.3.3',
528
- '2.5.1',
529
- '2.5.2',
530
- '2.5.3',
531
- '2.5.4',
532
- '2.5.5',
533
- '2.5.6',
534
- '4.1.3'
535
- ];
536
- const WCAG22_NEW_SCS = [
537
- '2.4.11',
538
- '2.4.12',
539
- '2.4.13',
540
- '2.5.7',
541
- '2.5.8',
542
- '3.2.6',
543
- '3.3.7',
544
- '3.3.8',
545
- '3.3.9'
546
- ];
547
- const isWcag22Sc = wcagSc.some((sc) => WCAG22_NEW_SCS.includes(sc));
548
- const isWcag21Sc = !isWcag22Sc && wcagSc.some((sc) => WCAG21_NEW_SCS.includes(sc));
549
- const versionTagPrefix = isWcag22Sc ? 'wcag22' : isWcag21Sc ? 'wcag21' : 'wcag2';
550
-
551
- const lvl = typeof metaIn.level === 'string' ? metaIn.level.trim().toUpperCase() : '';
552
- if (lvl === 'A') {
553
- tags.push(versionTagPrefix + 'a');
554
- } else if (lvl === 'AA') {
555
- tags.push(versionTagPrefix + 'a', versionTagPrefix + 'aa');
556
- } else if (lvl === 'AAA') {
557
- tags.push(versionTagPrefix + 'a', versionTagPrefix + 'aa', versionTagPrefix + 'aaa');
558
- }
559
-
560
- // Build normativeMappings so downstream consumers (like adapters) can derive WCAG SC/level
561
- const normativeMappingsFromMeta = wcagSc.map((sc) => {
562
- const m = { standard: 'WCAG', requirement: sc };
563
- if (lvl === 'A' || lvl === 'AA' || lvl === 'AAA') m.level = lvl;
564
- return m;
565
- });
566
-
567
- const checksIds = Array.isArray(entry.checksIds)
568
- ? entry.checksIds
569
- .map(String)
570
- .map((s) => s.trim())
571
- .filter(Boolean)
572
- : [];
573
-
574
- return {
575
- ruleId,
576
- title: metaIn.title || ruleId,
577
- description: metaIn.description || '',
578
-
579
- i18n:
580
- titleKey || descriptionKey
581
- ? { titleKey: titleKey || '', descriptionKey: descriptionKey || '' }
582
- : null,
583
-
584
- helpUrl: '',
585
- tags,
586
-
587
- normativeMappings: normativeMappingsFromMeta,
588
-
589
- defaultSeverity: 'serious',
590
- defaultConfidence: 'medium',
591
- type: 'automatic',
592
- coverage: null,
593
-
594
- ruleInterfaceVersion: '1.0.0',
595
- ruleVersion: '0.0.0',
596
- normative: true,
597
- atomic: false,
598
- deprecated: false,
599
- deprecation: null,
600
- category: null,
601
- standard: null,
602
- applicability: '',
603
- expectation: '',
604
- references: [],
605
- requirements: null,
606
- mappings: null,
607
-
608
- // optional catalog meta passthrough
609
- data: {
610
- details: {
611
- kind: 'compositeRule',
612
- wcagSc,
613
- level:
614
- typeof metaIn.level === 'string' && metaIn.level.trim() ? metaIn.level.trim() : null
615
- }
616
- },
617
-
618
- __checksIds: checksIds
619
- };
620
- }
621
-
622
- for (let i = 0; i < composites.length; i++) {
623
- const entry = composites[i];
624
- const cDef0 = buildCompositeDef(entry);
625
- if (!cDef0) continue;
626
-
627
- // Conformance-level gate: if scan is AA, suppress AAA composites even if tags match
628
- const compositeLevel =
629
- cDef0 && cDef0.data && cDef0.data.details && normalizeLevel(cDef0.data.details.level);
630
-
631
- if (!isAllowedByTargetLevel(compositeLevel, targetLevel)) continue;
632
-
633
- // Localize title/description (uses def.i18n.* keys)
634
- const cDefResolved = resolveRuleDefI18n(cDef0, engineOptionsResolved);
635
-
636
- // Apply same selection logic to composites
637
- if (!ruleMatchesRunOnly(cDefResolved, runOnly, ENGINE_TAG)) continue;
638
-
639
- const checksIds = Array.isArray(cDef0.__checksIds) ? cDef0.__checksIds : [];
640
-
641
- // rollup metrics (stable order)
642
- let failCount = 0;
643
- let cantTellCount = 0;
644
- let notApplicableCount = 0;
645
- let passCount = 0;
646
- let missingCount = 0;
647
-
648
- const contributors = [];
649
-
650
- let rolledFailSeverity = null; // max severity among FAIL contributors
651
- let rolledCantTellSeverity = null; // max severity among CANTTELL contributors (optional)
652
-
653
- for (let j = 0; j < checksIds.length; j++) {
654
- const tid = checksIds[j];
655
- const child = tid ? byRuleId[tid] : null;
656
-
657
- if (!child) {
658
- missingCount += 1;
659
- contributors.push({ testId: tid, outcome: 'missing' });
660
- continue;
661
- }
662
-
663
- const out = child.outcome;
664
- const childSev = normalizeSeverity(child && child.severity);
665
-
666
- contributors.push({ testId: tid, outcome: out, severity: childSev || null });
667
-
668
- if (out === 'fail' && childSev) {
669
- rolledFailSeverity = maxSeverity(rolledFailSeverity, childSev);
670
- } else if (out === 'cantTell' && childSev) {
671
- rolledCantTellSeverity = maxSeverity(rolledCantTellSeverity, childSev);
672
- }
673
-
674
- if (out === 'fail') failCount += 1;
675
- else if (out === 'cantTell') cantTellCount += 1;
676
- else if (out === 'notApplicable') notApplicableCount += 1;
677
- else if (out === 'pass') passCount += 1;
678
- }
679
-
680
- // outcome precedence:
681
- // fail if any fail
682
- // cantTell if any cantTell OR missing and none fail
683
- // notApplicable if all notApplicable (and there is at least one test)
684
- // pass otherwise
685
- let outcome = 'pass';
686
- let reasonCode = 'composite.rollup.pass.otherwise';
687
-
688
- if (failCount > 0) {
689
- outcome = 'fail';
690
- reasonCode = 'composite.rollup.fail.anyFail';
691
- } else if (cantTellCount > 0) {
692
- outcome = 'cantTell';
693
- reasonCode = 'composite.rollup.cantTell.anyCantTell';
694
- } else if (missingCount > 0) {
695
- outcome = 'cantTell';
696
- reasonCode = 'composite.rollup.cantTell.missingChild';
697
- } else if (checksIds.length > 0 && notApplicableCount === checksIds.length) {
698
- outcome = 'notApplicable';
699
- reasonCode = 'composite.rollup.notApplicable.allInapplicable';
700
- } else if (checksIds.length === 0) {
701
- outcome = 'cantTell';
702
- reasonCode = 'composite.rollup.cantTell.emptyComposite';
703
- }
704
-
705
- const raw = {
706
- outcome,
707
- occurrences: [],
708
-
709
- // REQUIRED by your reporting schema (top-level)
710
- summaryKey: 'Composite rule rollup',
711
- i18nKey: 'composite_rollup_summary',
712
- i18nParams: { reasonCode, testCount: String(checksIds.length) },
713
-
714
- // REQUIRED by your reporting schema (machine-readable payload)
715
- data: {
716
- details: {
717
- reasonCode,
718
- checksIds: checksIds.slice(),
719
- contributors,
720
- metrics: {
721
- failCount,
722
- cantTellCount,
723
- notApplicableCount,
724
- passCount,
725
- missingCount
726
- }
727
- }
728
- },
729
-
730
- engineOptions: {
731
- ...(engineOptionsResolved || {}),
732
- locale: normalizeLocale(engineOptionsResolved && engineOptionsResolved.locale)
733
- }
734
- };
735
-
736
- // Promote composite severity based on contributors (deterministic).
737
- // - If composite fails: use max severity among failing children.
738
- // - If composite cantTell: use max severity among cantTell children (fallback to failing if you prefer).
739
- if (outcome === 'fail' && rolledFailSeverity) {
740
- raw.severity = rolledFailSeverity;
741
- } else if (outcome === 'cantTell' && rolledCantTellSeverity) {
742
- raw.severity = rolledCantTellSeverity;
743
- }
744
-
745
- rulesResults.push(
746
- normalizeRuleResult(cDefResolved, raw, SCHEMA_VERSION, policy, sharedHelpers)
747
- );
748
- }
749
- } catch (e) {
750
- // no-throws: omit rulesResults if anything goes wrong
751
- }
752
-
753
- // Optional perf counters passthrough (only when enabled). Deterministic.
754
- let perfStats = null;
755
- try {
756
- if (
757
- engineOptionsResolved &&
758
- engineOptionsResolved.perfStats &&
759
- sharedHelpers &&
760
- typeof sharedHelpers.getPerfStats === 'function'
761
- ) {
762
- perfStats = sharedHelpers.getPerfStats();
763
- }
764
- } catch (e) {
765
- perfStats = null;
766
- }
767
-
768
- if (ruleTimings) {
769
- if (perfStats && engineOptionsResolved && engineOptionsResolved.profileRules) {
770
- perfStats.ruleTimings = ruleTimings; // (whatever your timing map is)
771
- }
772
- }
773
-
774
- return {
775
- engine: { tag: ENGINE_TAG, schemaVersion: SCHEMA_VERSION },
776
- url,
777
- title,
778
- timestamp,
779
- perfStats,
780
- contextSelector: ctxSelector,
781
- checksResults,
782
- rulesResults,
783
- overriddenBuiltinIds
784
- };
785
- }
786
-
787
- module.exports = { runCore };