@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
@@ -22,6 +22,27 @@ import sys
22
22
  from .a11yaudit import CRIT, T, compute_score
23
23
  from .contrast import parse_color, decode_png, sample_rgb, hexs, luminance, ratio
24
24
 
25
+ # textos de las funciones renderizadas que NO viven en locales (errores de
26
+ # carga y limits): bilingües aquí, igual que el catálogo (invariante es/en)
27
+ _LOAD_ERR = {'es': 'no se pudo cargar: {e}',
28
+ 'en': 'could not load: {e}'}
29
+ _LIMITS_HCM = {
30
+ 'es': ('Heurística de revisión (1.4.3/1.4.11 en HCM): los fills '
31
+ 'coloreados hardcoded en SVG suelen caer al heredado con '
32
+ 'forced-colors. La comprobación definitiva es visual con '
33
+ 'Windows High Contrast — esto la prepara, no la sustituye.'),
34
+ 'en': ('Review heuristic (1.4.3/1.4.11 under HCM): hardcoded SVG fills '
35
+ 'usually fall back to inherited under forced-colors. The definitive '
36
+ 'check is visual on Windows High Contrast — this prepares it, '
37
+ 'it does not replace it.'),
38
+ }
39
+ _LIMITS_MOTION = {
40
+ 'es': ('Mide CSS animations y video[autoplay]. No cubre animaciones '
41
+ 'JS/WebGL ni parallax por scroll — revisión manual.'),
42
+ 'en': ('Measures CSS animations and video[autoplay]. Does not cover '
43
+ 'JS/WebGL animations or scroll parallax — manual review.'),
44
+ }
45
+
25
46
  from . import a11yi18n
26
47
  # browser pool: Chromium reutilizable entre llamadas consecutivas
27
48
  _POOL = {'playwright': None, 'browser': None, 'type': None}
@@ -71,7 +92,7 @@ def _detect_browser(pw, preferred=None):
71
92
  def _get_browser(pw, headless=True, preferred=None):
72
93
  """Devuelve un browser del pool (o crea uno si no existe)."""
73
94
  if _POOL['browser'] is not None and _POOL['browser'].is_connected() and \
74
- _POOL['type'] == (preferred or 'auto'):
95
+ (preferred in (None, 'auto') or _POOL['type'] == preferred):
75
96
  return _POOL['browser']
76
97
  _close_pool()
77
98
  br, kind = _detect_browser(pw, preferred)
@@ -104,10 +125,52 @@ def _t(lang, key, n=None):
104
125
 
105
126
 
106
127
  # ------------------------------------------------------------------- JS -----
128
+ # Accessible-name computation, spliced into _JS below. Module-level so the
129
+ # accname PRECEDENCE is pinnable by test_dom as a plain string (no browser
130
+ # needed): labelledby (multi-id list, texts joined in order) > aria-label >
131
+ # implicit <label> > content > title. Static string — no page data ever lands
132
+ # here.
133
+ _JS_NAMEOF = r'''
134
+ const nameOf = el => {
135
+ let n = '';
136
+ // 1. aria-labelledby: a whitespace-SEPARATED id list — resolve each id
137
+ // within the root (shadow roots carry getElementById too), join the
138
+ // name texts in ORDER, skip missing ids (accname step 2B)
139
+ if (el.getAttribute('aria-labelledby')) {
140
+ const root = el.getRootNode();
141
+ const byId = id => (root.getElementById ? root.getElementById(id)
142
+ : root.querySelector('#' + CSS.escape(id)));
143
+ const parts = [];
144
+ for (const id of el.getAttribute('aria-labelledby').trim().split(/\s+/)) {
145
+ const ref = byId(id);
146
+ if (ref) parts.push((ref.innerText || '').trim());
147
+ }
148
+ n = parts.join(' ').trim();
149
+ }
150
+ // 2. aria-label
151
+ if (!n) n = (el.getAttribute('aria-label') || '').trim();
152
+ // 3. implicit <label>
153
+ if (!n && el.labels && el.labels[0]) n = el.labels[0].innerText.trim();
154
+ // 4. content: input value/image alt, element text, descendant img alt
155
+ if (!n && el.tagName === 'INPUT' && ['submit', 'button', 'reset'].includes(el.type)) n = el.value || '';
156
+ if (!n && el.tagName === 'INPUT' && el.type === 'image') n = el.alt || '';
157
+ if (!n && ['A', 'BUTTON', 'SUMMARY'].includes(el.tagName)) {
158
+ n = (el.innerText || '').trim();
159
+ // accname: a descendant image's alt contributes to the link's name
160
+ if (!n) { const im = el.querySelector('img[alt]'); if (im) n = (im.getAttribute('alt') || '').trim(); }
161
+ }
162
+ if (!n && el.tagName === 'IMG') n = el.getAttribute('alt') || '';
163
+ // 5. title — the LAST resort in the accname order
164
+ if (!n) n = (el.getAttribute('title') || '').trim();
165
+ return n.trim();
166
+ };
167
+ '''
168
+
107
169
  _JS = r'''(maxEj) => {
108
170
  const INTER = 'a[href], button, input, select, textarea, summary, [role="button"], [role="link"], [tabindex]';
109
171
  const out = { contrast: {}, contrastReview: 0, contrastZones: [], targets: [], unnamed: [], fields: [],
110
- imgs: [], iframes: [], headings: [], tabindex: [], ariaHidden: [],
172
+ placeholderContrast: [],
173
+ imgs: [], canvasNoName: [], chartsNoEquiv: [], iframes: [], headings: [], tabindex: [], ariaHidden: [],
111
174
  blank: 0, videos: 0, videoSubs: 0, tables: 0, tableTh: 0,
112
175
  focus: [], focusFail: [], focusContrast: [], focusObscured: [], marks: 0,
113
176
  ids: {}, lang: null, title: '', viewport: null, refresh: null,
@@ -345,6 +408,41 @@ _JS = r'''(maxEj) => {
345
408
  out.colorOnly.push(path(el));
346
409
  }
347
410
 
