@kinti/a11y-toolkit 5.22.1 → 5.22.2

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 (36) hide show
  1. package/a11y_toolkit/__init__.py +5 -0
  2. package/a11y_toolkit/a11y.py +115 -0
  3. package/a11y_toolkit/a11yact.py +167 -0
  4. package/a11y_toolkit/a11yaudit.py +1951 -0
  5. package/a11y_toolkit/a11ybadge.py +102 -0
  6. package/a11y_toolkit/a11ybudget.py +122 -0
  7. package/a11y_toolkit/a11ycrit.py +1017 -0
  8. package/a11y_toolkit/a11ydiff.py +192 -0
  9. package/a11y_toolkit/a11ydisprove.py +175 -0
  10. package/a11y_toolkit/a11ydocx.py +132 -0
  11. package/a11y_toolkit/a11ydom.py +1831 -0
  12. package/a11y_toolkit/a11yevidence.py +272 -0
  13. package/a11y_toolkit/a11yfix.py +330 -0
  14. package/a11y_toolkit/a11yi18n.py +100 -0
  15. package/a11y_toolkit/a11yinit.py +113 -0
  16. package/a11y_toolkit/a11yjourney.py +284 -0
  17. package/a11y_toolkit/a11yledger.py +210 -0
  18. package/a11y_toolkit/a11ymutants.py +406 -0
  19. package/a11y_toolkit/a11yopenacr.py +207 -0
  20. package/a11y_toolkit/a11ypdf.py +273 -0
  21. package/a11y_toolkit/a11yroute.py +378 -0
  22. package/a11y_toolkit/a11ysarif.py +139 -0
  23. package/a11y_toolkit/a11yscroll.py +212 -0
  24. package/a11y_toolkit/a11ystatement.py +158 -0
  25. package/a11y_toolkit/a11yvalidate.py +127 -0
  26. package/a11y_toolkit/a11yvpat.py +238 -0
  27. package/a11y_toolkit/a11yvtt.py +136 -0
  28. package/a11y_toolkit/a11ywcag3.py +262 -0
  29. package/a11y_toolkit/arialive.js +107 -0
  30. package/a11y_toolkit/arialive_js.py +113 -0
  31. package/a11y_toolkit/contrast.py +536 -0
  32. package/a11y_toolkit/locales/_template.json +468 -0
  33. package/a11y_toolkit/locales/en.json +525 -0
  34. package/a11y_toolkit/locales/es.json +525 -0
  35. package/a11y_toolkit/server.py +1529 -0
  36. package/package.json +2 -1
