@kinti/a11y-toolkit 5.28.0 → 5.30.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.
@@ -97,13 +97,22 @@ def act_ids(signal):
97
97
  def earl(report, url=None):
98
98
  """Informe de auditoría → EARL 1.0 JSON-LD (solo hallazgos con mapeo ACT)."""
99
99
  assertions = []
100
- # site crawls anidan en reports[]; entrada hostil (no-dict/no-list) → []
101
- _hls = report.get('findings') if isinstance(report, dict) else None
102
- if not isinstance(_hls, list) and isinstance(report, dict) and isinstance(report.get('reports'), list):
103
- _hls = [h for sub in report['reports']
104
- if isinstance(sub, dict) for h in sub.get('findings', [])
105
- if isinstance(h, dict)]
106
- for h in (_hls if isinstance(_hls, list) else []):
100
+ # site crawls anidan en reports[]: cada hallazgo pertenece a SU página —
101
+ # aplanar sin más atribuía el fallo de /gallery a la PORTADA (revisión
102
+ # externa, 3ª pasada). Se conserva el par (hallazgo, url de su página).
103
+ pares = []
104
+ if isinstance(report, dict):
105
+ _hls = report.get('findings')
106
+ # precedencia como a11yevidence: findings top-level NO VACÍOS son las
107
+ # copias re-verificadas; una lista vacía es «sin hallazgos propios» y
108
+ # los de las páginas anidadas siguen siendo del crawl
109
+ if isinstance(_hls, list) and _hls:
110
+ pares = [(h, url or report.get('url', '')) for h in _hls]
111
+ elif isinstance(report.get('reports'), list):
112
+ pares = [(h, (sub.get('url') or url or report.get('url', '')))
113
+ for sub in report['reports'] if isinstance(sub, dict)
114
+ for h in sub.get('findings', []) if isinstance(h, dict)]
115
+ for h, _subj in pares:
107
116
  if not isinstance(h, dict):
108
117
  continue
109
118
  if h.get('status') in _NOT_DEAD or h.get('disprover_status') in _NOT_DEAD:
@@ -116,7 +125,7 @@ def earl(report, url=None):
116
125
  assertions.append({
117
126
  '@type': 'earl:Assertion',
118
127
  'earl:subject': {'@type': 'earl:TestSubject',
119
- 'url': url or report.get('url', '')},
128
+ 'url': _subj},
120
129
  'earl:test': {'@type': 'earl:TestCase',
121
130
  'url': _ACT_URL.format(rid=rid),
122
131
  'title': name},
@@ -237,6 +237,7 @@ CRIT = {
237
237
  '3.2.6': '3.2.6 Ayuda coherente',
238
238
  '1.4.5': '1.4.5 Imágenes de texto',
239
239
  '1.4.11': '1.4.11 Contraste no textual',
240
+ '1.4.12': '1.4.12 Espaciado de texto',
240
241
  '1.4.13': '1.4.13 Contenido al pasar el foco o el puntero',
241
242
  '3.3.3': '3.3.3 Sugerencia ante errores',
242
243
  '1.4.2': '1.4.2 Control del audio',
@@ -293,6 +294,7 @@ CRIT = {
293
294
  '3.2.6': '3.2.6 Consistent Help',
294
295
  '1.4.5': '1.4.5 Images of Text',
295
296
  '1.4.11': '1.4.11 Non-text Contrast',
297
+ '1.4.12': '1.4.12 Text Spacing',
296
298
  '1.4.13': '1.4.13 Content on Hover or Focus',
297
299
  '3.3.3': '3.3.3 Error Suggestion',
298
300
  '1.4.2': '1.4.2 Audio Control',
@@ -343,6 +345,11 @@ _OVERLAY_WIDGETS = (
343
345
  ('Recite Me', ('recite.me',)),
344
346
  ('User1st', ('user1st.com',)),
345
347
  ('UsableNet', ('usablenet.com',)),
348
+ # ronda 18-nov contra overlayfactsheet.com (46 productos nombrados allí;
349
+ # solo entran dominios verificados contra la web oficial de cada vendedor)
350
+ ('Eye-Able', ('eye-able.com',)),
351
+ ('AccessiWay', ('accessiway.com',)),
352
+ ('Equally AI', ('equally.ai',)),
346
353
  )
347
354
 
348
355
  # texto de un skip link (es/en/pt/fr — el vocabulario del patrón 3e12e1)
@@ -350,7 +357,7 @@ _SKIP_TEXT = re.compile(
350
357
  r'skip|jump to|saltar|ir al contenido|ir para o conte[uú]do|passer au contenu', re.I)
351
358
 
352
359
  # encabezados cortos legítimos (acrónimos y términos técnicos): «FAQ», «API»…
353
- _SHORT_HEADINGS = {'FAQ', 'API', 'CSS', 'APP', 'MAP', 'EN', 'DE', 'ES', 'PT', 'FR',
360
+ _SHORT_HEADINGS = {'FAQ', 'API', 'CSS', 'SVG', 'APP', 'MAP', 'EN', 'DE', 'ES', 'PT', 'FR',
354
361
  'IT', 'UI', 'UX', 'ID', 'TV', 'HR', 'PR', 'AI', 'PC', 'OK', '3D',
355
362
  'IOS', 'OS', 'GB', 'MB', 'KB', 'PDF', 'RSS', 'URL', 'WWW', 'XML',
356
363
  'HTTP', 'FAQS', 'BLOG', 'HOME', 'INICIO', 'NOTAS', 'AGENDA'}
@@ -476,6 +483,8 @@ class _Auditor(HTMLParser):
476
483
  self.controls_raw = [] # (kind, attrs, texto, [nombres imgs internas], hidden)
477
484
  self.headings_raw = [] # (nivel, attrs, texto, hidden)
478
485
  self.fields_raw = [] # (tag, kind, attrs, dentro_de_label, hidden)
486
+ self._fields_in_label = [] # campos que el <label> ABIERTO envuelve
487
+ self._wrap_label_text = {} # id(attrs del campo) → texto de su label envolvente
479
488
  self._heading_attrs = {}
480
489
  self.videos = 0
481
490
  self.videos_with_captions = 0
@@ -510,8 +519,13 @@ class _Auditor(HTMLParser):
510
519
  self.missing_autocomplete = []
511
520
  self.autocomplete_invalid = []
512
521
  self.autocomplete_mismatch = []
522
+ self.heading_role_removed = [] # h1-h6 con rol que sustituye al de heading
523
+ self.text_spacing_important = [] # 1.4.12: spacing !important inline (ACT 24afc2/78fd32/9e45ec)
513
524
  self.links = {} # nombre normalizado → set de hrefs
525
+ self.links_elems = {} # entry_key → primeros elems (marcas 2.4.4)
514
526
  self.generics = 0
527
+ self.generic_link_elems = [] # marcas 2.4.4
528
+ self._label_elem_stack = [] # elem por <label> abierto (marcas 3.3.2)
515
529
  self.labels_for_dups = {} # id → n labels (los >1, varios)
516
530
  self._label_for_stack = [] # valor `for` de cada <label> abierto (None = envolvente)
517
531
  self._label_text_for = {} # id del for → texto del label (decisión post-parse)
@@ -519,7 +533,10 @@ class _Auditor(HTMLParser):
519
533
  self._list_depth = 0
520
534
  self._li_depth = 0
521
535
  self._bad_list = 0
522
- self.label_no_name = [] # (texto visible, aria-label) 2.5.3
536
+ self.label_no_name = [] # (texto visible, nombre efectivo) 2.5.3
537
+ self.label_no_name_elems = [] # marcas 2.5.3
538
+ self.label_in_name_raw = [] # (visible, aria-label, ids labelledby, attrs) — crudo, POST-parse decide
539
+ self.orphan_label_elems = [] # marcas 3.3.2
523
540
  self.lang_parts_invalid = [] # lang inválidos en elementos no-html
524
541
  self.down_events = [] # onmousedown/ontouchstart/onpointerdown
525
542
  self.captchas = [] # detección 3.3.8 — SOLO en contexto de autenticación
@@ -528,7 +545,7 @@ class _Auditor(HTMLParser):
528
545
  self._required_pend = [] # (tag, attrs) required: decide post-parse con el label
529
546
  self.mobiles = [] # marquee/blink/inline infinite animation (2.2.2)
530
547
  self._landmark_ids = set() # ids de landmarks: objetivos válidos de skip link
531
- self.nav_hrefs = set() # hrefs inside <nav> (site-level 3.2.3 signature)
548
+ self.nav_hrefs = [] # hrefs inside <nav> EN ORDEN (3.2.3 juzga el ORDEN relativo)
532
549
  self.help_hrefs = set() # help/contact links (site-level 3.2.6 signature)
533
550
  self.images_of_text = []
534
551
  self.vague_headings = []
@@ -551,6 +568,7 @@ class _Auditor(HTMLParser):
551
568
  self._group_role_depth = 0 # <div role=group/radiogroup> abierto (con nombre)
552
569
  self.has_search = False
553
570
  self.has_sitemap = False
571
+ self.has_index = False # índice/TOC/relacionados: vía 2.4.5 (4ª pasada)
554
572
  self.gestures = [] # touchmove/drag handlers (2.5.1)
555
573
  self.focus_blur = [] # onfocus="blur()": foco robado (2.1.1)
556
574
  self.focus_blur_elems = []
@@ -568,52 +586,29 @@ class _Auditor(HTMLParser):
568
586
  return
569
587
  self._ctrl.pop()
570
588
  a = c['attrs']
571
- text = ' '.join(c['text']).strip()
589
+ # nombre desde el texto VISIBLE (4ª pasada): el crudo incluía texto
590
+ # con display:none/visibility:hidden que accname excluye. .sr-only
591
+ # (clip) sigue contando: está en el árbol de accesibilidad; y el
592
+ # <title> de un svg interno entra por su canal (alternativo, no
593
+ # renderizado, PERO sí nombre)
594
+ text = ' '.join(x for x in (
595
+ ''.join(c.get('text_visible', [])).strip(),
596
+ ' '.join(c.get('text_alt', [])).strip()) if x)
572
597
  # decisión de nombre POST-parse: los ids de un aria-labelledby pueden
573
598
  # declararse después del control; se registra todo en crudo
574
599
  self.controls_raw.append((c.get('kind') or tag, a, text, c.get('img_attrs', []),
575
600
  c.get('hidden', False)))
576
- # 2.5.3 label in name — algoritmo de WCAG Understanding 2.5.3: sin el
577
- # contenido entre paréntesis, minúsculas, sin puntuación, y la
578
- # etiqueta visible contenida POR PALABRAS en el nombre («just ice» ≠
579
- # «justice»; «Discover It» falla contra «Discover Italy»). Una
580
- # etiqueta visible de un solo carácter/símbolo (X, emoji) es texto no
581
- # verbal: exenta. La etiqueta es la que se VEE (la oculta por CSS no)
582
- # concatenación DOM fiel: sin espacios artificiales — los del DOM ya
583
- # vienen en los propios nodos de texto (2ee8b8: «W C A G» ≠ «ACT»)
601
+ # 2.5.3 label in name — el VEREDICTO se decide POST-parse (los ids de
602
+ # aria-labelledby pueden declararse después del control). Aquí solo se
603
+ # registra lo crudo; el algoritmo vive abajo, sobre el nombre EFECTIVO
604
+ # por precedencia accname (revisión externa, 4ª pasada: comparar
605
+ # contra aria-label penalizaba controles nombrados por labelledby y
606
+ # aprobaba el caso inverso)
584
607
  _vis = ''.join(c.get('text_visible', [])).strip()
585
608
  _al = (a.get('aria-label') or '').strip()
586
- # página con fuente-icono declarada (Material Icons, Font Awesome…):
587
- # el «texto» de un botón puede ser un glifo no verbal — exento
588
- _icon_font = bool(re.search(
589
- r"font-family\s*:[^;}]*?(Material[+ ]Icons|Font Awesome|glyphicon|icomoon|feather)"
590
- r"|@font-face[^}]*?(Material[+ ]Icons|Font Awesome|glyphicon|icomoon|feather)",
591
- self._styles_text, re.I)) or bool(re.search(
592
- r'fonts\.googleapis\.com/icon|/material-icons|font-?awesome|/icomoon',
593
- ' '.join(getattr(self, '_icon_links', [])), re.I))
594
- # página con fuente-icono: el «texto» del control puede ser un glifo
595
- # no verbal (ligadura Material «shopping_cart») — exento en CUALQUIER
596
- # control (enlaces-icono incluidos), no solo <button>
597
- if not _icon_font and _vis and _al:
598
- def _lin_words(txt):
599
- txt = re.sub(r'\([^)]*\)', ' ', txt)
600
- # la puntuación se ELIMINA sin partir palabras («11×3=33» →
601
- # «1133»: una sola palabra) — algoritmo 2.5.3
602
- return [w for w in re.sub(r'[^\w\s]|_', '', txt.lower()).split() if w]
603
- _vp, _ap2 = _lin_words(_vis), _lin_words(_al)
604
- _mismatch = False
605
- if _vp and _ap2:
606
- if len(_vp) == 1 and len(_vp[0]) <= 2 and _vp[0].isalpha():
607
- _mismatch = False # letra-símbolo única (X): texto no verbal
608
- else:
609
- # RODAJA CONTIGUA EXACTA: «discover it» no cabe en
610
- # «discover italy» (it ≠ italy); «download specification»
611
- # no cabe en «download the specification»; «you how are»
612
- # no en «how are you» aunque estén todas las palabras
613
- _mismatch = not any(_ap2[i:i + len(_vp)] == _vp
614
- for i in range(len(_ap2) - len(_vp) + 1))
615
- if _mismatch:
616
- self.label_no_name.append((_vis[:40], _al[:60]))
609
+ _lb_ids = (a.get('aria-labelledby') or '').split()
610
+ if _vis and (_al or _lb_ids) and len(self.label_in_name_raw) < 30:
611
+ self.label_in_name_raw.append((_vis[:80], _al[:120], _lb_ids[:6], a))
617
612
  if tag == 'a' and not c.get('hidden'):
618
613
  if (a.get('target') or '').lower() == '_blank':
619
614
  self.blank_total += 1
@@ -636,8 +631,13 @@ class _Auditor(HTMLParser):
636
631
  if name and href:
637
632
  entry_key = ' '.join(name.lower().split())[:60]
638
633
  self.links.setdefault(entry_key, set()).add(href)
634
+ _le_list = self.links_elems.setdefault(entry_key, [])
635
+ if len(_le_list) < 5:
636
+ _le_list.append(a)
639
637
  if entry_key in _GENERIC_TEXT:
640
638
  self.generics += 1
639
+ if len(self.generic_link_elems) < 5:
640
+ self.generic_link_elems.append(a)
641
641
 
642
642
  def _field_note(self):
643
643
  """El elemento que acaba de abrirse es un campo: marca su <label> ancestro."""
@@ -683,6 +683,16 @@ class _Auditor(HTMLParser):
683
683
  # ruta determinista del elemento (kernel de anotación): nth-of-type
684
684
  # SIEMPRE (los id duplicados no pueden romper la ruta) y los void no
685
685
  # abren pila (no tienen handle_endtag)
686
+ # tbody IMPLÍCITO bajo <table>: el navegador normaliza <table><tr>
687
+ # insertando <tbody>; sin reflejarlo, las rutas nth-of-type que
688
+ # cruzan la mesa no resuelven en el DOM real (Chromium: table>tr
689
+ # casa CERO elementos — revisión externa 2026-11-22). Se abre igual
690
+ # que un tag normal y </table> lo cierra con el resto de la pila.
691
+ if tag == 'tr' and self._path_stack and self._path_stack[-1][0] == 'table':
692
+ _parent_tb = self._path_stack[-1]
693
+ _parent_tb[2]['tbody'] = _parent_tb[2].get('tbody', 0) + 1
694
+ self._path_stack.append(
695
+ ('tbody', _parent_tb[1] + '>' + path_segment('tbody', _parent_tb[2]['tbody']), {}))
686
696
  if self._path_stack:
687
697
  _parent = self._path_stack[-1]
688
698
  _parent[2][tag] = _parent[2].get(tag, 0) + 1
@@ -718,8 +728,10 @@ class _Auditor(HTMLParser):
718
728
  _hidden_aria = True
719
729
  elif _ah_val == 'false':
720
730
  _hidden_aria = False
731
+ # inert (4ª pasada): el subtroke queda no interactivo Y fuera del
732
+ # árbol de accesibilidad — un botón dentro de inert JAMÁS es enfocable
721
733
  _hidden = _inh or 'hidden' in a or 'display:none' in _style \
722
- or 'visibility:hidden' in _style or _hidden_aria
734
+ or 'visibility:hidden' in _style or _hidden_aria or 'inert' in a
723
735
  # <template> es contenido INERTE (spec HTML): no renderiza, no recibe
724
736
  # foco, sus ids no existen — se audita como oculto y los colectores
725
737
  # que no consultan _hidden llevan guardia explícita
@@ -853,12 +865,20 @@ class _Auditor(HTMLParser):
853
865
  'img_attrs': [], 'hidden': _hidden})
854
866
  href = (a.get('href') or '').strip()
855
867
  if self._in_nav and href and not href.startswith('#'):
856
- self.nav_hrefs.add(href.split('#')[0].rstrip('/'))
868
+ _nv = href.split('#')[0].rstrip('/')
869
+ if _nv not in self.nav_hrefs:
870
+ self.nav_hrefs.append(_nv)
857
871
  if href and re.search(r'help|contact|support|ayuda|contacto|soporte|asistencia',
858
872
  href, re.I):
859
873
  self.help_hrefs.add(href.split('#')[0].rstrip('/'))
860
874
  if href and re.search(r'sitemap|site-map|mapa-del-sitio|mapa_web|mapaweb', href, re.I):
861
875
  self.has_sitemap = True
876
+ # 2.4.5 vía adicional (4ª pasada): un índice/TOC o bloque de
877
+ # relacionados SON formas de encontrar páginas
878
+ if href and re.search(
879
+ r'(?:^|[/\-_!.])(?:index|indice|indice-de-contenidos|contents|toc|related|relacionados|ver-tambien|see-also)(?:$|[/\-_!.])',
880
+ href.split('#')[0].rstrip('/'), re.I):
881
+ self.has_index = True
862
882
  elif tag == 'input':
863
883
  self._field_note()
864
884
  kind = (a.get('type') or 'text').lower()
@@ -873,8 +893,19 @@ class _Auditor(HTMLParser):
873
893
  if kind == 'search' or re.search(r'search|busqueda|b[uú]squeda', (a.get('name') or '') + (a.get('id') or ''), re.I):
874
894
  self.has_search = True
875
895
  if kind in _FIELDS:
896
+ if self._wrap_labels(a):
897
+ self._fields_in_label.append(id(a))
876
898
  self.fields_raw.append((tag, kind, a, self._wrap_labels(a), _hidden))
877
- if 'autocomplete' not in a and kind != 'search' and (
899
+ # 1.3.5 aplicabilidad y cobertura por SEPARADO (4ª pasada):
900
+ # type=email asumía «dato de la persona usuaria» aunque fuera
901
+ # el correo del DESTINATARIO, y autocomplete=off daba la
902
+ # condición por cubierta — off/on no identifican propósito
903
+ _recipient = re.search(
904
+ r'(?<![a-z0-9])(to|recipient|destinatari[oa]s?|destino|friend|amigo)(?![a-z0-9])',
905
+ ((a.get('name') or '') + ' ' + (a.get('id') or '')), re.I)
906
+ _tok_ac = (a.get('autocomplete') or '').strip().lower()
907
+ _covered = bool(_tok_ac) and _tok_ac not in ('off', 'on')
908
+ if (not _covered) and kind != 'search' and not _recipient and (
878
909
  kind in ('email', 'tel')
879
910
  or _PERSONAL_DATA.search((a.get('name') or '') + ' ' + (a.get('id') or ''))):
880
911
  self.missing_autocomplete.append(f'input type={kind} name={a.get("name") or "?"}'[:44])
@@ -920,11 +951,15 @@ class _Auditor(HTMLParser):
920
951
  f'{_mal} (input name={a.get("name") or "?"})'[:60])
921
952
  elif tag in ('select', 'textarea'):
922
953
  self._field_note()
954
+ if self._wrap_labels(a):
955
+ self._fields_in_label.append(id(a))
923
956
  self.fields_raw.append((tag, tag, a, self._wrap_labels(a), _hidden))
924
957
  elif tag == 'label':
925
958
  self._label_depth += 1
926
959
  self._label_text_current = []
960
+ self._fields_in_label = [] # campos que ESTE label envuelve
927
961
  self._labels_stack.append(False)
962
+ self._label_elem_stack.append(a)
928
963
  self._label_for_stack.append(a.get('for') or None)
929
964
  if a.get('for'):
930
965
  self._labels_for[a['for']] = self._labels_for.get(a['for'], 0) + 1
@@ -1056,6 +1091,16 @@ class _Auditor(HTMLParser):
1056
1091
  style = a.get('style') or ''
1057
1092
  if 'animation' in style and 'infinite' in style:
1058
1093
  self.mobiles.append(f'{tag}[style animation…infinite]')
1094
+ # 1.4.12 text spacing (ACT 24afc2/78fd32/9e45ec): un !important en
1095
+ # line/letter/word-spacing inline impide al usuario re-espaciar el
1096
+ # texto con su hoja de estilos — fallo mecánico, cero ambigüedad
1097
+ if not self._in_template:
1098
+ _sp = re.search(
1099
+ r'(letter|word)-spacing\s*:[^;"}]*!important|'
1100
+ r'line-height\s*:[^;"}]*!important', style, re.I)
1101
+ if _sp and len(self.text_spacing_important) < 12:
1102
+ self.text_spacing_important.append(
1103
+ f'{tag}[{_sp.group(0)[:34]}]')
1059
1104
  # v3.12: 2.5.1 gesture without click alternative (attribute-level hint)
1060
1105
  if a.get('ontouchmove') or a.get('ondrag'):
1061
1106
  if not (a.get('onclick') or tag in ('input', 'button', 'a')):
@@ -1239,9 +1284,17 @@ class _Auditor(HTMLParser):
1239
1284
  if tag in ('h1', 'h2', 'h3', 'h4', 'h5', 'h6'):
1240
1285
  # role=none/presentation APAGA la semántica del encabezado; un
1241
1286
  # aria-level válido la SOBRESCRIBE (accname: h3[aria-level=4] ES 4)
1242
- if (a.get('role') or '').strip().lower() in ('none', 'presentation') \
1243
- or self._in_template:
1287
+ _hrole = (a.get('role') or '').strip().lower()
1288
+ if _hrole in ('none', 'presentation') or self._in_template:
1244
1289
  pass
1290
+ elif _hrole and _hrole != 'heading':
1291
+ # CUALQUIER otro rol explícito SUSTITUYE al de heading (la
1292
+ # primera regla de ARIA): h2 role=button desaparece de la
1293
+ # navegación por encabezados del AT — se registra (1.3.1)
1294
+ if not _hidden and len(self.heading_role_removed) < 12:
1295
+ _nm = (a.get('aria-label') or '').strip()[:24]
1296
+ self.heading_role_removed.append(
1297
+ f'{tag} role="{_hrole}"' + (f' "{_nm}"' if _nm else ''))
1245
1298
  else:
1246
1299
  self._heading_level = int(tag[1])
1247
1300
  _alv = re.match(r'\d+', str(a.get('aria-level') or ''))
@@ -1344,8 +1397,11 @@ class _Auditor(HTMLParser):
1344
1397
  if _svgtxt:
1345
1398
  if self._ctrl:
1346
1399
  # nombre SÍ (accname from content); VISIBLE no — el
1347
- # <title> de svg es texto alternativo, no renderizado
1400
+ # <title> de svg es texto alternativo, no renderizado.
1401
+ # Canal aparte (4ª pasada): el nombre del control parte
1402
+ # del texto VISIBLE y el título-vía-svg entra aquí
1348
1403
  self._ctrl[-1]['text'].append(_svgtxt)
1404
+ self._ctrl[-1].setdefault('text_alt', []).append(_svgtxt)
1349
1405
  for _fr in reversed(self._el_stack):
1350
1406
  if _fr[0] == 'svg':
1351
1407
  self._svg_titles[id(_fr[1])] = _svgtxt
@@ -1375,8 +1431,18 @@ class _Auditor(HTMLParser):
1375
1431
  _lfor = self._label_for_stack.pop()
1376
1432
  if _lfor and txt:
1377
1433
  self._label_text_for[_lfor] = txt
1378
- if self._labels_stack and not self._labels_stack.pop():
1379
- self.orphan_labels += 1
1434
+ # texto del label ENVOLVENTE por campo (a11ylocate indexa el
1435
+ # campo por su nombre visible — la misma resolución del auditor)
1436
+ if txt:
1437
+ for _fa in getattr(self, '_fields_in_label', []):
1438
+ self._wrap_label_text[_fa] = txt
1439
+ if self._labels_stack:
1440
+ # pila paralela de elems: pop SIEMPRE (un pop por cierre)
1441
+ _le = self._label_elem_stack.pop() if self._label_elem_stack else None
1442
+ if not self._labels_stack.pop():
1443
+ self.orphan_labels += 1
1444
+ if _le is not None and len(self.orphan_label_elems) < 5:
1445
+ self.orphan_label_elems.append(_le)
1380
1446
  elif tag == 'fieldset':
1381
1447
  self._in_fieldset = False
1382
1448
  elif tag == 'form':
@@ -1561,7 +1627,10 @@ class _Auditor(HTMLParser):
1561
1627
  self._ctrl[-1]['text_visible'].append(data)
1562
1628
  if self._heading_level is not None and not _hidden_ah:
1563
1629
  self._heading_text.append(data)
1564
- m = _SENSORIAL.search(data)
1630
+ # las CITAS son menciones legítimas (un checklist que cita el
1631
+ # anti-patrón «el botón de la derecha» para enseñarlo no incumple:
1632
+ # espejo de _sin_citas del corrector de plantillas)
1633
+ m = _SENSORIAL.search(re.sub(r'«[^»]*»|“[^”]*”|"[^"]*"', ' ', data))
1565
1634
  if m and len(self.sensory) < 6:
1566
1635
  self.sensory.append(m.group(0).strip()[:60])
1567
1636
 
@@ -1867,9 +1936,14 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
1867
1936
  if _fa.get('role') == a.get('role') and not a.get('id') and not _fa.get('id')),
1868
1937
  '')