411
+ // ---- 1.4.3 contraste del placeholder (::placeholder) ----
412
+ // El placeholder ES texto que la gente con visión baja tiene que leer (y el
413
+ // 1.4.3 no distingue pseudo-elementos). El gris típico sobre blanco falla.
414
+ // Excepciones espejo del text_: control disabled (inactivo) y fondos de
415
+ // imagen (ahí ya manda la revisión manual). Sin color propio del autor el
416
+ // navegador pinta su gris por defecto: getComputedStyle lo devuelve igual,
417
+ // y si ese gris falla, el fallo es real y visible — se corrige estilando el
418
+ // placeholder, no dejando de usarlo.
419
+ for (const el of deepQ('input[placeholder], textarea[placeholder]')) {
420
+ if (out.placeholderContrast.length >= 12) break;
421
+ if (el.disabled || el.closest('fieldset[disabled]')) continue;
422
+ if (!vis(el)) continue;
423
+ if ((el.value || '').length) continue; // con valor, el placeholder no se ve
424
+ const ps = getComputedStyle(el, '::placeholder');
425
+ const fg = parseCol(ps.color);
426
+ if (!fg) continue;
427
+ const bg = bgOf(el);
428
+ if (bg.image) continue;
429
+ const px = parseFloat(ps.fontSize || getComputedStyle(el).fontSize);
430
+ const bold = parseInt(ps.fontWeight || getComputedStyle(el).fontWeight || '400', 10) >= 700;
431
+ const isLarge = px >= 24 || (bold && px >= 18.66);
432
+ const a = (fg.a === undefined) ? 1 : fg.a;
433
+ const comp = { r: Math.round(fg.r * a + bg.r * (1 - a)),
434
+ g: Math.round(fg.g * a + bg.g * (1 - a)),
435
+ b: Math.round(fg.b * a + bg.b * (1 - a)), a: 1 };
436
+ const r = ratioOf(comp, bg);
437
+ const threshold = isLarge ? 3.0 : 4.5;
438
+ if (r >= threshold) continue;
439
+ out.placeholderContrast.push({
440
+ example: path(el) + ' ::placeholder',
441
+ fg: 'rgb(' + fg.r + ',' + fg.g + ',' + fg.b + ')',
442
+ bg: 'rgb(' + bg.r + ',' + bg.g + ',' + bg.b + ')',
443
+ ratio: Math.round(r * 100) / 100, large: isLarge });
444
+ }
445
+
348
446
  // ---- 1.3.2 meaningful sequence: DOM order vs visual order, same parent ----
