@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.
@@ -22,6 +22,7 @@ import os
22
22
  import re
23
23
  import sys
24
24
  import urllib.request
25
+ from urllib.parse import unquote
25
26
  from html.parser import HTMLParser
26
27
  from . import a11yi18n
27
28
 
@@ -63,6 +64,76 @@ def path_segment(tag, nth):
63
64
  pueden romper la identidad)."""
64
65
  return f'{tag}:nth-of-type({nth})'
65
66
 
67
+
68
+ class _ElementPaths:
69
+ """Store one segment and parent index per distinct route."""
70
+
71
+ def __init__(self, implicit_tbody=True):
72
+ self.stack = []
73
+ self._implicit_tbody = implicit_tbody
74
+ self._nodes = [None]
75
+ self._node_ids = {}
76
+
77
+ def _child(self, tag):
78
+ if self.stack:
79
+ _, parent, siblings = self.stack[-1]
80
+ nth = siblings[tag] = siblings.get(tag, 0) + 1
81
+ else:
82
+ parent, nth = 0, 1
83
+ key = (parent, path_segment(tag, nth))
84
+ index = self._node_ids.get(key)
85
+ if index is None:
86
+ index = self._node_ids[key] = len(self._nodes)
87
+ self._nodes.append(key)
88
+ return index
89
+
90
+ def start(self, tag):
91
+ # Browsers insert a tbody for a row directly inside a table.
92
+ if self._implicit_tbody and tag == 'tr' and self.stack and self.stack[-1][0] == 'table':
93
+ self.stack.append(('tbody', self._child('tbody'), {}))
94
+ index = self._child(tag)
95
+ if tag not in VOID_TAGS:
96
+ self.stack.append((tag, index, {}))
97
+ return index
98
+
99
+ def end(self, tag):
100
+ if tag in VOID_TAGS:
101
+ return
102
+ for index in range(len(self.stack) - 1, -1, -1):
103
+ if self.stack[index][0] == tag:
104
+ del self.stack[index:]
105
+ break
106
+
107
+ def format(self, index):
108
+ segments = []
109
+ while index:
110
+ index, segment = self._nodes[index]
111
+ segments.append(segment)
112
+ return '>'.join(reversed(segments))
113
+
114
+ def lookup(self, path):
115
+ index = 0
116
+ for segment in path.split('>'):
117
+ index = self._node_ids.get((index, segment))
118
+ if index is None:
119
+ break
120
+ return index
121
+
122
+
123
+ class _Table:
124
+ def __init__(self, attrs, counted):
125
+ self.attrs = attrs
126
+ self.counted = counted
127
+ border = (attrs.get('border') or '0').strip()
128
+ bordered = counted and border.isdecimal() and any(int(digit) for digit in border)
129
+ self.suspect_layout = not bordered and bool(
130
+ {'cellpadding', 'cellspacing', 'width', 'border'} & attrs.keys())
131
+ self.data = bordered or 'summary' in attrs
132
+ self.has_th = False
133
+ self.header_ids = set()
134
+ self.references = []
135
+
136
+
66
137
  # roles que convierten cualquier elemento en campo etiquetable (e086e5).
67
138
  # OJO: 'search' NO está — es un LANDMARK (WAI-ARIA 1.2), no un widget: un
68
139
  # <form role="search"> sin aria-label es un landmark sin etiqueta, no un
@@ -356,6 +427,38 @@ _OVERLAY_WIDGETS = (
356
427
  _SKIP_TEXT = re.compile(
357
428
  r'skip|jump to|saltar|ir al contenido|ir para o conte[uú]do|passer au contenu', re.I)
358
429
 
430
+ # 3.2.1: un select[autofocus] solo cambia el contexto si lleva un script que
431
+ # lo haga. Eventos que dispara quien aterrizó en el control sin elegirlo (el
432
+ # foco llega solo al cargar; después, la primera tecla o el cambio de opción) y
433
+ # llamadas que cambian el contexto: navegación, ventana nueva, envío, foco.
434
+ _FOCUS_EVENTS = ('onfocus', 'onchange', 'oninput', 'onkeydown', 'onkeyup', 'onkeypress')
435
+ _CTX_CHANGE = re.compile(
436
+ r'\blocation\s*=(?!=)|\blocation\.href\b|\blocation\.(?:replace|assign|reload)\s*\('
437
+ r'|\bwindow\.open\s*\(|\.submit\s*\(|\.focus\s*\(', re.I)
438
+
439
+ # contexto requerido por rol (ARIA 1.2; la misma tabla que la regla
440
+ # aria-required-parent del motor de referencia). El ancestro vale por rol
441
+ # explícito o por la etiqueta implícita de ese rol. `group` nunca es destino:
442
+ # vale como paso intermedio y entonces hace falta el contexto DEL grupo (un
443
+ # treeitem en un group solo está bien si el group vive en un tree o en otro
444
+ # treeitem del mismo tipo).
445
+ _ROLE_PARENTS = {
446
+ 'listitem': ('list',),
447
+ 'menuitem': ('group', 'menu', 'menubar'),
448
+ 'menuitemcheckbox': ('group', 'menu', 'menubar'),
449
+ 'menuitemradio': ('group', 'menu', 'menubar'),
450
+ 'option': ('group', 'listbox'),
451
+ 'tab': ('tablist',),
452
+ 'treeitem': ('group', 'tree'),
453
+ }
454
+ _IMPLICIT_PARENT = {'list': ('ul', 'ol'), 'menu': ('menu',)}
455
+ # roles para los que, dentro de un group, un ancestro del MISMO rol cierra el
456
+ # contexto (un treeitem carpeta agrupa sus hijos en un group)
457
+ _OWN_GROUP_ROLE = {'treeitem'}
458
+ # saltos de aria-owns que se siguen en cadena antes de cortar (un dueño que a
459
+ # su vez es owned por otro): corta también los ciclos A owns B owns A
460
+ _OWN_DEPTH = 8
461
+
359
462
  # encabezados cortos legítimos (acrónimos y términos técnicos): «FAQ», «API»…
360
463
  _SHORT_HEADINGS = {'FAQ', 'API', 'CSS', 'SVG', 'APP', 'MAP', 'EN', 'DE', 'ES', 'PT', 'FR',
361
464
  'IT', 'UI', 'UX', 'ID', 'TV', 'HR', 'PR', 'AI', 'PC', 'OK', '3D',
@@ -385,8 +488,8 @@ class _Auditor(HTMLParser):
385
488
  # CSS (tag:nth-of-type(n) desde la raíz). id(attrs) es estable dentro
386
489
  # del parseo (cada attrs es un dict nuevo) → los recolectores pueden
387
490
  # resolver la ruta de LO QUE COGIERON sin cambiar sus tuplas.
388
- self._path_stack = [] # [(tag, path, {tag: nth})] del elemento abierto
389
- self._elem_paths = {} # id(attrs) → ruta del elemento
491
+ self._paths = _ElementPaths()
492
+ self._elem_paths = {} # id(attrs) → índice de ruta
390
493
  super().__init__(convert_charrefs=True)
391
494
  self.imgs_no_alt = []
392
495
  self.alt_quality_bad = [] # (razón, alt, attrs) — emitida en findings
@@ -495,9 +598,7 @@ class _Auditor(HTMLParser):
495
598
  self.media_autoplay_elems = []
496
599
  self.tables = 0
497
600
  self.tables_with_th = 0
498
- self._in_table = False
499
- self._th_in_table = False
500
- self._table_stack = [] # (th_había, attrs) por <table> abierta
601
+ self._table_stack = []
501
602
  self.tables_no_th_elems = []
502
603
  self.blank_no_warning = 0
503
604
  self.blank_total = 0
@@ -521,6 +622,30 @@ class _Auditor(HTMLParser):
521
622
  self.autocomplete_mismatch = []
522
623
  self.heading_role_removed = [] # h1-h6 con rol que sustituye al de heading
523
624
  self.text_spacing_important = [] # 1.4.12: spacing !important inline (ACT 24afc2/78fd32/9e45ec)
625
+ self.a_no_href = [] # 2.1.1: <a> sin href usado como control
626
+ self.nested_main = [] # 1.3.1: main anidado en seccionante
627
+ self.fake_lists = [] # 1.3.1: lista falsa con viñetas y <br>
628
+ self.alert_polite = [] # 4.1.2: role=alert gritando en aria-live=polite
629
+ self.headers_bad = [] # 1.3.1: headers= apuntando fuera de tabla o a no-th (ACT d0f69e/a25f45)
630
+ self.lang_xml_mismatch = [] # 3.1.2: lang y xml:lang discrepando (ACT 5b7ae0)
631
+ self.nested_interactive = [] # 4.1.2: interactivo DENTRO de interactivo
632
+ self.select_auto_focus = [] # 3.2.1: select[autofocus] + script de cambio de contexto
633
+ self.select_auto_focus_elems = []
634
+ self.skip_broken = [] # 2.4.1: skip/fragmento a id inexistente (F89)
635
+ self.skip_broken_elems = []
636
+ self.role_orphans = [] # 1.3.1: rol sin su padre requerido (ACT ff89c9)
637
+ self.role_orphan_elems = []
638
+ self._skip_hrefs = [] # (fragmento, attrs) de enlaces de salto (vocabulario ya filtrado)
639
+ self._name_anchors = set() # <a name="…">: destino de fragmento legítimo
640
+ self._role_ctx_pending = [] # (attrs, rol, ancestros DOM) a resolver post-parse
641
+ self._owned_by = {} # id → attrs del elemento que lo declara en aria-owns
642
+ self._owner_ancestors = {} # id(attrs) → ancestros DOM del dueño (aria-owns)
643
+ self.invoker_bad = [] # 4.1.2: commandfor sin destino o tipo erróneo
644
+ self.aria_level_gt6 = [] # 1.3.1: aria-level>6 (los lectores lo degradan)
645
+ self._invokers = [] # (idref, command) pendientes de validar
646
+ self._id_tag = {} # id → (tag, popover?) para validar invokers
647
+ self._p_bullets = None # contador de viñetas del <p> abierto
648
+ self._p_brs = 0
524
649
  self.links = {} # nombre normalizado → set de hrefs
525
650
  self.links_elems = {} # entry_key → primeros elems (marcas 2.4.4)
526
651
  self.generics = 0
@@ -609,13 +734,24 @@ class _Auditor(HTMLParser):
609
734
  _lb_ids = (a.get('aria-labelledby') or '').split()
610
735
  if _vis and (_al or _lb_ids) and len(self.label_in_name_raw) < 30:
611
736
  self.label_in_name_raw.append((_vis[:80], _al[:120], _lb_ids[:6], a))
737
+ # enlaces de salto: el vocabulario se decide AQUÍ, con el texto ya
738
+ # completo: el límite solo corta entre saltos, nunca delante de ellos
739
+ # (antes se recogían los 12 primeros enlaces internos y un salto que
740
+ # venía detrás de 12 notas al pie quedaba fuera sin ser examinado)
741
+ if tag == 'a' and text:
742
+ _skip_href = (a.get('href') or '').strip()
743
+ if _skip_href.startswith('#') and len(_skip_href) > 1 \
744
+ and _SKIP_TEXT.search(text) and len(self._skip_hrefs) < 12:
745
+ self._skip_hrefs.append((_skip_href[1:], a))
612
746
  if tag == 'a' and not c.get('hidden'):
613
747
  if (a.get('target') or '').lower() == '_blank':
614
748
  self.blank_total += 1
615
749
  _img_alts = ' '.join((ia.get('alt') or '')
616
750
  for ia in c.get('img_attrs', []))
751
+ # title NO cuenta como aviso: quien navega solo con teclado
752
+ # jamás lo ve (hover-only). Salvan: texto visible, aria-label
753
+ # (el lector lo anuncia) y el alt de una imagen interna
617
754
  if not _BLANK_HINT.search(text) and not _BLANK_HINT.search(a.get('aria-label') or '') \
618
- and not _BLANK_HINT.search(a.get('title') or '') \
619
755
  and not _BLANK_HINT.search(_img_alts):
620
756
  self.blank_no_warning += 1
621
757
  self.blank_no_warning_elems.append(a)
@@ -680,29 +816,7 @@ class _Auditor(HTMLParser):
680
816
  or (_ti_mark.isdecimal() and int(_ti_mark) >= 0):
681
817
  for _sp in self._stray_pend:
682
818
  _sp[3] = True
683
- # ruta determinista del elemento (kernel de anotación): nth-of-type
684
- # SIEMPRE (los id duplicados no pueden romper la ruta) y los void no
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']), {}))
696
- if self._path_stack:
697
- _parent = self._path_stack[-1]
698
- _parent[2][tag] = _parent[2].get(tag, 0) + 1
699
- _seg = path_segment(tag, _parent[2][tag])
700
- _path = _parent[1] + '>' + _seg
701
- else:
702
- _path = path_segment(tag, 1)
703
- self._elem_paths[id(a)] = _path
704
- if tag not in VOID_TAGS:
705
- self._path_stack.append((tag, _path, {}))
819
+ self._elem_paths[id(a)] = self._paths.start(tag)
706
820
  # rasgos estructurales para el scope de aplicabilidad (a11yscope):
707
821
  # evidencia POSITIVA — cero <video> habilita proponer 1.2.x como no
708
822
  # aplicable; la ausencia de señal jamás cuenta como ausencia de
@@ -715,6 +829,7 @@ class _Auditor(HTMLParser):
715
829
  if a.get('id') and not self._in_template:
716
830
  # ids dentro de <template> no existen: ni dup_ids ni refs rotas
717
831
  self.ids[a['id']] = self.ids.get(a['id'], 0) + 1
832
+ self._id_tag[a['id']] = (tag, 'popover' in a)
718
833
  if self.root_tag is None:
719
834
  self.root_tag = tag
720
835
  # visibilidad heredada para accname y enfocabilidad: aria-hidden se
@@ -909,7 +1024,7 @@ class _Auditor(HTMLParser):
909
1024
  _tok_ac = (a.get('autocomplete') or '').strip().lower()
910
1025
  _covered = bool(_tok_ac) and _tok_ac not in ('off', 'on')
911
1026
  if (not _covered) and kind != 'search' and not _recipient and (
912
- kind in ('email', 'tel')
1027
+ kind in ('email', 'tel', 'password')
913
1028
  or _PERSONAL_DATA.search((a.get('name') or '') + ' ' + (a.get('id') or ''))):
914
1029
  self.missing_autocomplete.append(f'input type={kind} name={a.get("name") or "?"}'[:44])
915
1030
  self.autocomplete_elems.append(a)
@@ -1002,37 +1117,31 @@ class _Auditor(HTMLParser):
1002
1117
  self._list_depth += 1
1003
1118
  elif tag == 'li':
1004
1119
  self._li_depth += 1
1005
- elif tag == 'table':
1006
- # role=presentation/none la declara de MAQUETACIÓN: no se exige th
1007
- # (el mail HTML y las grids legacy viven aquí) — y el contenido de
1008
- # <template> es inerte
1009
- if (a.get('role') or '').strip().lower() in ('presentation', 'none') \
1010
- or self._in_template:
1011
- pass
1012
- else:
1013
- self.tables += 1
1014
- self._in_table = True
1015
- # sospecha de maquetación (attrs presentacionales de la era
1016
- # <table width=… cellpadding=0 border=0>): sin th NI marcadores
1017
- # de datos no se exige th (FP clásico años-90). OJO border:
1018
- # el spec dice que border≠0 declara tabla de DATOS — solo el
1019
- # «0» (o sin valor, que es 0) es maquetación
1020
- _bv = (a.get('border') or '0').strip()
1021
- _border_data = _bv.isdecimal() and int(_bv) > 0
1022
- _suspect = (bool({'cellpadding', 'cellspacing', 'width'} & set(a))
1023
- or ('border' in a and not _border_data)) and not _border_data
1024
- _data = 'summary' in a or _border_data
1025
- # pila por tabla anidada, CON IDENTIDAD: una </table> de una
1026
- # tabla presentation/none (no apilada) jamás popea la entrada
1027
- # de la tabla externa que la envuelve
1028
- self._table_stack.append([self._th_in_table, a, _suspect, _data])
1029
- self._th_in_table = False
1030
- elif tag == 'th':
1031
- self._th_in_table = True
1032
- elif tag == 'caption' and self._table_stack:
1033
- self._table_stack[-1][3] = True # marcador de tabla de DATOS
1034
- elif tag == 'td' and self._table_stack and ('scope' in a or 'headers' in a):
1035
- self._table_stack[-1][3] = True # asociaciones explícitas = datos
1120
+ if tag == 'br' and self._p_bullets is not None and not self._in_template:
1121
+ self._p_brs += 1
1122
+ if tag == 'p' and not self._in_template:
1123
+ self._p_bullets = 0
1124
+ self._p_brs = 0
1125
+ if tag == 'table':
1126
+ counted = not self._in_template and (
1127
+ (a.get('role') or '').strip().lower() not in ('presentation', 'none'))
1128
+ self._table_stack.append(_Table(a, counted))
1129
+ self.tables += int(counted)
1130
+ elif tag in ('th', 'td', 'caption') and self._table_stack and not self._in_template:
1131
+ table = self._table_stack[-1]
1132
+ if table.counted:
1133
+ if tag == 'caption':
1134
+ table.data = True
1135
+ else:
1136
+ table.has_th |= tag == 'th'
1137
+ if tag == 'td' and ('scope' in a or 'headers' in a):
1138
+ table.data = True
1139
+ cell_id = a.get('id')
1140
+ role = (a.get('role') or '').strip().lower()
1141
+ if cell_id and (tag == 'th' or role in ('columnheader', 'rowheader')):
1142
+ table.header_ids.add(cell_id)
1143
+ if (a.get('headers') or '').strip(' \t\n\f\r'):
1144
+ table.references.append(a)
1036
1145
  elif tag == 'main' or (a.get('role') or '').lower() == 'main':
1037
1146
  self.hay_main = True
1038
1147
  if a.get('id'):
@@ -1284,6 +1393,21 @@ class _Auditor(HTMLParser):
1284
1393
  # <area> es void: sin pila de control — se registra directo (el
1285
1394
  # nombre le llega del alt)
1286
1395
  self.controls_raw.append(('area', a, '', [], _hidden))
1396
+ if tag == 'main' and not self._in_template:
1397
+ # main es top-level por definición: anidado
1398
+ # en section/aside/nav/article/main/header/footer no es ni landmark
1399
+ # válido ni estructura honesta (1.3.1)
1400
+ # [-1] es el PROPIO main (ya apilado cuando corre este chequeo):
1401
+ # el ancestro a mirar empieza uno antes
1402
+ for index in range(len(self._paths.stack) - 2, -1, -1):
1403
+ _utag = self._paths.stack[index][0]
1404
+ if _utag in ('section', 'aside', 'nav', 'article', 'main',
1405
+ 'header', 'footer'):
1406
+ if len(self.nested_main) < 8:
1407
+ self.nested_main.append(f'<{_utag}> … <main>')
1408
+ break
1409
+ if _utag == 'body':
1410
+ break
1287
1411
  if tag in ('h1', 'h2', 'h3', 'h4', 'h5', 'h6'):
1288
1412
  # role=none/presentation APAGA la semántica del encabezado; un
1289
1413
  # aria-level válido la SOBRESCRIBE (accname: h3[aria-level=4] ES 4)
@@ -1305,9 +1429,11 @@ class _Auditor(HTMLParser):
1305
1429
  _alv = re.match(r'\d+', str(a.get('aria-level') or ''))
1306
1430
  if _alv:
1307
1431
  self._heading_level = int(_alv.group())
1432
+ if int(_alv.group()) > 6 and len(self.aria_level_gt6) < 6:
1433
+ self.aria_level_gt6.append(
1434
+ f'{tag} aria-level="{_alv.group()}"')
1308
1435
  self._heading_text = []
1309
1436
  self._heading_attrs = a
1310
- self._heading_route = self._elem_paths.get(id(a))
1311
1437
  self._heading_hidden = _hidden
1312
1438
  self._heading_tag = tag
1313
1439
  elif (a.get('role') or '').lower() == 'heading' and not self._in_template:
@@ -1316,29 +1442,109 @@ class _Auditor(HTMLParser):
1316
1442
  # basura JAMÁS tira el parse (int guardado)
1317
1443
  _alv = re.match(r'\d+', str(a.get('aria-level') or ''))
1318
1444
  self._heading_level = int(_alv.group()) if _alv else 2
1445
+ if _alv and int(_alv.group()) > 6 and len(self.aria_level_gt6) < 6:
1446
+ self.aria_level_gt6.append(
1447
+ f'[role=heading] aria-level="{_alv.group()}"')
1319
1448
  self._heading_text = []
1320
1449
  self._heading_attrs = a
1321
- self._heading_route = self._elem_paths.get(id(a))
1322
1450
  self._heading_hidden = _hidden
1323
1451
  self._heading_tag = tag
1452
+ # select[autofocus] (3.2.1): el control recibe el foco al cargar, pero
1453
+ # el atributo SOLO no cambia nada (medido en Chromium 147 sin interfaz:
1454
+ # foco en el control, opción inicial intacta). Es hallazgo cuando
1455
+ # además lleva un script de cambio de contexto en un evento que dispara
1456
+ # quien aterrizó allí sin elegirlo (el foco, un cambio de opción, una tecla)
1457
+ if tag == 'select' and 'autofocus' in a and not self._in_template \
1458
+ and not _hidden:
1459
+ for _ev in _FOCUS_EVENTS:
1460
+ _code = a.get(_ev) or ''
1461
+ if _code and _CTX_CHANGE.search(_code) \
1462
+ and len(self.select_auto_focus) < 5:
1463
+ self.select_auto_focus.append(f'select[autofocus][{_ev}="{_code[:40]}"]')
1464
+ self.select_auto_focus_elems.append(a)
1465
+ break
1466
+ # roles con contexto requerido (ARIA 1.2 §5.2.7: el elemento debe
1467
+ # estar contenido en, o ser owned por, un elemento del rol de contexto;
1468
+ # ACT ff89c9). SOLO roles EXPLÍCITOS (el li implícito fuera de lista es
1469
+ # otra familia, muy FP). Aquí solo se REGISTRA: el veredicto es
1470
+ # post-parse porque el dueño por aria-owns puede venir después.
1471
+ _rv = (a.get('role') or '').strip().lower()
1472
+ if _rv in _ROLE_PARENTS and not self._in_template and not _hidden \
1473
+ and len(self._role_ctx_pending) < 400:
1474
+ self._role_ctx_pending.append(
1475
+ (a, _rv, [(_t, _fa) for _t, _fa, _ in self._el_stack if _fa is not a]))
1476
+ if a.get('aria-owns') and len(self._owner_ancestors) < 400:
1477
+ self._owner_ancestors[id(a)] = \
1478
+ [(tag, a)] + [(_t, _fa) for _t, _fa, _ in self._el_stack if _fa is not a]
1479
+ for _owned_id in str(a['aria-owns']).split():
1480
+ self._owned_by.setdefault(_owned_id, a)
1481
+ # destino clásico de fragmento: <a name="…"> también resuelve #…
1482
+ if tag == 'a' and a.get('name'):
1483
+ self._name_anchors.add(a['name'])
1484
+ # interactivo dentro de interactivo (4.1.2): el modelo de contenido lo
1485
+ # prohíbe; el AT anuncia mal el interno y el externo pierde su límite.
1486
+ # Ancestros por el ÁRBOL REAL (_el_stack), no por _ctrl (malformados).
1487
+ # Exento a>a puro: todos los navegadores lo reparan a hermanos.
1488
+ _INTER_HOST = ('a', 'button', 'summary', 'select', 'textarea')
1489
+ if tag in _INTER_HOST or (tag == 'input' and (a.get('type') or 'text')
1490
+ not in ('hidden', 'submit', 'button', 'reset', 'image')) \
1491
+ or (a.get('role') or '').strip().lower() in ('button', 'link'):
1492
+ if len(self.nested_interactive) < 6:
1493
+ for _anc_tag, _anc_a, _ in reversed(self._el_stack):
1494
+ if _anc_a is a:
1495
+ continue # el propio elemento ya viaja en la pila
1496
+ _anc_inter = _anc_tag in _INTER_HOST
1497
+ if _anc_tag == 'a':
1498
+ if not (_anc_a.get('href') or '').strip():
1499
+ _anc_inter = False # ancla sin href: no interactiva
1500
+ elif tag == 'a' and not (_anc_a.get('role') or a.get('role')):
1501
+ _anc_inter = False # a>a puro: reparado a hermanos
1502
+ if _anc_inter:
1503
+ self.nested_interactive.append(f'<{tag}> dentro de <{_anc_tag}>')
1504
+ break
1505
+ # invoker commands (4.1.2): commandfor ha de resolver Y el comando casar
1506
+ # con el tipo de destino (show-modal/close → dialog; show/hide/toggle →
1507
+ # popover). Se valida POST-parse (el destino puede venir después)
1508
+ if tag == 'button' and a.get('commandfor'):
1509
+ if len(self._invokers) < 8:
1510
+ self._invokers.append(((a.get('commandfor') or '').strip(),
1511
+ (a.get('command') or '').strip().lower()))
1512
+ # ── patrones de estructura y de estado ──
1513
+ if not self._in_template:
1514
+ # <a> SIN href con vida de control (2.1.1): tabindex>=0,
1515
+ # onclick o rol interactivo. Sin href NO es enlace: el AT no lo
1516
+ # anuncia como tal aunque sea enfocable y le echen un click.
1517
+ # Exento: tabindex=-1 (ancla objetivo legítima) y <a> puro con id
1518
+ # (ancla con nombre de toda la vida).
1519
+ if tag == 'a' and not (a.get('href') or '').strip():
1520
+ _anchor_role = (a.get('role') or '').strip().lower()
1521
+ _viva = ((a.get('onclick') or '')
1522
+ or _anchor_role in ('button', 'link', 'tab', 'menuitem')
1523
+ or (a.get('tabindex') or '').strip() not in ('', '-1'))
1524
+ if _viva and len(self.a_no_href) < 12:
1525
+ _tx = ' '.join(self._ctrl[-1]['text']).strip()[:20] if self._ctrl else ''
1526
+ self.a_no_href.append('<a>' + (f' "{_tx}"' if _tx else ''))
1527
+ # role=alert ES assertive en sí mismo (ARIA): un aria-live
1528
+ # polite encima lo contradice (4.1.2, estado que no es el que dice)
1529
+ _role_low = (a.get('role') or '').strip().lower()
1530
+ _live = (a.get('aria-live') or '').strip().lower()
1531
+ if _role_low == 'alert' and _live == 'polite' and len(self.alert_polite) < 8:
1532
+ self.alert_polite.append('role="alert" + aria-live="polite"')
1533
+ if _lang_v := (a.get('lang') or '').strip():
1534
+ _xml = (a.get('{http://www.w3.org/XML/1998/namespace}lang')
1535
+ or a.get('xml:lang') or '').strip()
1536
+ if _xml and _lang_v.lower() != _xml.lower() and len(self.lang_xml_mismatch) < 8:
1537
+ self.lang_xml_mismatch.append(f'{tag} lang="{_lang_v}" xml:lang="{_xml}"')
1538
+
1324
1539
  ti = a.get('tabindex')
1325
1540
  if ti and ti.isdecimal() and int(ti) > 0 and not self._in_template:
1326
1541
  self.positive_tabindices.append((tag, int(ti)))
1327
1542
  self.positive_tabindex_elems.append(a)
1328
1543
 
1329
1544
  def handle_endtag(self, tag):
1330
- # pila de rutas del kernel: pop normal si casa; si hay anidamiento
1331
- # malformado, se descarta hasta el que casa; suelto, se ignora
1332
- if self._path_stack:
1333
- if self._path_stack[-1][0] == tag:
1334
- self._path_stack.pop()
1335
- else:
1336
- for _i in range(len(self._path_stack) - 1, -1, -1):
1337
- if self._path_stack[_i][0] == tag:
1338
- del self._path_stack[_i:]
1339
- break
1545
+ self._paths.end(tag)
1340
1546
  if tag not in _VOID:
1341
- # LAS PILAS SE SINCRONIZAN como _path_stack: buscar el frame que
1547
+ # LAS PILAS SE SINCRONIZAN con las rutas: buscar el frame que
1342
1548
  # casa y descartar hasta él (un </span> suelto ya no arrastra el
1343
1549
  # elemento abierto de verdad — el texto no se malatribuye)
1344
1550
  _idx = None
@@ -1354,12 +1560,12 @@ class _Auditor(HTMLParser):
1354
1560
  self._close_control(tag)
1355
1561
  return
1356
1562
  _nframes = len(self._el_stack) - _idx
1357
- _closed_attrs = None # attrs del frame que CASA (el último popeado)
1358
1563
  for _ in range(_nframes):
1359
1564
  if not self._el_stack:
1360
1565
  break
1361
1566
  _etag, _eattrs, _ebuf = self._el_stack.pop()
1362
- _closed_attrs = _eattrs
1567
+ if _etag == 'table':
1568
+ self._finish_table(self._table_stack.pop())
1363
1569
  if _etag == 'canvas':
1364
1570
  self.canvases.append((_eattrs, ' '.join(_ebuf).strip(),
1365
1571
  self.canvas_hidden.pop(id(_eattrs), False)))
@@ -1462,6 +1668,16 @@ class _Auditor(HTMLParser):
1462
1668
  self._form_auth = False
1463
1669
  elif tag == 'nav':
1464
1670
  self._in_nav = max(0, self._in_nav - 1)
1671
+ elif tag == 'p':
1672
+ # lista falsa = ≥2 viñetas tipográficas + separadores <br>
1673
+ # en un párrafo fuera de listas reales
1674
+ if self._p_bullets is not None and self._p_bullets >= 2 \
1675
+ and self._p_brs >= 1 and self._list_depth == 0 \
1676
+ and len(self.fake_lists) < 8:
1677
+ self.fake_lists.append(f'<p> • × {self._p_bullets}, '
1678
+ f'<br> × {self._p_brs}')
1679
+ self._p_bullets = None
1680
+ self._p_brs = 0
1465
1681
  elif tag == 'li':
1466
1682
  self._li_depth = max(0, self._li_depth - 1)
1467
1683
  elif tag in ('ul', 'ol'):
@@ -1476,34 +1692,89 @@ class _Auditor(HTMLParser):
1476
1692
  self.videos_no_caps_elems.append(_vattrs)
1477
1693
  if not _vdesc:
1478
1694
  self.videos_no_desc_elems.append(_vattrs)
1479
- elif tag == 'table':
1480
- if self._table_stack and _closed_attrs is not None:
1481
- _th_saved, _tattrs, _suspect, _data = self._table_stack[-1]
1482
- # IDENTIDAD: solo decide la entrada cuya tabla se CIERRA (el
1483
- # </table> de una presentation/template NUNCA apilada resbala
1484
- # sin tocar la pila — antes popeaba la entrada de la externa)
1485
- if _closed_attrs is _tattrs:
1486
- self._table_stack.pop()
1487
- if self._th_in_table:
1488
- self.tables_with_th += 1
1489
- elif _data or not _suspect:
1490
- self.tables_no_th_elems.append(_tattrs)
1491
- else:
1492
- # maquetación por heurística: fuera del cómputo
1493
- self.tables -= 1
1494
- self._th_in_table = _th_saved
1495
- self._in_table = bool(self._table_stack)
1496
- elif tag == 'th':
1497
- pass
1498
1695
  elif self._heading_level and tag == getattr(self, '_heading_tag', None):
1499
1696
  # el veredicto de nombre vacío es POST-parse (labelledby resuelto,
1500
1697
  # aria-label tras strip, nombres de imgs internas)
1501
- self.headings_raw.append((self._heading_level, dict(self._heading_attrs or {}),
1698
+ self.headings_raw.append((self._heading_level, self._heading_attrs,
1502
1699
  ' '.join(self._heading_text).strip(),
1503
- getattr(self, '_heading_hidden', False),
1504
- getattr(self, '_heading_route', None)))
1700
+ getattr(self, '_heading_hidden', False)))
1505
1701
  self._heading_level = None
1506
1702
 
1703
+ def _finish_table(self, table):
1704
+ if not table.counted:
1705
+ return
1706
+ if table.has_th:
1707
+ self.tables_with_th += 1
1708
+ elif table.data or not table.suspect_layout:
1709
+ self.tables_no_th_elems.append(table.attrs)
1710
+ else:
1711
+ self.tables -= 1
1712
+ for cell in table.references:
1713
+ for token in re.split(r'[ \t\n\f\r]+', cell['headers'].strip(' \t\n\f\r')):
1714
+ if token not in table.header_ids or token == cell.get('id'):
1715
+ self.headers_bad.append((token, cell))
1716
+ break
1717
+
1718
+ def close(self):
1719
+ super().close()
1720
+ while self._table_stack:
1721
+ self._finish_table(self._table_stack.pop())
1722
+
1723
+ def _finding_paths(self, elements):
1724
+ paths = []
1725
+ for attrs in elements:
1726
+ path = self.element_path(attrs)
1727
+ if path:
1728
+ paths.append(path)
1729
+ if len(paths) == 5:
1730
+ break
1731
+ return paths
1732
+
1733
+ def element_path(self, attrs):
1734
+ index = self._elem_paths.get(id(attrs))
1735
+ return self._paths.format(index) if index is not None else None
1736
+
1737
+ def _context_satisfied(self, role, chain, need=None, _depth=0):
1738
+ """¿La cadena de ancestros (del más cercano al más lejano) da a `role`
1739
+ su contexto requerido? El ancestro vale por rol explícito o por etiqueta
1740
+ implícita (ul/ol = list). Un `group` aceptado como paso obliga a
1741
+ seguir: el grupo necesita su propio contexto. Y cualquier elemento de
1742
+ la cadena puede estar owned por aria-owns: su dueño hace entonces de
1743
+ ancestro (ARIA 1.2: «contained inside (or owned by)»), también en
1744
+ cadena (un listbox que posee un group que posee la option)."""
1745
+ if need is None:
1746
+ need = _ROLE_PARENTS[role]
1747
+ for anc_tag, anc_a in chain:
1748
+ anc_role = (anc_a.get('role') or '').strip().lower()
1749
+ if anc_role in ('presentation', 'none'):
1750
+ continue # transparente en el árbol de accesibilidad
1751
+
1752
+ def _is(required):
1753
+ return anc_role == required or (
1754
+ not anc_role and anc_tag in _IMPLICIT_PARENT.get(required, ()))
1755
+ if 'group' in need and _is('group'):
1756
+ need = tuple(r for r in need if r != 'group') + (
1757
+ (role,) if role in _OWN_GROUP_ROLE else ())
1758
+ elif any(_is(r) for r in need):
1759
+ return True
1760
+ # este elemento está owned: se reintenta con su dueño de ancestro
1761
+ # (la cadena del dueño empieza por él) y lo que falte hasta aquí
1762
+ if _depth < _OWN_DEPTH:
1763
+ owner = self._owned_by.get(anc_a.get('id') or '')
1764
+ if owner is not None and self._context_satisfied(
1765
+ role, self._owner_ancestors[id(owner)], need, _depth + 1):
1766
+ return True
1767
+ return False
1768
+
1769
+ def _role_context_satisfied(self, attrs, role, chain):
1770
+ """Contexto por DOM o, si el DOM no basta, por aria-owns: el elemento
1771
+ está declarado en el aria-owns de otro, y su dueño hace de ancestro."""
1772
+ owner = self._owned_by.get(attrs.get('id') or '')
1773
+ if owner is not None and \
1774
+ self._context_satisfied(role, self._owner_ancestors[id(owner)]):
1775
+ return True
1776
+ return self._context_satisfied(role, chain)
1777
+
1507
1778
  _RE_CHAR_KEY = re.compile(r'key(?:Code)?\s*===?\s*["\']([a-zA-Z0-9])["\']', re.S)
1508
1779
 
1509
1780
  def handle_script_wait(self, data):
@@ -1638,6 +1909,11 @@ class _Auditor(HTMLParser):
1638
1909
  m = _SENSORIAL.search(re.sub(r'«[^»]*»|“[^”]*”|"[^"]*"', ' ', data))
1639
1910
  if m and len(self.sensory) < 6:
1640
1911
  self.sensory.append(m.group(0).strip()[:60])
1912
+ # viñetas tipográficas en prosa = lista falsa (umbral ≥2;
1913
+ # un solo guion de cita o de lista de definición NO es lista)
1914
+ if self._p_bullets is not None:
1915
+ self._p_bullets += len(re.findall(
1916
+ r'(?:^|\s)[•‣▪●◦∙]\s*\S', data))
1641
1917
 
1642
1918
 
1643
1919
 
@@ -1897,7 +2173,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
1897
2173
  or ' '.join(x for x in _img_names if x).strip()
1898
2174
  or (a.get('alt') or '').strip()):
1899
2175
  p.controls_by_kind.setdefault(kind, []).append(a)
1900
- for level, a, text, hidden, _hroute in p.headings_raw:
2176
+ for level, a, text, hidden in p.headings_raw:
1901
2177
  if hidden:
1902
2178
  continue
1903
2179
  lb, al, _ti = _name_sources(a)
@@ -1980,52 +2256,43 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
1980
2256
  findings[-1]['examples'] = examples[:5]
1981
2257
 
1982
2258
  if p.alt_quality_bad:
1983
- _p_q = [p._elem_paths[id(_a)] for _r, _alt, _a in p.alt_quality_bad
1984
- if id(_a) in p._elem_paths][:5]
2259
+ _p_q = p._finding_paths(a for _, _, a in p.alt_quality_bad)
1985
2260
  add_ej('medium', '1.1.1', 'alt_quality',
1986
2261
  [_alt[:40] for _r, _alt, _a in p.alt_quality_bad],
1987
2262
  n=len(p.alt_quality_bad), paths=_p_q)
1988
2263
  if p.imgs_no_alt:
1989
- _p_img = [p._elem_paths[id(_a)] for _a in p.imgs_no_alt_elems
1990
- if id(_a) in p._elem_paths][:5]
2264
+ _p_img = p._finding_paths(p.imgs_no_alt_elems)
1991
2265
  add_ej('high', '1.1.1', 'img_no_alt', p.imgs_no_alt,
1992
2266
  n=len(p.imgs_no_alt), paths=_p_img)
1993
2267
  if p.input_img_no_alt:
1994
2268
  add('high', '1.1.1', 'input_img_alt', n=p.input_img_no_alt)
1995
2269
  if p.canvas_no_layer:
1996
- _p_canvas = [p._elem_paths[id(_a)] for _a in p.canvas_no_layer_elems
1997
- if id(_a) in p._elem_paths][:5]
2270
+ _p_canvas = p._finding_paths(p.canvas_no_layer_elems)
1998
2271
  add_ej('medium', '1.1.1', 'canvas_no_accessible_layer', p.canvas_no_layer,
1999
2272
  n=len(p.canvas_no_layer), paths=_p_canvas)
2000
2273
  for tag, controls in p.controls_by_kind.items():
2001
2274
  add('high', '4.1.2', 'ctrl_name', n=len(controls), tag=tag,
2002
- paths=[p._elem_paths[id(_a)] for _a in controls
2003
- if id(_a) in p._elem_paths][:5])
2275
+ paths=p._finding_paths(controls))
2004
2276
  if p.aria_hidden_focusable:
2005
2277
  add('high', '4.1.2', 'aria_hidden_focusable',
2006
2278
  n=len(p.aria_hidden_focusable), tag=p.aria_hidden_focusable[0],
2007
- paths=[p._elem_paths[id(_a)] for _a in p.aria_hidden_focusable_elems
2008
- if id(_a) in p._elem_paths][:5])
2279
+ paths=p._finding_paths(p.aria_hidden_focusable_elems))
2009
2280
  if p.fields_no_label:
2010
2281
  add_ej('high', '3.3.2', 'field_label',
2011
2282
  [f'{t} name={n or "(no name)"}' for t, n, _i in p.fields_no_label],
2012
2283
  n=len(p.fields_no_label),
2013
- paths=[p._elem_paths[id(_a)] for _a in p.fields_no_label_elems
2014
- if id(_a) in p._elem_paths][:5])
2284
+ paths=p._finding_paths(p.fields_no_label_elems))
2015
2285
  if p.stray_clicks:
2016
2286
  add('high', '2.1.1', 'click_nonfocusable',
2017
2287
  n=len(p.stray_clicks), tag=p.stray_clicks[0],
2018
- paths=[p._elem_paths[id(_a)] for _a in p.stray_click_elems
2019
- if id(_a) in p._elem_paths][:5])
2288
+ paths=p._finding_paths(p.stray_click_elems))
2020
2289
  if p.role_no_tabindex:
2021
2290
  add_ej('low', '2.1.1', 'role_no_tabindex', p.role_no_tabindex,
2022
2291
  n=len(p.role_no_tabindex), example=', '.join(p.role_no_tabindex[:3]),
2023
- paths=[p._elem_paths[id(_a)] for _a in p.role_no_tabindex_elems
2024
- if id(_a) in p._elem_paths][:5])
2292
+ paths=p._finding_paths(p.role_no_tabindex_elems))
2025
2293
  if p.orphan_labels:
2026
2294
  add('low', '3.3.2', 'label_orphan', n=p.orphan_labels,
2027
- paths=[p._elem_paths[id(_a)] for _a in p.orphan_label_elems
2028
- if id(_a) in p._elem_paths][:5])
2295
+ paths=p._finding_paths(p.orphan_label_elems))
2029
2296
  if p._bad_list:
2030
2297
  add('medium', '1.3.1', 'list_structure', n=p._bad_list)
2031
2298
  if p.root_tag in ('svg', 'math'):
@@ -2051,12 +2318,10 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2051
2318
  if p.iframes_no_title:
2052
2319
  add_ej('medium', '4.1.2', 'iframe_title', p.iframes_no_title,
2053
2320
  n=len(p.iframes_no_title),
2054
- paths=[p._elem_paths[id(_a)] for _a in p.iframes_no_title_elems
2055
- if id(_a) in p._elem_paths][:5])
2321
+ paths=p._finding_paths(p.iframes_no_title_elems))
2056
2322
  if p.videos and p.videos_no_caps_elems:
2057
2323
  add('medium', '1.2.2', 'video_captions', n=len(p.videos_no_caps_elems),
2058
- paths=[p._elem_paths[id(_a)] for _a in p.videos_no_caps_elems
2059
- if id(_a) in p._elem_paths][:5])
2324
+ paths=p._finding_paths(p.videos_no_caps_elems))
2060
2325
  if p.viewport:
2061
2326
  # valores inválidos también blocksn (ACT b4f0c3): user-scalable ha de
2062
2327
  # ser yes/true o numérico ≥ 1; maximum-scale numérico — si no parsea,
@@ -2070,8 +2335,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2070
2335
  allows = v in ('yes', 'true')
2071
2336
  if not allows:
2072
2337
  add('high', '1.4.4', 'zoom_no',
2073
- paths=([p._elem_paths[id(p._viewport_elem)]]
2074
- if p._viewport_elem and id(p._viewport_elem) in p._elem_paths else None))
2338
+ paths=p._finding_paths([p._viewport_elem]))
2075
2339
  m_ms = re.search(r'maximum-scale\s*=\s*([\w.-]+)', p.viewport, re.I)
2076
2340
  if m_ms:
2077
2341
  _v_ms = m_ms.group(1)
@@ -2085,8 +2349,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2085
2349
  # mismo daño que user-scalable=no (bloquea el zoom del usuario):
2086
2350
  # misma severidad — ACT b4f0c3 no las distingue
2087
2351
  add('high', '1.4.4', 'zoom_max', v=_v_ms,
2088
- paths=([p._elem_paths[id(p._viewport_elem)]]
2089
- if p._viewport_elem and id(p._viewport_elem) in p._elem_paths else None))
2352
+ paths=p._finding_paths([p._viewport_elem]))
2090
2353
  # meta refresh (2.2.1/ACT bc659a): gana el PRIMER meta que parsea según
2091
2354
  # los pasos del HTML (dígitos + ; o , o fin — un «0: url» con dos puntos
2092
2355
  # NO parsea y se salta); 0 segundos = redirección inmediata y > 72000
@@ -2102,14 +2365,12 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2102
2365
  break
2103
2366
  if _mr is not None and 0 < _mr <= 72000:
2104
2367
  add('medium', '2.2.1', 'meta_refresh', v=_mr,
2105
- paths=([p._elem_paths[id(_mr_elem)]]
2106
- if _mr_elem and id(_mr_elem) in p._elem_paths else None))
2368
+ paths=p._finding_paths([_mr_elem]))
2107
2369
  if p.positive_tabindices:
2108
2370
  add_ej('medium', '2.4.3', 'tabindex_pos',
2109
2371
  [f'{t}[tabindex={i}]' for t, i in p.positive_tabindices],
2110
2372
  n=len(p.positive_tabindices),
2111
- paths=[p._elem_paths[id(_a)] for _a in p.positive_tabindex_elems
2112
- if id(_a) in p._elem_paths][:5])
2373
+ paths=p._finding_paths(p.positive_tabindex_elems))
2113
2374
  # un toggle cuenta como mecanismo de abatido SOLO si la función que
2114
2375
  # invoca colapsa de verdad (su cuerpo, en el script de la página, toca
2115
2376
  # `display`): mover off-screen o aria-hidden no colapsa el bloque (3e12e1)
@@ -2161,17 +2422,93 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2161
2422
  if p.heading_role_removed:
2162
2423
  add_ej('medium', '1.3.1', 'heading_role_removed', p.heading_role_removed,
2163
2424
  n=len(p.heading_role_removed), example=', '.join(p.heading_role_removed[:4]))
2425
+ if p.nested_main:
2426
+ add_ej('medium', '1.3.1', 'nested_main', p.nested_main,
2427
+ n=len(p.nested_main), example=', '.join(p.nested_main[:4]))
2428
+ if p.fake_lists:
2429
+ add_ej('low', '1.3.1', 'fake_list', p.fake_lists,
2430
+ n=len(p.fake_lists), example=', '.join(p.fake_lists[:3]))
2431
+ if p.a_no_href:
2432
+ add_ej('medium', '2.1.1', 'a_no_href', p.a_no_href,
2433
+ n=len(p.a_no_href), example=', '.join(p.a_no_href[:4]))
2434
+ if p.alert_polite:
2435
+ add_ej('low', '4.1.2', 'alert_polite', p.alert_polite,
2436
+ n=len(p.alert_polite), example=', '.join(p.alert_polite[:3]))
2437
+ if p.lang_xml_mismatch:
2438
+ add_ej('low', '3.1.2', 'lang_xml_mismatch', p.lang_xml_mismatch,
2439
+ n=len(p.lang_xml_mismatch), example=', '.join(p.lang_xml_mismatch[:4]))
2440
+ if p.nested_interactive:
2441
+ add_ej('medium', '4.1.2', 'nested_interactive', p.nested_interactive,
2442
+ n=len(p.nested_interactive), example=', '.join(p.nested_interactive[:4]))
2443
+ if p.aria_level_gt6:
2444
+ add_ej('low', '1.3.1', 'aria_level_gt6', p.aria_level_gt6,
2445
+ n=len(p.aria_level_gt6), example=', '.join(p.aria_level_gt6[:4]))
2446
+ # invokers: validación POST-parse contra el registro de ids (el destino
2447
+ # puede declararse después del botón)
2448
+ for _ref, _cmd in p._invokers:
2449
+ _dst = p._id_tag.get(_ref)
2450
+ if _dst is None:
2451
+ if len(p.invoker_bad) < 8:
2452
+ p.invoker_bad.append(f'commandfor="{_ref[:20]}" sin destino')
2453
+ elif _cmd in ('show-modal', 'close') and _dst[0] != 'dialog':
2454
+ if len(p.invoker_bad) < 8:
2455
+ p.invoker_bad.append(
2456
+ f'command="{_cmd}" sobre <{_dst[0]}> (exige <dialog>)')
2457
+ elif _cmd in ('show-popover', 'hide-popover', 'toggle-popover') \
2458
+ and not _dst[1]:
2459
+ if len(p.invoker_bad) < 8:
2460
+ p.invoker_bad.append(
2461
+ f'command="{_cmd}" sobre <{_dst[0]}> sin atributo popover')
2462
+ if p.invoker_bad:
2463
+ add_ej('medium', '4.1.2', 'invoker_command_bad', p.invoker_bad,
2464
+ n=len(p.invoker_bad), example=', '.join(p.invoker_bad[:4]))
2465
+ # select[autofocus] (3.2.1): solo los que llevan script de cambio de
2466
+ # contexto; el atributo solo no cambia nada y no es hallazgo
2467
+ if p.select_auto_focus:
2468
+ add_ej('medium', '3.2.1', 'select_auto_focus', p.select_auto_focus,
2469
+ n=len(p.select_auto_focus), example=', '.join(p.select_auto_focus[:4]),
2470
+ paths=p._finding_paths(p.select_auto_focus_elems))
2471
+ # contexto requerido por rol: se resuelve aquí porque el dueño por
2472
+ # aria-owns puede declararse después que el elemento que salva
2473
+ for _a, _rv, _chain in p._role_ctx_pending:
2474
+ if not p._role_context_satisfied(_a, _rv, _chain) and len(p.role_orphans) < 8:
2475
+ p.role_orphans.append(f'role="{_rv}": {"/".join(_ROLE_PARENTS[_rv])}')
2476
+ p.role_orphan_elems.append(_a)
2477
+ if p.role_orphans:
2478
+ add_ej('medium', '1.3.1', 'role_orphan', p.role_orphans,
2479
+ n=len(p.role_orphans), example=', '.join(p.role_orphans[:4]),
2480
+ paths=p._finding_paths(p.role_orphan_elems))
2481
+ # skips (F89): SOLO enlaces con vocabulario de salto (patrón 3e12e1) cuyo
2482
+ # destino no existe. Una nota al pie rota es otro aviso (y menor): el
2483
+ # mecanismo de bypass ROTO es lo que deja a quien navega atrapado en la
2484
+ # repetitive nav (2.4.1 medium). El navegador decodifica el fragmento
2485
+ # antes de buscar el id (#secci%C3%B3n llega a id="sección") y también
2486
+ # resuelve el destino clásico <a name="…"> (medido en Chromium 147).
2487
+ for _ref, _a in p._skip_hrefs:
2488
+ _target = unquote(_ref)
2489
+ if _target and _target not in p.ids and _target not in p._name_anchors \
2490
+ and len(p.skip_broken) < 8:
2491
+ p.skip_broken.append(f'#{_ref[:24]}')
2492
+ p.skip_broken_elems.append(_a)
2493
+ if p.skip_broken:
2494
+ add_ej('medium', '2.4.1', 'skip_broken', p.skip_broken,
2495
+ n=len(p.skip_broken), example=', '.join(p.skip_broken[:4]),
2496
+ paths=p._finding_paths(p.skip_broken_elems))
2497
+ if p.headers_bad:
2498
+ examples = [f'headers="{token[:20]}"' for token, _ in p.headers_bad[:5]]
2499
+ add_ej('medium', '1.3.1', 'headers_attr_bad', examples,
2500
+ n=len(p.headers_bad), example=', '.join(examples[:4]),
2501
+ paths=p._finding_paths(cell for _, cell in p.headers_bad))
2502
+
2164
2503
  if p.text_spacing_important:
2165
2504
  add_ej('medium', '1.4.12', 'text_spacing_important', p.text_spacing_important,
2166
2505
  n=len(p.text_spacing_important), example=', '.join(p.text_spacing_important[:4]))
2167
2506
  if p.tables and p.tables_with_th < p.tables:
2168
2507
  add('medium', '1.3.1', 'table_no_th', n=p.tables - p.tables_with_th,
2169
- paths=[p._elem_paths[id(_a)] for _a in p.tables_no_th_elems
2170
- if id(_a) in p._elem_paths][:5])
2508
+ paths=p._finding_paths(p.tables_no_th_elems))
2171
2509
  if p.blank_no_warning:
2172
2510
  add('low', '3.2.5', 'blank_no_warning', n=p.blank_no_warning,
2173
- paths=[p._elem_paths[id(_a)] for _a in p.blank_no_warning_elems
2174
- if id(_a) in p._elem_paths][:5])
2511
+ paths=p._finding_paths(p.blank_no_warning_elems))
2175
2512
  dups = sum(1 for _c, k in p.ids.items() if k > 1)
2176
2513
  if dups:
2177
2514
  add_ej('low', '4.1.2', 'dup_ids',
@@ -2200,8 +2537,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2200
2537
  if p.missing_autocomplete:
2201
2538
  add_ej('medium', '1.3.5', 'autocomplete', p.missing_autocomplete,
2202
2539
  n=len(p.missing_autocomplete), example=', '.join(p.missing_autocomplete[:4]),
2203
- paths=[p._elem_paths[id(_a)] for _a in p.autocomplete_elems
2204
- if id(_a) in p._elem_paths][:5])
2540
+ paths=p._finding_paths(p.autocomplete_elems))
2205
2541
  if p.autocomplete_invalid:
2206
2542
  add_ej('medium', '1.3.5', 'autocomplete_invalid', p.autocomplete_invalid,
2207
2543
  n=len(p.autocomplete_invalid), example=', '.join(p.autocomplete_invalid[:4]))
@@ -2210,8 +2546,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2210
2546
  n=len(p.autocomplete_mismatch), example=', '.join(p.autocomplete_mismatch[:4]))
2211
2547
  if p.media_autoplay:
2212
2548
  add('medium', '1.4.2', 'video_autoplay', n=p.media_autoplay,
2213
- paths=[p._elem_paths[id(_a)] for _a in p.media_autoplay_elems
2214
- if id(_a) in p._elem_paths][:5])
2549
+ paths=p._finding_paths(p.media_autoplay_elems))
2215
2550
  # 2.5.3, veredicto POST-parse (4ª pasada): el nombre EFECTIVO por
2216
2551
  # precedencia accname — labelledby (ids resueltos, unidos en orden) GANA
2217
2552
  # a aria-label. El nombre del propio contenido cumple trivialmente.
@@ -2247,8 +2582,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2247
2582
  add_ej('medium', '2.5.3', 'label_in_name',
2248
2583
  [f'«{t}» vs name «{al}»' for t, al in p.label_no_name],
2249
2584
  n=len(p.label_no_name), example=f'{_ln[0]} ≠ {_ln[1]}',
2250
- paths=[p._elem_paths[id(_a)] for _a in p.label_no_name_elems
2251
- if id(_a) in p._elem_paths][:5])
2585
+ paths=p._finding_paths(p.label_no_name_elems))
2252
2586
  if p.lang_parts_invalid:
2253
2587
  add_ej('medium', '3.1.2', 'element_lang_invalid', p.lang_parts_invalid,
2254
2588
  n=len(p.lang_parts_invalid), example=', '.join(p.lang_parts_invalid[:4]))
@@ -2259,8 +2593,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2259
2593
  if p.placeholder_only:
2260
2594
  add_ej('high', '3.3.2', 'placeholder_only', p.placeholder_only,
2261
2595
  n=len(p.placeholder_only), example=', '.join(p.placeholder_only[:3]),
2262
- paths=[p._elem_paths[id(_a)] for _a in p.placeholder_only_elems
2263
- if id(_a) in p._elem_paths][:5])
2596
+ paths=p._finding_paths(p.placeholder_only_elems))
2264
2597
  if p.required_no_indication:
2265
2598
  add_ej('low', '3.3.2', 'required_no_indication', p.required_no_indication,
2266
2599
  n=len(p.required_no_indication), example=', '.join(p.required_no_indication[:3]))
@@ -2303,8 +2636,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2303
2636
  if p.focus_blur:
2304
2637
  add_ej('high', '2.1.1', 'onfocus_blur', p.focus_blur,
2305
2638
  n=len(p.focus_blur),
2306
- paths=[p._elem_paths[id(_a)] for _a in p.focus_blur_elems
2307
- if id(_a) in p._elem_paths][:5])
2639
+ paths=p._finding_paths(p.focus_blur_elems))
2308
2640
  if p.motions:
2309
2641
  add_ej('low', '2.5.4', 'motion_actuation', p.motions,
2310
2642
  n=len(p.motions), example=', '.join(p.motions[:3]))
@@ -2313,8 +2645,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2313
2645
  n=len(p.orientation_locks), example=', '.join(p.orientation_locks[:2]))
2314
2646
  if p.videos and p.videos_no_desc_elems:
2315
2647
  add('low', '1.2.3', 'audio_desc_missing', n=len(p.videos_no_desc_elems),
2316
- paths=[p._elem_paths[id(_a)] for _a in p.videos_no_desc_elems
2317
- if id(_a) in p._elem_paths][:5])
2648
+ paths=p._finding_paths(p.videos_no_desc_elems))
2318
2649
  if p.sensory:
2319
2650
  add('low', '1.3.3', 'sensory_text', example='; '.join(p.sensory[:2])[:70])
2320
2651
  lm_dups = [f'{lm} ×{t[1]}' for lm, t in p.landmarks.items()
@@ -2324,15 +2655,13 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2324
2655
  if p.generics >= 2: # un enlace genérico único suele desambiguarse por contexto
2325
2656
  gen = [f'«{k}»' for k in p.links if k in _GENERIC_TEXT][:4]
2326
2657
  add('low', '2.4.4', 'generic_link', n=p.generics, example=', '.join(gen),
2327
- paths=[p._elem_paths[id(_a)] for _a in p.generic_link_elems
2328
- if id(_a) in p._elem_paths][:5])
2658
+ paths=p._finding_paths(p.generic_link_elems))
2329
2659
  same = sum(1 for _k, hrefs in p.links.items() if len(hrefs) > 1)
2330
2660
  if same:
2331
2661
  _same_elems = [p.links_elems.get(_k, [None])[0]
2332
2662
  for _k, _hs in p.links.items() if len(_hs) > 1]
2333
2663
  add('low', '2.4.4', 'same_name_links', n=same,
2334
- paths=[p._elem_paths[id(_a)] for _a in _same_elems
2335
- if _a is not None and id(_a) in p._elem_paths][:5])
2664
+ paths=p._finding_paths(_same_elems))
2336
2665
  ak_dups = [f'"{k}" ×{v}' for k, v in p.accesskeys.items() if v > 1]
2337
2666
  if ak_dups:
2338
2667
  add('low', '2.1.1', 'accesskey_dup', n=len(ak_dups), example=', '.join(ak_dups[:4]))
@@ -2394,6 +2723,39 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2394
2723
  if overlays:
2395
2724
  res['overlay_widgets'] = overlays
2396
2725
  res['overlay_widgets_note'] = _t(lang, 'overlay_widgets_note')
2726
+
2727
+ # enlace a la declaración de accesibilidad: requisito LEGAL europeo
2728
+ # (Directiva 2016/2102 art. 7 y RD 1112/2018) que nuestras auditorías de
2729
+ # conformidad deben poder verificar, pero NINGÚN criterio WCAG lo dicta —
2730
+ # sale como dato de informe (presente con su href / ausente), jamás
2731
+ # hallazgo. Vocabulario es/en/pt/fr/de/nl/sv/fi/da en ambos órdenes.
2732
+ _stmt = re.compile(
2733
+ r'toegankelijkheidsverklaring|tillg[aä]nglighetsredog[oö]relse|'
2734
+ r'saavutettavuusseloste|'
2735
+ r'(declaraci[oó]n|statement|erkl[aä]rung|declara[cç][aã]o|verklaring|'
2736
+ r'redog[oö]relse|seloste|erkl[eæ]ring)[^a-z0-9]{0,4}'
2737
+ r'(?:(?:de|da|do|di|della|du|of|zur|zum)\s+)?[^a-z0-9]{0,4}'
2738
+ r'(accesibilidad|accessibility|barrierefreiheit|acessibilidade|'
2739
+ r'accesibilidade|toegankelijkheid|tillg[aä]nglighet|saavutettavuus|'
2740
+ r'dostupnost)|'
2741
+ r'(accesibilidad|accessibility|barrierefreiheit|acessibilidade|'
2742
+ r'accesibilidade|toegankelijkheid|tillg[aä]nglighet|saavutettavuus)'
2743
+ r'[^a-z0-9]{0,4}(?:(?:de|da|do|di|della|du|of|zur|zum)\s+)?[^a-z0-9]{0,4}'
2744
+ r'(declaraci[oó]n|statement|erkl[aä]rung|declara[cç][aã]o|verklaring|'
2745
+ r'redog[oö]relse|seloste|erkl[eæ]ring)', re.I)
2746
+ _stmt_links = []
2747
+ for _tag, _a, _txt, _imgs, _hidden in p.controls_raw:
2748
+ if len(_stmt_links) >= 3:
2749
+ break
2750
+ _href = (_a.get('href') or '').strip()
2751
+ _img_alts = ' '.join((ia.get('alt') or '') for ia in (_imgs or []))
2752
+ _full = ' '.join(x for x in (_txt, _img_alts) if x).strip()
2753
+ if _href and not _hidden and _stmt.search(_full or ''):
2754
+ _stmt_links.append({'text': _full[:60], 'href': _href[:120]})
2755
+ res['accessibility_statement'] = {'found': bool(_stmt_links),
2756
+ 'links': _stmt_links}
2757
+ if not _stmt_links:
2758
+ res['accessibility_statement_note'] = _t(lang, 'statement_note')
2397
2759
  return res
2398
2760
 
2399
2761