@kinti/a11y-toolkit 5.29.0 → 5.31.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.
@@ -48,19 +48,32 @@ def _capture(url, engine, auth_state=None):
48
48
  def _pair_entry(name_a, name_b, sa, sb):
49
49
  d = a11ydiff.diff(sa, sb)
50
50
  # behavioral verdict: DOM-level facts only — the tree is informational
51
- # across engines (engines compute some roles/names differently by design)
52
- focus = d['focus']
51
+ # across engines (engines compute some roles/names differently by design).
52
+ # SIMÉTRICO (revisión externa, 4ª pasada): diff es direccional y el orden
53
+ # de los pares sale del nombre del motor — una parada que falta en un
54
+ # motor leía «removed» (bloquea) y en el otro «added» (no bloqueaba); y
55
+ # una reordenación con UNA alta quedaba enmascarada. El veredicto se
56
+ # calcula aquí por conjunto en AMBAS direcciones, y el ORDEN de las
57
+ # paradas compartidas se juzga independiente de altas y bajas
58
+ oa, ob = sa.get('focus_order', []), sb.get('focus_order', [])
59
+ sa_set, sb_set = set(oa), set(ob)
60
+ focus_missing = sorted((sa_set - sb_set) | (sb_set - sa_set))
61
+ common_a = [x for x in oa if x in sb_set]
62
+ common_b = [x for x in ob if x in sa_set]
63
+ order_diverged = common_a != common_b
53
64
  ok = not (d['added'] or d['removed'] or d['renamed']
54
- or focus['removed'] or focus['reordered'])
65
+ or focus_missing or order_diverged)
55
66
  return {
56
67
  'engines': [name_a, name_b],
57
68
  'ok': ok,
58
69
  'added': d['added'],
59
70
  'removed': d['removed'],
60
71
  'renamed': d['renamed'],
61
- 'focus': {'removed': focus['removed'], 'added': focus['added'],
62
- 'reordered': focus['reordered'],
63
- 'first_divergence': focus['first_divergence']},
72
+ 'focus': {'removed': d['focus']['removed'], 'added': d['focus']['added'],
73
+ 'reordered': d['focus']['reordered'],
74
+ 'first_divergence': d['focus']['first_divergence'],
75
+ 'missing_in_either': focus_missing,
76
+ 'order_diverged': order_diverged},
64
77
  'tree_changed': bool(d['tree']['changed']),
65
78
  'tree_first_differences': (d['tree']['first_differences'] or [])[:3],
66
79
  }