349
447
  {
350
448
  const byParent = new Map();
@@ -423,26 +521,7 @@ _JS = r'''(maxEj) => {
423
521
  }
424
522
 
425
523
  // ---- nombres accesibles renderizados ----
426
- const nameOf = el => {
427
- let n = (el.getAttribute('aria-label') || '').trim();
428
- if (!n && el.labels && el.labels[0]) n = el.labels[0].innerText.trim();
429
- if (!n && el.getAttribute('aria-labelledby')) {
430
- const root = el.getRootNode();
431
- const ref = root.getElementById ? root.getElementById(el.getAttribute('aria-labelledby'))
432
- : root.querySelector('#' + CSS.escape(el.getAttribute('aria-labelledby')));
433
- if (ref) n = (ref.innerText || '').trim();
434
- }
435
- if (!n) n = (el.getAttribute('title') || '').trim();
436
- if (!n && el.tagName === 'INPUT' && ['submit', 'button', 'reset'].includes(el.type)) n = el.value || '';
437
- if (!n && el.tagName === 'INPUT' && el.type === 'image') n = el.alt || '';
438
- if (!n && ['A', 'BUTTON', 'SUMMARY'].includes(el.tagName)) {
439
- n = (el.innerText || '').trim();
440
- // accname: a descendant image's alt contributes to the link's name
441
- if (!n) { const im = el.querySelector('img[alt]'); if (im) n = (im.getAttribute('alt') || '').trim(); }
442
- }
443
- if (!n && el.tagName === 'IMG') n = el.getAttribute('alt') || '';
444
- return n.trim();
445
- };
524
+ /*__NAMEOF__*/
446
525
  for (const el of deepQ('a[href], button, summary, [role="button"], [role="link"]')) {
447
526
  if (!vis(el) || el.closest('[aria-hidden="true"]')) continue;
448
527
  if (!nameOf(el) && out.unnamed.length < 30) out.unnamed.push(path(el));
@@ -456,6 +535,43 @@ _JS = r'''(maxEj) => {
456
535
  if (!vis(el)) continue;
457
536
  if (!el.hasAttribute('alt') && out.imgs.length < 30) out.imgs.push(el.getAttribute('src') || '');
458
537
  }
538
+ // canvas: el pase rendered es el JUEZ del nombre computado (el estático es
539
+ // filtro — la capa suele inyectarse por JS al renderizar el gráfico)
540
+ for (const el of deepQ('canvas')) {
541
+ if (!vis(el)) continue;
542
+ const _role = (el.getAttribute('role') || '').toLowerCase();
543
+ if (_role === 'presentation' || _role === 'none') continue;
544
+ if (el.closest('[aria-hidden="true"]')) continue;
545
+ const _fallback = (el.textContent || '').trim();
546
+ if (!nameOf(el) && !_fallback && out.canvasNoName.length < 20)
547
+ out.canvasNoName.push(path(el));
548
+ }
549
+ // charts CON nombre: ¿hay equivalente de datos visible para la máquina?
550
+ // (aria-details / aria-describedby resolubles, o una tabla en el entorno).
551
+ // Hallazgo de REVISIÓN (low): si los datos viven en prosa cercana, pasa.
552
+ const _chartName = el => (el.getAttribute('aria-label') || '').trim()
553
+ || (el.getAttribute('title') || '').trim()
554
+ || [...el.querySelectorAll('title')].map(t => t.textContent.trim())[0]
555
+ || ((el.getAttribute('aria-labelledby') || '').split(/\s+/)
556
+ .filter(Boolean).some(id => document.getElementById(id)) ? 'named' : '');
557
+ for (const el of deepQ('canvas, svg[role="img"]')) {
558
+ if (!vis(el)) continue;
559
+ if (el.closest('[aria-hidden="true"]')) continue;
560
+ const _r = (el.getAttribute('role') || '').toLowerCase();
561
+ if (el.tagName.toLowerCase() === 'svg' && _r !== 'img') continue;
562
+ if (!_chartName(el)) continue; // sin nombre: ya lo acusan las señales de nombre
563
+ let _equiv = [...(el.getAttribute('aria-details') || '').split(/\s+/),
564
+ ...(el.getAttribute('aria-describedby') || '').split(/\s+/)]
565
+ .filter(Boolean).some(id => document.getElementById(id));
566
+ if (!_equiv) {
567
+ // solo el entorno SEMÁNTICO (figure/section/celda/lista) cuenta como
568
+ // "cerca" — el parent genérico contaminaría (la tabla de OTRO chart
569
+ // en el mismo main haría pasar a todos)
570
+ const _scope = el.closest('figure, section, td, li');
571
+ _equiv = !!(_scope && _scope.querySelector('table'));
572
+ }
573
+ if (!_equiv && out.chartsNoEquiv.length < 15) out.chartsNoEquiv.push(path(el));
574
+ }
459
575
  for (const el of deepQ('iframe')) {
460
576
  if (!((el.getAttribute('title') || '').trim() || (el.getAttribute('aria-label') || '').trim())
461
577
  && out.iframes.length < 20) out.iframes.push(el.getAttribute('src') || '');
@@ -564,7 +680,8 @@ _JS = r'''(maxEj) => {
564
680
  if (prevFocus && prevFocus.blur) { try { prevFocus.focus(); } catch (e) {} }
565
681
 
566
682
  return out;
567
- }'''
683
+ }''' # /*__NAMEOF__*/ is spliced in below — keep nameOf in _JS_NAMEOF only
684
+ _JS = _JS.replace('/*__NAMEOF__*/', _JS_NAMEOF.strip('\n'))
568
685
 
569
686
 
570
687
  def _add(findings, lang, severity, code, key, examples=None, **fmt):
@@ -608,6 +725,20 @@ def audit_dom(data, url='(rendered)', lang='en', color_scheme='light'):
608
725
  if remaining:
609
726
  _add(findings, lang, 'low', '1.4.3', 'contrast_review', n=remaining)
610
727
 
728
+ # 1b. Contraste del placeholder (::placeholder): el gris típico sobre
729
+ # blanco falla 1.4.3 y el AT lo lee como texto real (Léonie Watson,
730
+ # estado del sector 2026). Severidad de contrast_fail (medium: la misma
731
+ # clase de texto que falla, no grave como un bloqueo de uso).
732
+ ph_failures = data.get('placeholderContrast') or []
733
+ if ph_failures:
734
+ det = '; '.join(
735
+ f"{f['fg']} vs {f['bg']} = {f['ratio']}:1 ({f['example']})"
736
+ for f in ph_failures[:4])
737
+ _add(findings, lang, 'medium', '1.4.3', 'placeholder_contrast',
738
+ examples=[f"{f['example']} → {f['fg']} vs {f['bg']} = {f['ratio']}:1"
739
+ for f in ph_failures],
740
+ n=len(ph_failures), det=det)
741
+
611
742
  # 2. Target size 2.5.8 (enlaces inline → baja: la excepción de espaciado
612
743
  # probablemente aplica y no es medible aquí; bloques → media)
613
744
  targets = data.get('targets') or []
@@ -668,6 +799,12 @@ def audit_dom(data, url='(rendered)', lang='en', color_scheme='light'):
668
799
  if data.get('imgs'):
669
800
  _add(findings, lang, 'high', '1.1.1', 'img_no_alt',
670
801
  examples=data['imgs'], n=len(data['imgs']))
802
+ if data.get('canvasNoName'):
803
+ _add(findings, lang, 'high', '1.1.1', 'canvas_no_accessible_layer',
804
+ examples=data['canvasNoName'], n=len(data['canvasNoName']))
805
+ if data.get('chartsNoEquiv'):
806
+ _add(findings, lang, 'low', '1.1.1', 'chart_no_data_equivalent',
807
+ examples=data['chartsNoEquiv'], n=len(data['chartsNoEquiv']))
671
808
  if data.get('ariaHidden'):
672
809
  _add(findings, lang, 'high', '4.1.2', 'aria_hidden_focusable',
673
810
  n=len(data['ariaHidden']), tag='control')
@@ -685,7 +822,7 @@ def audit_dom(data, url='(rendered)', lang='en', color_scheme='light'):
685
822
  if re.search(r'user-scalable\s*=\s*(no|0)', vp, re.I):
686
823
  _add(findings, lang, 'high', '1.4.4', 'zoom_no')
687
824
  elif (m := re.search(r'maximum-scale\s*=\s*([\d.]+)', vp, re.I)) and float(m.group(1)) < 2:
688
- _add(findings, lang, 'medium', '1.4.4', 'zoom_max', v=m.group(1))
825
+ _add(findings, lang, 'high', '1.4.4', 'zoom_max', v=m.group(1))
689
826
  if data.get('refresh'):
690
827
  m = re.match(r'\s*(\d+)', str(data['refresh']))
691
828
  segs = int(m.group(1)) if m else 0
@@ -694,14 +831,14 @@ def audit_dom(data, url='(rendered)', lang='en', color_scheme='light'):
694
831
  _add(findings, lang, 'medium', '2.4.3', 'tabindex_pos',
695
832
  examples=data['tabindex'], n=len(data['tabindex']))
696
833
  if not (data.get('main') or data.get('skip')):
697
- _add(findings, lang, 'medium', '2.4.1', 'no_bypass')
834
+ _add(findings, lang, 'low', '2.4.1', 'no_bypass')
698
835
 
699
836
  levels = [h['lvl'] for h in (data.get('headings') or []) if h['text']]
700
837
  h1s = sum(1 for h in data.get('headings') or [] if h['lvl'] == 1 and h['text'])
701
838
  empties = sum(1 for h in data.get('headings') or [] if not h['text'])
702
839
  if levels:
703
840
  if h1s == 0:
704
- _add(findings, lang, 'medium', '1.3.1', 'no_h1')
841
+ _add(findings, lang, 'low', '1.3.1', 'no_h1')
705
842
  elif h1s > 1:
706
843
  _add(findings, lang, 'low', '1.3.1', 'multi_h1', n=h1s)
707
844
  prev, jumps = 0, []
@@ -713,7 +850,7 @@ def audit_dom(data, url='(rendered)', lang='en', color_scheme='light'):
713
850
  _add(findings, lang, 'low', '1.3.1', 'heading_skips',
714
851
  skips=', '.join(jumps[:5]))
715
852
  else:
716
- _add(findings, lang, 'medium', '1.3.1', 'no_headings')
853
+ _add(findings, lang, 'low', '1.3.1', 'no_headings')
717
854
  if empties:
718
855
  _add(findings, lang, 'low', '1.3.1', 'empty_heading', n=empties)
719
856
  tables, con_th = data.get('tables', 0), data.get('tableTh', 0)
@@ -811,7 +948,7 @@ _JS_FORM_STATE = r'''(pre) => {
811
948
  suggested: 0, native: 0 };
812
949
  for (const el of f.querySelectorAll(FIELDS_JS)) {
813
950
  if (el.disabled) continue;
814
- info.campos++;
951
+ info.fields++;
815
952
  const key = (el.name || el.id || el.type) + '@' + (f.id || f.action || '');
816
953
  const shot_before = pre[key] || {};
817
954
  let identified = false, sugerido = false;
@@ -851,13 +988,13 @@ _JS_FORM_STATE = r'''(pre) => {
851
988
  return out;
852
989
  }'''
853
990
 
854
- def audit_forms(url, timeout=45, lang='en', auth_state=None):
991
+ def audit_forms(url, timeout=45, lang='en', auth_state=None, browser='auto'):
855
992
  """3.3.1 Error Identification / 3.3.3 Error Suggestion — the guided flow:
856
993
  fill every validatable field with INVALID data, really submit, then judge
857
994
  how errors are identified and announced in the post-submit DOM."""
858
995
  from playwright.sync_api import sync_playwright
859
996
  with sync_playwright() as p:
860
- nav = p.chromium.launch()
997
+ nav = _get_browser(p, preferred=browser)
861
998
  ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
862
999
  page = ctx.new_page() if auth_state else nav.new_page()
863
1000
  try:
@@ -882,7 +1019,7 @@ def audit_forms(url, timeout=45, lang='en', auth_state=None):
882
1019
  'remediation': _t(lang, key + '_rem').format(**fmt)})
883
1020
 
884
1021
  if navigated:
885
- add('low', '3.3.1', 'form_navigated', example=page.url if False else 'submit')
1022
+ add('low', '3.3.1', 'form_navigated', example='submit')
886
1023
  elif touched and state is not None:
887
1024
  unidentified = [f['form'] for f in state['forms']
888
1025
  if f['fields'] and f['identified'] == 0 and f['native'] == 0
@@ -916,56 +1053,64 @@ def sr_transcript(url, timeout=45, lang='en', auth_state=None, browser='auto'):
916
1053
  structure; this function returns it as prose an agent can READ and
917
1054
  understand from a blind user's perspective.
918
1055
  """
1056
+ # J4 (ronda 4): el driver de playwright NUNCA se paraba — una fuga
1057
+ # de proceso por llamada en un servidor MCP de larga vida
919
1058
  from playwright.sync_api import sync_playwright
920
1059
  pw = sync_playwright().start()
921
- nav = _get_browser(pw, preferred=browser)
922
- ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
923
- page = ctx.new_page() if auth_state else nav.new_page()
924
1060
  try:
925
- page.goto(url, wait_until='load', timeout=timeout * 1000)
926
- page.wait_for_timeout(400)
927
- except Exception as e:
928
- ctx.close()
929
- _close_pool()
930
- return {'error': str(e)[:100]}
931
-
932
- try:
933
- tree = page.locator('body').aria_snapshot()
934
- except Exception:
935
- tree = None
936
- try:
937
- ctx.close()
938
- except Exception:
939
- pass
1061
+ nav = _get_browser(pw, preferred=browser)
1062
+ ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1063
+ page = ctx.new_page() if auth_state else nav.new_page()
1064
+ try:
1065
+ page.goto(url, wait_until='load', timeout=timeout * 1000)
1066
+ page.wait_for_timeout(400)
1067
+ except Exception as e:
1068
+ ctx.close()
1069
+ _close_pool()
1070
+ return {'error': str(e)[:100]}
940
1071
 
941
- if not tree:
942
- return {'url': url, 'mode': 'sr-transcript',
943
- 'error': 'accessibility tree not available (Playwright >= 1.49 required)'}
1072
+ try:
1073
+ tree = page.locator('body').aria_snapshot()
1074
+ except Exception:
1075
+ tree = None
1076
+ try:
1077
+ ctx.close()
1078
+ except Exception:
1079
+ pass
944
1080
 
945
- # parse the YAML-like snapshot into linearized announcements
946
- import re
947
- announcements = []
948
- for line in tree.split('\n'):
949
- stripped = line.strip()
950
- if not stripped.startswith('- '):
951
- continue
952
- # quitar el guion inicial; el resto es el anuncio
953
- announcement = stripped[2:].rstrip(':')
954
- if announcement:
955
- announcements.append(announcement)
1081
+ if not tree:
1082
+ return {'url': url, 'mode': 'sr-transcript',
1083
+ 'error': 'accessibility tree not available (Playwright >= 1.49 required)'}
956
1084
 
957
- return {
958
- 'url': url,
959
- 'mode': 'sr-transcript',
960
- 'announcements': announcements[:200], # cap
961
- 'total': len(announcements),
962
- 'arbol_raw': tree[:5000] if len(tree) > 5000 else tree,
963
- 'note': ('Linearized announcement order — what a screen reader user hears. '
964
- 'Roles and names as computed by the browser. Use this to understand '
965
- 'the page from a blind user\'s perspective.'),
966
- }
1085
+ # parse the YAML-like snapshot into linearized announcements
1086
+ import re
1087
+ announcements = []
1088
+ for line in tree.split('\n'):
1089
+ stripped = line.strip()
1090
+ if not stripped.startswith('- '):
1091
+ continue
1092
+ # quitar el guion inicial; el resto es el anuncio
1093
+ announcement = stripped[2:].rstrip(':')
1094
+ if announcement:
1095
+ announcements.append(announcement)
1096
+
1097
+ return {
1098
+ 'url': url,
1099
+ 'mode': 'sr-transcript',
1100
+ 'announcements': announcements[:200], # cap
1101
+ 'total': len(announcements),
1102
+ 'arbol_raw': tree[:5000] if len(tree) > 5000 else tree,
1103
+ 'note': ('Linearized announcement order — what a screen reader user hears. '
1104
+ 'Roles and names as computed by the browser. Use this to understand '
1105
+ 'the page from a blind user\'s perspective.'),
1106
+ }
967
1107
 
968
1108
 
1109
+ finally:
1110
+ try:
1111
+ pw.stop()
1112
+ except Exception: # noqa: BLE001
1113
+ pass
969
1114
  _JS_HOVER_TEST = r'''() => {
970
1115
  // find elements that show tooltips/overlays on hover
971
1116
  const candidates = [];
@@ -984,11 +1129,11 @@ _JS_HOVER_TEST = r'''() => {
984
1129
  return candidates;
985
1130
  }'''
986
1131
 
987
- def audit_hover(url, timeout=45, lang='en', auth_state=None):
1132
+ def audit_hover(url, timeout=45, lang='en', auth_state=None, browser='auto'):
988
1133
  """1.4.13 Content on Hover or Focus: do tooltips dismiss on Escape?"""
989
1134
  from playwright.sync_api import sync_playwright
990
1135
  with sync_playwright() as p:
991
- nav = p.chromium.launch()
1136
+ nav = _get_browser(p, preferred=browser)
992
1137
  ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
993
1138
  page = ctx.new_page() if auth_state else nav.new_page()
994
1139
  try:
@@ -1167,14 +1312,14 @@ def audit_reflow(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1167
1312
  el layout)."""
1168
1313
  from playwright.sync_api import sync_playwright
1169
1314
  with sync_playwright() as p:
1170
- nav = p.chromium.launch()
1315
+ nav = _get_browser(p, preferred=browser)
1171
1316
  page = nav.new_page(viewport={'width': 1280, 'height': 800})
1172
1317
  try:
1173
1318
  page.goto(url, wait_until='load', timeout=timeout * 1000)
1174
1319
  page.wait_for_timeout(300)
1175
1320
  except Exception as e: # noqa: BLE001
1176
1321
  nav.close()
1177
- return {'error': f'no se pudo cargar: {e}'}
1322
+ return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
1178
1323
 
1179
1324
  page.set_viewport_size({'width': 320, 'height': 800})
1180
1325
  page.wait_for_timeout(500)
@@ -1229,6 +1374,55 @@ _STOP_META = r"""(i) => {
1229
1374
  return el ? el.getAttribute('data-a11yruta') : ('parada ' + i);
1230
1375
  }"""
1231
1376
 
1377
+ # 2.4.1 rendered: el primer skip link REAL (texto del vocabulario del patrón
1378
+ # 3e12e1 + destino con id existente) se activa con un click de la acción por
1379
+ # defecto (los handlers corren igual que con un usuario) y se comprueba que el
1380
+ # destino quede EXPUESTO tras la activación. El foco NO se exige: los
1381
+ # navegadores modernos mueven el inicio del recorrido secuencial al destino
1382
+ # aunque no tenga tabindex=-1, así que exigir activeElement==destino sería
1383
+ # fabricar falsos positivos (la recomendación del tabindex es de calidad, no
1384
+ # de cumplimiento). Lo que sí es fallo real: el bypass lleva a contenido que
1385
+ # sigue oculto (display:none, hidden, details cerrado, subárbol aria-hidden),
1386
+ # es decir, el mecanismo no lleva a nada perceivable.
1387
+ _SKIP_TEXT_JS = ('skip|jump to|saltar|ir al contenido|ir para o conte|'
1388
+ 'passer au contenu|main content|contenido principal')
1389
+ _JS_SKIP_FIND = ('() => { const re = new RegExp(' + json.dumps(_SKIP_TEXT_JS) + ', "i");\n'
1390
+ ' for (const a of document.querySelectorAll(\'a[href^="#"]\')) {\n'
1391
+ ' const href = a.getAttribute("href"); const id = href.slice(1);\n'
1392
+ ' if (!id) continue;\n'
1393
+ ' if (!document.getElementById(id)) continue;\n'
1394
+ ' const txt = ((a.textContent || "") + " " + (a.getAttribute("aria-label") || "")).trim();\n'
1395
+ ' if (!re.test(txt)) continue;\n'
1396
+ ' return {href: href, id: id, label: txt.slice(0, 40)};\n'
1397
+ ' }\n'
1398
+ ' return null; }')
1399
+ _JS_SKIP_AFTER = r"""(id) => {
1400
+ const t = document.getElementById(id);
1401
+ if (!t) return {exposed: false, focus_path: null};
1402
+ let node = t, closed_details = false;
1403
+ while (node && node !== document.documentElement) {
1404
+ if (node.tagName === 'DETAILS' && !node.open) { closed_details = true; break; }
1405
+ node = node.parentElement;
1406
+ }
1407
+ let render_ok = true;
1408
+ if (typeof t.checkVisibility === 'function') {
1409
+ render_ok = t.checkVisibility({checkVisibilityCSS: true, checkOpacity: false});
1410
+ } else {
1411
+ let n = t;
1412
+ while (n && n !== document.documentElement) {
1413
+ const s = getComputedStyle(n);
1414
+ if (s.display === 'none' || s.visibility === 'hidden') { render_ok = false; break; }
1415
+ n = n.parentElement;
1416
+ }
1417
+ }
1418
+ const exposed = render_ok && !t.hidden && !closed_details
1419
+ && t.closest('[aria-hidden="true"]') === null;
1420
+ const ae = document.activeElement;
1421
+ const focus_path = (ae && ae !== document.body && ae !== document.documentElement)
1422
+ ? (ae.tagName.toLowerCase() + (ae.id ? '#' + ae.id : '')) : null;
1423
+ return {exposed: exposed, focus_path: focus_path};
1424
+ }"""
1425
+
1232
1426
 
1233
1427
  def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, browser='auto'):
