@kinti/a11y-toolkit 5.25.2 → 5.27.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 (44) hide show
  1. package/README.md +1 -1
  2. package/a11y_toolkit/a11y.py +31 -4
  3. package/a11y_toolkit/a11yact.py +9 -1
  4. package/a11y_toolkit/a11yannotate.py +185 -0
  5. package/a11y_toolkit/a11yaudit.py +903 -186
  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 +110 -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 +451 -96
  14. package/a11y_toolkit/a11yen301549.py +147 -0
  15. package/a11y_toolkit/a11yengines.py +157 -0
  16. package/a11y_toolkit/a11yevidence.py +182 -36
  17. package/a11y_toolkit/a11yfix.py +131 -52
  18. package/a11y_toolkit/a11yinit.py +30 -5
  19. package/a11y_toolkit/a11yjourney.py +110 -4
  20. package/a11y_toolkit/a11yledger.py +119 -12
  21. package/a11y_toolkit/a11ylocate.py +247 -0
  22. package/a11y_toolkit/a11yopenacr.py +28 -7
  23. package/a11y_toolkit/a11ypatches.py +154 -0
  24. package/a11y_toolkit/a11ypatterns.py +344 -0
  25. package/a11y_toolkit/a11ypdf.py +109 -53
  26. package/a11y_toolkit/a11yrgaa.py +60 -0
  27. package/a11y_toolkit/a11yroute.py +34 -12
  28. package/a11y_toolkit/a11ysarif.py +70 -21
  29. package/a11y_toolkit/a11yscope.py +296 -0
  30. package/a11y_toolkit/a11yscroll.py +7 -5
  31. package/a11y_toolkit/a11ystatement.py +30 -6
  32. package/a11y_toolkit/a11ytrace.py +293 -0
  33. package/a11y_toolkit/a11yvalidate.py +21 -15
  34. package/a11y_toolkit/a11yvpat.py +54 -11
  35. package/a11y_toolkit/a11yvtt.py +22 -6
  36. package/a11y_toolkit/a11ywiz.py +121 -0
  37. package/a11y_toolkit/contrast.py +62 -24
  38. package/a11y_toolkit/locales/en.json +222 -24
  39. package/a11y_toolkit/locales/es.json +223 -25
  40. package/a11y_toolkit/rgaa.json +2661 -0
  41. package/a11y_toolkit/server.py +247 -59
  42. package/package.json +2 -2
  43. package/a11y_toolkit/a11yplan.py +0 -214
  44. package/a11y_toolkit/a11ywcagem.py +0 -237
@@ -38,11 +38,20 @@ def _t(lang, key):
38
38
  return T.get(lang, T['en'])[key]
39
39
 
40
40
 
41
+ # Techos anti-bomba de descompresión: por stream y ACUMULADO entre streams
42
+ # (una bomba repartida en 100 streams de 20MB no descomprime 2GB; lo que
43
+ # llegó hasta el techo basta para auditar — doctrina de lectura parcial).
44
+ _STREAM_CAP = 20_000_000 # 20 MB por stream descomprimido
45
+ _STREAM_BUDGET = 120_000_000 # 120 MB en total entre todos los streams
46
+
47
+
41
48
  def _uncompressed_streams(data, limit=60):
42
49
  """Los streams FlateDecode, descomprimidos (zlib es stdlib) — ahí viven
43
50
  el XMP, el contenido y buena parte de la estructura."""
44
- out = []
51
+ out, total = [], 0
45
52
  for m in re.finditer(rb'stream\r?\n', data):
53
+ if total >= _STREAM_BUDGET:
54
+ break # techo acumulado: dejar de inflar, auditar lo que llegó
46
55
  start = m.end()
47
56
  end = data.find(b'endstream', start)
48
57
  if end == -1:
@@ -50,14 +59,92 @@ def _uncompressed_streams(data, limit=60):
50
59
  chunk = data[start:end].rstrip(b'\r\n')
51
60
  try:
52
61
  d = zlib.decompressobj()
53
- out.append(d.decompress(chunk, 20_000_000)) # bomba: techo por stream
62
+ dec = d.decompress(chunk, _STREAM_CAP) # bomba: techo por stream
54
63
  except Exception: # noqa: BLE001