@@ -46,6 +46,15 @@ MANUAL_AA = [
46
46
  _STATES = ('automated-fail', 'automated-review', 'not-flagged', 'manual-only',
47
47
  'agent-verified', 'not-run', 'not-applicable')
48
48
 
49
+ # modo interno → la herramienta que la persona ejecuta (para la nota not-run)
50
+ _MODE_TOOL = {
51
+ 'static': 'a11y_audit_url', 'site': 'a11ytoolkit audit --pages',
52
+ 'rendered': 'a11y_audit_dom', 'keyboard': 'a11y_keyboard',
53
+ 'forms': 'a11y_forms', 'reflow': 'a11y_reflow', 'hover': 'a11y_hover',
54
+ 'scroll': 'a11y_scroll', 'journey': 'a11y_journey_verdict',
55
+ 'reduced-motion': 'a11y_reduced_motion', 'forced-colors': 'a11y_forced_colors',
56
+ }
57
+
49
58
 
50
59
  def _canon(obj):
51
60
  return json.dumps(obj, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
@@ -165,6 +174,13 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
165
174
  else:
166
175
  pages.append(inf)
167
176
 
177
+ # SOLO informes ACEPTADOS cuentan como cobertura: un informe con 'error'
178
+ # no miró nada (la revisión externa 2026-11-22: cero informes, o solo
179
+ # informes de error, y el pack declaraba 34 criterios not-flagged que
180
+ # nadie había mirado). Siguen sellados como artefactos — son entradas —
181
+ # pero no aportan evidencia de chequeo ejecutado.
182
+ pages = [p for p in pages if not (isinstance(p, dict) and p.get('error'))]
183
+
168
184
  # matriz de criterios: los que tocamos (estado según hallazgos) + manuales
169
185
  from .a11ycrit import _C as _CAT, effort
170
186
  codes_aa = sorted(k for k, v in _CAT.items() if v[0] in ('A', 'AA'))
@@ -229,10 +245,9 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
229
245
  if val:
230
246
  values[code] = val
231
247
 
232
- # criterios que requieren modo rendered (si solo corrió static, su estado
233
- # real es not-run, no not-flagged: la herramienta SÍ tiene señal pero el
234
- # modo que la produce no se incluyó)
235
- from .a11ycrit import RENDERED_ONLY as _RENDERED_ONLY # canónico (a11ycrit)
248
+ # criterios que requieren modos que este pack no incluye → not-run con el
249
+ # nombre de la herramienta que falta (canónico en a11ycrit, re-derivado)
250
+ from .a11ycrit import MODES_BY_CRITERION as _MODES_BY
236
251
 
237
252
  matrix = []
238
253
  _manual_codes = {m.split(' ')[0] for m in MANUAL_AA}
@@ -249,11 +264,18 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
249
264
  continue
250
265
  if code in _manual_codes:
251
266
  continue # covered by the manual-only rows appended below
252
- state = touched.get(code, 'not-flagged')
253
-
254
- # not-run: el criterio requiere rendered y este pack no lo incluye
255
- if state == 'not-flagged' and code in _RENDERED_ONLY and 'rendered' not in modes_included:
256
- state = 'not-run'
267
+ state = touched.get(code)
268
+
269
+ # cobertura derivada de lo EJECUTADO: not-flagged solo si la muestra
270
+ # incluye un informe aceptado de un modo capaz de emitir la señal del
271
+ # criterio (MODES_BY_CRITERION, re-derivada por el test de invariantes).
272
+ # Sin hallazgo y sin modo → not-run: la máquina NO miró este criterio.
273
+ if state is None:
274
+ modes = _MODES_BY.get(code, ())
275
+ if modes and modes_included & set(modes):
276
+ state = 'not-flagged'
277
+ else:
278
+ state = 'not-run'
257
279
 
258
280
  # verificados: promueve not-flagged/not-run/manual-only → agent-verified
259
281
  # (pero automated-fail permanece: un fallo no se borra verificando)
@@ -264,8 +286,9 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
264
286
  if state == 'not-flagged':
265
287
  note = tx['not_flagged']
266
288
  elif state == 'not-run':
267
- note = ('requires rendered mode (a11y_audit_dom) — this pack only '
268
- 'includes the static audit, so no signal was tried')
289
+ # nombra la HERRAMIENTA que falta, no el modo interno
290
+ missing = sorted({_MODE_TOOL.get(m, m) for m in _MODES_BY.get(code, ())})
291
+ note = tx['not_run'].format(modes=', '.join(missing) or '—')
269
292
  elif state == 'agent-verified':
270
293
  note = tx['verified']
271
294
 
@@ -111,14 +111,16 @@ class _Serializer(HTMLParser):
111
111
  def _emit(self, tag, attrs, depth):
112
112
  region = self._region()
113
113
  cls = sorted((attrs.get('class') or '').split())
114
- # sin \n/\r en los valores: un attr hostil no puede falsificar
115
- # líneas del material que se hashea (dos documentos distintos, un
116
- # mismo digest sería una divergencia perdida)
117
- stable = sorted('{}={}'.format(k, v.replace('\n', ' ').replace('\r', ' '))
114
+ # (4ª pasada) serialización SIN colisiones: json.dumps cita cada
115
+ # valor y cada token — class="alpha.beta" y class="alpha beta" ya no
116
+ # comparten vista, y un valor con espacios jamás se lee como dos
117
+ # atributos. Los digests cambian con respecto a la vista anterior:
118
+ # 'serialization' declara la versión para no comparar cruces
119
+ stable = sorted('{}={}'.format(k, json.dumps(v, ensure_ascii=False))
118
120
  for k, v in attrs.items()
119
121
  if k not in _VOLATILE and k != 'class')
120
122
  for view, extra in (('structure', ''),
121
- ('classes', ' .' + '.'.join(cls) if cls else ''),
123
+ ('classes', ' ' + json.dumps(cls, ensure_ascii=False) if cls else ''),
122
124
  ('attributes', ' ' + ' '.join(stable) if stable else '')):
123
125
  self.lines[view].setdefault(region, []).append(
124
126
  '{} {}{}'.format(depth, tag, extra))
@@ -224,6 +226,7 @@ def fingerprint_pages(pages, lang='en'):
224
226
 
225
227
  return {
226
228
  'mode': 'template-fingerprints',
229
+ 'serialization': 'classes-and-attrs-json-2',
227
230
  'pages_total': len(entries),
228
231
  'templates_total': len(templates),
229
232
  'views': list(VIEWS),
@@ -62,10 +62,24 @@ _JS_PHRASES = """<script>
62
62
  if(v.patternMismatch)return el.pattern?F.pattern.replace('%%p',el.pattern):F.req;
63
63
  return '';}
64
64
  document.querySelectorAll('form[data-a11yfx]').forEach(function(f){
65
+ // la BURBUJA nativa no se anuncia a lectores: la capa la sustituye
66
+ // replicando su SEMÁNTICA exacta (revisión externa, 3ª pasada: la capa
67
+ // anterior cambiaba QUÉ envíos eran posibles). OJO: noValidate=true se
68
+ // REFLEJA al atributo novalidate — el estado nativo se captura ANTES
69
+ var nativo=f.hasAttribute('novalidate');
65
70
  f.noValidate=true;
66
71
  f.addEventListener('submit',function(ev){
72
+ // 1) novalidate ORIGINAL en el form: el envío pasa sin validar (nativo)
73
+ if(nativo)return;
74
+ // 2) formnovalidate en el SUBMITTER (el botón «Guardar borrador»):
75
+ // ese envío NO valida (como nativo) — la capa lo bloqueaba
76
+ var sub=ev.submitter;
77
+ if(sub&&sub.formNoValidate)return;
67
78
  var first=null;
68
- f.querySelectorAll('input,select,textarea').forEach(function(el){
79
+ // 3) f.elements: TODOS los controles del form, incluidos los
80
+ // asociados con form= FUERA del árbol (querySelectorAll descendiente
81
+ // los saltaba y validaba envíos con campos vacíos)
82
+ Array.prototype.forEach.call(f.elements,function(el){
69
83
  var id=el.getAttribute('data-a11yfx-err'),msg=id?document.getElementById(id):null;
70
84
  if(!el.checkValidity()){var t=sug(el)||el.validationMessage||'';
71
85
  el.setAttribute('aria-invalid','true');
@@ -338,9 +352,14 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
338
352
  fr = _PHRASES.get(lang, _PHRASES['en'])
339
353
  js = _JS_PHRASES % {k: _json.dumps(v) for k, v in fr.items()}
340
354
  # case-insensitive: </BODY> perdía el JS y `applied` seguía
341
- # declarando la capa (aria-describedby colgantes)
355
+ # declarando la capa (aria-describedby colgantes). Y sin
356
+ # </body> EN ABSOLUTO (fragmento): el script va al FINAL —
357
+ # declarar la capa sin insertarla dejaba referencias rotas
358
+ _antes = fixed
342
359
  fixed = re.sub(r'</body\s*>', lambda _mb: js + '\n' + _mb.group(0),
343
360
  fixed, count=1, flags=re.I)
361
+ if fixed == _antes:
362
+ fixed = fixed.rstrip('\n') + '\n' + js + '\n'
344
363
  applied.append({'signal': 'form_error_missing',
345
364
  'fix': f"accessible error layer on {state['forms']} form(s), "
346
365
  f"{state['fields']} field(s) — 3.3.1 identification + "
@@ -103,7 +103,13 @@ def merge_block(content):
103
103
  def install_gate(path='.'):
104
104
  """Install the write-time gate hook in .claude/settings.json (idempotent:
105
105
  an existing a11ytoolkit guard-hook entry is left alone, as is every hook
106
- the user added). Returns {'gate': 'installed'|'already', 'file': path}."""
106
+ the user added). Returns {'gate': 'installed'|'already', 'file': path}.
107
+
108
+ Un fichero existente ILEGIBLE (o sin forma de objeto) jamás se toca: la
109
+ revisión externa (2026-11-22) cazó que un error de lectura partía de {}
110
+ y REEMPLAZABA el fichero — permisos de Claude incluidos. Ahora error
111
+ limpio con el original intacto. La escritura válida es atómica
112
+ (tmp + rename): un corte a mitad no deja un settings.json medio."""
107
113
  sdir = os.path.join(path, '.claude')
108
114
  os.makedirs(sdir, exist_ok=True)
109
115
  spath = os.path.join(sdir, 'settings.json')
@@ -111,8 +117,15 @@ def install_gate(path='.'):
111
117
  if os.path.exists(spath):
112
118
  try:
113
119
  data = json.load(open(spath, encoding='utf-8'))
114
- except Exception: # noqa: BLE001 — never clobber an unparseable file
115
- data = {}
120
+ except Exception as e: # noqa: BLE001 — conservar, jamás machacar
121
+ return {'error': f'cannot read existing {spath} ({e.__class__.__name__}): '
122
+ 'fix or remove it by hand — this tool refuses to '
123
+ 'overwrite an unreadable config',
124
+ 'gate': 'skipped', 'file': spath}
125
+ if not isinstance(data, dict):
126
+ return {'error': f'{spath} is valid JSON but not an object — this '
127
+ 'tool refuses to overwrite it',
128
+ 'gate': 'skipped', 'file': spath}
116
129
  hooks = data.setdefault('hooks', {}).setdefault('PreToolUse', [])
117
130
  for entry in hooks:
118
131
  cmds = [h.get('command', '') for h in entry.get('hooks', [])]
@@ -120,9 +133,11 @@ def install_gate(path='.'):
120
133
  return {'gate': 'already', 'file': spath}
121
134
  hooks.append({'matcher': GATE_MATCHER,
122
135
  'hooks': [{'type': 'command', 'command': GATE_CMD}]})
123
- with open(spath, 'w', encoding='utf-8') as f:
136
+ tmp = spath + '.a11y-tmp'
137
+ with open(tmp, 'w', encoding='utf-8') as f:
124
138
  json.dump(data, f, ensure_ascii=False, indent=2)
125
139
  f.write('\n')
140
+ os.replace(tmp, spath) # atómico: o el fichero nuevo entero, o el viejo
126
141
  return {'gate': 'installed', 'file': spath}
127
142
 
128
143
 
@@ -159,7 +174,11 @@ def main(argv):
159
174
  res = init(a.path, gate=not a.no_gate)
160
175
  if res.get('malformed_marker'):
161
176
  print('! ' + res['warning'])
162
- if res.get('gate'):
177
+ if res.get('error'):
178
+ # el gate se negó a tocar un settings.json ilegible: el AGENTS.md ya
179
+ # se actualizó (eso es seguro), pero el estado del gate es un ERROR
180
+ print('! ' + res['error'])
181
+ if res.get('gate') and res['gate'] != 'skipped':
163
182
  print(f"✓ write-time gate {res['gate']}: {res['file']}"
164
183
  f" (block: NEW high/medium · disable: A11Y_GATE=off)")
165
184
  verb = 'updated' if res['already_present'] else ('created' if res['created'] else 'installed into')
@@ -137,6 +137,13 @@ def verdict(task, steps, outcome, url='', lang='en'):
137
137
  verdict = 'blocked'
138
138
  elif not completed:
139
139
  verdict = 'fail'
140
+ elif not steps:
141
+ # un «completado» SIN pasos registrados no es evidencia de nada
142
+ # (revisión externa, 4ª pasada: steps [] + completed true sellaba
143
+ # pass con 100) — nadie caminó, nadie miró. fail estructural con
144
+ # la razón al lado; JAMÁS un pass sellado de un paseo vacío
145
+ verdict = 'fail'
146
+ score = 0
140
147
  elif (not workaround and high == 0 and score >= _RULES['pass_threshold']):
141
148
  verdict = 'pass'
142
149
  else:
@@ -110,6 +110,13 @@ def _hash_url(url):
110
110
 
111
111
 
112
112
  def _record(url, report, ledger=None, path='a11y-ledger.json'):
113
+ # un informe FALLIDO jamás escribe (revisión externa 2026-11-22: con
114
+ # {'error': …} findings quedaba vacío y TODAS las señales activas
115
+ # pasaban a «resolved» — el libro mentía). Se conserva el último estado
116
+ # válido y se devuelve el error.
117
+ if not isinstance(report, dict) or report.get('error'):
118
+ return {'error': 'the audit report failed (error field) — the last '
119
+ 'valid ledger state is preserved'}
113
120
  if ledger is None:
114
121
  ledger = _load(path)
115
122
  now = datetime.now(timezone.utc).isoformat(timespec='seconds')
@@ -304,6 +311,8 @@ def main(argv):
304
311
  report = json.load(f)
305
312
  r = record(a.url, report, path=a.ledger)
306
313
  print(json.dumps(r, ensure_ascii=False, indent=1))
314
+ if isinstance(r, dict) and r.get('error'):
315
+ return 1 # informe fallido: error de ejecución, no un verde
307
316
  elif a.cmd == 'gaps':
308
317
  print(json.dumps(gaps(a.url, path=a.ledger, lang=a.lang), ensure_ascii=False, indent=1))
309
318
  elif a.cmd == 'summary':
@@ -156,10 +156,16 @@ def _index(p):
156
156
  lb, al, ti = _name_sources(a)
157
157
  content_name = direct_text.get(a.get('id') or '', '') \
158
158
  if kind.split(':', 1)[-1] in _NAME_FROM_CONTENT else ''
159
+ # label como nombre (la MISMA resolución que el auditor): el <label
160
+ # for=id> y el <label> envolvente cuentan — un campo correctamente
161
+ # etiquetado existe por su nombre visible (revisión externa
162
+ # 2026-11-22: se caía del índice y locate decía «no encontrado»)
163
+ label_name = (getattr(p, '_label_text_for', {}).get(a.get('id'), '')
164
+ or getattr(p, '_wrap_label_text', {}).get(id(a), '')).strip()
159
165
  # el kind de un input es su type ('email'): normalizo al formato
160
166
  # 'input:email' que usan los aliases de rol
161
167
  role_kind = f'input:{kind}' if tag == 'input' else kind
162
- _add(a, role_kind, lb or al or ti or content_name)
168
+ _add(a, role_kind, lb or al or label_name or content_name or ti)
163
169
 
164
170
  return items
165
171
 
@@ -106,6 +106,8 @@ def generate_openacr(pack=None, reports=None, product='', product_version=None,
106
106
  if not isinstance(scope, dict):
107
107
  return {'error': t['error_scope']}
108
108
  from .a11yevidence import apply_scope
109
+ from .a11yevidence import _sha256
110
+ scope_sha = (scope.get('sha256') or _sha256(scope)) if isinstance(scope, dict) else None
109
111
  pack = apply_scope(pack, scope, lang=lang)
110
112
  if not isinstance(pack, dict) or 'criteria' not in pack:
111
113
  return {'error': t['error_no_pack']}
@@ -116,6 +118,10 @@ def generate_openacr(pack=None, reports=None, product='', product_version=None,
116
118
 
117
119
  from .a11ycrit import _C as _CAT
118
120
  pack_sha = pack.get('sha256', '')
121
+ try:
122
+ scope_sha
123
+ except NameError:
124
+ scope_sha = None
119
125
  by_code = _findings_by_code(pack)
120
126
  report_date = report_date or datetime.date.today().isoformat()
121
127
 
@@ -177,9 +183,18 @@ def generate_openacr(pack=None, reports=None, product='', product_version=None,
177
183
  + ' — ' + f['remarks']))
178
184
 
179
185
  doc = '\n'.join(lines) + '\n'
186
+ # (5ª pasada) el alcance aplicado queda VINCULADO al borrador: el sello
187
+ # del pack cubre los informes; el del alcance, las exclusiones que
188
+ # cambiaron esta matriz — ambos viajan en el YAML y en el resultado
189
+ if scope_sha:
190
+ lines.insert(0, '# applied scope sha256: ' + scope_sha
191
+ + ' (exclusions confirmed by a human; the pack seal below '
192
+ 'covers the reports, this one covers the exclusions)')
193
+ doc = '\n'.join(lines) + '\n'
180
194
  res = {'yaml': doc, 'summary': summary,
181
195
  'levels': {f['code']: f['adherence'] for f in rows},
182
- 'pack_sha256': pack_sha, 'format': 'openacr', 'draft': True, 'lang': lang}
196
+ 'pack_sha256': pack_sha, 'format': 'openacr', 'draft': True, 'lang': lang,
197
+ **({'scope_sha256': scope_sha, 'derived': True} if scope_sha else {})}
183
198
  if output_path:
184
199
  with open(output_path, 'w', encoding='utf-8') as fh:
185
200
  fh.write(doc)
@@ -57,6 +57,13 @@ _INSIDE = r'''() => {
57
57
  }'''
58
58
 
59
59
 
60
+ def _num_or_none(v):
61
+ try:
62
+ return float((v or '').strip())
63
+ except ValueError:
64
+ return None
65
+
66
+
60
67
  def _finding(findings, lang, severity, criterion, key, **fmt):
61
68
  cat = _P['es' if lang == 'es' else 'en']
62
69
  findings.append({'severity': severity, 'criterion': criterion,
@@ -66,12 +73,30 @@ def _finding(findings, lang, severity, criterion, key, **fmt):
66
73
 
67
74
 
68
75
  def _test_dialogs(page, findings, lang, cap=3):
69
- """Visible dialogs: Esc closes; focus stays inside (modal); returns after."""
76
+ """Visible dialogs: Esc closes; focus stays inside (modal); returns after.
77
+ (6a pasada) identidad FIJADA por handle -- un Locator se re-resuelve y, al
78
+ cerrar el primer dialogo, apuntaba al siguiente y lo acusaba de no
79
+ cerrar. Y el ciclo de foco se recorre ENTERO (ida con Tab y vuelta con
80
+ Shift+Tab, hasta el doble de paradas + 3): un unico Tab dejaba escapar
81
+ el foco en el segundo salto."""
70
82
  loc = page.locator('[role="dialog"]:visible, [role="alertdialog"]:visible, '
71
83
  'dialog[open]:visible')
72
84
  n = min(loc.count(), cap)
85
+ _inside_js = ('(dlg) => { const a = document.activeElement;'
86
+ ' return dlg === a || dlg.contains(a); }')
87
+ # (7a pasada) TODOS los handles ANTES de tocar nada: cerrar el primer
88
+ # dialogo cambiaba los indices de la lista visible y el segundo quedaba
89
+ # SIN PROBAR
90
+ handles = []
73
91
  for i in range(n):
74
- d = loc.nth(i)
92
+ try:
93
+ h = loc.nth(i).element_handle()
94
+ except Exception: # noqa: BLE001
95
+ h = None
96
+ handles.append(h)
97
+ for d in handles:
98
+ if d is None:
99
+ continue
75
100
  try:
76
101
  d.evaluate('el => (el.querySelector("a[href],button,input,select,textarea,[tabindex]") '
77
102
  '|| el).focus()')
@@ -79,13 +104,30 @@ def _test_dialogs(page, findings, lang, cap=3):
79
104
  continue
80
105
  is_modal = (d.get_attribute('aria-modal') or '').lower() == 'true'
81
106
  if is_modal:
82
- page.keyboard.press('Tab')
83
- page.wait_for_timeout(120)
84
- try:
85
- inside = page.evaluate(_INSIDE)
86
- except Exception: # noqa: BLE001
87
- inside = True
88
- if not inside:
107
+ stops = d.evaluate(
108
+ 'el => el.querySelectorAll('
109
+ '"a[href],button,input,select,textarea,[tabindex]").length')
110
+ leaked = False
111
+ for _step in range(min(stops * 2 + 3, 12)):
112
+ page.keyboard.press('Tab')
113
+ page.wait_for_timeout(90)
114
+ try:
115
+ inside = page.evaluate(_inside_js, d)
116
+ except Exception: # noqa: BLE001
117
+ inside = True
118
+ if not inside:
119
+ leaked = True
120
+ if not leaked:
121
+ for _step in range(3):
122
+ page.keyboard.press('Shift+Tab')
123
+ page.wait_for_timeout(90)
124
+ try:
125
+ inside = page.evaluate(_inside_js, d)
126
+ except Exception: # noqa: BLE001
127
+ inside = True
128
+ if not inside:
129
+ leaked = True
130
+ if leaked:
89
131
  _finding(findings, lang, 'medium', '2.4.3', 'pattern_modal_focus_escapes')
90
132
  page.keyboard.press('Escape')
91
133
  page.wait_for_timeout(250)
@@ -141,27 +183,56 @@ def _test_tablists(page, findings, lang, cap=3):
141
183
  continue
142
184
 
143
185
 
186
+ def _panel_visible(page, b):
187
+ """(6a pasada) activar un disclosure consiste en MOSTRAR contenido, no
188
+ en voltear un atributo: el panel es el aria-controls y su VISIBILIDAD
189
+ decide. None cuando no hay panel identificable."""
190
+ cid = (b.get_attribute('aria-controls') or '').strip()
191
+ if not cid:
192
+ return None
193
+ try:
194
+ return page.locator('#' + cid).first.is_visible()
195
+ except Exception: # noqa: BLE001
196
+ return None
197
+
198
+
144
199
  def _test_disclosures(page, findings, lang, cap=8):
145
- """Disclosure buttons: activation must FLIP the exposed state.
146
- Menu buttons are excluded — they are the menu pattern's subject."""
200
+ """Disclosure buttons: KEYBOARD activation (Enter, then Space) must open
201
+ the panel -- un disclosure que solo reacciona al raton es teclado-muerto
202
+ y la prueba antigua (solo click) lo aprobaba (6a pasada). Menu buttons
203
+ are excluded -- they are the menu pattern's subject."""
147
204
  loc = page.locator('button[aria-expanded]:visible:not([aria-haspopup="menu"]), '
148
205
  '[role="button"][aria-expanded]:visible:not([aria-haspopup="menu"])')
149
206
  n = min(loc.count(), cap)
150
207
  for i in range(n):
151
208
  b = loc.nth(i)
152
209
  try:
153
- before = (b.get_attribute('aria-expanded') or '').lower()
154
210
  name = ((b.get_attribute('aria-label') or '') or b.inner_text()
155
211
  or 'disclosure').strip().replace('\n', ' ')[:40]
156
- b.click()
157
- page.wait_for_timeout(250)
158
- after = (b.get_attribute('aria-expanded') or '').lower()
159
- if before == after and before in ('true', 'false'):
212
+ before = (b.get_attribute('aria-expanded') or '').lower()
213
+ panel_before = _panel_visible(page, b)
214
+ b.evaluate('el => el.focus()')
215
+ worked = None
216
+ for key in ('Enter', ' '):
217
+ page.keyboard.press(key)
218
+ page.wait_for_timeout(220)
219
+ after = (b.get_attribute('aria-expanded') or '').lower()
220
+ panel = _panel_visible(page, b)
221
+ if after != before or (panel is True and panel_before is not True):
222
+ worked = (key, after, panel)
223
+ break
224
+ if worked is None:
225
+ if before in ('true', 'false'):
226
+ _finding(findings, lang, 'high', '2.1.1',
227
+ 'pattern_disclosure_keyboard_dead', name=name)
228
+ continue
229
+ _key, after, panel = worked
230
+ if after in ('true', 'false') and panel is False and panel_before is False:
231
+ # voltorea el estado pero el panel NUNCA se muestra
160
232
  _finding(findings, lang, 'medium', '4.1.2',
161
233
  'pattern_disclosure_state_frozen', name=name)
162
- elif after in ('true', 'false') and after != before:
163
- b.click() # dejar la página como estaba
164
- page.wait_for_timeout(150)
234
+ page.keyboard.press(_key) # dejar la página como estaba (toggle)
235
+ page.wait_for_timeout(150)
165
236
  except Exception: # noqa: BLE001
166
237
  continue
167
238
 
@@ -183,17 +254,22 @@ def _test_comboboxes(page, findings, lang, cap=3):
183
254
  try:
184
255
  c.evaluate('el => el.focus()')
185
256
  before = (c.get_attribute('aria-expanded') or '').lower()
257
+ # (6a pasada) el popup es el del PROPIO control (aria-controls):
258
+ # un listbox AJENO visible hacia fracasar el Escape de un
259
+ # combobox correcto -- y aprobar su apertura
260
+ cid = (c.get_attribute('aria-controls') or '').strip()
261
+ popup_sel = ('#' + cid) if cid else '[role="listbox"]:visible'
186
262
  page.keyboard.press('ArrowDown')
187
263
  page.wait_for_timeout(300)
188
264
  after = (c.get_attribute('aria-expanded') or '').lower()
189
- opened = after == 'true' or _visible_open(page, '[role="listbox"]:visible')
265
+ opened = after == 'true' or _visible_open(page, popup_sel)
190
266
  if not opened and before != 'true':
191
267
  _finding(findings, lang, 'medium', '2.1.1', 'pattern_combobox_no_open')
192
268
  continue
193
269
  page.keyboard.press('Escape')
194
270
  page.wait_for_timeout(250)
195
271
  closed = (c.get_attribute('aria-expanded') or '').lower() != 'true' \
196
- and not _visible_open(page, '[role="listbox"]:visible')
272
+ and not _visible_open(page, popup_sel)
197
273
  if not closed:
198
274
  _finding(findings, lang, 'medium', '2.1.1', 'pattern_combobox_esc_no_close')
199
275
  except Exception: # noqa: BLE001
@@ -208,16 +284,26 @@ def _test_menu_buttons(page, findings, lang, cap=3):
208
284
  for i in range(n):
209
285
  b = loc.nth(i)
210
286
  try:
211
- b.click()
212
- page.wait_for_timeout(300)
213
- opened = _visible_open(page, '[role="menu"]:visible') \
214
- or (b.get_attribute('aria-expanded') or '').lower() == 'true'
287
+ # (6a pasada) apertura por TECLADO (Enter/ArrowDown/Space): un
288
+ # menu que solo abre con raton es teclado-muerto; y «abierto» es
289
+ # el MENU VISIBLE (o su panel aria-controls) -- voltorear
290
+ # aria-expanded sin mostrar nada ya no aprueba
291
+ cid = (b.get_attribute('aria-controls') or '').strip()
292
+ menu_sel = ('#' + cid) if cid else '[role="menu"]:visible'
293
+ b.evaluate('el => el.focus()')
294
+ opened = False
295
+ for key in ('Enter', 'ArrowDown', ' '):
296
+ page.keyboard.press(key)
297
+ page.wait_for_timeout(250)
298
+ if _visible_open(page, menu_sel):
299
+ opened = True
300
+ break
215
301
  if not opened:
216
302
  _finding(findings, lang, 'medium', '2.1.1', 'pattern_menu_no_open')
217
303
  continue
218
304
  page.keyboard.press('Escape')
219
305
  page.wait_for_timeout(250)
220
- closed = not _visible_open(page, '[role="menu"]:visible') \
306
+ closed = not _visible_open(page, menu_sel) \
221
307
  and (b.get_attribute('aria-expanded') or '').lower() != 'true'
222
308
  if not closed:
223
309
  _finding(findings, lang, 'medium', '2.1.1', 'pattern_menu_esc_no_close')
@@ -238,17 +324,29 @@ def _test_sliders(page, findings, lang, cap=3):
238
324
  _finding(findings, lang, 'medium', '4.1.2', 'pattern_slider_no_state',
239
325
  name=((s.get_attribute('aria-label') or '') or 'slider')[:40])
240
326
  now = (s.get_attribute('aria-valuenow') or '').strip()
327
+ # (6a pasada) la direccion sale del VALOR y sus LIMITES: en el
328
+ # maximo las teclas que INCREMENTAN no pueden mover nada y el
329
+ # slider correcto fallaba -- se prueba una tecla que PUEDA mover
330
+ _mn = _num_or_none(s.get_attribute('aria-valuemin'))
331
+ _mx = _num_or_none(s.get_attribute('aria-valuemax'))
332
+ _nv = _num_or_none(now)
333
+ if _nv is not None and _mx is not None and _nv >= _mx:
334
+ _keys = ('ArrowLeft', 'ArrowDown') # en el tope: decrementar
335
+ elif _nv is not None and _mn is not None and _nv <= _mn:
336
+ _keys = ('ArrowRight', 'ArrowUp') # en el suelo: incrementar
337
+ else:
338
+ _keys = ('ArrowRight', 'ArrowUp')
241
339
  s.evaluate('el => el.focus()')
242
- page.keyboard.press('ArrowRight')
243
- page.wait_for_timeout(150)
244
- after_r = (s.get_attribute('aria-valuenow') or '').strip()
245
- if after_r == now:
246
- page.keyboard.press('ArrowUp')
340
+ value_changed = False
341
+ for _k in _keys:
342
+ page.keyboard.press(_k)
247
343
  page.wait_for_timeout(150)
248
- after_up = (s.get_attribute('aria-valuenow') or '').strip()
249
- if after_up == now:
250
- _finding(findings, lang, 'high', '2.1.1', 'pattern_slider_arrows_dead')
251
- continue
344
+ if (s.get_attribute('aria-valuenow') or '').strip() != now:
345
+ value_changed = True
346
+ break
347
+ if not value_changed:
348
+ _finding(findings, lang, 'high', '2.1.1', 'pattern_slider_arrows_dead')
349
+ continue
252
350
  # devolver el valor original (dejar la página como estaba)
253
351
  if now and (s.get_attribute('aria-valuenow') or '').strip() != now:
254
352
  s.evaluate('(el, v) => el.setAttribute("aria-valuenow", v)', now)
@@ -258,18 +356,15 @@ def _test_sliders(page, findings, lang, cap=3):
258
356
 
259
357
  def audit_patterns(url, timeout=45, lang='en', auth_state=None, browser='auto'):
260
358
  """One url → widget patterns found + contract findings (filter, not verdict)."""
261
- from playwright.sync_api import sync_playwright
262
- from .a11ydom import _get_browser
359
+ from .a11ydom import _get_browser, _pooled_page
263
360
  lang = 'es' if lang == 'es' else 'en'
264
- with sync_playwright() as p:
265
- nav = _get_browser(p, preferred=browser)
266
- ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
267
- page = ctx.new_page() if auth_state else nav.new_page()
361
+ nav = _get_browser(preferred=browser)
362
+ page, close_page = _pooled_page(nav, auth_state)
363
+ try:
268
364
  try:
269
365
  page.goto(url, wait_until='load', timeout=timeout * 1000)
270
366
  page.wait_for_timeout(400)
271
367
  except Exception as e: # noqa: BLE001
272
- nav.close()
273
368
  return {'error': f'could not load: {e}'}
274
369
 
275
370
  counts = page.evaluate(_COUNTS)
@@ -280,7 +375,8 @@ def audit_patterns(url, timeout=45, lang='en', auth_state=None, browser='auto'):
280
375
  _test_comboboxes(page, findings, lang)
281
376
  _test_menu_buttons(page, findings, lang)
282
377
  _test_sliders(page, findings, lang)
283
- nav.close()
378
+ finally:
379
+ close_page()
284
380
 
285
381
  limits = ('Only patterns VISIBLE at page load are tested: opening a closed '
286
382
  'dialog means guessing a trigger flow — never acceptable on a '