1234
1428
  """Detección de TRAMPAS DE TECLADO (2.1.2) con Tab real.
@@ -1240,7 +1434,7 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1240
1434
  """
1241
1435
  from playwright.sync_api import sync_playwright
1242
1436
  with sync_playwright() as p:
1243
- nav = p.chromium.launch()
1437
+ nav = _get_browser(p, preferred=browser)
1244
1438
  ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1245
1439
  page = ctx.new_page() if auth_state else nav.new_page()
1246
1440
  try:
@@ -1248,7 +1442,7 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1248
1442
  page.wait_for_timeout(400)
1249
1443
  except Exception as e: # noqa: BLE001
1250
1444
  nav.close()
1251
- return {'error': f'no se pudo cargar: {e}'}
1445
+ return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
1252
1446
 
1253
1447
  page.evaluate("document.querySelectorAll('[data-a11ystop]').forEach(e => {"
1254
1448
  " e.removeAttribute('data-a11ystop'); e.removeAttribute('data-a11yruta'); })")
@@ -1321,6 +1515,29 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1321
1515
  esc_releases = False
1322
1516
  except Exception:
1323
1517
  esc_releases = None
1518
+ # 2.4.1 rendered: un skip link real debe llevar a contenido expuesto
1519
+ skip = {'checked': 0, 'label': None, 'target_exposed': None,
1520
+ 'focus_after': None, 'broken': []}
1521
+ if not focus_navigated:
1522
+ try:
1523
+ found = page.evaluate(_JS_SKIP_FIND)
1524
+ if found:
1525
+ skip['checked'] = 1
1526
+ skip['label'] = found.get('label')
1527
+ # click por acción por defecto (clip del texto visible o
1528
+ # no, el hash navigation y los handlers corren igual)
1529
+ page.evaluate(
1530
+ "h => { for (const a of document.querySelectorAll('a[href]')) {"
1531
+ " if (a.getAttribute('href') === h) { a.click(); return true; } }"
1532
+ " return false; }", found['href'])
1533
+ page.wait_for_timeout(350)
1534
+ after = page.evaluate(_JS_SKIP_AFTER, found['id'])
1535
+ skip['target_exposed'] = after.get('exposed')
1536
+ skip['focus_after'] = after.get('focus_path')
1537
+ if not after.get('exposed'):
1538
+ skip['broken'].append(found['id'])
1539
+ except Exception: # noqa: BLE001 — SPA o contexto destruido: sin dato
1540
+ pass
1324
1541
  try:
1325
1542
  nav.close()
1326
1543
  except Exception:
@@ -1348,6 +1565,13 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1348
1565
  'remediation': _t(lang, 'kbd_trap_rem'),
1349
1566
  'examples': elems,
1350
1567
  })
1568
+ if skip['broken']:
1569
+ findings.append({
1570
+ 'severity': 'medium', 'criterion': CRIT.get(lang, CRIT['es']).get('2.4.1', '2.4.1'),
1571
+ 'signal': 'skip_target_hidden',
1572
+ 'issue': _t(lang, 'skip_target_hidden').format(
1573
+ label=skip.get('label') or 'skip link', id=', '.join(skip['broken'])),
1574
+ 'remediation': _t(lang, 'skip_target_hidden_rem')})
1351
1575
  from .a11yaudit import compute_score
1352
1576
  return {
1353
1577
  'url': url,
@@ -1360,14 +1584,25 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1360
1584
  'cycle': {'detected': bool(cycle),
1361
1585
  'elements': [paths.get(i, f'tab stop {i}') for i in cycle] if cycle else [],
1362
1586
  'escape_releases': esc_releases},
1587
+ 'skip_link': {'checked': skip['checked'], 'label': skip.get('label'),
1588
+ 'target_exposed': skip.get('target_exposed'),
1589
+ 'focus_after': skip.get('focus_after')},
1363
1590
  'findings': findings,
1364
1591
  'limits': (('Real Tab walk in Chromium (max {n} steps). Focus inside cross-origin '
1365
1592
  'iframes is not trackable and is marked as such. A cycle that Escape '
1366
- 'releases (a correct modal) is NOT reported as a finding.'
1593
+ 'releases (a correct modal) is NOT reported as a finding. The first '
1594
+ 'real skip link is activated once: a target still hidden after '
1595
+ 'activation is reported (2.4.1), but focus not landing on it is not '
1596
+ 'measured (modern browsers move the sequential-focus start regardless '
1597
+ 'of tabindex).'
1367
1598
  ).format(n=max_steps) if lang == 'en' else
1368
1599
  ('Recorrido con Tab real en Chromium (tope {n} pasos). El foco dentro de '
1369
1600
  'iframes entre dominios no es rastreable y se marca como tal. Un ciclo '
1370
- 'con Escape operativo (modal correcto) NO se reporta como hallazgo.'
1601
+ 'con Escape operativo (modal correcto) NO se reporta como hallazgo. Se '
1602
+ 'activa una vez el primer skip link real: si el destino sigue oculto '
1603
+ 'tras activarlo se reporta (2.4.1), pero que el foco no caiga en él no '
1604
+ 'se mide (los navegadores modernos mueven el inicio del recorrido '
1605
+ 'secuencial con o sin tabindex).'
1371
1606
  ).format(n=max_steps)),
1372
1607
  }