55
64
  continue
65
+ out.append(dec)
66
+ total += len(dec)
56
67
  if len(out) >= limit:
57
68
  break
58
69
  return out
59
70
 
60
71
 
72
+ # ── 1.4.3 en PDF: contraste del texto contra el fondo efectivo ──
73
+ # Parseo de la secuencia de operadores: `rg`/`g`/`k` cambian el color de
74
+ # relleno (con el que se escribe texto), `re` declara un rectángulo —
75
+ # candidato a FONDO solo si un operador de pintado (f/F/B/B*/b) lo pinta
76
+ # después, con el relleno VIGENTE —, y `Tj`/`TJ` escriben texto (TJ también
77
+ # en forma de array: `[(H) -3 (ola)] TJ`). El fondo por defecto del PDF es
78
+ # blanco si nadie lo pinta: un rect oscuro pintado antes del texto cambia
79
+ # el fondo efectivo — no acusar blanco-sobre-oscuro como bajo (el mismo bug
80
+ # que CSS var() en HTML). Los operandos de `re` NUNCA se interpretan como
81
+ # color (bug histórico: `0 0 612 792 re` se leía como triple RGB).
82
+ _RE_STREAM_OPS = re.compile(
83
+ r'(?P<r>[\d.]+)\s+(?P<g>[\d.]+)\s+(?P<b>[\d.]+)\s+rg\b' # relleno RGB
84
+ r'|(?P<gray>[\d.]+)\s+g\b' # relleno gris
85
+ r'|(?P<k1>[\d.]+)\s+(?P<k2>[\d.]+)\s+(?P<k3>[\d.]+)\s+(?P<k4>[\d.]+)\s+k\b' # relleno CMYK
86
+ r'|(?P<x1>[\d.]+)\s+(?P<y1>[\d.]+)\s+(?P<w1>[\d.]+)\s+(?P<h1>[\d.]+)\s+re\b' # rectángulo
87
+ r'|(?P<paint>\b[fFBb]\*?(?![\w*]))' # pintado del path
88
+ r'|(?P<text>\((?:[^()\\]|\\.)*\)\s*(?:Tj|TJ)|\]\s*TJ)') # texto (cadena o array)
89
+
90
+
91
+ def _l(r, g, b):
92
+ def lin(v):
93
+ v /= 255.0
94
+ return v / 12.92 if v <= 0.03928 else ((v + 0.055) / 1.055) ** 2.4
95
+ return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
96
+
97
+
98
+ def _ratio(f, b):
99
+ l1, l2 = max(f, b), min(f, b)
100
+ return (l1 + 0.05) / (l2 + 0.05)
101
+
102
+
103
+ def _stream_low_contrast(text):
104
+ """Un content stream (ya decodificado latin-1) → lista de ejemplos
105
+ 'color sobre fondo' por debajo de 4.5:1. Escaneo secuencial
106
+ determinista de los operadores de color/pintado/texto."""
107
+ hits = []
108
+ fill = (0, 0, 0) # relleno vigente: el color con el que se escribe
109
+ bg = (255, 255, 255) # fondo efectivo: blanco salvo rect pintado
110
+ rect_pending = False # un `re` declarado, esperando su operador de pintado
111
+ for m in _RE_STREAM_OPS.finditer(text):
112
+ if m.group('r') is not None: # rg — relleno RGB
113
+ try:
114
+ fill = tuple(max(0, min(255, round(float(x) * 255)))
115
+ for x in (m.group('r'), m.group('g'), m.group('b')))
116
+ except ValueError:
117
+ pass
118
+ elif m.group('gray') is not None: # g — relleno en escala de grises
119
+ try:
120
+ v = max(0, min(255, round(float(m.group('gray')) * 255)))
121
+ fill = (v, v, v)
122
+ except ValueError:
123
+ pass
124
+ elif m.group('k1') is not None: # k — relleno CMYK (aprox. naive)
125
+ try:
126
+ c_, mm_, y_, black = (max(0.0, min(1.0, float(x))) for x in
127
+ (m.group('k1'), m.group('k2'),
128
+ m.group('k3'), m.group('k4')))
129
+ fill = tuple(max(0, min(255, round(255 * (1 - x) * (1 - black))))
130
+ for x in (c_, mm_, y_))
131
+ except ValueError:
132
+ pass
133
+ elif m.group('x1') is not None: # re — rectángulo: solo candidato a fondo
134
+ rect_pending = True # sin pintado posterior no cambia nada
135
+ elif m.group('paint') is not None: # f/F/B/B*/b — pinta el path pendiente
136
+ if rect_pending:
137
+ bg = fill # pintado con el relleno VIGENTE: ese rect es el fondo
138
+ rect_pending = False
139
+ else: # Tj / TJ — texto con el relleno vigente
140
+ ratio_ = _ratio(_l(*fill), _l(*bg))
141
+ if ratio_ < 4.5:
142
+ hits.append(f'rgb({fill[0]},{fill[1]},{fill[2]})'
143
+ f' sobre rgb({bg[0]},{bg[1]},{bg[2]})'
144
+ f' \u2192 {ratio_:.2f}:1')
145
+ return hits
146
+
147
+
61
148
  def pdf_screen(path_or_bytes, lang='en'):
