@kinti/a11y-toolkit 5.31.0 → 5.33.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.
@@ -20,7 +20,7 @@ must not mutate the page it measures.
20
20
  CLI (infrastructure, not a tool — D17, like corpus/mutants/engines):
21
21
  a11ytrace.py https://web [--steps 25] [-o trace.json] # needs Playwright
22
22
  a11ytrace.py https://web --script journey.json -o t.json # scripted real journey
23
- a11ytrace.py diff before.json after.json # exit 0 ok / 2 divergences
23
+ a11ytrace.py diff before.json after.json # exit 0 ok / 1 invalid / 2 regression
24
24
 
25
25
  Script file: a JSON list of actions — {"kind":"click","selector":"#pay"},
26
26
  {"kind":"fill","selector":"#email","value":"…"}, {"kind":"select",…},
@@ -82,6 +82,33 @@ _COLLECTOR = r'''() => {
82
82
  # aún no existe — el paso se graba, simplemente sin anuncios de ese instante.
83
83
  _DRAIN = '() => window.__a11yTraceDrain ? window.__a11yTraceDrain() : []'
84
84
 
85
+ # (issue #16) estado de diálogo TRAS cada acción — mínimo y no sensible: el
86
+ # CONTEO de modales abiertos (role=dialog/alertdialog con aria-modal, o
87
+ # dialog[open]) y si el foco está dentro de uno. Nada de contenido, ids ni
88
+ # texto: dos builds con el mismo viaje deben poder comparar este estado sin
89
+ # que nada de la página viaje al JSON
90
+ _DIALOG_STATE_JS = '''() => {
91
+ const modals = [...document.querySelectorAll(
92
+ '[role="dialog"][aria-modal="true"], [role="alertdialog"][aria-modal="true"], dialog[open]')]
93
+ .filter(el => el.getClientRects().length > 0); // display:none (hidden) no cuenta,
94
+ // aunque el CSS fije position (getClientRects mide lo real)
95
+ const a = document.activeElement;
96
+ return {open: modals.length, focus_inside: modals.some(m => m === a || m.contains(a))};
97
+ }'''
98
+
99
+
100
+ class _TraceHttpError(Exception):
101
+ def __init__(self, status, url):
102
+ super().__init__(f'HTTP {status}: could not capture the requested page')
103
+ self.status = status
104
+ self.url = url
105
+
106
+
107
+ def _goto(page, url, timeout):
108
+ response = page.goto(url, wait_until='load', timeout=timeout)
109
+ if response is not None and response.status >= 400:
110
+ raise _TraceHttpError(response.status, page.url)
111
+
85
112
 
86
113
  def _run_script_action(page, act):
87
114
  """One scripted action → (label, ok). Selector-valued actions target CSS."""
@@ -104,7 +131,7 @@ def _run_script_action(page, act):
104
131
  page.wait_for_timeout(int(act.get('ms', 300)))
105
132
  return f'wait:{act.get("ms", 300)}', True
106
133
  if kind == 'goto':
107
- page.goto(act.get('url', ''), wait_until='load', timeout=30000)
134
+ _goto(page, act.get('url', ''), timeout=30000)
108
135
  # la navegación destruye el recolector (contexto nuevo): re-inyectarlo
109
136
  # o el drain de ESTE paso y de los siguientes tronaría/volvería vacío
110
137
  page.evaluate(_COLLECTOR)
@@ -112,7 +139,7 @@ def _run_script_action(page, act):
112
139
  return f'unknown:{kind or sel}', False
113
140
 
114
141
 
115
- def _run_script(page, script):
142
+ def _run_script(page, script, dialog_state=False):
116
143
  """Scripted actions → (walk, navigations). Factored out of trace() so the
117
144
  loop is testable against a fake page (no Playwright needed)."""
118
145
  walk = []
@@ -123,6 +150,8 @@ def _run_script(page, script):
123
150
  continue
124
151
  try:
125
152
  label, _ok = _run_script_action(page, act)
153
+ except _TraceHttpError:
154
+ raise
126
155
  except Exception as e: # noqa: BLE001 — a failed action is a recorded step too
127
156
  label = f'{act.get("kind", "?")}:{act.get("selector") or act.get("key") or ""}'
128
157
  label += f' (failed: {str(e)[:60]})'
@@ -132,25 +161,40 @@ def _run_script(page, script):
132
161
  if page.url != url_now:
133
162
  navigations += 1
134
163
  url_now = page.url
135
- walk.append({'step': i + 1, 'action': label, 'focus': info,
136
- 'announcements': anns, 'url': page.url})
164
+ step = {'step': i + 1, 'action': label, 'focus': info,
165
+ 'announcements': anns, 'url': page.url}
166
+ if dialog_state:
167
+ try:
168
+ step['dialog'] = page.evaluate(_DIALOG_STATE_JS)
169
+ except Exception: # noqa: BLE001 — contexto destruido: sin dato
170
+ step['dialog'] = None
171
+ walk.append(step)
137
172
  return walk, navigations
138
173
 
139
174
 
140
- def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None, browser='auto'):
175
+ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None, browser='auto',
176
+ capture_dialog_state=False):
141
177
  """One url → the behavioral trace (replayable JSON).
142
178
 
143
179
  script: optional list of scripted actions (click/fill/select/press/wait/
144
180
  goto, each with a CSS selector where applicable) — a REAL journey instead
145
181
  of the keyboard walk. Each action becomes a recorded step; the announcement
146
182
  collector and the focus signature stay identical, so trace diff works the
147
- same over scripted traces."""
183
+ same over scripted traces.
184
+
185
+ capture_dialog_state (issue #16): graba tras cada paso el estado mínimo
186
+ de diálogo (cuántos modales abiertos + foco dentro de uno) — nada de
187
+ contenido. Para trace diff --gate-dialog-state: un Escape que devuelve
188
+ el foco al opener pero DEJA el modal abierto es una divergencia de
189
+ estado que el foco solo no ve."""
148
190
  from .a11ydom import _get_browser, _pooled_page
149
191
  nav = _get_browser(preferred=browser)
150
192
  page, close_page = _pooled_page(nav, auth_state)
151
193
  try:
152
194
  try:
153
- page.goto(url, wait_until='load', timeout=timeout * 1000)
195
+ _goto(page, url, timeout=timeout * 1000)
196
+ except _TraceHttpError:
197
+ raise
154
198
  except Exception as e: # noqa: BLE001
155
199
  return {'error': f'could not load: {e}'}
156
200
  page.wait_for_timeout(400)
@@ -161,7 +205,7 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
161
205
  url_now = page.url
162
206
  if script:
163
207
  ended_by = 'script_done'
164
- walk, navigations = _run_script(page, script)
208
+ walk, navigations = _run_script(page, script, dialog_state=capture_dialog_state)
165
209
  else:
166
210
  ended_by = 'step_cap'
167
211
  for i in range(steps):
@@ -175,8 +219,14 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
175
219
  if page.url != url_now:
176
220
  navigations += 1
177
221
  url_now = page.url
178
- walk.append({'step': i + 1, 'focus': info,
179
- 'announcements': anns, 'url': page.url})
222
+ step = {'step': i + 1, 'focus': info,
223
+ 'announcements': anns, 'url': page.url}
224
+ if capture_dialog_state:
225
+ try:
226
+ step['dialog'] = page.evaluate(_DIALOG_STATE_JS)
227
+ except Exception: # noqa: BLE001
228
+ step['dialog'] = None
229
+ walk.append(step)
180
230
 
181
231
  tree = None
182
232
  try:
@@ -185,11 +235,14 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
185
235
  tree = tree[:60_000] + '\n… (truncated)'
186
236
  except Exception: # noqa: BLE001
187
237
  tree = None
238
+ except _TraceHttpError as e:
239
+ return {'error': str(e), 'url': e.url, 'http_status': e.status}
188
240
  finally:
189
241
  close_page()
190
242
 
191
243
  data = {'mode': 'trace', 'url': url,
192
244
  'ts': datetime.now(timezone.utc).isoformat(),
245
+ **({'dialog_state_captured': True} if capture_dialog_state else {}),
193
246
  'steps': walk,
194
247
  'summary': {'steps_taken': len(walk),
195
248
  'announcements': sum(len(s.get('announcements') or [])
@@ -204,10 +257,84 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
204
257
  return data
205
258
 
206
259
 
207
- def trace_diff(a, b):
208
- """Two traces → verdict. Focus behavior gates; announcements inform."""
209
- fa = [s.get('focus') for s in a.get('steps', [])]
210
- fb = [s.get('focus') for s in b.get('steps', [])]
260
+ def _has_dialog_state(state):
261
+ return (isinstance(state, dict)
262
+ and type(state.get('open')) is int and state['open'] >= 0
263
+ and isinstance(state.get('focus_inside'), bool))
264
+
265
+
266
+ def _dialog_gate(a, b):
267
+ """(issue #16) comparación OPT-IN del estado de diálogo por paso.
268
+
269
+ Devuelve {'status': 'off'|'inconclusive'|'pass'|'regression', ...}:
270
+ - off: no se pidió el gate
271
+ - inconclusive: falta estado (alguna traza sin dialog_state_captured,
272
+ un paso sin 'dialog') o las SECUENCIAS DE ACCIÓN divergen (el estado
273
+ solo es comparable paso a paso cuando el viaje es el mismo) — JAMÁS
274
+ un falso PASS
275
+ - regression: mismas acciones y foco, pero el estado de diálogo difiere
276
+ en algún paso (p. ej. el Escape dejó el modal abierto en el candidato)
277
+ - pass: estado idéntico en todos los pasos
278
+ """
279
+ sa = a.get('steps', [])
280
+ sb = b.get('steps', [])
281
+ if not (a.get('dialog_state_captured') and b.get('dialog_state_captured')):
282
+ return {'status': 'inconclusive',
283
+ 'reason': 'dialog state not captured in both traces — re-run '
284
+ 'trace --capture-dialog-state'}
285
+ acts_a = [s.get('action') for s in sa]
286
+ acts_b = [s.get('action') for s in sb]
287
+ if acts_a != acts_b or len(sa) != len(sb):
288
+ return {'status': 'inconclusive',
289
+ 'reason': 'action sequences diverge — dialog state is only '
290
+ 'comparable step-by-step on the same journey'}
291
+ if not sa:
292
+ return {'status': 'inconclusive', 'reason': 'no steps with dialog evidence'}
293
+ state_divergences = []
294
+ for i, (x, y) in enumerate(zip(sa, sb)):
295
+ if not (_has_dialog_state(x.get('dialog')) and _has_dialog_state(y.get('dialog'))):
296
+ return {'status': 'inconclusive',
297
+ 'reason': f'step {i + 1} lacks dialog state (destroyed '
298
+ 'context?) — evidence missing'}
299
+ if x['dialog'] != y['dialog']:
300
+ state_divergences.append({'step': i + 1, 'before': x['dialog'],
301
+ 'after': y['dialog']})
302
+ if state_divergences:
303
+ return {'status': 'regression', 'divergences': state_divergences}
304
+ return {'status': 'pass', 'steps_compared': len(sa)}
305
+
306
+
307
+ def _trace_error(trace):
308
+ if not isinstance(trace, dict):
309
+ return 'expected a trace object'
310
+ if 'error' in trace or (
311
+ type(trace.get('http_status')) is int and trace['http_status'] >= 400):
312
+ return 'capture failed'
313
+ if not isinstance(trace.get('steps'), list):
314
+ return 'expected a steps list'
315
+ for index, step in enumerate(trace['steps'], 1):
316
+ if (not isinstance(step, dict) or 'focus' not in step
317
+ or (step['focus'] is not None and not isinstance(step['focus'], str))
318
+ or (step.get('announcements') is not None
319
+ and not isinstance(step['announcements'], list))):
320
+ return f'invalid step {index}'
321
+ return None
322
+
323
+
324
+ def trace_diff(a, b, gate_dialog_state=False):
325
+ """Two traces → verdict. Focus behavior gates; announcements inform.
326
+
327
+ gate_dialog_state (issue #16): OPT-IN — compara también el estado de
328
+ diálogo capturado (trace --capture-dialog-state). Sin foco perdido ni
329
+ reordenado pero con el modal ABIERTO donde antes cerraba: regresión.
330
+ Evidencia faltante o acciones distintas → INCONCLUSIVE, nunca un falso
331
+ PASS. El foco sigue siendo el único gate por defecto."""
332
+ for label, capture in (('reference', a), ('candidate', b)):
333
+ error = _trace_error(capture)
334
+ if error:
335
+ return {'ok': False, 'error': f'{label} trace: {error}'}
336
+ fa = [s['focus'] for s in a['steps']]
337
+ fb = [s['focus'] for s in b['steps']]
211
338
  set_a, set_b = set(fa), set(fb)
212
339
  common_a = [x for x in fa if x in set_b]
213
340
  common_b = [x for x in fb if x in set_a]
@@ -216,24 +343,33 @@ def trace_diff(a, b):
216
343
  reordered = common_a != common_b
217
344
  first_divergence = next((i for i, (x, y) in enumerate(zip(common_a, common_b))
218
345
  if x != y), None)
219
- ann_a = sum(len(s.get('announcements', [])) for s in a.get('steps', []))
220
- ann_b = sum(len(s.get('announcements', [])) for s in b.get('steps', []))
346
+ ann_a = sum(len(s.get('announcements') or []) for s in a['steps'])
347
+ ann_b = sum(len(s.get('announcements') or []) for s in b['steps'])
221
348
  collapsed = ann_a > 0 and ann_b == 0
349
+ gate = _dialog_gate(a, b) if gate_dialog_state else {'status': 'off'}
222
350
  ok = not (lost or reordered)
351
+ if gate['status'] == 'regression':
352
+ ok = False # el estado diverge con las mismas acciones: bloquea
223
353
  return {
224
354
  'ok': ok,
225
355
  'summary': {'steps': {'before': len(fa), 'after': len(fb)},
226
356
  'focus_lost': len(lost), 'focus_gained': len(gained),
227
357
  'reordered': reordered,
358
+ 'dialog_gate': gate['status'],
228
359
  'announcements': {'before': ann_a, 'after': ann_b,
229
360
  'collapsed': collapsed}},
230
361
  'focus': {'before': fa, 'after': fb, 'lost': lost, 'gained': gained,
231
362
  'first_divergence': first_divergence},
363
+ **({'dialog_gate': gate} if gate_dialog_state else {}),
232
364
  'note': ('focus behavior is the gate: a lost or forked tab sequence '
233
365
  'blocks (exit 2). Announcement counts are reported, not '
234
366
  'gated — content changes legitimately between builds; a '
235
367
  'collapsed layer (had announcements, now zero) is flagged '
236
- 'informationally'),
368
+ 'informationally'
369
+ + (' — dialog gate ON (opt-in): same actions + same focus '
370
+ 'but diverging modal state blocks; missing evidence or '
371
+ 'diverging actions read INCONCLUSIVE, never a pass'
372
+ if gate_dialog_state else '')),
237
373
  }
238
374
 
239
375
 
@@ -250,10 +386,16 @@ def main(argv):
250
386
  s1.add_argument('--script', help='JSON file: scripted journey (click/fill/select/press/wait/goto)')
251
387
  s1.add_argument('--auth-state', help='Playwright storage_state JSON (session)')
252
388
  s1.add_argument('--timeout', type=int, default=45)
389
+ s1.add_argument('--capture-dialog-state', action='store_true',
390
+ help='record minimal dialog state per step (open modal '
391
+ 'count + focus inside) for diff --gate-dialog-state')
253
392
  s1.add_argument('-o', '--out', default='trace.json')
254
393
  s2 = sub.add_parser('diff')
255
394
  s2.add_argument('a')
256
395
  s2.add_argument('b')
396
+ s2.add_argument('--gate-dialog-state', action='store_true',
397
+ help='opt-in: compare captured dialog state (focus stays '
398
+ 'the only default gate; missing evidence = INCONCLUSIVE)')
257
399
  a = p.parse_args(argv)
258
400
 
259
401
  if a.cmd == 'trace':
@@ -267,7 +409,8 @@ def main(argv):
267
409
  return 1
268
410
  try:
269
411
  d = trace(a.url, steps=a.steps, output=a.out, auth_state=a.auth_state,
270
- timeout=a.timeout, script=script)
412
+ timeout=a.timeout, script=script,
413
+ capture_dialog_state=a.capture_dialog_state)
271
414
  except ImportError:
272
415
  print(json.dumps({'error': 'Playwright not installed: pip install '
273
416
  'playwright && playwright install chromium'}))
@@ -278,12 +421,18 @@ def main(argv):
278
421
  print(json.dumps({'url': d['url'], 'summary': d['summary'],
279
422
  'out': a.out}, ensure_ascii=False, indent=1))
280
423
  return 0
281
- with open(a.a, encoding='utf-8') as f:
282
- ja = json.load(f)
283
- with open(a.b, encoding='utf-8') as f:
284
- jb = json.load(f)
285
- verdict = trace_diff(ja, jb)
424
+ try:
425
+ with open(a.a, encoding='utf-8') as f:
426
+ ja = json.load(f)
427
+ with open(a.b, encoding='utf-8') as f:
428
+ jb = json.load(f)
429
+ except (OSError, ValueError) as e:
430
+ print(json.dumps({'ok': False, 'error': f'could not read trace: {e}'}))
431
+ return 1
432
+ verdict = trace_diff(ja, jb, gate_dialog_state=a.gate_dialog_state)
286
433
  print(json.dumps(verdict, ensure_ascii=False, indent=1))
434
+ if 'error' in verdict:
435
+ return 1
287
436
  return 0 if verdict['ok'] else 2
288
437
 
289
438
 
@@ -14,6 +14,9 @@ Honest boundaries, by design:
14
14
  - The criterion→outcome mapping is OURS. The W3C has published no
15
15
  official WCAG 2 → WCAG 3 mapping (transition materials are planned);
16
16
  every grouping is a documented approximation.
17
+ - NO forced landing: WCAG 2.2 criteria the draft has no provision for
18
+ (`_NO_EQUIVALENT`) are listed apart in `no_equivalent`, never grouped
19
+ under an unrelated outcome.
17
20
 
18
21
  CLI:
19
22
  a11ywcag3.py --from-audit informe.json [--lang es] [-o salida.json]
@@ -26,7 +29,7 @@ import re
26
29
  import sys
27
30
 
28
31
  from .a11yi18n import pair
29
- from .a11ycrit import _SIGNAL_CRIT
32
+ from .a11ycrit import _C, _SIGNAL_CRIT
30
33
 
31
34
  TXT = pair('wcag3') # locales/<lang>.json — community-editable
32
35
 
@@ -80,7 +83,10 @@ _OUTCOMES = {
80
83
  # criterio WCAG 2.2 → outcomes del borrador. CURADO por a11y-toolkit:
81
84
  # el W3C no ha publicado mapeo oficial (los materiales de transición están
82
85
  # planificados). Cubre el 100% de los criterios alcanzables por señales del
83
- # toolkit (pinned por tests/test_wcag3.py) más los evidentes sin señal.
86
+ # toolkit (pinned por tests/test_wcag3.py) más los evidentes sin señal; los
87
+ # que el borrador no cubre van a _NO_EQUIVALENT. Cada fila se colocó contra
88
+ # el Working Draft publicado: la guía donde vive la provisión equivalente,
89
+ # no la que se le parece.
84
90
  _CRIT_OUTCOME = {
85
91
  '1.1.1': ['2.1.1', '2.1.3'], # alt texto / alternativas no textuales
86
92
  '1.2.2': ['2.1.5'],
@@ -89,41 +95,38 @@ _CRIT_OUTCOME = {
89
95
  '1.2.5': ['2.1.6'],
90
96
  '1.3.1': ['2.7.3'],
91
97
  '1.3.2': ['2.7.3'],
92
- '1.3.3': ['2.2.3'], # instrucciones sin rasgos sensoriales
98
+ '1.3.3': ['2.11.1'], # instrucciones sin rasgos sensoriales
93
99
  '1.3.4': ['2.12.3'],
94
- '1.3.5': ['2.3.5'],
95
- '1.4.1': ['2.2.1'], # "Hue not relied on" es core req del draft
100
+ '1.3.5': ['2.3.5', '2.9.1'], # + "Automated entry allowed": el relleno automático depende del propósito
101
+ '1.4.1': ['2.1.8'], # "Hue not relied on" es core req del draft
96
102
  '1.4.2': ['2.12.4'],
97
103
  '1.4.3': ['2.2.1'],
98
104
  '1.4.4': ['2.2.1', '2.12.3'],
99
- '1.4.5': ['2.2.1'],
105
+ '1.4.5': ['2.2.1', '2.2.2'], # + "Text detectable": el texto en imagen no tiene equivalente
100
106
  '1.4.10': ['2.12.3'],
101
107
  '1.4.12': ['2.2.1'],
102
- '1.4.13': ['2.3.4'],
108
+ '1.4.13': ['2.4.5'], # el contenido en hover/foco vive en Input operation
103
109
  '2.1.1': ['2.4.1'],
104
110
  '2.1.2': ['2.4.1'],
105
- '2.1.4': ['2.4.5'],
111
+ '2.1.4': ['2.4.1'], # "No keyboard conflicts" + "Custom keys documented"
106
112
  '2.2.1': ['2.9.2'],
107
- '2.2.2': ['2.12.5'],
113
+ '2.2.2': ['2.6.1'], # pausar/parar/ocultar = "No visual motion" (daño físico)
108
114
  '2.3.1': ['2.6.1'], # sin señal hoy; la vía del daño físico
109
- '2.4.1': ['2.3.3'],
115
+ '2.4.1': ['2.7.3', '2.3.3'], # bloques identificables (Structure) + foco sin bloques repetidos
110
116
  '2.4.2': ['2.7.2'],
111
117
  '2.4.3': ['2.3.3'],
112
118
  '2.4.4': ['2.3.5'],
113
- '2.4.5': ['2.3.3'],
114
119
  '2.4.6': ['2.7.3', '2.2.3'],
115
120
  '2.4.7': ['2.3.1'],
116
121
  '2.4.11': ['2.7.4'],
117
- '2.5.1': ['2.4.3'],
122
+ '2.5.1': ['2.4.5', '2.4.3'], # "Path-based gesture not relied on" + entrada simple de puntero
118
123
  '2.5.2': ['2.4.3'],
119
- '2.5.3': ['2.4.4', '2.3.5'],
124
+ '2.5.3': ['2.3.5'], # "Label included in programmatic name"
120
125
  '2.5.4': ['2.4.5'],
121
126
  '2.5.7': ['2.4.3'],
122
- '2.5.8': ['2.4.3'],
123
127
  '3.1.1': ['2.2.2'],
124
128
  '3.1.2': ['2.2.2'],
125
129
  '3.2.1': ['2.3.4'],
126
- '3.2.2': ['2.3.4'],
127
130
  '3.2.3': ['2.8.1'],
128
131
  '3.2.4': ['2.8.1'],
129
132
  '3.2.5': ['2.3.4'],
@@ -132,15 +135,31 @@ _CRIT_OUTCOME = {
132
135
  '3.3.2': ['2.3.5', '2.5.2'],
133
136
  '3.3.3': ['2.5.1'],
134
137
  '3.3.4': ['2.5.2'],
135
- '3.3.7': ['2.9.6'], # el draft lo llama "Unnecessary steps"
138
+ '3.3.7': ['2.9.4'], # "No redundant entry" vive en Retain information
136
139
  '3.3.8': ['2.4.6'],
137
140
  '4.1.2': ['2.3.5'],
138
141
  '4.1.3': ['2.12.5'],
139
142
  }
140
143
 
144
+ # criterios 2.2 para los que el borrador de sept-2026 NO tiene provisión
145
+ # equivalente (leído provisión a provisión; el del tamaño de objetivo lo
146
+ # confirma la issue #808 del propio grupo). No se fuerzan bajo un outcome
147
+ # ajeno: sus hallazgos se listan aparte en `no_equivalent`. Re-visitar en cada
148
+ # re-baseline: en cuanto el borrador los cubra, vuelven a _CRIT_OUTCOME.
149
+ _NO_EQUIVALENT = ('2.4.5', '2.5.8', '3.2.2')
150
+
141
151
  _CODE = re.compile(r'^(\d+\.\d+\.\d+)')
142
152
 
143
153
 
154
+ def _name_22(code, lang):
155
+ """Nombre del criterio en el catálogo 2.2 (misma extracción que `criterion()`)."""
156
+ try:
157
+ _, languages = _C[code]
158
+ return (languages.get(lang) or languages['en'])[0]
159
+ except (KeyError, TypeError, IndexError):
160
+ return code
161
+
162
+
144
163
  def preview(report, lang='en'):
145
164
  """Re-agrupa un informe WCAG 2.2 bajo los outcomes del borrador WCAG 3.
146
165
 
@@ -154,8 +173,10 @@ def preview(report, lang='en'):
154
173
  'hint': 'audit first, then preview the same report'}
155
174
 
156
175
  per_outcome = {}
176
+ no_equivalent = {}
157
177
  unmapped = []
158
178
  mapped_count = 0
179
+ no_equiv_count = 0
159
180
  for i, f in enumerate(report['findings']):
160
181
  if not isinstance(f, dict):
161
182
  # nada desaparece en silencio: un finding deforme también se reporta
@@ -169,6 +190,18 @@ def preview(report, lang='en'):
169
190
  else:
170
191
  sig = str(f.get('signal') or '')
171
192
  code = _SIGNAL_CRIT.get(sig)
193
+ if code in _NO_EQUIVALENT:
194
+ # el borrador no tiene provisión equivalente: se lista aparte,
195
+ # nunca bajo un outcome ajeno ni en el cajón de "sin mapear"
196
+ no_equiv_count += 1
197
+ e = no_equivalent.setdefault(code, {'findings': 0, 'high': 0, 'medium': 0,
198
+ 'low': 0, 'signals': set()})
199
+ e['findings'] += 1
200
+ sev = str(f.get('severity') or '').lower()
201
+ if sev in ('high', 'medium', 'low'):
202
+ e[sev] += 1
203
+ e['signals'].add(str(f.get('signal') or code))
204
+ continue
172
205
  if not code or code not in _CRIT_OUTCOME:
173
206
  unmapped.append({'finding': i, 'signal': f.get('signal'),
174
207
  'criterion': f.get('criterion')})
@@ -202,12 +235,24 @@ def preview(report, lang='en'):
202
235
  'criteria_22': sorted(e['criteria_22']),
203
236
  })
204
237
 
205
- return {
238
+ no_equiv = []
239
+ for code in sorted(no_equivalent, key=_vers):
240
+ e = no_equivalent[code]
241
+ no_equiv.append({
242
+ 'criterion_22': code,
243
+ 'criterion_name': _name_22(code, lang),
244
+ 'findings': e['findings'],
245
+ 'severity': {'high': e['high'], 'medium': e['medium'], 'low': e['low']},
246
+ 'signals': sorted(e['signals']),
247
+ })
248
+
249
+ res = {
206
250
  'mode': 'wcag3-preview',
207
251
  'lang': lang,
208
252
  'draft': dict(DRAFT),
209
253
  'disclaimer': t['disclaimer'],
210
254
  'mapping_note': t['mapping_note'],
255
+ 'no_equivalent_note': t['no_equivalent_note'],
211
256
  'no_score': t['no_score'],
212
257
  'conformance_model': {
213
258
  'levels': 'single conformance level (no A/AA/AAA in the draft)',
@@ -216,16 +261,33 @@ def preview(report, lang='en'):
216
261
  'source': DRAFT['intro'],
217
262
  },
218
263
  'outcomes': outcomes,
264
+ 'no_equivalent': no_equiv,
219
265
  'counts': {
220
266
  'findings_total': len(report['findings']),
221
267
  'findings_mapped': mapped_count,
222
268
  'findings_unmapped': len(unmapped),
269
+ 'findings_no_equivalent': no_equiv_count,
223
270
  'outcomes_touched': len(outcomes),
224
271
  'outcomes_in_draft': len(_OUTCOMES),
225
272
  },
226
273
  'unmapped': unmapped,
227
- 'source_report': {'url': report.get('url'), 'mode': report.get('mode')},
274
+ 'source_report': {'url': report.get('url'), 'mode': report.get('mode'),
275
+ 'http_status': report.get('http_status')},
228
276
  }
277
+ # el informe de ORIGEN falló (una respuesta HTTP 4xx/5xx conserva los
278
+ # hallazgos y declara el error; también un error del motor): su estado
279
+ # viaja con la vista previa. El mapa se conserva para leerlo, pero ninguna
280
+ # capa puede darlo por bueno: MCP lo marca isError y el CLI sale 1
281
+ _st = report.get('http_status')
282
+ if not isinstance(_st, int) or isinstance(_st, bool):
283
+ _st = None
284
+ if report.get('error') or (_st is not None and _st >= 400):
285
+ res['error'] = str(report.get('error') or
286
+ t['source_http_error'].format(status=_st))
287
+ res['source_error_note'] = t['source_error_note']
288
+ if _st is not None:
289
+ res['http_status'] = _st
290
+ return res
229
291
 
230
292
 
231
293
  def main(argv):
@@ -31,6 +31,18 @@
31
31
  "heading_role_removed_rem": "The correct pattern for an interactive heading is the control INSIDE: <h2><button>…</button></h2> keeps both heading and button; on the element itself, only use role=heading if that is its real function.",
32
32
  "text_spacing_important": "{n} inline styles with letter/line/word-spacing set to !important: {example}. The user cannot re-space the text with their own stylesheet (1.4.12, ACT rules 24afc2/78fd32/9e45ec).",
33
33
  "text_spacing_important_rem": "Drop the !important from inline spacing (normal specificity is enough): 1.4.12 requires users be able to raise line height to 1.5x and letter/word spacing without losing content.",
34
+ "a_no_href": "{n} <a> links without href acting as controls: {example}. Without href it is not a link: screen readers will not announce it as one even though it takes focus and clicks (2.1.1).",
35
+ "a_no_href_rem": "If it opens or navigates, give it the correct href (or make it a <button>); if it is only a target anchor, drop the tabindex and click handler.",
36
+ "nested_main": "{n} mains nested inside sectioning elements: {example}. main is top-level: inside section/aside/nav/article it stops being a valid landmark (1.3.1).",
37
+ "nested_main_rem": "Move main to the root of body (one per page); inside sections use headings, not another main.",
38
+ "fake_list": "{n} fake lists built with typographic bullets and <br> breaks: {example}. Screen readers do not announce them as lists nor count their items (1.3.1).",
39
+ "fake_list_rem": "Turn them into real <ul><li> lists: navigable structure and item counts come for free.",
40
+ "alert_polite": "{n} role=alert with aria-live=polite: {example}. The explicit polite SILENCES the role's implicit assertiveness (that is how Chromium exposes it); some screen readers historically honored the implicit value and announce differently. Review the intent (1.4.2/4.1.2).",
41
+ "alert_polite_rem": "For an interrupting alert leave the role alone; for a gentler one role=status expresses it without contradiction. Depending on which of the two wins per reader is the part to avoid.",
42
+ "lang_xml_mismatch": "{n} elements whose lang and xml:lang disagree: {example}. The screen reader cannot tell which language to apply (3.1.2, ACT 5b7ae0).",
43
+ "lang_xml_mismatch_rem": "Make lang and xml:lang identical on the element (same subtag, any casing).",
44
+ "headers_attr_bad": "{n} headers= attributes pointing outside their table or to non-header cells: {example}. The cell-header relationship breaks (1.3.1, ACT d0f69e/a25f45).",
45
+ "headers_attr_bad_rem": "Every headers= id must exist, be a th (or a cell with columnheader/rowheader role) and live in THE SAME table; for simple tables scope is enough.",
34
46
  "autocomplete_rem": "Add autocomplete with the right token (email, tel, name, postal-code…, 1.3.5): free accessibility and autofill at zero cost.",
35
47
  "blank_no_warning": "{n} links with target=\"_blank\" that do not warn they open a new window.",
36
48
  "blank_no_warning_rem": "Add a text hint (or title/aria-label): \"(opens in a new window)\", or let the user decide.",
@@ -104,6 +116,7 @@
104
116
  },
105
117
  "images_of_text_rem": "Except for logotypes, present text as real text (1.4.5): it rescales, reflows and translates; an image does not.",
106
118
  "overlay_widgets_note": "A third-party accessibility overlay widget was detected (see overlay_widgets). Overlays do not make a site accessible — see the community Overlay Fact Sheet (overlayfactsheet.com). Reported as information for procurement diligence, not as a WCAG finding.",
119
+ "statement_note": "No visible link to an accessibility statement. Directive (EU) 2016/2102 (art. 7) and its national transpositions require it linked; reported as data for legal review, not a WCAG failure.",
107
120
  "img_no_alt": {
108
121
  "one": "1 <img> without an alt attribute (not even alt=\"\").",
109
122
  "other": "{n} <img> without an alt attribute (not even alt=\"\")."
@@ -229,7 +242,19 @@
229
242
  "alt_quality": "{n} images with low-quality alt text (filenames, generic words or placeholders).",
230
243
  "alt_quality_rem": "Alt like \"image\", \"foto\", \"img_123.jpg\" or a dash says nothing to a screen-reader user. Replace it with what the image conveys in its context; if the image is decorative, use alt=\"\" so assistive tech skips it.",
231
244
  "onfocus_blur": "{n} element(s) whose onfocus handler removes focus (onfocus=\"blur()\"): keyboard users cannot reach them at all.",
232
- "onfocus_blur_rem": "Remove the onfocus=\"blur()\" handler: stealing focus makes the element unreachable by keyboard (2.1.1). If the element must not be focusable, use tabindex=\"-1\" instead of taking focus away."
245
+ "onfocus_blur_rem": "Remove the onfocus=\"blur()\" handler: stealing focus makes the element unreachable by keyboard (2.1.1). If the element must not be focusable, use tabindex=\"-1\" instead of taking focus away.",
246
+ "nested_interactive": "{n} interactive elements nested inside other interactives: {example}. The HTML content model forbids it: the inner control is misannounced and the outer loses its boundary (4.1.2).",
247
+ "nested_interactive_rem": "Make them siblings and fake the visual nesting with an expanded hit area (a stretched ::before over the primary link) or by wrapping the text in a heading; give the secondary action a contextual name (\"Favorite: set menu\").",
248
+ "invoker_command_bad": "{n} buttons with broken invoker commands: {example}. commandfor does not resolve or the command does not match the target type (show-modal/close require <dialog>; the popover commands require the popover attribute) (4.1.2).",
249
+ "invoker_command_bad_rem": "Point commandfor at an existing id of the right type: <dialog> for show-modal/close, [popover] for show/hide/toggle-popover. Without a target there is no behavior and no managed states.",
250
+ "aria_level_gt6": "{n} headings with aria-level greater than 6: {example}. The value is valid ARIA and Chromium exposes it as-is; the documented JAWS behavior is to downgrade it to another level (TetraLogical 2026 matrix): verify intent and your target screen reader (1.3.1).",
251
+ "aria_level_gt6_rem": "If the real hierarchy fits within h1-h6, drop the extra aria-level; if you genuinely need deeper levels, verify with the screen reader your users run before trusting the written number.",
252
+ "role_orphan": "{n} roles without their required container: {example}. A listitem without a list, a tab without a tablist or an option without a listbox lose the structure their role announces (1.3.1).",
253
+ "role_orphan_rem": "Wrap them in their role's container (list, menu, listbox, tablist, tree) or the equivalent implicit element (ul/ol for list).",
254
+ "skip_broken": "{n} skip links pointing at nonexistent targets: {example}. The bypass mechanism aims at an id that does not exist and the user stays trapped in the repeated navigation (2.4.1, F89).",
255
+ "skip_broken_rem": "Point the link at the real id of the main content (or create the id): a broken bypass is worse than no bypass.",
256
+ "select_auto_focus": "{n} selects with autofocus carry a script that changes the context ({example}). The page loads with focus already on the control, so the navigation, new window, submit or focus move it triggers is one key away for someone who never chose to enter it (3.2.1).",
257
+ "select_auto_focus_rem": "Remove the autofocus from the select, or keep it and run the script on activation (a Go button) instead of on focus or on selection change."
233
258
  },
234
259
  "badge": {
235
260
  "name": "a11y-toolkit",
@@ -286,7 +311,13 @@
286
311
  "docx_no_lang_rem": "Review → Language → set the whole-document language.",
287
312
  "docx_table_no_header": "{n} tables with no marked header row: cells lose their column context (1.3.1).",
288
313
  "docx_table_no_header_rem": "Table → mark the header row (\"Repeat header rows\" for multi-page tables).",
289
- "limits": "Structural XML screening: not a substitute for human review (reading order of complex tables, meaning of under-described images, embedded charts)."
314
+ "limits": "Structural XML screening: not a substitute for human review (reading order of complex tables, meaning of under-described images, embedded charts).",
315
+ "docx_fake_list": "{n} fake list groups: bullets or numbers typed as text instead of a real Word list. Screen readers do not announce them as lists nor count their items.",
316
+ "docx_fake_list_rem": "Apply a real Word list (Home → Bullets/Numbering): the navigable structure comes for free and the number recalculates itself.",
317
+ "docx_heading_skips": "{n} heading level jumps (e.g. Heading 1 → Heading 3): the navigation pane hierarchy comes out flat.",
318
+ "docx_heading_skips_rem": "Fix the intermediate levels: each heading should step down by one (1→2→3); check which level belonged between the two.",
319
+ "docx_generic_link": "{n} links without purpose in their text: repeated \"click here\", the raw URL as text, or an image-only link with no description.",
320
+ "docx_generic_link_rem": "Write the destination in the link text (\"Download the annual report (PDF, 2 MB)\"); screen readers pull the link list out of context."
290
321
  },
291
322
  "dom": {
292
323
  "contrast_fail": "{n} text areas with insufficient contrast: {det}. (computed fg/background, with alpha compositing).",
@@ -532,7 +563,14 @@
532
563
  "pdf_scanned": "no text layer (0 characters in content): looks like a scan — fully invisible (1.1.1).",
533
564
  "pdf_scanned_rem": "Apply OCR with real text and tag the result.",
534
565
  "pdf_untagged": "no structure tree (/StructTreeRoot): reading order and semantic roles do not exist for the reader. THE root failure of inaccessible PDFs (1.3.1).",
535
- "pdf_untagged_rem": "Tag the document (export as tagged PDF from authoring, or remediate in Acrobat): without a tree, everything else is cosmetic."
566
+ "pdf_untagged_rem": "Tag the document (export as tagged PDF from authoring, or remediate in Acrobat): without a tree, everything else is cosmetic.",
567
+ "pdf_ocr_layer_note": "All text in this PDF is drawn in invisible render mode (Tr 3): what is visible is imagery. Check whether the scan carries tagging and alternatives; the invisible layer may announce text nobody sees. Review data, not a direct failure.",
568
+ "pdf_table_no_header": "{n} tagged TD cells and zero TH: tables sit in the tag tree with no header row.",
569
+ "pdf_table_no_header_rem": "Re-tag the header row as TH (or /TH with scope) in the source authoring tool; without it, the reader announces no columns.",
570
+ "pdf_no_heading_tags": "Tagged document with no H1-H6 at all: heading navigation does not exist. A letter or brochure without headings can be legitimate: review.",
571
+ "pdf_no_heading_tags_rem": "Apply heading styles in the source document and export tagged; H1-H6 are the map of the document.",
572
+ "pdfua_contradiction": "The XMP claims PDF/UA part {part} but is missing: {missing}. The seal contradicts its own document.",
573
+ "pdfua_contradiction_rem": "Either complete it (language, title, tagging) or remove the pdfuaid declaration from the XMP: a lying seal is worse than no seal."
536
574
  },
537
575
  "scroll": {
538
576
  "limits": "Infinite-scroll auditor: heuristics with real focus and a live-region observer over {n} batches. Not a substitute for screen-reader testing on the real feed.",
@@ -676,7 +714,10 @@
676
714
  "mapping_note": "The criterion-to-outcome mapping is curated by a11y-toolkit: the W3C has not published an official WCAG 2 to WCAG 3 mapping (transition materials are planned). Treat every grouping as an approximation.",
677
715
  "model_tags": "Core requirement tags in the draft: physical harm, risk, barrier and friction (per the W3C introduction; they qualify requirements, not findings).",
678
716
  "model_tiers": "Reporting tiers 1-6, where tier 3 corresponds to conformance. Counts and thresholds are still to be determined by the W3C.",
679
- "no_score": "No score, tier or conformance level is produced on purpose: the draft's tier thresholds are still to be determined by the W3C."
717
+ "no_score": "No score, tier or conformance level is produced on purpose: the draft's tier thresholds are still to be determined by the W3C.",
718
+ "no_equivalent_note": "no_equivalent lists WCAG 2.2 criteria whose findings the September 2026 draft has no equivalent provision for, as read by a11y-toolkit (target size, multiple ways, change of context on input). They are listed apart instead of being grouped under an unrelated outcome, and re-checked on every re-baseline of the draft.",
719
+ "source_error_note": "The source audit failed: its error travels with this preview. The mapping is kept so the findings can still be read, but nothing here may pass a gate, a budget or a conformance claim.",
720
+ "source_http_error": "HTTP {status}: the source audit got an error response, not the requested page."
680
721
  },
681
722
  "scope": {
682
723
  "notice": "Machine proposals are not exclusions: 'proposed-excluded' rows need a human answer before anything downstream (evidence pack, VPAT, OpenACR) may treat the criterion as not applicable.",
@@ -741,4 +782,4 @@
741
782
  "journeyrec": {
742
783
  "bad_format": "Not an a11y-journey/1 record: verification refuses to judge it."
743
784
  }
744
- }
785
+ }