1869
1938
  _placeholder = (a.get('placeholder') or '').strip() if tag != 'select' else ''
1939
+ # el <label> SOLO cuenta con TEXTO (4ª pasada: un label VACÍO daba
1940
+ # nombre y Chromium exponía el campo sin nombre)
1941
+ _label_txt = (getattr(p, '_label_text_for', {}).get(a.get('id'), '')
1942
+ or getattr(p, '_wrap_label_text', {}).get(id(a), '')).strip()
1870
1943
  _has_real_name = bool(al or lb or ti
1871
- or (en_label and _is_labelable)
1872
- or (_is_labelable and a.get('id') and a['id'] in p._labels_for)
1944
+ or (en_label and _is_labelable and _label_txt)
1945
+ or (_is_labelable and a.get('id') and a['id'] in p._labels_for
1946
+ and getattr(p, '_label_text_for', {}).get(a.get('id'), '').strip())
1873
1947
  or _content_name)
1874
1948
  if not (_has_real_name or _placeholder):
1875
1949
  p.fields_no_label.append((kind or tag, (a.get('name') or '')[:60], a.get('id')))
@@ -1944,7 +2018,9 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
1944
2018
  paths=[p._elem_paths[id(_a)] for _a in p.role_no_tabindex_elems
1945
2019
  if id(_a) in p._elem_paths][:5])