62
149
  """Cribado estructural de accesibilidad de un PDF (fichero local)."""
63
150
  if isinstance(path_or_bytes, (bytes, bytearray)):
@@ -75,19 +162,33 @@ def pdf_screen(path_or_bytes, lang='en'):
75
162
  return {'error': 'not a PDF (no %PDF- marker)'}
76
163
 
77
164
  streams = _uncompressed_streams(data)
78
- todo = data + b'\n'.join(streams[:40])
165
+ # `todo` respeta el MISMO presupuesto acumulado: ensamblar 40 streams de
166
+ # 20MB sería una segunda bomba
167
+ parts, total_todo = [data], len(data)
168
+ for s in streams[:40]:
169
+ if total_todo + len(s) > _STREAM_BUDGET:
170
+ break
171
+ parts += [b'\n', s]
172
+ total_todo += len(s) + 1
173
+ todo = b''.join(parts)
79
174
 
80
175
  def present(pat):
81
176
  return re.search(pat, todo) is not None
82
177
 
83
178
  encrypted = b'/Encrypt' in data # el trailer vive al FINAL del fichero
84
- tagged = present(rb'/StructTreeRoot\s+\d+\s+0\s+R') or present(rb'/StructTreeRoot')
179
+ # tagged: la forma canónica es la referencia del catálogo (/StructTreeRoot
180
+ # N 0 R). Una mención suelta (p. ej. dentro de un content stream) solo
181
+ # cuenta como estructura cuando el documento además declara /Marked true.
85
182
  marked = present(rb'/Marked\s+true')
183
+ tagged = present(rb'/StructTreeRoot\s+\d+\s+0\s+R') or \
184
+ (marked and present(rb'/StructTreeRoot'))
86
185
  lang_doc = re.search(rb'/Lang\s*\(([^)]{2,20})\)', todo)
87
186
  title_meta = re.search(rb'/Title\s*\(([^)]{1,300})\)', todo) or \
88
187
  re.search(rb'<dc:title>.{0,200}?<rdf:li[^>]*>([^<]{1,300})</rdf:li>', todo, re.S)
89
188
  n_pages = len(re.findall(rb'/Type\s*/Page[^s]', todo))
90
- n_alt = len(re.findall(rb'/Alt\s*\(', todo))
189
+ # /Alt acepta literal (/Alt (…)) y hex (/Alt <FEFF…>, la forma natural
190
+ # UTF-16BE para alt no latino) — misma paridad que /TU
191
+ n_alt = len(re.findall(rb'/Alt\s*[<(]', todo))
91
192
  n_actual = len(re.findall(rb'/ActualText', todo))
92
193
  n_imgs = len(re.findall(rb'/Subtype\s*/Image', todo))
93
194
  n_outline = len(re.findall(rb'/Outlines\s+\d+\s+0\s+R', todo))
@@ -100,56 +201,11 @@ def pdf_screen(path_or_bytes, lang='en'):
100
201
  findings = []
101
202
 