1373
1608
 
@@ -1521,7 +1756,7 @@ def audit_forced_colors(url, timeout=45, lang='en', auth_state=None, browser='au
1521
1756
  from .a11yaudit import _t as _t_audit, CRIT, compute_score
1522
1757
 
1523
1758
  with sync_playwright() as p:
1524
- nav = p.chromium.launch()
1759
+ nav = _get_browser(p, preferred=browser)
1525
1760
  ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1526
1761
  page = ctx.new_page() if auth_state else nav.new_page()
1527
1762
  try:
@@ -1553,10 +1788,7 @@ def audit_forced_colors(url, timeout=45, lang='en', auth_state=None, browser='au
1553
1788
  'findings': findings,
1554
1789
  'summary': {s2: sum(1 for h in findings if h['severity'] == s2)
1555
1790
  for s2 in ('high', 'medium', 'low')},
1556
- 'limits': ('Heurística de revisión (1.4.3/1.4.11 en HCM): los fills '
1557
- 'coloreados hardcoded en SVG suelen caer al heredado con '
1558
- 'forced-colors. La comprobación definitiva es visual con '
1559
- 'Windows High Contrast — esto la prepara, no la sustituye.'),
1791
+ 'limits': _LIMITS_HCM.get(lang, _LIMITS_HCM['en']),
1560
1792
  }
1561
1793
 
1562
1794
 
@@ -1590,7 +1822,7 @@ def audit_reduced_motion(url, timeout=45, lang='en', auth_state=None, browser='a
1590
1822
  from .a11yaudit import _t as _t_audit, CRIT, compute_score
1591
1823
 
1592
1824
  with sync_playwright() as p:
1593
- nav = p.chromium.launch()
1825
+ nav = _get_browser(p, preferred=browser)
1594
1826
  ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1595
1827
  page = ctx.new_page() if auth_state else nav.new_page()
1596
1828
  try:
@@ -1625,8 +1857,7 @@ def audit_reduced_motion(url, timeout=45, lang='en', auth_state=None, browser='a
1625
1857
  'findings': findings,
1626
1858
  'summary': {s2: sum(1 for h in findings if h['severity'] == s2)
1627
1859
  for s2 in ('high', 'medium', 'low')},
1628
- 'limits': ('Mide CSS animations y video[autoplay]. No cubre '
1629
- 'animaciones JS/WebGL ni parallax por scroll — revisión manual.'),
1860
+ 'limits': _LIMITS_MOTION.get(lang, _LIMITS_MOTION['en']),
1630
1861
  }
1631
1862
 
1632
1863
 
@@ -1639,7 +1870,7 @@ def audit_dom_url(url, timeout=45, lang='en', auth_state=None, browser='auto', c
1639
1870
  iniciada) para auditar detrás de login."""
1640
1871
  from playwright.sync_api import sync_playwright
1641
1872
  with sync_playwright() as p:
1642
- nav = p.chromium.launch()
1873
+ nav = _get_browser(p, preferred=browser)
1643
1874
  ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1644
1875
  page = ctx.new_page() if auth_state else nav.new_page()
1645
1876
  if color_scheme in ('dark', 'light'):
@@ -1652,7 +1883,7 @@ def audit_dom_url(url, timeout=45, lang='en', auth_state=None, browser='auto', c
1652
1883
  except Exception as e: # noqa: BLE001
1653
1884
  if not page.content() or page.url in ('about:blank', ''):
1654
1885
  nav.close()
1655
- return {'error': f'no se pudo cargar: {e}'}
1886
+ return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
1656
1887
  try:
1657
1888
  data = page.evaluate(_JS, MAX_EXAMPLES)
1658
1889
  # 1.4.12: inject the WCAG spacing overrides, count clipped texts
@@ -1720,7 +1951,7 @@ def contrast_dom(url, selector, text_color=None, sample=4, lang='en', timeout=45
1720
1951
  from .contrast import T as _TC
1721
1952
  t9 = _TC.get(lang, _TC['es'])
1722
1953
  with sync_playwright() as p:
1723
- nav = p.chromium.launch()
1954
+ nav = _get_browser(p, preferred=browser)
1724
1955
  ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1725
1956
  page = ctx.new_page() if auth_state else nav.new_page()
1726
1957
  try:
@@ -1770,23 +2001,243 @@ def contrast_dom(url, selector, text_color=None, sample=4, lang='en', timeout=45
1770
2001
  pass
1771
2002
 
1772
2003
 
2004
+ # --- contrast walk: perceptual pass over EVERY rendered text element --------
2005
+
2006
+ _JS_WALK = r'''(maxEls) => {
2007
+ const visible = el => !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length);
2008
+ const directText = el => [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim());
2009
+ const parseC = s => { const m = String(s).match(/rgba?\(([\d.]+),\s*([\d.]+),\s*([\d.]+)(?:,\s*([\d.]+))?\)/);
2010
+ return m ? {r:+m[1], g:+m[2], b:+m[3], a: m[4] === undefined ? 1 : +m[4]} : null; };
2011
+ const effBg = el => {
2012
+ const layers = [];
2013
+ let image = null, n = el;
2014
+ while (n && n.nodeType === 1) {
2015
+ const cs = getComputedStyle(n);
2016
+ if (!image && cs.backgroundImage && cs.backgroundImage !== 'none') image = cs.backgroundImage;
2017
+ const c = parseC(cs.backgroundColor);
2018
+ if (c) { layers.push(c); if (c.a >= 1) break; }
2019
+ n = n.parentElement;
2020
+ }
2021
+ let r = 255, g = 255, b = 255;
2022
+ for (let i = layers.length - 1; i >= 0; i--) {
2023
+ const L = layers[i];
2024
+ r = L.r * L.a + r * (1 - L.a); g = L.g * L.a + g * (1 - L.a); b = L.b * L.a + b * (1 - L.a);
2025
+ }
2026
+ return {r: Math.round(r), g: Math.round(g), b: Math.round(b), image};
2027
+ };
2028
+ const path = el => {
2029
+ const parts = [];
2030
+ let n = el, depth = 0;
2031
+ while (n && n.nodeType === 1 && depth < 5) {
2032
+ if (n.id) { parts.unshift('#' + (window.CSS && CSS.escape ? CSS.escape(n.id) : n.id)); break; }
2033
+ const parent = n.parentElement;
2034
+ if (!parent) { parts.unshift(n.tagName.toLowerCase()); break; }
2035
+ const same = [...parent.children].filter(c => c.tagName === n.tagName);
2036
+ let s = n.tagName.toLowerCase();
2037
+ if (same.length > 1) s += ':nth-of-type(' + (same.indexOf(n) + 1) + ')';
2038
+ parts.unshift(s);
2039
+ n = parent; depth++;
2040
+ }
2041
+ return parts.join(' > ') || 'body';
2042
+ };
2043
+ const out = [];
2044
+ for (const el of document.querySelectorAll('body *')) {
2045
+ if (out.length >= maxEls) break;
2046
+ if (!visible(el) || !directText(el)) continue;
2047
+ const cs = getComputedStyle(el);
2048
+ const color = parseC(cs.color);
2049
+ if (!color) continue;
2050
+ if (color.a < 1) { out.push({skip: 'translucent', path: path(el)}); continue; }
2051
+ const fs = parseFloat(cs.fontSize) || 16;
2052
+ const fw = parseInt(cs.fontWeight) || 400;
2053
+ const bg = effBg(el);
2054
+ out.push({path: path(el), tag: el.tagName.toLowerCase(),
2055
+ text: (el.innerText || '').replace(/\s+/g, ' ').trim().slice(0, 60),
2056
+ color, bg: {r: bg.r, g: bg.g, b: bg.b, a: 1},
2057
+ bg_image: bg.image ? bg.image.slice(0, 100) : null,
2058
+ font_px: Math.round(fs * 10) / 10, bold: fw >= 700});
2059
+ }
2060
+ return out;
2061
+ }'''
2062
+
2063
+
2064
+ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
2065
+ lang='en', timeout=45, auth_state=None, browser='auto'):
2066
+ """Contraste PERCIBIDO de cada text_ renderizado de la página (1.4.3).
2067
+
2068
+ La capa informe de la familia de contraste: donde audit_dom audita y
2069
+ contrast-dom mide UN elemento contra lo que sea que tenga detrás, el walk
2070
+ recorre TODOS los text_ visibles y emite la tabla por elemento que consume
2071
+ un equipo de design system: ratio real, umbral (4.5 normal / 3.0 large por
2072
+ font-size/weight computados), verdict_ y sugerencia de color. Los fondos
2073
+ con imagen/gradiente se miden por PIXELES (peor caso, misma mecánica que
2074
+ contrast-dom) hasta max_sample; el resto queda honestamente sin medir.
2075
+ Con dark=True repite el pase bajo prefers-color-scheme: dark y añade el
2076
+ delta (nuevos fallos / resueltos) — la condición de display que el CSS
2077
+ declarado no ve.
2078
+
2079
+ Filtro honesto, no veredicto: text_ en shadow DOM, canvas, vídeo y
2080
+ pseudo-elementos no se captura; lo no medido se declara, jamás inventado.
2081
+ """
2082
+ from playwright.sync_api import sync_playwright
2083
+ from .contrast import ratio as _ratio, suggest as _suggest, parse_color
2084
+
2085
+ def _verdicts(entries):
2086
+ for e in entries:
2087
+ if e['ratio'] is not None:
2088
+ e['verdict'] = 'pass' if e['ratio'] >= e['threshold'] else 'fail'
2089
+
2090
+ def _pass(page):
2091
+ raw = page.evaluate(_JS_WALK, max_walk)
2092
+ entries, shot_jobs, skipped = [], [], 0
2093
+ for row in raw:
2094
+ if row.get('skip') == 'translucent':
2095
+ skipped += 1
2096
+ continue
2097
+ fg = {k: row['color'][k] for k in ('r', 'g', 'b')}
2098
+ bg = {k: row['bg'][k] for k in ('r', 'g', 'b')}
2099
+ large = row['font_px'] >= 24 or (row['font_px'] >= 18.66 and row['bold'])
2100
+ thr = 3.0 if large else 4.5
2101
+ entry = {'path': row['path'], 'tag': row['tag'], 'text': row['text'],
2102
+ 'font_px': row['font_px'], 'bold': row['bold'],
2103
+ 'large_text': large, 'threshold': thr,
2104
+ 'color': hexs(fg), 'bg': hexs(bg),
2105
+ 'bg_image': row['bg_image'], 'pixel_sampled': False,
2106
+ 'ratio': None, 'verdict': 'unmeasured'}
2107
+ if row['bg_image']:
2108
+ shot_jobs.append((entry, fg))
2109
+ else:
2110
+ entry['ratio'] = round(_ratio(fg, bg), 2)
2111
+ entries.append(entry)
2112
+ sampled = 0
2113
+ for entry, fg in shot_jobs:
2114
+ if sampled >= max_sample:
2115
+ continue # stays unmeasured — honest cap, never invented
2116
+ try:
2117
+ loc = page.locator(entry['path']).first
2118
+ box = loc.bounding_box()
2119
+ if not box or box['width'] < 3 or box['height'] < 3:
2120
+ continue
2121
+ m = _samples_background(loc, box, fg)
2122
+ if m:
2123
+ entry['ratio'] = m['worst_ratio']
2124
+ entry['median_ratio'] = m['median_ratio']
2125
+ entry['pixel_sampled'] = True
2126
+ sampled += 1
2127
+ except Exception: # noqa: BLE001 — one dead locator must not kill the walk
2128
+ continue
2129
+ _verdicts(entries)
2130
+ return entries, skipped
2131
+
2132
+ def _summarize(entries, skipped):
2133
+ fails = [e for e in entries if e['verdict'] == 'fail']
2134
+ worst = min((e for e in entries if e['ratio'] is not None),
2135
+ key=lambda e: e['ratio'], default=None)
2136
+ return {'pass': sum(1 for e in entries if e['verdict'] == 'pass'),
2137
+ 'fail': len(fails),
2138
+ 'unmeasured': sum(1 for e in entries if e['verdict'] == 'unmeasured'),
2139
+ 'fails_4_5_normal_text': sum(1 for e in fails if e['threshold'] >= 4.5),
2140
+ 'fails_3_0_large_text': sum(1 for e in fails if e['threshold'] < 4.5),
2141
+ 'translucent_text_skipped': skipped,
2142
+ 'pixel_sampled': sum(1 for e in entries if e['pixel_sampled']),
2143
+ 'worst_ratio': worst['ratio'] if worst else None,
2144
+ 'worst_element': worst['path'] if worst else None}
2145
+
2146
+ with sync_playwright() as p:
2147
+ def _run(scheme):
2148
+ nav = _get_browser(p, preferred=browser)
2149
+ ctx = (nav.new_context(storage_state=auth_state, color_scheme=scheme)
2150
+ if auth_state else nav.new_context(color_scheme=scheme))
2151
+ page = ctx.new_page()
2152
+ try:
2153
+ page.goto(url, wait_until='load', timeout=timeout * 1000)
2154
+ page.wait_for_timeout(300)
2155
+ return _pass(page)
2156
+ finally:
2157
+ try:
2158
+ ctx.close()
2159
+ nav.close()
2160
+ except Exception: # noqa: BLE001
2161
+ pass
2162
+
2163
+ entries, skipped = _run('light')
2164
+ report = {'mode': 'contrast-walk', 'url': url, 'scheme': 'light',
2165
+ 'checked': len(entries),
2166
+ 'elements': entries,
2167
+ 'summary': _summarize(entries, skipped)}
2168
+
2169
+ # suggestions for the worst flat-background fails (pixel zones have no
2170
+ # single background to suggest against — honest skip)
2171
+ fails = sorted((e for e in entries if e['verdict'] == 'fail' and not e['bg_image']),
2172
+ key=lambda e: e['ratio'])
2173
+ for e in fails[:8]:
2174
+ s = _suggest(parse_color(e['color']), parse_color(e['bg']),
2175
+ target=e['threshold'], lang=lang)
2176
+ if s:
2177
+ e['suggestion'] = s
2178
+
2179
+ if dark:
2180
+ entries_d, skipped_d = _run('dark')
2181
+ report['dark'] = {'scheme': 'dark', 'checked': len(entries_d),
2182
+ 'elements': entries_d,
2183
+ 'summary': _summarize(entries_d, skipped_d)}
2184
+ light_fails = {e['path'] for e in entries if e['verdict'] == 'fail'}
2185
+ dark_fails = {e['path'] for e in entries_d if e['verdict'] == 'fail'}
2186
+ report['dark_delta'] = {
2187
+ 'new_fails': sorted(dark_fails - light_fails)[:20],
2188
+ 'resolved': sorted(light_fails - dark_fails)[:20],
2189
+ 'note': ('a site that ignores prefers-color-scheme shows a zero '
2190
+ 'delta: same colors in both passes')}
2191
+
2192
+ report['limits'] = (
2193
+ 'Computed ratios cover effective background-color with alpha '
2194
+ 'compositing; text over images/gradients is pixel-sampled '
2195
+ '(worst-case) up to the cap, the rest is declared unmeasured. Text '
2196
+ 'in shadow DOM, canvas, video and pseudo-elements is not captured. '
2197
+ 'A fail is a filter finding (1.4.3), not a verdict — judge the '
2198
+ 'zone with contrast-dom.'
2199
+ if lang == 'en' else
2200
+ 'Los ratios computados cubren background-color efectivo con '
2201
+ 'composición alfa; el text_ sobre imágenes/gradientes se muestrea '
2202
+ 'por píxeles (peor caso) hasta el tope y el resto se declara sin '
2203
+ 'medir. El text_ en shadow DOM, canvas, vídeo y pseudo-elementos '
2204
+ 'no se captura. Un fallo es un hallazgo de filtro (1.4.3), no un '
2205
+ 'veredicto — juzga la zona con contrast-dom.')
2206
+ return report
2207
+
2208
+
1773
2209
  def contrast_dom_main(argv):
1774
- ap = argparse.ArgumentParser(description='Real text-over-anything contrast: screenshot + pixel sampling (auto-region)')
2210
+ ap = argparse.ArgumentParser(description='Real text-over-anything contrast: screenshot + pixel sampling (auto-region); --walk = perceptual pass over every text element')
1775
2211
  ap.add_argument('url')
1776
- ap.add_argument('--selector', required=True, help='CSS selector of the text element')
2212
+ ap.add_argument('--selector', help='CSS selector of the text element (required without --walk)')
2213
+ ap.add_argument('--walk', action='store_true',
2214
+ help='perceptual pass over every rendered text element (per-element table + suggestions)')
2215
+ ap.add_argument('--max-walk', type=int, default=400, help='max elements collected per pass (default 400)')
2216
+ ap.add_argument('--max-sample', type=int, default=24, help='max image/gradient backgrounds pixel-sampled (default 24)')
2217
+ ap.add_argument('--dark', action='store_true', help='add a second pass under prefers-color-scheme: dark + delta')
1777
2218
  ap.add_argument('--text', help='text color (default: computed from the element)')
1778
2219
  ap.add_argument('--sample', type=int, default=4)
1779
2220
  ap.add_argument('--lang', default='en', choices=['en', 'es'])
1780
2221
  ap.add_argument('--timeout', type=int, default=45)
1781
2222
  a = ap.parse_args(argv)
1782
2223
  try:
1783
- res = contrast_dom(a.url, a.selector, text_color=a.text, sample=a.sample,
1784
- lang=a.lang, timeout=a.timeout)
2224
+ if a.walk:
2225
+ if not a.selector:
2226
+ res = contrast_walk(a.url, max_walk=a.max_walk, max_sample=a.max_sample,
2227
+ dark=a.dark, lang=a.lang, timeout=a.timeout)
2228
+ else:
2229
+ res = {'error': '--walk covers the whole page: drop --selector'}
2230
+ else:
2231
+ if not a.selector:
2232
+ res = {'error': 'need --selector ".hero h1" (or --walk for the whole page)'}
2233
+ else:
2234
+ res = contrast_dom(a.url, a.selector, text_color=a.text, sample=a.sample,
2235
+ lang=a.lang, timeout=a.timeout)
1785
2236
  except ImportError:
1786
2237
  print(json.dumps({'error': 'Playwright not installed'}))
1787
2238
  return 1
1788
2239
  print(json.dumps(res, ensure_ascii=False, indent=1))
1789
- return 0
2240
+ return 1 if isinstance(res, dict) and 'error' in res else 0
1790
2241
 
1791
2242
 
1792
2243
  def main(argv):
@@ -1852,5 +2303,24 @@ def kbd_main(argv):
1852
2303
  return 0
1853
2304
 
1854
2305
 
2306
+ def hover_main(argv):
2307
+ # the same audit the MCP tool a11y_hover runs (audit_hover, verbatim) —
2308
+ # 1.4.13 Content on Hover or Focus: do tooltips dismiss on Escape?
2309
+ ap = argparse.ArgumentParser(description='Tooltip dismissibility (1.4.13): hover + Escape, real browser')
2310
+ ap.add_argument('url')
2311
+ ap.add_argument('--lang', default='en', choices=['en', 'es'])
2312
+ ap.add_argument('--timeout', type=int, default=45)
2313
+ ap.add_argument('--auth-state', dest='auth_state',
2314
+ help='Path to a Playwright storage_state JSON to audit behind login')
2315
+ a = ap.parse_args(argv)
2316
+ try:
2317
+ res = audit_hover(a.url, timeout=a.timeout, lang=a.lang, auth_state=a.auth_state)
2318
+ except ImportError:
2319
+ print(json.dumps({'error': 'Playwright not installed'}))
2320
+ return 1
2321
+ print(json.dumps(res, ensure_ascii=False, indent=1))
2322
+ return 0
2323
+
2324
+
1855
2325
  if __name__ == '__main__':
1856
2326
  sys.exit(main(sys.argv[1:]))