@kinti/a11y-toolkit 5.26.0 → 5.28.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 (45) hide show
  1. package/README.md +1 -1
  2. package/a11y_toolkit/a11y.py +30 -4
  3. package/a11y_toolkit/a11yact.py +9 -1
  4. package/a11y_toolkit/a11yannotate.py +185 -0
  5. package/a11y_toolkit/a11yaudit.py +924 -196
  6. package/a11y_toolkit/a11ybadge.py +24 -17
  7. package/a11y_toolkit/a11ybudget.py +145 -1
  8. package/a11y_toolkit/a11ycorpus.py +58 -24
  9. package/a11y_toolkit/a11ycrit.py +114 -53
  10. package/a11y_toolkit/a11ydiff.py +104 -34
  11. package/a11y_toolkit/a11ydisprove.py +15 -8
  12. package/a11y_toolkit/a11ydocx.py +8 -6
  13. package/a11y_toolkit/a11ydom.py +567 -97
  14. package/a11y_toolkit/a11yen301549.py +53 -1
  15. package/a11y_toolkit/a11yengines.py +157 -0
  16. package/a11y_toolkit/a11yevidence.py +81 -33
  17. package/a11y_toolkit/a11yfix.py +131 -52
  18. package/a11y_toolkit/a11ygate.py +225 -0
  19. package/a11y_toolkit/a11yinit.py +73 -7
  20. package/a11y_toolkit/a11yjourney.py +110 -4
  21. package/a11y_toolkit/a11yledger.py +119 -12
  22. package/a11y_toolkit/a11ylocate.py +247 -0
  23. package/a11y_toolkit/a11yopenacr.py +10 -3
  24. package/a11y_toolkit/a11ypatches.py +154 -0
  25. package/a11y_toolkit/a11ypatterns.py +344 -0
  26. package/a11y_toolkit/a11ypdf.py +109 -53
  27. package/a11y_toolkit/a11yrgaa.py +60 -0
  28. package/a11y_toolkit/a11yroute.py +34 -12
  29. package/a11y_toolkit/a11ysarif.py +45 -18
  30. package/a11y_toolkit/a11yscope.py +67 -15
  31. package/a11y_toolkit/a11yscroll.py +7 -5
  32. package/a11y_toolkit/a11ystatement.py +30 -6
  33. package/a11y_toolkit/a11ytrace.py +293 -0
  34. package/a11y_toolkit/a11yvalidate.py +21 -15
  35. package/a11y_toolkit/a11yvpat.py +34 -7
  36. package/a11y_toolkit/a11yvtt.py +22 -6
  37. package/a11y_toolkit/a11ywiz.py +121 -0
  38. package/a11y_toolkit/contrast.py +62 -24
  39. package/a11y_toolkit/locales/en.json +185 -20
  40. package/a11y_toolkit/locales/es.json +186 -21
  41. package/a11y_toolkit/rgaa.json +2661 -0
  42. package/a11y_toolkit/server.py +157 -54
  43. package/package.json +2 -2
  44. package/a11y_toolkit/a11yplan.py +0 -214
  45. package/a11y_toolkit/a11ywcagem.py +0 -237
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @kinti/a11y-toolkit (npm launcher)
2
2
 
3
- Zero-dependency WCAG 2.2 accessibility engine: **34 MCP tools + CLI**. This
3
+ Zero-dependency WCAG 2.2 accessibility engine: **37 MCP tools + CLI**. This
4
4
  npm package is a thin Node launcher — the engine itself is Python