102
203
  # ── 1.4.3 en PDF: contraste del texto contra el fondo efectivo ──
103
- # Parseo de la secuencia: `rg` cambia el color de relleno de texto,
104
- # `re` + `f` pinta un rectángulo (fondo), `Tj`/`TJ` escriben texto.
105
- # El fondo por defecto del PDF es blanco si nadie lo pinta. Si un rect
106
- # oscuro precede al texto, el fondo efectivo es ese fill — no acusar
107
- # blanco-sobre-oscuro como bajo (el mismo bug que CSS var() en HTML).
108
- def _l(r, g, b):
109
- def lin(v):
110
- v /= 255.0
111
- return v / 12.92 if v <= 0.03928 else ((v + 0.055) / 1.055) ** 2.4
112
- return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
113
-
114
- def _ratio(f, b):
115
- l1, l2 = max(f, b), min(f, b)
116
- return (l1 + 0.05) / (l2 + 0.05)
117
-
118
- blanc = _l(255, 255, 255)
119
204
  low_hits = []
120
205
  for stream in streams:
121
- text = stream.decode('latin-1', 'replace')
122
- text_color = (0, 0, 0)
123
- bg_color = (255, 255, 255) # el PDF no pinta fondo por defecto
124
- painted_bg = False
125
- for m in re.finditer(
126
- r'([\d.]+)\s+([\d.]+)\s+([\d.]+)\s+(rg|re)\b'
127
- r'|\b(f)\b'
128
- r'|\((?:[^()\\]|\\.)*\)\s*(Tj|TJ)'
129
- , text):
130
- op = m.group(4) or m.group(5) or m.group(6)
131
- if op in ('rg', 're'):
132
- try:
133
- text_color = tuple(
134
- max(0, min(255, round(float(x) * 255)))
135
- for x in m.groups()[:3])
136
- except ValueError:
137
- pass
138
- if op == 're':
139
- # el rect se pinta con el fill actual: es el FONDO
140
- bg_color = text_color
141
- elif op == 'f':
142
- pass # el f pinta con el fill ya establecido (fondo ya guardado)
143
- else: # Tj / TJ
144
- lt = _l(*text_color)
145
- lb = _l(*bg_color)
146
- ratio = _ratio(lt, lb)
147
- if ratio < 4.5:
148
- ej = (f'rgb({text_color[0]},{text_color[1]},{text_color[2]})'
149
- f' sobre rgb({bg_color[0]},{bg_color[1]},{bg_color[2]})'
150
- f' \u2192 {ratio:.2f}:1')
151
- if ej not in [x.split(' \u2014 ')[0] for x in low_hits]:
152
- low_hits.append(ej)
206
+ for ej in _stream_low_contrast(stream.decode('latin-1', 'replace')):
207
+ if ej not in low_hits:
208
+ low_hits.append(ej)
153
209
  if len(low_hits) >= 4:
154
210
  break
155
211
  if low_hits:
@@ -0,0 +1,60 @@
1
+ #!/usr/bin/env python3
2
+ """RGAA 4.1 — the French legal standard as data.
3
+
4
+ Generated by scripts/rgaa_ingest.py from the OFFICIAL government JSON
5
+ (github.com/DISIC/accessibilite.numerique.gouv.fr — open data, 106/106
6
+ criteria with a mechanical bridge to WCAG SC). This module is the thin
7
+ loader + the lookup surfaces other modules use; never hand-edit the JSON.
8
+
9
+ The RGAA has its own numbering (1.1–13.12 across 13 topics) and NO A/AA
10
+ levels — every criterion is conformant / not conformant. Titles and tests
11
+ are French (the standard's language); the WCAG bridge lives in each
12
+ criterion's `wcag` list.
13
+ """
14
+
15
+ import json
16
+ import os
17
+
18
+ _HERE = os.path.dirname(os.path.abspath(__file__))
19
+
20
+ with open(os.path.join(_HERE, 'rgaa.json'), encoding='utf-8') as _f:
21
+ _DATA = json.load(_f)
22
+
23
+ STANDARD_NAME = 'RGAA 4.1 (France)'
24
+ VERSION = _DATA['version']
25
+ WCAG_BASE = _DATA['wcag_base']
26
+ SOURCE = _DATA['source']
27
+ TOPICS = [(t['number'], t['name']) for t in _DATA['topics']]
28
+ CRITERIA = _DATA['criteria'] # 106: {num, topic, number, title, tests, notes, wcag}
29
+
30
+ # índice inverso: WCAG SC code → [números RGAA] (el puente mecánico)
31
+ _BY_SC = {}
32
+ for _c in CRITERIA:
33
+ for _w in _c['wcag']:
34
+ _sc = _w.split(' ')[0]
35
+ _BY_SC.setdefault(_sc, []).append(_c['num'])
36
+
37
+
38
+ def rgaa_for_sc(sc_code):
39
+ """'1.1.1' → ['1.1', …]: los criterios RGAA que verifican ese SC.
40
+ Devuelve [] si ningún criterio RGAA lo referencia."""
41
+ return list(_BY_SC.get(sc_code, []))
42
+
43
+
44
+ def criterion(num):
45
+ """'1.1' → el criterio completo, o None."""
46
+ return next((c for c in CRITERIA if c['num'] == num), None)
47
+
48
+
49
+ def standard_block(lang='en'):
50
+ """Bloque 'standard' para informes audit --standard rgaa."""
51
+ names = {'en': 'RGAA 4.1 — the French web accessibility framework',
52
+ 'es': 'RGAA 4.1 — el marco francés de accesibilidad web'}
53
+ return {
54
+ 'name': names.get(lang) or names['en'],
55
+ 'version': VERSION,
56
+ 'topics': len(TOPICS),
57
+ 'criteria': len(CRITERIA),
58
+ 'wcag_base': WCAG_BASE,
59
+ 'source': SOURCE,
60
+ }
@@ -105,8 +105,12 @@ ROUTES = [
105
105
  'cli': 'a11ytoolkit kbd https://…',
106
106
  'prompts': []},