1946
2020
  if p.orphan_labels:
1947
- add('low', '3.3.2', 'label_orphan', n=p.orphan_labels)
2021
+ add('low', '3.3.2', 'label_orphan', n=p.orphan_labels,
2022
+ paths=[p._elem_paths[id(_a)] for _a in p.orphan_label_elems
2023
+ if id(_a) in p._elem_paths][:5])
1948
2024
  if p._bad_list:
1949
2025
  add('medium', '1.3.1', 'list_structure', n=p._bad_list)
1950
2026
  if p.root_tag in ('svg', 'math'):
@@ -2077,6 +2153,12 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2077
2153
  add('low', '1.3.1', 'no_headings')
2078
2154
  if p.empty_h:
2079
2155
  add('low', '1.3.1', 'empty_heading', n=p.empty_h)
2156
+ if p.heading_role_removed:
2157
+ add_ej('medium', '1.3.1', 'heading_role_removed', p.heading_role_removed,
2158
+ n=len(p.heading_role_removed), example=', '.join(p.heading_role_removed[:4]))
2159
+ if p.text_spacing_important:
2160
+ add_ej('medium', '1.4.12', 'text_spacing_important', p.text_spacing_important,
2161
+ n=len(p.text_spacing_important), example=', '.join(p.text_spacing_important[:4]))
2080
2162
  if p.tables and p.tables_with_th < p.tables:
2081
2163
  add('medium', '1.3.1', 'table_no_th', n=p.tables - p.tables_with_th,
2082
2164
  paths=[p._elem_paths[id(_a)] for _a in p.tables_no_th_elems
@@ -2125,11 +2207,43 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2125
2207
  add('medium', '1.4.2', 'video_autoplay', n=p.media_autoplay,
2126
2208
  paths=[p._elem_paths[id(_a)] for _a in p.media_autoplay_elems
2127
2209
  if id(_a) in p._elem_paths][:5])
2210
+ # 2.5.3, veredicto POST-parse (4ª pasada): el nombre EFECTIVO por
2211
+ # precedencia accname — labelledby (ids resueltos, unidos en orden) GANA
2212
+ # a aria-label. El nombre del propio contenido cumple trivialmente.
2213
+ def _lin_words(txt):
2214
+ txt = re.sub(r'\([^)]*\)', ' ', txt)
2215
+ return [w for w in re.sub(r'[^\w\s]|_', '', txt.lower()).split() if w]
2216
+ _icon_font = bool(re.search(
2217
+ r"font-family\s*:[^;}]*?(Material[+ ]Icons|Font Awesome|glyphicon|icomoon|feather)"
2218
+ r"|@font-face[^}]*?(Material[+ ]Icons|Font Awesome|glyphicon|icomoon|feather)",
2219
+ getattr(p, '_styles_text', ''), re.I)) or bool(re.search(
2220
+ r'fonts\.googleapis\.com/icon|/material-icons|font-?awesome|/icomoon',
2221
+ ' '.join(getattr(p, '_icon_links', [])), re.I))
2222
+ for _vis, _al, _lb_ids, _a in p.label_in_name_raw:
2223
+ _lb_txt = ' '.join((p._id_texts.get(i, '') or '').strip()
2224
+ for i in _lb_ids if (p._id_texts.get(i, '') or '').strip())
2225
+ _name_eff = _lb_txt or _al
2226
+ _vp, _np2 = _lin_words(_vis), _lin_words(_name_eff)
2227
+ if not (_vp and _np2):
2228
+ continue
2229
+ if len(_vp) == 1 and len(_vp[0]) <= 2 and _vp[0].isalpha():
2230
+ continue # letra-símbolo única (X, emoji): texto no verbal
2231
+ # fuente-icono: SOLO controles de token único (ligadura); un botón de
2232
+ # texto con dos palabras JAMÁS es un glifo (4ª pasada)
2233
+ if _icon_font and len(_vp) == 1:
2234
+ continue
2235
+ # RODAJA CONTIGUA EXACTA: «discover it» no cabe en «discover italy»
2236
+ if not any(_np2[i:i + len(_vp)] == _vp for i in range(len(_np2) - len(_vp) + 1)):
2237
+ p.label_no_name.append((_vis[:40], _name_eff[:60]))
2238
+ if len(p.label_no_name_elems) < 5:
2239
+ p.label_no_name_elems.append(_a)
2128
2240
  if p.label_no_name:
2129
2241
  _ln = p.label_no_name[0]
2130
2242
  add_ej('medium', '2.5.3', 'label_in_name',
2131
- [f'«{t}» vs aria-label «{al}»' for t, al in p.label_no_name],
2132
- n=len(p.label_no_name), example=f'{_ln[0]} ≠ {_ln[1]}')
2243
+ [f'«{t}» vs name «{al}»' for t, al in p.label_no_name],
2244
+ n=len(p.label_no_name), example=f'{_ln[0]} ≠ {_ln[1]}',
2245
+ paths=[p._elem_paths[id(_a)] for _a in p.label_no_name_elems
2246
+ if id(_a) in p._elem_paths][:5])
2133
2247
  if p.lang_parts_invalid:
2134
2248
  add_ej('medium', '3.1.2', 'element_lang_invalid', p.lang_parts_invalid,
2135
2249
  n=len(p.lang_parts_invalid), example=', '.join(p.lang_parts_invalid[:4]))
@@ -2204,10 +2318,16 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2204
2318
  add('low', '1.3.1', 'landmark_dup', n=len(lm_dups), example=', '.join(lm_dups[:4]))
2205
2319
  if p.generics >= 2: # un enlace genérico único suele desambiguarse por contexto
2206
2320
  gen = [f'«{k}»' for k in p.links if k in _GENERIC_TEXT][:4]
2207
- add('low', '2.4.4', 'generic_link', n=p.generics, example=', '.join(gen))
2321
+ add('low', '2.4.4', 'generic_link', n=p.generics, example=', '.join(gen),
2322
+ paths=[p._elem_paths[id(_a)] for _a in p.generic_link_elems
2323
+ if id(_a) in p._elem_paths][:5])
2208
2324
  same = sum(1 for _k, hrefs in p.links.items() if len(hrefs) > 1)
2209
2325
  if same:
2210
- add('low', '2.4.4', 'same_name_links', n=same)
2326
+ _same_elems = [p.links_elems.get(_k, [None])[0]
2327
+ for _k, _hs in p.links.items() if len(_hs) > 1]
2328
+ add('low', '2.4.4', 'same_name_links', n=same,
2329
+ paths=[p._elem_paths[id(_a)] for _a in _same_elems
2330
+ if _a is not None and id(_a) in p._elem_paths][:5])
2211
2331
  ak_dups = [f'"{k}" ×{v}' for k, v in p.accesskeys.items() if v > 1]
2212
2332
  if ak_dups:
2213
2333
  add('low', '2.1.1', 'accesskey_dup', n=len(ak_dups), example=', '.join(ak_dups[:4]))
@@ -2333,7 +2453,7 @@ class _CheckedRedirect(urllib.request.HTTPRedirectHandler):
2333
2453
  _OPENER = urllib.request.build_opener(_CheckedRedirect)
2334
2454
 
2335
2455
 
2336
- def _fetch(url, timeout=30, truncate_at=None, accept_ct=()):
2456
+ def _fetch(url, timeout=30, truncate_at=None, accept_ct=(), _meta=None):
2337
2457
  scheme = url.split(':', 1)[0].lower() if ':' in url else ''
2338
2458
  if scheme not in ('http', 'https'):
2339
2459
  # política única para TODAS las rutas de descarga (audit_url la
@@ -2345,6 +2465,11 @@ def _fetch(url, timeout=30, truncate_at=None, accept_ct=()):
2345
2465
  'Accept-Encoding': 'gzip',
2346
2466
  })