5
5
  (stdlib-only), run through [uv](https://docs.astral.sh/uv/) so nothing is
6
6
  installed globally.
@@ -5,6 +5,9 @@
5
5
  a11ytoolkit image path.jpg --text "#ffffff" [--region x,y,w,h] [--sample 4]
6
6
  a11ytoolkit audit --url https://client.web | --file page.html
7
7
  a11ytoolkit declaration --entity "Name" --url https://… --status partial [options]
8
+ a11ytoolkit engines https://web # same page in 3 engines: behavioral divergences
9
+ a11ytoolkit trace https://web -o t.json && a11ytoolkit trace diff t1.json t2.json # journey gate
10
+ a11ytoolkit patterns https://web # APG keyboard contracts: dialog, tablist, disclosure
8
11
  a11ytoolkit snapshot https://mysite --out before.json # needs Playwright
9
12
  a11ytoolkit diff before.json after.json
10
13
  a11ytoolkit audit --url https://web --pages 5 # light same-domain crawl
@@ -28,11 +31,19 @@
28
31
  a11ytoolkit wcag3 --from-audit audit.json # WCAG 3 draft preview (no score)
29
32
  a11ytoolkit route --goal "gate my PR" # which tools for the task
30
33
  a11ytoolkit route --file page.html # diagnosis: read the page, order the exams
34
+ a11ytoolkit dom https://web # rendered audit (needs Playwright)
35
+ a11ytoolkit hover https://mysite # tooltip dismissibility (1.4.13)
36
+ a11ytoolkit criteria --list --level AA --new-in 2.2 # criterion's alias: the Quick Ref
37
+ a11ytoolkit wizard --url https://client.web --lang es # guided: standard, audit, scope, annex
31
38
  a11ytoolkit mutants --seed 7 --n 12 # the engine's sealed self-exam
32
39
  a11ytoolkit corpus build && a11ytoolkit corpus verify # versioned audit corpus (dataset + baselines)
33
40
  a11ytoolkit fingerprints page1.html page2.html --dir p/ # twin-page detection (one audit per template)
34
41
  a11ytoolkit audit --url https://web --standard en301549 # EN 301 549 clause on every finding
35
42
  a11ytoolkit scope audit.json -o scope.json --standard en301549 # applicability: machine proposes, human confirms
43
+ a11ytoolkit annotate page.html --report r.json -o copy.html # per-element marks on a copy
44
+ a11ytoolkit locate --file page.html --query "Submit" # element by accessible name → route
45
+ a11ytoolkit patches --file page.html -o patches.json # sealed fix record (verify with --verify)
46
+ a11ytoolkit guard --file page.html # write-time gate: NEW high/medium refuse the save
36
47
  """
37
48
 
38
49
  import sys
@@ -50,9 +61,7 @@ from . import a11ybudget
50
61
  from . import a11ycrit
51
62
  from . import a11ydiff
52
63
  from . import a11ysarif
53
- from . import a11ywcagem
54
64
  from . import a11ycorpus
55
- from . import a11yplan
56
65
  from . import contrast
57
66
  from . import a11ystatement
58
67
  from . import a11yjourney
@@ -67,6 +76,14 @@ from . import a11yroute
67
76
  from . import a11ymutants
68
77
  from . import a11yfingerprints
69
78
  from . import a11yscope
79
+ from . import a11yannotate
80
+ from . import a11ylocate
81
+ from . import a11ypatches
82
+ from . import a11ygate
83
+ from . import a11yengines
84
+ from . import a11ytrace
85
+ from . import a11ypatterns
86
+ from . import a11ywiz
70
87
 
71
88
  SUBCOMMANDS = {
72
89
  'pair': (contrast, 'pair'),
@@ -76,12 +93,13 @@ SUBCOMMANDS = {
76
93
  'snapshot': (a11ydiff, 'snapshot'),
77
94
  'diff': (a11ydiff, 'diff'),
78
95
  'criterion': (a11ycrit, None),
96
+ 'criteria': (a11ycrit, None),
79
97
  'sarif': (a11ysarif, None),
80
- 'wcagem': (a11ywcagem, None),
81
98
  'corpus': (a11ycorpus, None),
82
- 'plan': (a11yplan, None),
83
99
  'fix': (a11yfix, None),
84
100
  'kbd': (a11ydom, 'kbd_main'),
101
+ 'hover': (a11ydom, 'hover_main'),
102
+ 'dom': (a11ydom, None),
85
103
  'scroll': (a11yscroll, None),
86
104
  'forms': (a11ydom, 'forms_main'),
87
105
  'validate': (a11yvalidate, None),
@@ -105,6 +123,14 @@ SUBCOMMANDS = {
105
123
  'mutants': (a11ymutants, None),
106
124
  'fingerprints': (a11yfingerprints, None),
107
125
  'scope': (a11yscope, None),
126
+ 'annotate': (a11yannotate, None),
127
+ 'locate': (a11ylocate, None),
128
+ 'patches': (a11ypatches, None),
129
+ 'guard': (a11ygate, None),
130
+ 'engines': (a11yengines, None),
131
+ 'trace': (a11ytrace, None),
132
+ 'patterns': (a11ypatterns, None),
133
+ 'wizard': (a11ywiz, None),
108
134
  }
109
135
 
110
136
 
@@ -97,7 +97,15 @@ def act_ids(signal):
97
97
  def earl(report, url=None):
98
98
  """Informe de auditoría → EARL 1.0 JSON-LD (solo hallazgos con mapeo ACT)."""
99
99
  assertions = []
100
- for h in report.get('findings', []):
100
+ # site crawls anidan en reports[]; entrada hostil (no-dict/no-list) → []
101
+ _hls = report.get('findings') if isinstance(report, dict) else None
102
+ if not isinstance(_hls, list) and isinstance(report, dict) and isinstance(report.get('reports'), list):
103
+ _hls = [h for sub in report['reports']
104
+ if isinstance(sub, dict) for h in sub.get('findings', [])
105
+ if isinstance(h, dict)]
106
+ for h in (_hls if isinstance(_hls, list) else []):
107
+ if not isinstance(h, dict):
108
+ continue
101
109
  if h.get('status') in _NOT_DEAD or h.get('disprover_status') in _NOT_DEAD:
102
110
  continue
103
111
  rules = ACT_MAP.get(normalize_signal(h.get('signal', '')))
@@ -0,0 +1,185 @@
1
+ #!/usr/bin/env python3
2
+ """Per-element annotation — the kernel that turns findings into marks.
3
+
4
+ A finding says "2 <img> without alt"; the kernel says WHICH imgs exactly:
5
+ the auditor now stamps every finding it can with `paths` (deterministic CSS
6
+ routes computed during the parse: tag:nth-of-type(n) from the root — ids are
7
+ ignored on purpose, duplicate ids cannot break identity), and
8
+ `annotate(html, report)` re-parses the SAME html with the SAME route
9
+ algorithm (shared: VOID_TAGS / path_segment from a11yaudit) to inject
10
+ `data-a11y-id="mN"` attributes at byte-exact positions — offset surgery,
11
+ the rest of the document is preserved byte for byte.
12
+
13
+ The honesty rule, same as everywhere: what cannot be located is returned in
14
+ `unplaced` — a finding without a mark, never a wrong mark. That includes the
15
+ whole-report case: if the report's `source_sha256` does not match this html,
16
+ NOTHING is injected (paths can collide by accident on a different document and
17
+ a mark would land on the wrong element) — every finding falls to `unplaced`
18
+ and the result carries `source_mismatch: True` plus a `note`.
19
+
20
+ Output:
21
+ {'annotated_html': str, # the COPY with data-a11y-id attrs
22
+ 'marks': [{id, path, criterion, severity, signal}, …],
23
+ 'unplaced': [{criterion, signal}, …], # findings without paths
24
+ 'source_mismatch': bool, 'note': str} # note only on mismatch
25
+
26
+ CLI:
27
+ a11yannotate.py page.html --report audit.json -o copy.html [--marks m.json]
28
+ """
29
+
30
+ import argparse
31
+ import json
32
+ import sys
33
+ from html.parser import HTMLParser
34
+
35
+ from .a11yaudit import VOID_TAGS, path_segment
36
+
37
+ # nota de mismatch, bilingüe (mismo patrón que _labels en a11yaudit):
38
+ # annotate no tiene idioma propio — 'en' por defecto, idioma explícito opcional
39
+ _NOTES = {
40
+ 'es': 'el informe no proviene de este html (source_sha256 distinto): '
41
+ 'sin marcas, todo el informe cae a unplaced — nunca una marca en el '
42
+ 'elemento equivocado',
43
+ 'en': 'the report did not come from this html (source_sha256 differs): '
44
+ 'no marks, the whole report falls to unplaced — never a '
45
+ 'wrong-element mark',
46
+ }
47
+
48
+
49
+ class _Locator(HTMLParser):
50
+ """Re-parses the original html and records, for every element route, the
51
+ byte offset where an attribute could be injected (right after the tag
52
+ name). Same route algorithm as the auditor → same routes → exact match."""
53
+
54
+ def __init__(self):
55
+ super().__init__(convert_charrefs=True)
56
+ self.route_offset = {} # path → insertion offset
57
+ self._line_starts = None # built lazily at feed()
58
+ self._stack = [] # mirrors the auditor's path stack
59
+
60
+ def feed(self, data):
61
+ lines = data.split('\n')
62
+ starts, off = [], 0
63
+ for _ln in lines:
64
+ starts.append(off)
65
+ off += len(_ln) + 1
66
+ self._line_starts = starts
67
+ super().feed(data)
68
+
69
+ def handle_starttag(self, tag, attrs):
70
+ pos = self.getpos() # (line, col) — 1-based line
71
+ if self._stack:
72
+ parent = self._stack[-1]
73
+ parent[2][tag] = parent[2].get(tag, 0) + 1
74
+ path = parent[1] + '>' + path_segment(tag, parent[2][tag])
75
+ else:
76
+ path = path_segment(tag, 1)
77
+ # offset absoluto del '<' + largo de "<tag" → punto de inyección
78
+ try:
79
+ abs_off = self._line_starts[pos[0] - 1] + pos[1]
80
+ except IndexError:
81
+ return
82
+ self.route_offset[path] = abs_off + 1 + len(tag)
83
+ if tag not in VOID_TAGS:
84
+ self._stack.append((tag, path, {}))
85
+
86
+ def handle_endtag(self, tag):
87
+ if self._stack:
88
+ if self._stack[-1][0] == tag:
89
+ self._stack.pop()
90
+ else:
91
+ for i in range(len(self._stack) - 1, -1, -1):
92
+ if self._stack[i][0] == tag:
93
+ del self._stack[i:]
94
+ break
95
+
96
+
97
+ def annotate(html_text, report, lang='en'):
98
+ """Informe (dict de audit_html/audit_url) + html ORIGINAL → copia marcada.
99
+
100
+ El html debe ser el mismo que produjo el informe (mismo parseo, mismas
101
+ rutas). Si el informe sella un source_sha256 y no casa con este html, NO
102
+ se inyecta nada — todo el informe cae a unplaced con source_mismatch True
103
+ (los paths pueden colisionar por accidente en otro documento y la marca
104
+ caería en el elemento equivocado).
105
+ """
106
+ import hashlib
107
+ src_hash = report.get('source_sha256')
108
+ mismatch = bool(src_hash) and src_hash != hashlib.sha256(
109
+ html_text.encode('utf-8', 'replace')).hexdigest()
110
+
111
+ loc = _Locator()
112
+ try:
113
+ loc.feed(html_text)
114
+ loc.close()
115
+ except Exception: # noqa: BLE001 — html hostil: sin marcas, sin caída
116
+ return {'annotated_html': html_text, 'marks': [],
117
+ 'unplaced': [{'criterion': h.get('criterion'), 'signal': h.get('signal')}
118
+ for h in report.get('findings', []) if isinstance(h, dict)]}
119
+
120
+ findings = [h for h in report.get('findings', []) if isinstance(h, dict)]
121
+ if mismatch:
122
+ # la puerta del docstring: un informe de OTRO html jamás se inyecta
123
+ return {'annotated_html': html_text, 'marks': [],
124
+ 'unplaced': [{'criterion': h.get('criterion'), 'signal': h.get('signal')}
125
+ for h in findings],
126
+ 'source_mismatch': True,
127
+ 'note': _NOTES.get(lang, _NOTES['en'])}
128
+
129
+ marks, unplaced, injections = [], [], [] # injections: (offset, id)
130
+ by_off = {} # offset → id ya asignado: dos findings sobre el MISMO
131
+ # elemento comparten marca (dos data-a11y-id en el mismo
132
+ # offset serían HTML inválido — el DOM descarta el segundo)
133
+ n = 0
134
+ for h in findings:
135
+ did_place = False
136
+ for path in (h.get('paths') or []):
137
+ off = loc.route_offset.get(path)
138
+ if off is None:
139
+ continue
140
+ if off not in by_off:
141
+ n += 1
142
+ by_off[off] = f'm{n}'
143
+ injections.append((off, by_off[off]))
144
+ marks.append({'id': by_off[off], 'path': path,
145
+ 'criterion': h.get('criterion'), 'severity': h.get('severity'),
146
+ 'signal': h.get('signal')})
147
+ did_place = True
148
+ if not did_place:
149
+ unplaced.append({'criterion': h.get('criterion'), 'signal': h.get('signal')})
150
+
151
+ # cirugía por offsets, en orden DESCENDENTE para no invalidar posiciones
152
+ out = html_text
153
+ for off, mid in sorted(injections, key=lambda x: -x[0]):
154
+ out = out[:off] + f' data-a11y-id="{mid}"' + out[off:]
155
+ return {'annotated_html': out, 'marks': marks,
156
+ 'unplaced': unplaced, 'source_mismatch': mismatch}
157
+
158
+
159
+ def main(argv):
160
+ ap = argparse.ArgumentParser(description='Annotate a copy of the HTML with '
161
+ 'per-element marks from an audit report')
162
+ ap.add_argument('html_file', help='the ORIGINAL html the report audited')
163
+ ap.add_argument('--report', required=True, help='audit report JSON (must carry paths)')
164
+ ap.add_argument('-o', '--out', default='annotated.html')
165
+ ap.add_argument('--marks', help='write the marks list here (JSON)')
166
+ ap.add_argument('--lang', default='en', choices=['es', 'en'],
167
+ help='language of the mismatch note')
168
+ a = ap.parse_args(argv)
169
+ html_text = open(a.html_file, encoding='utf-8', errors='replace').read()
170
+ report = json.load(open(a.report, encoding='utf-8'))
171
+ res = annotate(html_text, report, lang=a.lang)
172
+ with open(a.out, 'w', encoding='utf-8') as f:
173
+ f.write(res['annotated_html'])
174
+ if a.marks:
175
+ with open(a.marks, 'w', encoding='utf-8') as f:
176
+ json.dump(res['marks'], f, ensure_ascii=False, indent=1)
177
+ print(json.dumps({'out': a.out, 'marks': len(res['marks']),
178
+ 'unplaced': len(res['unplaced']),
179
+ 'source_mismatch': res['source_mismatch']},
180
+ ensure_ascii=False))
181
+ return 0
182
+
183
+
184
+ if __name__ == '__main__':
185
+ sys.exit(main(sys.argv[1:]))