107
107
  {'id': 'statement',
108
+ # 'document' lives HERE, not in the pdf route: the English verb ("document
109
+ # the accessibility of my site") is a statement goal; pdf keywords stay
110
+ # unambiguous (pdf/docx/word/'documento')
108
111
  'patterns': ['statement', 'declaración', 'declaracion', 'eaa', 'ley',
109
- 'legal', 'rd 1112', 'acta', '11/2023', 'compliance doc'],
112
+ 'legal', 'rd 1112', 'acta', '11/2023', 'compliance doc',
113
+ 'document'],
110
114
  'tools': [
111
115
  ('a11y_audit_url', 'los hallazgos alimentan la lista de contenido no accesible',
112
116
  'findings feed the non-accessible content list'),
@@ -142,7 +146,7 @@ ROUTES = [
142
146
  'cli': 'a11ytoolkit vpat pack.json --product "Acme" -o vpat.html',
143
147
  'prompts': []},
144
148
  {'id': 'media',
145
- 'patterns': ['video', 'caption', 'subtítulo', 'subtitulo', 'subtitulo',
149
+ 'patterns': ['video', 'caption', 'subtítulo', 'subtitulo',
146
150
  'vtt', 'audio description', 'audiodescripción', 'podcast'],
147
151
  'tools': [
148
152
  ('a11y_vtt_check', 'el CONTENIDO de los subtítulos: cps, solapes, cobertura',
@@ -152,7 +156,7 @@ ROUTES = [
152
156
  ],
153
157
  'cli': None, 'prompts': []},
154
158
  {'id': 'pdf',
155
- 'patterns': ['pdf', 'documento', 'document', 'docx', 'word', 'informe pdf'],
159
+ 'patterns': ['pdf', 'documento', 'docx', 'word', 'informe pdf'],
156
160
  'tools': [
157
161
  ('a11y_audit_pdf', 'cribado estructural + formularios: lo que nadie automatiza',
158
162
  'structural screening + forms: what nobody automates'),
@@ -233,39 +237,55 @@ _NOTE = {
233
237
  # ── diagnóstico secuencial: la EVIDENCIA manda, la severidad solo desempata ──
234
238
  # Traducción cruzada del diagnóstico diferencial (medicina): primero la
235
239
  # 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:
240
+ # examen reduce más la incertumbre. No es una prioridad fija de criterios:
237
241
  # una página sin formularios no necesita el examen de formularios por muy
238
242
  # grave que sea 3.3.1 sobre el papel. detect() devuelve None (síntoma
239
- # ausente) o la evidencia en una línea.
243
+ # ausente) o el dato crudo; la línea de evidencia se redacta por idioma
244
+ # con _DIAG_EV (antes llegaba siempre en inglés, también con lang='es').
240
245
  _DIAG = [
241
246
  {'id': 'forms', 'severity': 'high', 'tool': 'a11y_forms',
242
247
  # ojo: sin \b dentro de las llaves del f-string (barra invertida DENTRO
243
248
  # de llaves es SyntaxError antes de 3.12; el guardián de test_solido lo
244
249
  # 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'
250
+ 'detect': lambda h: (len(re.findall(r"<(?:input|select|textarea)", h))
246
251
  if re.search(r'<(?:input|select|textarea)\b', h) else None),
247
252
  'why': ('formularios presentes: rellenar inválido, enviar y juzgar el aviso de errores',
248
253
  'forms present: fill invalid data, submit, judge the error announcement')},
249
254
  {'id': 'menus', 'severity': 'high', 'tool': 'a11y_keyboard',
250
- 'detect': lambda h: ('menus or disclosure widgets'
255
+ 'detect': lambda h: (True
251
256
  if re.search(r'<(?:nav|details)\b|aria-expanded', h) else None),
252
257
  'why': ('menús o desplegables: la zona clásica de trampas de teclado',
253
258
  'menus or disclosure widgets: the classic keyboard-trap zone')},
254
259
  {'id': 'video', 'severity': 'medium', 'tool': 'a11y_vtt_check',
255
- 'detect': lambda h: (f'{h.count("<video")} <video>' if '<video' in h else None),
260
+ 'detect': lambda h: (h.count('<video') if '<video' in h else None),
256
261
  'why': ('vídeo presente: que existan subtítulos no basta — juzgar su CONTENIDO',
257
262
  'video present: captions existing is not enough — judge their CONTENT')},
258
263
  {'id': 'animation', 'severity': 'medium', 'tool': 'a11y_reduced_motion',
259
- 'detect': lambda h: ('animated content'
264
+ 'detect': lambda h: (True
260
265
  if re.search(r'animation|transition|<marquee', h) else None),
261
266
  'why': ('contenido animado: ¿respeta prefers-reduced-motion?',
262
267
  'animated content: does it honor prefers-reduced-motion?')},
263
268
  {'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),
269
+ 'detect': lambda h: (h.count('<svg') if h.count('<svg') >= 2 else None),
265
270
  'why': ('iconografía SVG en volumen: los fills fijos caen en forced-colors',
266
271
  'SVG iconography at volume: hardcoded fills fall in forced-colors')},
267
272
  ]
268
273
 
274
+ # evidencia por síntoma e idioma: {n} recibe el dato crudo de detect()
275
+ _DIAG_EV = {
276
+ 'forms': {'es': '{n} campos de formulario', 'en': '{n} form fields'},
277
+ 'menus': {'es': 'menús o desplegables', 'en': 'menus or disclosure widgets'},
278
+ 'video': {'es': '{n} <video>', 'en': '{n} <video>'},
279
+ 'animation': {'es': 'contenido animado', 'en': 'animated content'},
280
+ 'svg': {'es': '{n} <svg> inline', 'en': '{n} inline <svg>'},
281
+ }
282
+
283
+
284
+ def _evidence(sid, raw, lang):
285
+ """La línea de evidencia de un síntoma, en el idioma pedido."""
286
+ tpl = _DIAG_EV[sid]['es' if lang == 'es' else 'en']
287
+ return tpl.format(n=raw) if isinstance(raw, int) else tpl
288
+
269
289
  _RANK = {'high': 0, 'medium': 1, 'low': 2}
270
290
 
271
291
  _GUARANTEE = {
@@ -291,7 +311,8 @@ def diagnose(html_text, url='(html)', lang='en', goal=None):
291
311
  for d in _DIAG:
292
312
  ev = d['detect'](html_text)
293
313
  if ev:
294
- symptoms.append({'symptom': d['id'], 'evidence': ev})
314
+ symptoms.append({'symptom': d['id'],
315
+ 'evidence': _evidence(d['id'], ev, t)})
295
316
  hit.append(d)
296
317
  # sort estable: severidad como desempate, orden de tabla dentro de cada nivel
297
318
  hit.sort(key=lambda d: _RANK[d['severity']])
@@ -301,7 +322,8 @@ def diagnose(html_text, url='(html)', lang='en', goal=None):
301
322
  evidences = {d['id']: d['detect'](html_text) for d in _DIAG}
302
323
  for i, d in enumerate(hit, 2):
303
324
  steps.append({'step': i, 'tool': d['tool'], 'why': d['why'][idx],
304
- 'symptom': d['id'], 'evidence': evidences[d['id']]})
325
+ 'symptom': d['id'],
326
+ 'evidence': _evidence(d['id'], evidences[d['id']], t)})
305
327
  steps.append({'step': len(steps) + 1, 'tool': 'a11y_audit_dom',
306
328
  'why': ('profundizar lo que el estático no ve: contraste computado, 2.5.8, foco',
307
329
  'deepen what static cannot see: computed contrast, 2.5.8, focus')[idx]})
@@ -17,6 +17,7 @@ CLI:
17
17
  import argparse
18
18
  import json
19
19
 
20
+ from .a11yact import _NOT_DEAD
20
21
  from .a11yaudit import normalize_signal # noqa: E402 (compat 5.10)
21
22
  import sys
22
23
 
@@ -55,31 +56,67 @@ def _help_uri(criterion_text):
55
56
  return _BASE + slug if slug else 'https://www.w3.org/TR/WCAG22/'
56
57
 
57
58
 
58
- def from_report(report, driver_version='3.2.0'):
59
+ def from_report(report, driver_version=None, standard=None, target=None):
59
60
  """Informe(s) del auditor → dict SARIF 2.1.0.
60
61
 
61
62
  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]
63
+ (con la lista 'reports'). Con standard='en301549' cada regla gana
64
+ properties/tags con su cláusula EN 301 549 V4.1.1 (9.x web por defecto,
65
+ 10.x documents, 11.x software) — filtrable en code scanning."""
66
+ if driver_version is None:
67
+ # versión del driver = fuente única (estaba congelada en '3.2.0' con el
68
+ # motor en 5.26: GitHub mostraba una versión muerta en code scanning)
69
+ from .server import VERSION as _V # lazy: server importa este módulo
70
+ driver_version = _V
71
+ from . import a11yen301549 as _enstd
72
+ pages = report.get('reports') if isinstance(report.get('reports'), list) else [report]
64
73
  rules = {}
65
74
  results = []
75
+ skipped = 0 # hallazgos truncados/hostiles: se saltan, jamás un KeyError
76
+ _tgt = target or _enstd.target_for_mode(report.get('mode', 'static'))
66
77
  for pg in pages:
78
+ if not isinstance(pg, dict):
79
+ skipped += 1
80
+ continue
67
81
  url = pg.get('url', '(html)')
68
- for h in pg.get('findings', []):
69
- code = h['criterion'].split(' ')[0]
82
+ for h in pg.get('findings', []) or []:
83
+ if not isinstance(h, dict):
84
+ skipped += 1
85
+ continue
86
+ if h.get('status') in _NOT_DEAD or h.get('disprover_status') in _NOT_DEAD:
87
+ # hallazgo muerto (disprover rejected / not-rechecked): no es
88
+ # evidencia y no navega a GitHub como alerta viva
89
+ continue
90
+ crit, issue = h.get('criterion'), h.get('issue')
91
+ if not isinstance(crit, str) or not isinstance(issue, str):
92
+ skipped += 1
93
+ continue # --from-audit hostil/truncado: degradar, no caer
94
+ code = crit.split(' ')[0]
70
95
  rule_id = f'WCAG-{code}-{normalize_signal(h.get("signal", ""))}'
71
96
  if rule_id not in rules:
72
- rules[rule_id] = {
97
+ rule = {
73
98
  'id': rule_id,
74
- 'shortDescription': {'text': h['criterion']},
75
- 'helpUri': _help_uri(h['criterion']),
99
+ 'shortDescription': {'text': crit},
100
+ 'helpUri': _help_uri(crit),
76
101
  }
77
- message = h['issue']
102
+ # target explícito = mandato del usuario: recalcula SIEMPRE
103
+ # (las cláusulas embebidas pueden ser de otro target); sin
104
+ # target, la embebida manda (misma fuente, misma pasada)
105
+ clause = (_enstd.clause_for(code, _tgt) if target
106
+ else (h.get('clause') or _enstd.clause_for(code, _tgt)))
107
+ if standard == 'en301549' and clause:
108
+ rule['properties'] = {
109
+ 'standard': _enstd.STANDARD_NAME,
110
+ 'en301549': clause,
111
+ 'tags': [f'en301549:{clause}', 'wcag22:' + code],
112
+ }
113
+ rules[rule_id] = rule
114
+ message = issue
78
115
  if h.get('remediation'):
79
- message += ' — Fix: ' + h['remediation']
116
+ message += ' — Fix: ' + str(h['remediation'])
80
117
  results.append({
81
118
  'ruleId': rule_id,
82
- 'level': LEVEL.get(h['severity'], 'note'),
119
+ 'level': LEVEL.get(h.get('severity'), 'note'),
83
120
  'message': {'text': message},
84
121
  'locations': [{
85
122
  'physicalLocation': {
@@ -87,18 +124,22 @@ def from_report(report, driver_version='3.2.0'):
87
124
  },
88
125
  }],
89
126
  })
127
+ run = {
128
+ 'tool': {'driver': {
129
+ 'name': 'a11y-toolkit',
130
+ 'version': driver_version,
131
+ 'informationUri': 'https://github.com/kinti/a11y-toolkit',
132
+ 'rules': sorted(rules.values(), key=lambda r: r['id']),
133
+ }},
134
+ 'results': results,
135
+ }
136
+ if skipped:
137
+ # exportación degradada, no silenciada: lo saltado queda contado
138
+ run['properties'] = {'skippedFindings': skipped}
90
139
  return {
91
140
  '$schema': 'https://json.schemastore.org/sarif-2.1.0.json',
92
141
  '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
- }],
142
+ 'runs': [run],
102
143
  }
103
144
 
104
145
 
@@ -111,6 +152,12 @@ def main(argv):
111
152
  ap.add_argument('-o', '--out', default='a11y.sarif')
112
153
  ap.add_argument('--pages', type=int, default=1)
113
154
  ap.add_argument('--lang', default='en', choices=['en', 'es'])
155
+ ap.add_argument('--standard', choices=['en301549'], default=None,
156
+ help='añade cláusula EN 301 549 V4.1.1 a cada regla '
157
+ '(properties + tags, filtrable en code scanning)')
158
+ ap.add_argument('--target', choices=['web', 'documents', 'software'],
159
+ default=None, help='target EN: web=9.x, documents=10.x, '
160
+ 'software=11.x (default: según el modo del informe)')
114
161
  a = ap.parse_args(argv)
115
162
  if a.from_audit:
116
163
  with open(a.from_audit, encoding='utf-8') as f:
@@ -124,12 +171,14 @@ def main(argv):
124
171
  if 'error' in report:
125
172
  print(json.dumps(report))
126
173
  return 1
127
- sarif = from_report(report)
174
+ sarif = from_report(report, standard=a.standard, target=a.target)
128
175
  with open(a.out, 'w', encoding='utf-8') as f:
129
176
  json.dump(sarif, f, ensure_ascii=False, indent=1)
130
177
  summary = report.get('summary', {'high': 0, 'medium': 0, 'low': 0})
131
178
  print(json.dumps({'sarif': a.out,
132
179
  'results': len(sarif['runs'][0]['results']),
180
+ 'skipped': sarif['runs'][0].get('properties', {})
181
+ .get('skippedFindings', 0),
133
182
  'score': report.get('score'),
134
183
  'summary': summary}))
135
184
  return 0