2347
2467
  with _OPENER.open(req, timeout=timeout) as r:
2468
+ # verdad de navegación (4ª pasada): seguir una redirección en
2469
+ # silencio hacía puntuar 100 la pantalla de acceso BAJO la URL pedida
2470
+ if _meta is not None:
2471
+ _meta['final_url'] = r.geturl()
2472
+ _meta['status'] = getattr(r, 'status', None)
2348
2473
  ceiling = truncate_at or MAX_HTML
2349
2474
  # TOTAL-CLOCK reading: the socket timeout is per-operation and a server
2350
2475
  # dribbling one byte per operation reset it forever. Read in chunks
@@ -2402,15 +2527,29 @@ _T_SCHEME = {
2402
2527
  def audit_url(url, timeout=30, lang='en', standard=None, target=None):
2403
2528
  if url.split(':')[0].lower() not in ('http', 'https'):
2404
2529
  return {'error': _T_SCHEME.get(lang, _T_SCHEME['es'])}
2530
+ _meta = {}
2405
2531
  try:
2406
- html_text = _fetch(url, timeout=timeout)
2532
+ html_text = _fetch(url, timeout=timeout, _meta=_meta)
2407
2533
  except _FetchError as e:
2408
2534
  return {'error': _t(lang, e.key).format(**e.fmt)}
2409
2535
  except ValueError as e:
2410
2536
  return {'error': str(e)}
2411
2537
  except Exception as e: # noqa: BLE001
2412
2538
  return {'error': _t(lang, 'fetch_error').format(e=e)}
2413
- return audit_html(html_text, url, lang=lang, standard=standard, target=target)
2539
+ # verdad de navegación (4ª pasada): el informe lleva la URL FINAL (la
2540
+ # página que de verdad se miró), la PEDIDA y el estado HTTP
2541
+ final_url = _meta.get('final_url') or url
2542
+ res = audit_html(html_text, final_url.split('#')[0], lang=lang,
2543
+ standard=standard, target=target)
2544
+ if final_url.split('#')[0] != url.split('#')[0]:
2545
+ res['requested_url'] = url
2546
+ res['redirect_note'] = (
2547
+ 'la URL pedida redirigió: el informe es de la página FINAL'
2548
+ if lang == 'es' else
2549
+ 'the requested URL redirected: this report is for the FINAL page')
2550
+ if _meta.get('status'):
2551
+ res['http_status'] = _meta['status']
2552
+ return res
2414
2553
 
2415
2554
 
2416
2555
  _LOC = re.compile(r'<loc>\s*([^<\s]+)\s*</loc>', re.I)
@@ -2477,13 +2616,28 @@ def evaluate_site(parsers, lang='en'):
2477
2616
  2.4.5 multiple ways. Pure function so tests need no network."""
2478
2617
  out = []
2479
2618
  if len(parsers) >= 3:
2480
- signatures = [frozenset(p.nav_hrefs) for p in parsers if p.nav_hrefs]
2481
- if len(signatures) >= 3 and len(set(signatures)) > 1:
2482
- out.append({'severity': 'medium', 'criterion': _crit(lang, '3.2.3'),
2483
- 'signal': 'nav_inconsistent',
2484
- 'issue': _t(lang, 'nav_inconsistent').format(
2485
- example=f'{len(set(signatures))} distintas en {len(signatures)} páginas'),
2486
- 'remediation': _t(lang, 'nav_inconsistent_rem')})
2619
+ # 3.2.3 evalúa el ORDEN RELATIVO de la navegación repetida (4ª
2620
+ # pasada): comparar conjuntos dejaba pasar dos enlaces intercambiados
2621
+ # y disparaba ante un enlace contextual INSERTADO sin mover a los
2622
+ # demás. Se juzga la secuencia de los enlaces COMPARTIDOS por par
2623
+ seqs = [list(p.nav_hrefs) for p in parsers if p.nav_hrefs]
2624
+ if len(seqs) >= 3:
2625
+ reordered_pairs = 0
2626
+ for i in range(len(seqs)):
2627
+ for j in range(i + 1, len(seqs)):
2628
+ shared = set(seqs[i]) & set(seqs[j])
2629
+ if len(shared) < 2:
2630
+ continue
2631
+ order_a = [h for h in seqs[i] if h in shared]
2632
+ order_b = [h for h in seqs[j] if h in shared]
2633
+ if order_a != order_b:
2634
+ reordered_pairs += 1
2635
+ if reordered_pairs:
2636
+ out.append({'severity': 'medium', 'criterion': _crit(lang, '3.2.3'),
2637
+ 'signal': 'nav_inconsistent',
2638
+ 'issue': _t(lang, 'nav_inconsistent').format(
2639
+ example=f'{reordered_pairs} pares de páginas con orden distinto en {len(seqs)}'),
2640
+ 'remediation': _t(lang, 'nav_inconsistent_rem')})
2487
2641
  # 3.2.6 Consistent Help (A, new in 2.2): help links stable across pages
2488
2642
  signatures_help = [frozenset(p.help_hrefs) for p in parsers if p.help_hrefs]
2489
2643
  if len(signatures_help) >= 2 and len(parsers) >= 3 and len(set(signatures_help)) > 1:
@@ -2495,11 +2649,22 @@ def evaluate_site(parsers, lang='en'):
2495
2649
  # 2.4.5 exige múltiples formas de encontrar PÁGINAS: con una muestra de
2496
2650
  # una sola página no hay proceso multi-página que reclamarlo (FP en
2497
2651
  # sitios de una página — la excepción del propio criterio)
2498
- if len(parsers) >= 2 and not any(p.has_search or p.has_sitemap for p in parsers):
2499
- out.append({'severity': 'medium', 'criterion': _crit(lang, '2.4.5'),
2500
- 'signal': 'no_multiple_ways',
2501
- 'issue': _t(lang, 'no_multiple_ways'),
2502
- 'remediation': _t(lang, 'no_multiple_ways_rem')})
2652
+ # 2.4.5 (4ª pasada): un índice/TOC o enlaces relacionados SON vías; sin
2653
+ # buscador NI sitemap en una muestra pequeña, la evidencia es PARCIAL —
2654
+ # la reseña baja a low y lo declara
2655
+ _has_way = any(p.has_search or p.has_sitemap for p in parsers)
2656
+ _has_index_way = any(getattr(p, 'has_index', False) for p in parsers)
2657
+ if len(parsers) >= 2 and not _has_way and not _has_index_way:
2658
+ entry = {'criterion': _crit(lang, '2.4.5'),
2659
+ 'signal': 'no_multiple_ways',
2660
+ 'issue': _t(lang, 'no_multiple_ways'),
2661
+ 'remediation': _t(lang, 'no_multiple_ways_rem')}
2662
+ entry['severity'] = 'medium' if len(parsers) >= 4 else 'low'
2663
+ entry['issue'] = entry['issue'] + (
2664
+ ' (partial evidence: search and sitemap not found in a small sample)'
2665
+ if lang == 'en' else
2666
+ ' (evidencia parcial: ni buscador ni sitemap en una muestra pequeña)')
2667
+ out.append(entry)
2503
2668
  return out
2504
2669
 
2505
2670
 
@@ -2544,17 +2709,24 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
2544
2709
  if next in seen:
2545
2710
  continue
2546
2711
  seen.add(next)
2712
+ _m = {}
2547
2713
  try:
2548
- html_pg = _fetch(next, timeout=timeout)
2714
+ html_pg = _fetch(next, timeout=timeout, _meta=_m)
2549
2715
  except Exception: # noqa: BLE001
2550
2716
  continue
2551
- pg, pg_err = _parse_page(html_pg, next)
2717
+ # enlaces y reporte contra la URL FINAL (4ª pasada: tras una
2718
+ # redirección, resolver contra la PEDIDA visitaba rutas equivocadas)
2719
+ next_final = ((_m.get('final_url') or next).split('#')[0]).rstrip('/')
2720
+ if next_final != next and next_final in seen:
2721
+ continue # la redirección aterrizó en una ya auditada
2722
+ seen.add(next_final)
2723
+ pg, pg_err = _parse_page(html_pg, next_final)
2552
2724
  if pg_err is not None:
2553
2725
  continue # página rota: no cuenta, el crawl sigue
2554
- reports.append(audit_html(html_pg, next, lang=lang))
2726
+ reports.append(audit_html(html_pg, next_final, lang=lang))
2555
2727
  parsers.append(pg)
2556
2728
  if len(reports) < max_pages and not from_sitemap:
2557
- for new in _internal_links(html_pg, next, url):
2729
+ for new in _internal_links(html_pg, next_final, url):
2558
2730
  if new not in seen:
2559
2731
  queue.append(new)
2560
2732
  site_findings = evaluate_site(parsers, lang=lang)
@@ -2729,7 +2901,11 @@ def main(argv):
2729
2901
  # --standard nunca se descarte en silencio en NINGUNA ruta del CLI
2730
2902
  res = _apply_standard(res, a.standard, a.target, a.lang)
2731
2903
  print(json.dumps(res, ensure_ascii=False, indent=1))
2732
- return 0
2904
+ # fallo de ejecución (error en el informe) ≠ hallazgo de accesibilidad:
2905
+ # la revisión externa cazó audit --url devolviendo 1 pero --file (y los
2906
+ # mains de a11ydom) devolviendo 0 CON error — un verde falso para cualquier
2907
+ # script que encauce por el código de salida
2908
+ return 1 if isinstance(res, dict) and res.get('error') else 0
2733
2909
 
2734
2910
 
2735
2911
  if __name__ == '__main__':