@@ -0,0 +1,378 @@
1
+ #!/usr/bin/env python3
2
+ """a11y_route — the router: tell the agent WHICH tools solve a task.
3
+
4
+ Two brains, one tool:
5
+ - GOAL routing: the agent states a goal in plain language — "gate my PR",
6
+ "arregla el contraste del hero" — and gets the ordered tool sequence
7
+ with the why of each step. Deterministic keyword index, not an LLM.
8
+ - SEQUENTIAL DIAGNOSIS (pass url= or html=): the router takes the page's
9
+ cheap vitals (the static pass) and lets the EVIDENCE order the next
10
+ exams — forms present → form error testing; menus → keyboard; video →
11
+ caption content. Severity only breaks ties: a page without forms does
12
+ not need the form exam no matter how severe 3.3.1 is on paper.
13
+ Diagnosis ORDERS the exams, never trims them — the full catalog stays
14
+ one route(goal) away.
15
+
16
+ The tables are the product: keep them in sync with the toolkit (the
17
+ test suite pins that every referenced tool exists).
18
+
19
+ CLI:
20
+ a11yroute.py --goal "gate my PR" [--lang en]
21
+ a11yroute.py --file page.html # diagnosis mode
22
+ a11yroute.py --url https://… # diagnosis mode
23
+ """
24
+
25
+ import argparse
26
+ import json
27
+ import re
28
+ import sys
29
+
30
+ from .a11yaudit import audit_html, _fetch
31
+
32
+ # Índice de rutas: patrones es/en → pasos ordenados. Una ruta gana por
33
+ # puntuación de coincidencias (subcadena sobre el goal en minúsculas);
34
+ # el empate lo decide el orden de la tabla. 'start' es el fallback honesto.
35
+ ROUTES = [
36
+ {'id': 'ci',
37
+ 'patterns': ['pr', 'pull request', 'ci', 'pipeline', 'github actions',
38
+ 'gate', 'commit', 'merge', 'cambios', 'before merging'],
39
+ 'tools': [
40
+ ('a11y_audit_url', 'pase exprés de lo tocado: el gate mínimo',
41
+ 'express pass over what changed: the minimum gate'),
42
+ ('cli:budget', 'solo hallazgos NUEVOS bloquean (regresión, no deuda vieja)',
43
+ 'only NEW findings block (regression, not old debt)'),
44
+ ],
45
+ 'cli': 'a11ytoolkit audit --changed # exit 2 on high/medium in changed files',
46
+ 'prompts': []},
47
+ {'id': 'deploy',
48
+ 'patterns': ['deploy', 'despliegue', 'regression', 'regresión',
49
+ 'before shipping', 'pre-deploy', 'antes de publicar'],
50
+ 'tools': [
51
+ ('a11y_snapshot', 'foto de interactivos + árbol antes de desplegar',
52
+ 'interactive elements + tree snapshot before deploying'),
53
+ ('a11y_diff', 'tras el deploy: hallazgos nuevos bloquean, resueltos celebran',
54
+ 'after deploy: new findings block, resolved ones are good news'),
55
+ ('cli:budget', 'el veredicto GO/NO-GO con evidencia',
56
+ 'the GO/NO-GO verdict with evidence'),
57
+ ],
58
+ 'cli': 'a11ytoolkit snapshot https://… --out before.json',
59
+ 'prompts': ['pre-deploy-check']},
60
+ {'id': 'contrast',
61
+ 'patterns': ['contrast', 'contraste', 'color', 'colour', 'legibility',
62
+ 'legible', '4.5', 'ratio', 'texto sobre imagen'],
63
+ 'tools': [
64
+ ('a11y_contrast_pair', 'el par exacto: ratio y veredicto por criterio',
65
+ 'the exact pair: ratio and per-criterion verdicts'),
66
+ ('a11y_contrast_dom', 'si el texto vive en una página: muestreo de la región real',
67
+ 'if the text lives on a page: real-region sampling'),
68
+ ('a11y_contrast_image', 'sobre imagen o degradado: píxeles, no suposiciones',
69
+ 'over image or gradient: pixels, not guesses'),
70
+ ('a11y_suggest_color', 'el color más cercano que pasa',
71
+ 'the nearest passing color'),
72
+ ],
73
+ 'cli': 'a11ytoolkit pair "#1f2328" "#fbfaf7"',
74
+ 'prompts': ['fix-contrast']},
75
+ {'id': 'rendered',
76
+ 'patterns': ['rendered', 'js', 'react', 'vue', 'angular', 'svelte',
77
+ 'spa', 'computado', 'real contrast'],
78
+ 'tools': [
79
+ ('a11y_audit_dom', 'auditoría renderizada: contraste computado, 2.5.8, foco',
80
+ 'rendered audit: computed contrast, 2.5.8, focus indicator'),
81
+ ('a11y_criterion', 'qué significa cada criterio que salga',
82
+ 'what each flagged criterion means'),
83
+ ],
84
+ 'cli': None, 'prompts': []},
85
+ {'id': 'forms',
86
+ 'patterns': ['form', 'formulario', 'error', 'validación', 'validacion',
87
+ '3.3', 'checkout', 'signup field'],
88
+ 'tools': [
89
+ ('a11y_forms', 'rellena inválido, envía y juzga el aviso de errores (3.3.1/3.3.3)',
90
+ 'fills invalid data, submits, judges error announcement (3.3.1/3.3.3)'),
91
+ ('a11y_audit_url', 'labels, autocomplete y nombres en el pase estático',
92
+ 'labels, autocomplete and names in the static pass'),
93
+ ],
94
+ 'cli': 'a11ytoolkit forms https://…/contact',
95
+ 'prompts': []},
96
+ {'id': 'keyboard',
97
+ 'patterns': ['keyboard', 'teclado', 'trap', 'trampa', 'focus', 'foco',
98
+ 'tab', 'esc', 'modal'],
99
+ 'tools': [
100
+ ('a11y_keyboard', 'detecta trampas de teclado con Tab real',
101
+ 'detects keyboard traps with real Tab walking'),
102
+ ('a11y_audit_dom', 'foco visible y no oscurecido, renderizado',
103
+ 'visible, unobscured focus, rendered'),
104
+ ],
105
+ 'cli': 'a11ytoolkit kbd https://…',
106
+ 'prompts': []},
107
+ {'id': 'statement',
108
+ 'patterns': ['statement', 'declaración', 'declaracion', 'eaa', 'ley',
109
+ 'legal', 'rd 1112', 'acta', '11/2023', 'compliance doc'],
110
+ 'tools': [
111
+ ('a11y_audit_url', 'los hallazgos alimentan la lista de contenido no accesible',
112
+ 'findings feed the non-accessible content list'),
113
+ ('a11y_generate_declaration', 'la declaración EAA/RD 1112 como borrador honesto',
114
+ 'the EAA/RD 1112 statement as an honest draft'),
115
+ ],
116
+ 'cli': 'a11ytoolkit declaration --entity "Acme" --url https://… --status partial --framework eaa',
117
+ 'prompts': ['declaration-eaa']},
118
+ {'id': 'evidence',
119
+ 'patterns': ['evidence', 'evidencia', 'pack', 'prove', 'demostrar',
120
+ 'conformity', 'buyer', 'auditor firmado', 'verify report'],
121
+ 'tools': [
122
+ ('a11y_audit_url', 'la materia prima: hallazgos con señal y remedio',
123
+ 'the raw material: findings with signal and remediation'),
124
+ ('a11y_evidence', 'el pack verificable: matriz 55, esfuerzo humano, sha256',
125
+ 'the verifiable pack: 55-matrix, human effort, sha256'),
126
+ ('a11y_disprove', 're-verifica antes de actuar: lo que no reproduce, fuera',
127
+ 're-verify before acting: what does not reproduce is out'),
128
+ ],
129
+ 'cli': 'a11ytoolkit evidence audit.json -o pack.json',
130
+ 'prompts': []},
131
+ {'id': 'vpat',
132
+ 'patterns': ['vpat', 'acr', 'procurement', 'licitación', 'licitacion',
133
+ 'tender', 'rfp', 'us market'],
134
+ 'tools': [
135
+ ('a11y_evidence', 'primero el pack: el VPAT se deriva de evidencia',
136
+ 'the pack first: the VPAT derives from evidence'),
137
+ ('a11y_generate_vpat', 'borrador VPAT 2.5: la máquina rellena, la persona firma',
138
+ 'VPAT 2.5 draft: the machine fills, the human signs'),
139
+ ('a11y_generate_openacr', 'OpenACR YAML (GSA): el ACR máquina que parsea el procurement',
140
+ 'OpenACR YAML (GSA): the machine-readable ACR procurement parses'),
141
+ ],
142
+ 'cli': 'a11ytoolkit vpat pack.json --product "Acme" -o vpat.html',
143
+ 'prompts': []},
144
+ {'id': 'media',
145
+ 'patterns': ['video', 'caption', 'subtítulo', 'subtitulo', 'subtitulo',
146
+ 'vtt', 'audio description', 'audiodescripción', 'podcast'],
147
+ 'tools': [
148
+ ('a11y_vtt_check', 'el CONTENIDO de los subtítulos: cps, solapes, cobertura',
149
+ 'caption CONTENT: cps, overlaps, coverage'),
150
+ ('a11y_audit_url', 'presencia de track y autoplay en el pase estático',
151
+ 'track presence and autoplay in the static pass'),
152
+ ],
153
+ 'cli': None, 'prompts': []},
154
+ {'id': 'pdf',
155
+ 'patterns': ['pdf', 'documento', 'document', 'docx', 'word', 'informe pdf'],
156
+ 'tools': [
157
+ ('a11y_audit_pdf', 'cribado estructural + formularios: lo que nadie automatiza',
158
+ 'structural screening + forms: what nobody automates'),
159
+ ('a11y_docx_screen', 'si es Word: alt, encabezados, idioma, tablas',
160
+ 'if it is Word: alt, headings, language, tables'),
161
+ ],
162
+ 'cli': None, 'prompts': []},
163
+ {'id': 'blindfold',
164
+ 'patterns': ['task', 'tarea', 'journey', 'blindfold', 'usuario ciego',
165
+ 'screen reader flow', 'comprar', 'signup flow', 'can a user'],
166
+ 'tools': [
167
+ ('blindfold-task', 'el prompt: el agente ES el usuario de lector, paso a paso',
168
+ 'the prompt: the agent IS the screen-reader user, step by step'),
169
+ ('a11y_journey_verdict', 'el veredicto determinista del recorrido',
170
+ 'the deterministic journey verdict'),
171
+ ],
172
+ 'cli': None, 'prompts': ['blindfold-task']},
173
+ {'id': 'wcag3',
174
+ 'patterns': ['wcag 3', 'wcag3', 'silver', 'futuro', 'future', 'draft wcag'],
175
+ 'tools': [
176
+ ('a11y_wcag3_preview', 'tus hallazgos 2.2 bajo los outcomes del borrador (sin score)',
177
+ 'your 2.2 findings under the draft outcomes (no score)'),
178
+ ],
179
+ 'cli': 'a11ytoolkit wcag3 --from-audit audit.json',
180
+ 'prompts': []},
181
+ {'id': 'scroll',
182
+ 'patterns': ['infinite scroll', 'scroll infinito', 'feed', 'lazy load',
183
+ 'paginación', 'pagination'],
184
+ 'tools': [('a11y_scroll', 'el foco sobrevive a cada tanda, lo nuevo se anuncia',
185
+ 'focus survives each batch, the new content is announced')],
186
+ 'cli': 'a11ytoolkit scroll https://…/feed', 'prompts': []},
187
+ {'id': 'motion',
188
+ 'patterns': ['animation', 'animación', 'animacion', 'motion', 'parallax',
189
+ 'reduced motion', 'vestibular'],
190
+ 'tools': [('a11y_reduced_motion', '¿respeta prefers-reduced-motion? Nadie lo automatizaba',
191
+ 'does it honor prefers-reduced-motion? Nobody automated it')],
192
+ 'cli': None, 'prompts': []},
193
+ {'id': 'names',
194
+ 'patterns': ['accessible name', 'nombre accesible', 'aria', 'role',
195
+ 'widget', '4.1.2', 'control sin nombre'],
196
+ 'tools': [
197
+ ('a11y_audit_url', 'detección estática: botones sin nombre, roles rotos',
198
+ 'static detection: unnamed buttons, broken roles'),
199
+ ('a11y_snapshot', 'los nombres REALES que anuncia el navegador',
200
+ 'the REAL names the browser announces'),
201
+ ('a11y_criterion', 'qué exige exactamente 4.1.2 (con reglas ACT)',
202
+ 'what 4.1.2 exactly requires (with ACT rules)'),
203
+ ],
204
+ 'cli': None, 'prompts': []},
205
+ {'id': 'criterion',
206
+ 'patterns': ['what is', 'qué es', 'que es', 'significa', 'criterio',
207
+ 'criterion', 'explain', 'regla', 'rule', '1.4.3', '2.4.7'],
208
+ 'tools': [('a11y_criterion', 'el criterio explicado, con fuente Understanding y ACT',
209
+ 'the criterion explained, with Understanding source and ACT')],
210
+ 'cli': None, 'prompts': []},
211
+ # fallback honesto: por dónde empieza todo el mundo
212
+ {'id': 'start',
213
+ 'patterns': [],
214
+ 'tools': [
215
+ ('a11y_audit_url', 'el pase exprés: score, hallazgos con remedio',
216
+ 'the express pass: score, findings with remediation'),
217
+ ('a11y_criterion', 'para entender cualquier criterio que salga',
218
+ 'to understand any criterion that comes up'),
219
+ ('a11y_evidence', 'cuando quieras pasarlo a evidencia firmable',
220
+ 'when you want it as signable evidence'),
221
+ ],
222
+ 'cli': 'a11ytoolkit audit --url https://…',
223
+ 'prompts': ['audit-page']},
224
+ ]
225
+
226
+ _NOTE = {
227
+ 'es': ('Índice determinista de goals→tools: no adivina. Si nada encajó, '
228
+ 'la ruta "start" es por donde empieza todo el mundo.'),
229
+ 'en': ('Deterministic goal→tools index: it does not guess. When nothing '
230
+ 'matched, the "start" route is where everyone begins.'),
231
+ }
232
+
233
+ # ── diagnóstico secuencial: la EVIDENCIA manda, la severidad solo desempata ──
234
+ # Traducción cruzada del diagnóstico diferencial (medicina): primero la
235
+ # constante vital barata —el pase estático— y sus síntomas deciden qué
236
+ # examen reduce más la incertidumbre. No es una prioridad fija de criterios:
237
+ # una página sin formularios no necesita el examen de formularios por muy
238
+ # grave que sea 3.3.1 sobre el papel. detect() devuelve None (síntoma
239
+ # ausente) o la evidencia en una línea.
240
+ _DIAG = [
241
+ {'id': 'forms', 'severity': 'high', 'tool': 'a11y_forms',
242
+ # ojo: sin \b dentro de las llaves del f-string (barra invertida DENTRO
243
+ # de llaves es SyntaxError antes de 3.12; el guardián de test_solido lo
244
+ # vigila) — la detección con \b vive en el re.search de fuera
245
+ 'detect': lambda h: (f'{len(re.findall(r"<(?:input|select|textarea)", h))} form fields'
246
+ if re.search(r'<(?:input|select|textarea)\b', h) else None),
247
+ 'why': ('formularios presentes: rellenar inválido, enviar y juzgar el aviso de errores',
248
+ 'forms present: fill invalid data, submit, judge the error announcement')},
249
+ {'id': 'menus', 'severity': 'high', 'tool': 'a11y_keyboard',
250
+ 'detect': lambda h: ('menus or disclosure widgets'
251
+ if re.search(r'<(?:nav|details)\b|aria-expanded', h) else None),
252
+ 'why': ('menús o desplegables: la zona clásica de trampas de teclado',
253
+ 'menus or disclosure widgets: the classic keyboard-trap zone')},
254
+ {'id': 'video', 'severity': 'medium', 'tool': 'a11y_vtt_check',
255
+ 'detect': lambda h: (f'{h.count("<video")} <video>' if '<video' in h else None),
256
+ 'why': ('vídeo presente: que existan subtítulos no basta — juzgar su CONTENIDO',
257
+ 'video present: captions existing is not enough — judge their CONTENT')},
258
+ {'id': 'animation', 'severity': 'medium', 'tool': 'a11y_reduced_motion',
259
+ 'detect': lambda h: ('animated content'
260
+ if re.search(r'animation|transition|<marquee', h) else None),
261
+ 'why': ('contenido animado: ¿respeta prefers-reduced-motion?',
262
+ 'animated content: does it honor prefers-reduced-motion?')},
263
+ {'id': 'svg', 'severity': 'low', 'tool': 'a11y_forced_colors',
264
+ 'detect': lambda h: (f'{h.count("<svg")} inline <svg>' if h.count('<svg') >= 2 else None),
265
+ 'why': ('iconografía SVG en volumen: los fills fijos caen en forced-colors',
266
+ 'SVG iconography at volume: hardcoded fills fall in forced-colors')},
267
+ ]
268
+
269
+ _RANK = {'high': 0, 'medium': 1, 'low': 2}
270
+
271
+ _GUARANTEE = {
272
+ 'es': ('El diagnóstico ORDENA los exámenes, nunca los recorta: el catálogo '
273
+ 'completo sigue a un route(goal) de distancia.'),
274
+ 'en': ('Diagnosis ORDERS the exams, never trims them: the full catalog '
275
+ 'stays one route(goal) away.'),
276
+ }
277
+
278
+
279
+ def diagnose(html_text, url='(html)', lang='en', goal=None):
280
+ """Pase barato → síntomas → exámenes ordenados por rendimiento esperado."""
281
+ t = 'es' if lang == 'es' else 'en'
282
+ idx = 0 if t == 'es' else 1
283
+ rep = audit_html(html_text, url=url, lang=t)
284
+ if 'error' in rep:
285
+ return {'mode': 'diagnose', 'lang': t, 'error': rep['error']}
286
+ vitals = {'tool': 'a11y_audit_url', 'score': rep.get('score'),
287
+ 'summary': rep.get('summary'),
288
+ 'signals': [f"{h['severity']}: {h['signal']}"
289
+ for h in rep.get('findings', [])]}
290
+ symptoms, hit = [], []
291
+ for d in _DIAG:
292
+ ev = d['detect'](html_text)
293
+ if ev:
294
+ symptoms.append({'symptom': d['id'], 'evidence': ev})
295
+ hit.append(d)
296
+ # sort estable: severidad como desempate, orden de tabla dentro de cada nivel
297
+ hit.sort(key=lambda d: _RANK[d['severity']])
298
+ steps = [{'step': 1, 'tool': 'a11y_audit_url',
299
+ 'why': ('constante vital ya medida: este pase barato decidió lo demás',
300
+ 'vitals already taken: this cheap pass decided the rest')[idx]}]
301
+ evidences = {d['id']: d['detect'](html_text) for d in _DIAG}
302
+ for i, d in enumerate(hit, 2):
303
+ steps.append({'step': i, 'tool': d['tool'], 'why': d['why'][idx],
304
+ 'symptom': d['id'], 'evidence': evidences[d['id']]})
305
+ steps.append({'step': len(steps) + 1, 'tool': 'a11y_audit_dom',
306
+ 'why': ('profundizar lo que el estático no ve: contraste computado, 2.5.8, foco',
307
+ 'deepen what static cannot see: computed contrast, 2.5.8, focus')[idx]})
308
+ return {'mode': 'diagnose', 'goal': goal, 'url': url, 'lang': t,
309
+ 'vitals': vitals, 'symptoms': symptoms, 'steps': steps,
310
+ 'guarantee': _GUARANTEE[t]}
311
+
312
+
313
+ def route(goal, lang='en', url=None, html=None):
314
+ """Goal en lenguaje natural → secuencia de tools con el porqué.
315
+ Con url= o html= → diagnóstico secuencial (la página decide el orden)."""
316
+ if html or url:
317
+ if html:
318
+ return diagnose(html, url=url or '(html)', lang=lang, goal=goal)
319
+ try:
320
+ html_text = _fetch(url, timeout=20)
321
+ except ValueError as e:
322
+ return {'mode': 'diagnose', 'lang': lang, 'error': str(e)}
323
+ except Exception as e: # noqa: BLE001
324
+ return {'mode': 'diagnose', 'lang': lang, 'error': f'fetch failed: {e}'}
325
+ if isinstance(html_text, dict):
326
+ return {'mode': 'diagnose', 'lang': lang,
327
+ 'error': html_text.get('error', 'fetch failed')}
328
+ return diagnose(html_text, url=url, lang=lang, goal=goal)
329
+ t = 'es' if lang == 'es' else 'en'
330
+ g = (goal or '').lower()
331
+ scored = []
332
+ for r in ROUTES:
333
+ # palabra completa: 'ci' no puede colarse dentro de 'licitación'
334
+ # o 'ciego' — la subcadena arruinaba el enrutado en español
335
+ score = sum(1 for p in r['patterns']
336
+ if re.search(rf'\b{re.escape(p)}\b', g))
337
+ if score:
338
+ scored.append((score, r))
339
+ if not scored:
340
+ best = next(r for r in ROUTES if r['id'] == 'start')
341
+ alt = []
342
+ else:
343
+ scored.sort(key=lambda x: -x[0])
344
+ best = scored[0][1]
345
+ alt = [r['id'] for _, r in scored[1:4]]
346
+ idx = 0 if t == 'es' else 1
347
+ steps_out = []
348
+ for i, one_step in enumerate(best['tools'], 1):
349
+ steps_out.append({'step': i, 'tool': one_step[0], 'why': one_step[idx]})
350
+ return {
351
+ 'mode': 'route', 'goal': goal, 'lang': t,
352
+ 'route': best['id'],
353
+ 'alternates': alt,
354
+ 'steps': steps_out,
355
+ 'prompts': [p for p in best['prompts']],
356
+ 'cli': best.get('cli'),
357
+ 'note': _NOTE[t],
358
+ }
359
+
360
+
361
+ def main(argv):
362
+ ap = argparse.ArgumentParser(description=__doc__)
363
+ ap.add_argument('--goal', default='', help='the task in plain language')
364
+ ap.add_argument('--url', help='diagnosis mode: read the page, order the exams')
365
+ ap.add_argument('--file', help='diagnosis mode: local HTML file')
366
+ ap.add_argument('--lang', default='en', choices=['en', 'es'])
367
+ a = ap.parse_args(argv)
368
+ html = None
369
+ if a.file:
370
+ with open(a.file, encoding='utf-8') as f:
371
+ html = f.read()
372
+ print(json.dumps(route(a.goal, lang=a.lang, url=a.url, html=html),
373
+ ensure_ascii=False, indent=1))
374
+ return 0
375
+
376
+
377
+ if __name__ == '__main__':
378
+ sys.exit(main(sys.argv[1:]))
@@ -0,0 +1,139 @@
1
+ #!/usr/bin/env python3
2
+ """SARIF 2.1.0 export — findings as GitHub code-scanning annotations.
3
+
4
+ Mechanism: findings travel in the OASIS interchange standard, not a bespoke
5
+ format. Upload with the official action:
6
+
7
+ - uses: github/codeql-action/upload-sarif@v3
8
+ with: { sarif_file: a11y.sarif }
9
+
10
+ Findings appear as repository alerts; in PRs, only new ones surface.
11
+
12
+ CLI:
13
+ a11ysarif.py --url https://example.com -o a11y.sarif [--lang es]
14
+ a11ysarif.py --from-audit audit.json -o a11y.sarif
15
+ """
16
+
17
+ import argparse
18
+ import json
19
+
20
+ from .a11yaudit import normalize_signal # noqa: E402 (compat 5.10)
21
+ import sys
22
+
23
+ from .a11yaudit import audit_url, audit_site, audit_html
24
+
25
+ LEVEL = {'high': 'error', 'medium': 'warning', 'low': 'note'}
26
+
27
+ # Criterio → Understanding URL oficial de WCAG 2.2
28
+ _UNDERSTANDING = {
29
+ '1.1.1': 'non-text-content',
30
+ '1.2.2': 'captions-prerecorded',
31
+ '1.3.1': 'info-and-relationships',
32
+ '1.3.5': 'identify-input-purpose',
33
+ '1.4.2': 'audio-control',
34
+ '1.4.3': 'contrast-minimum',
35
+ '1.4.4': 'resize-text',
36
+ '2.1.1': 'keyboard',
37
+ '2.2.1': 'timing-adjustable',
38
+ '2.4.1': 'bypass-blocks',
39
+ '2.4.2': 'page-titled',
40
+ '2.4.3': 'focus-order',
41
+ '2.4.4': 'link-purpose-in-context',
42
+ '2.4.7': 'focus-visible',
43
+ '2.5.8': 'target-size-minimum',
44
+ '3.1.1': 'language-of-page',
45
+ '3.2.5': 'change-on-request',
46
+ '3.3.2': 'labels-or-instructions',
47
+ '4.1.2': 'name-role-value',
48
+ }
49
+ _BASE = 'https://www.w3.org/WAI/WCAG22/Understanding/'
50
+
51
+
52
+ def _help_uri(criterion_text):
53
+ code = criterion_text.split(' ')[0]
54
+ slug = _UNDERSTANDING.get(code)
55
+ return _BASE + slug if slug else 'https://www.w3.org/TR/WCAG22/'
56
+
57
+
58
+ def from_report(report, driver_version='3.2.0'):
59
+ """Informe(s) del auditor → dict SARIF 2.1.0.
60
+
61
+ Acepta un informe individual (audit_html/audit_url) o uno 'site'
62
+ (con la lista 'reports')."""
63
+ pages = report.get('reports') if 'reports' in report else [report]
64
+ rules = {}
65
+ results = []
66
+ for pg in pages:
67
+ url = pg.get('url', '(html)')
68
+ for h in pg.get('findings', []):
69
+ code = h['criterion'].split(' ')[0]
70
+ rule_id = f'WCAG-{code}-{normalize_signal(h.get("signal", ""))}'
71
+ if rule_id not in rules:
72
+ rules[rule_id] = {
73
+ 'id': rule_id,
74
+ 'shortDescription': {'text': h['criterion']},
75
+ 'helpUri': _help_uri(h['criterion']),
76
+ }
77
+ message = h['issue']
78
+ if h.get('remediation'):
79
+ message += ' — Fix: ' + h['remediation']
80
+ results.append({
81
+ 'ruleId': rule_id,
82
+ 'level': LEVEL.get(h['severity'], 'note'),
83
+ 'message': {'text': message},
84
+ 'locations': [{
85
+ 'physicalLocation': {
86
+ 'artifactLocation': {'uri': url},
87
+ },
88
+ }],
89
+ })
90
+ return {
91
+ '$schema': 'https://json.schemastore.org/sarif-2.1.0.json',
92
+ 'version': '2.1.0',
93
+ 'runs': [{
94
+ 'tool': {'driver': {
95
+ 'name': 'a11y-toolkit',
96
+ 'version': driver_version,
97
+ 'informationUri': 'https://github.com/kinti/a11y-toolkit',
98
+ 'rules': sorted(rules.values(), key=lambda r: r['id']),
99
+ }},
100
+ 'results': results,
101
+ }],
102
+ }
103
+
104
+
105
+ def main(argv):
106
+ ap = argparse.ArgumentParser(description=__doc__)
107
+ g = ap.add_mutually_exclusive_group(required=True)
108
+ g.add_argument('--url')
109
+ g.add_argument('--file', help='HTML local')
110
+ g.add_argument('--from-audit', help='informe JSON ya generado')
111
+ ap.add_argument('-o', '--out', default='a11y.sarif')
112
+ ap.add_argument('--pages', type=int, default=1)
113
+ ap.add_argument('--lang', default='en', choices=['en', 'es'])
114
+ a = ap.parse_args(argv)
115
+ if a.from_audit:
116
+ with open(a.from_audit, encoding='utf-8') as f:
117
+ report = json.load(f)
118
+ elif a.url:
119
+ report = (audit_site(a.url, max_pages=a.pages, lang=a.lang)
120
+ if a.pages > 1 else audit_url(a.url, lang=a.lang))
121
+ else:
122
+ with open(a.file, encoding='utf-8', errors='replace') as f:
123
+ report = audit_html(f.read(), a.file, lang=a.lang)
124
+ if 'error' in report:
125
+ print(json.dumps(report))
126
+ return 1
127
+ sarif = from_report(report)
128
+ with open(a.out, 'w', encoding='utf-8') as f:
129
+ json.dump(sarif, f, ensure_ascii=False, indent=1)
130
+ summary = report.get('summary', {'high': 0, 'medium': 0, 'low': 0})
131
+ print(json.dumps({'sarif': a.out,
132
+ 'results': len(sarif['runs'][0]['results']),
133
+ 'score': report.get('score'),
134
+ 'summary': summary}))
135
+ return 0
136
+
137
+
138
+ if __name__ == '__main__':
139
+ sys.exit(main(sys.argv[1:]))