@kinti/a11y-toolkit 5.29.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.
@@ -44,7 +44,16 @@ _LIMITS_MOTION = {
44
44
  }
45
45
 
46
46
  from . import a11yi18n
47
- # browser pool: Chromium reutilizable entre llamadas consecutivas
47
+ import atexit
48
+
49
+ # browser pool: Chromium reutilizable entre llamadas consecutivas. El pool ES
50
+ # el dueño del driver — browser y Playwright nacen y mueren JUNTOS (la lección
51
+ # del «Event loop is closed»: una función abría `with sync_playwright()`,
52
+ # guardaba el browser en el pool y el with mataba la sesión que lo creó; el
53
+ # objeto huérfano quedaba en el pool con is_connected() rancio y envenenaba
54
+ # TODAS las llamadas siguientes del servidor MCP). Las auditorías nunca cierran
55
+ # el navegador del pool: cierran su página/contexto y lo devuelven caliente;
56
+ # el driver muere una sola vez, al reciclar el pool o al acabar el proceso.
48
57
  _POOL = {'playwright': None, 'browser': None, 'type': None}
49
58
 
50
59
  # cadena de detección: el primer navegador disponible gana.
@@ -89,27 +98,69 @@ def _detect_browser(pw, preferred=None):
89
98
  'pip install playwright && playwright install chromium')
90
99
 
91
100
 
92
- def _get_browser(pw, headless=True, preferred=None):
93
- """Devuelve un browser del pool (o crea uno si no existe)."""
101
+ def _get_browser(headless=True, preferred=None):
102
+ """Devuelve un browser del pool (o crea uno si no existe). El driver de
103
+ Playwright lo arranca y posee el PROPIO pool: el browser devuelto vive
104
+ mientras viva el pool, no la sesión de quien lo pidió."""
94
105
  if _POOL['browser'] is not None and _POOL['browser'].is_connected() and \
95
106
  (preferred in (None, 'auto') or _POOL['type'] == preferred):
96
107
  return _POOL['browser']
97
108
  _close_pool()
109
+ from playwright.sync_api import sync_playwright
110
+ pw = sync_playwright().start()
98
111
  br, kind = _detect_browser(pw, preferred)
112
+ _POOL['playwright'] = pw
99
113
  _POOL['browser'] = br
100
114
  _POOL['type'] = kind
101
115
  return br
102
116
 
103
117
 
104
118
  def _close_pool():
105
- """Cierra el pool (llamar al terminar el proceso o bajo demanda)."""
106
- if _POOL['browser']:
107
- try:
108
- _POOL['browser'].close()
109
- except Exception:
110
- pass
119
+ """Cierra el pool: browser y driver JUNTOS, en orden (browser, luego
120
+ playwright.stop). Llamada al reciclar y al terminar el proceso (atexit)."""
121
+ br, pw = _POOL['browser'], _POOL['playwright']
111
122
  _POOL['browser'] = None
112
123
  _POOL['playwright'] = None
124
+ _POOL['type'] = None
125
+ if br is not None:
126
+ try:
127
+ br.close()
128
+ except Exception: # noqa: BLE001
129
+ pass
130
+ if pw is not None:
131
+ try:
132
+ pw.stop()
133
+ except Exception: # noqa: BLE001
134
+ pass
135
+
136
+
137
+ atexit.register(_close_pool)
138
+
139
+
140
+ def _pooled_page(nav, auth_state=None, **kw):
141
+ """(page, close_page) sobre el navegador del pool: con auth_state abre un
142
+ contexto propio (storage_state) cuyo cierre se lleva también la página;
143
+ sin él, página directa. close_page traga errores — el navegador del pool
144
+ queda caliente para la siguiente llamada, JAMÁS se cierra aquí."""
145
+ if auth_state:
146
+ ctx = nav.new_context(storage_state=auth_state, **kw)
147
+ page = ctx.new_page()
148
+
149
+ def close_page():
150
+ try:
151
+ ctx.close()
152
+ except Exception: # noqa: BLE001
153
+ pass
154
+ return page, close_page
155
+
156
+ page = nav.new_page(**kw)
157
+
158
+ def close_page():
159
+ try:
160
+ page.close()
161
+ except Exception: # noqa: BLE001
162
+ pass
163
+ return page, close_page
113
164
 
114
165
  MAX_EXAMPLES = 6
115
166
 
@@ -172,7 +223,8 @@ _JS = r'''(maxEj) => {
172
223
  placeholderContrast: [],
173
224
  imgs: [], canvasNoName: [], chartsNoEquiv: [], iframes: [], headings: [], tabindex: [], ariaHidden: [],
174
225
  blank: 0, videos: 0, videoSubs: 0, tables: 0, tableTh: 0,
175
- focus: [], focusFail: [], focusContrast: [], focusObscured: [], marks: 0,
226
+ focus: [], focusFail: [], focusReview: [], focusContrast: [], focusObscured: [], marks: 0,
227
+ colorUnparsed: 0,
176
228
  ids: {}, lang: null, title: '', viewport: null, refresh: null,
177
229
  main: false, skip: false, elements: 0, shadow_roots: 0,
178
230
  colorOnly: [], orderInversions: 0, loopingAnims: 0 };
@@ -251,10 +303,31 @@ _JS = r'''(maxEj) => {
251
303
 
252
304
  // ---- contraste real: fondo efectivo con composición de alfas ----
253
305
  const parseCol = c => {
254
- const m = /rgba?\(([^)]+)\)/.exec(c || '');
255
- if (!m) return null;
256
- const p = m[1].split(',').map(x => parseFloat(x));
257
- return { r: p[0], g: p[1], b: p[2], a: p.length > 3 ? p[3] : 1 };
306
+ const s = String(c || '');
307
+ let m = /rgba?\(([^)]+)\)/.exec(s);
308
+ if (m) {
309
+ const p = m[1].split(',').map(x => parseFloat(x));
310
+ return { r: p[0], g: p[1], b: p[2], a: p.length > 3 ? p[3] : 1 };
311
+ }
312
+ // color(srgb r g b [/ a]) — CSS Color 4: Chromium devuelve ESTO para
313
+ // colores declarados modernos y sin parseo el texto se omitía en
314
+ // silencio (revisión externa, 3ª pasada). Otros espacios (display-p3,
315
+ // lab…) no se convierten: cuentan como no convertidos, jamás inventados
316
+ m = /color\(\s*srgb\s+([^)]+)\)/.exec(s);
317
+ if (m) {
318
+ const parts = m[1].split('/');
319
+ const rgb = parts[0].trim().split(/\s+/);
320
+ const conv = v => v.endsWith('%') ? parseFloat(v) * 2.55 : parseFloat(v) * 255;
321
+ const a = parts.length > 1
322
+ ? (parts[1].trim().endsWith('%') ? parseFloat(parts[1]) / 100 : parseFloat(parts[1]))
323
+ : 1;
324
+ if (rgb.length >= 3 && isFinite(conv(rgb[0])) && isFinite(conv(rgb[1]))
325
+ && isFinite(conv(rgb[2])) && isFinite(a)) {
326
+ return { r: Math.round(conv(rgb[0])), g: Math.round(conv(rgb[1])),
327
+ b: Math.round(conv(rgb[2])), a };
328
+ }
329
+ }
330
+ return null;
258
331
  };
259
332
  const over = (fg, bg) => ({
260
333
  r: Math.round(fg.r * fg.a + bg.r * (1 - fg.a)),
@@ -314,7 +387,7 @@ _JS = r'''(maxEj) => {
314
387
  }
315
388
  const s = getComputedStyle(el);
316
389
  const fg = parseCol(s.color);
317
- if (!fg) continue;
390
+ if (!fg) { out.colorUnparsed++; continue; } // declarado, jamás omitido en silencio
318
391
  // text-shadow: los colores de la sombra pintan DETRÁS del text_ y
319
392
  // participan como fondo peor-caso (8c33: #666 con sombra #aaa sobre
320
393
  // blanco falla por 1.6:1 aunque el fondo dé 5.7) — se decide, no se
@@ -638,20 +711,34 @@ _JS = r'''(maxEj) => {
638
711
  const activeEl = () => { let a = document.activeElement;
639
712
  while (a && a.shadowRoot && a.shadowRoot.activeElement) a = a.shadowRoot.activeElement;
640
713
  return a; };
714
+ // firma de la APARIENCIA relevante para el foco (outline/sombra/bordes):
715
+ // comparar reposo vs foco distingue un indicador REAL (aparece/cambia al
716
+ // enfocar) de un borde PERMANENTE que estaba ahí antes y seguirá ahí
717
+ // después — la revisión externa 2026-11-22 cazó un botón con borde 2px y
718
+ // outline:none puntuando como foco visible
719
+ const sigOf = el => { const s = getComputedStyle(el);
720
+ return [s.outlineStyle + '/' + s.outlineWidth, s.boxShadow || '',
721
+ ['Top', 'Right', 'Bottom', 'Left'].map(
722
+ k => s['border' + k + 'Width'] + s['border' + k + 'Style'] + s['border' + k + 'Color']).join(';')].join('|');
723
+ };
641
724
  const prevFocus = document.activeElement;
642
725
  for (const el of stops) {
726
+ const before = sigOf(el);
643
727
  try { el.focus(); } catch (e) { /* no enfocable */ }
644
728
  if (activeEl() !== el) {
645
729
  out.focusFail.push({ example: path(el), why: 'nofocus' });
646
730
  continue;
647
731
  }
648
732
  const s = getComputedStyle(el);
733
+ const changed = sigOf(el) !== before;
649
734
  const outline = s.outlineStyle !== 'none' && parseFloat(s.outlineWidth || '0') > 0;
650
735
  const shadow = s.boxShadow && s.boxShadow !== 'none';
651
736
  const edgePx = ['Top', 'Right', 'Bottom', 'Left'].some(
652
737
  k => parseFloat(s['border' + k + 'Width'] || '0') >= 2
653
738
  && s['border' + k + 'Style'] !== 'none');
654
739
  if (!outline && !shadow && !edgePx) out.focus.push(path(el));
740
+ else if (!changed && out.focusReview.length < 20)
741
+ out.focusReview.push({ example: path(el), why: 'static-appearance' });
655
742
  const fgf = parseCol(s.color);
656
743
  const bgf = bgOf(el);
657
744
  if (fgf && !bgf.image) {
@@ -788,6 +875,13 @@ def audit_dom(data, url='(rendered)', lang='en', color_scheme='light'):
788
875
  _add(findings, lang, 'low', '2.4.7', 'focus_not_focusable',
789
876
  examples=[f['example'] for f in data['focusFail']],
790
877
  n=len(data['focusFail']), det=', '.join(f['example'] for f in data['focusFail'][:4]))
878
+ # 3b. indicador AMBIGUO: hay borde/sombra/outline pero NO cambia al enfocar
879
+ # — decoración permanente, no indicador demostrado. Reseña (low), no fallo:
880
+ # el foco programático no dispara :focus-visible y el veredicto se reserva
881
+ if data.get('focusReview'):
882
+ _add(findings, lang, 'low', '2.4.7', 'focus_static_indicator',
883
+ examples=[f['example'] for f in data['focusReview']],
884
+ n=len(data['focusReview']), det=', '.join(f['example'] for f in data['focusReview'][:4]))
791
885
 
792
886
  # 4. Resto de señales (renderizadas)
793
887
  if data.get('unnamed'):
@@ -872,6 +966,10 @@ def audit_dom(data, url='(rendered)', lang='en', color_scheme='light'):
872
966
  'color_scheme': color_scheme,
873
967
  'nested_iframes': data.get('nested_iframes', 0),
874
968
  'shadow_roots': data.get('shadow_roots', 0),
969
+ # colores computados que ningún parser pudo convertir a sRGB (color
970
+ # spaces exóticos): DECLARADOS, jamás omitidos en silencio
971
+ **({'unparsed_colors': data['colorUnparsed']}
972
+ if data.get('colorUnparsed') else {}),
875
973
  'score': compute_score(findings),
876
974
  'score_note': _t(lang, 'score_note'),
877
975
  'interactive_elements': data.get('elements', 0),
@@ -911,11 +1009,15 @@ _JS_FORM_FILL = r'''() => {
911
1009
  }'''
912
1010
 
913
1011
  _JS_FORM_PRE = r'''() => {
914
- // PRE-submit: la ayuda ordinaria que ya existía (describedby, contexto).
915
- // Sin esto, "Tu email" contaba como identificación de error y "Use…"
916
- // como sugerencia — la crítica externa lo destapó: ayuda ≠ error.
1012
+ // PRE-submit: la ayuda ordinaria que ya existía (describedby, contexto,
1013
+ // alertas vivas). Sin esto, "Tu email" contaba como identificación de error
1014
+ // y "Use…" como sugerencia — la crítica externa lo destapó: ayuda ≠ error.
917
1015
  const FIELDS_JS = 'input:not([type=hidden]):not([type=submit]):not([type=button]):not([type=reset]):not([type=image]), select, textarea';
918
- const pre = {};
1016
+ const pre = { __alerts: [] };
1017
+ for (const a of document.querySelectorAll('[role=alert], [aria-live]')) {
1018
+ const t = (a.innerText || '').trim();
1019
+ if (t) pre.__alerts.push(t);
1020
+ }
919
1021
  for (const el of document.querySelectorAll(FIELDS_JS)) {
920
1022
  if (el.disabled) continue;
921
1023
  const key = (el.name || el.id || el.type) + '@' + (el.form ? (el.form.id || el.form.action || '') : '');
@@ -939,8 +1041,14 @@ _JS_FORM_STATE = r'''(pre) => {
939
1041
  const RX_SUG = /(format|example|ejemplo|usa |use |dd\/mm|mm\/dd|pattern|como |like |must be|debe)/i;
940
1042
  pre = pre || {};
941
1043
  const out = { forms: [], alerts: 0 };
1044
+ const prev_alerts = (pre.__alerts || []);
942
1045
  for (const a of document.querySelectorAll('[role=alert], [aria-live]')) {
943
- if ((a.innerText || '').trim() && RX_ERR.test(a.innerText)) out.alerts++;
1046
+ const t = (a.innerText || '').trim();
1047
+ // SOLO alertas NUEVAS o CAMBIADAS tras el envío cuentan como
1048
+ // identificación del error (revisión externa, 3ª pasada): una alerta
1049
+ // AJENA preexistente en la página hacia 100 al formulario que fallaba
1050
+ // en silencio
1051
+ if (t && RX_ERR.test(t) && !prev_alerts.includes(t)) out.alerts++;
944
1052
  }
945
1053
  const FIELDS_JS = 'input:not([type=hidden]):not([type=submit]):not([type=button]):not([type=reset]):not([type=image]), select, textarea';
946
1054
  for (const f of document.querySelectorAll('form')) {
@@ -952,7 +1060,9 @@ _JS_FORM_STATE = r'''(pre) => {
952
1060
  const key = (el.name || el.id || el.type) + '@' + (f.id || f.action || '');
953
1061
  const shot_before = pre[key] || {};
954
1062
  let identified = false, sugerido = false;
955
- if (el.getAttribute('aria-invalid') === 'true') identified = true;
1063
+ // aria-invalid SOLO no identifica (3.3.1 exige TEXTO que describa el
1064
+ // error): el atributo marca el estado, no lo explica — cuenta únicamente
1065
+ // acompañado de texto vía describedby/contexto/mensaje nativo abajo
956
1066
  const db = el.getAttribute('aria-describedby');
957
1067
  if (db) for (const id of db.split(/\s+/)) {
958
1068
  const r = document.getElementById(id);
@@ -1022,16 +1132,13 @@ def audit_forms(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1022
1132
  """3.3.1 Error Identification / 3.3.3 Error Suggestion — the guided flow:
1023
1133
  fill every validatable field with INVALID data, really submit, then judge
1024
1134
  how errors are identified and announced in the post-submit DOM."""
1025
- from playwright.sync_api import sync_playwright
1026
- with sync_playwright() as p:
1027
- nav = _get_browser(p, preferred=browser)
1028
- ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1029
- page = ctx.new_page() if auth_state else nav.new_page()
1135
+ nav = _get_browser(preferred=browser)
1136
+ page, close_page = _pooled_page(nav, auth_state)
1137
+ try:
1030
1138
  try:
1031
1139
  page.goto(url, wait_until='load', timeout=timeout * 1000)
1032
1140
  page.wait_for_timeout(400)
1033
1141
  except Exception as e: # noqa: BLE001
1034
- nav.close()
1035
1142
  return {'error': _t(lang, 'fetch_error').format(e=e)}
1036
1143
  url_before = page.url
1037
1144
  pre = page.evaluate(_JS_FORM_PRE)
@@ -1043,7 +1150,8 @@ def audit_forms(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1043
1150
  page.wait_for_timeout(900)
1044
1151
  navigated = page.url.split('#')[0] != url_before.split('#')[0]
1045
1152
  state = None if navigated else page.evaluate(_JS_FORM_STATE, pre)
1046
- nav.close()
1153
+ finally:
1154
+ close_page()
1047
1155
 
1048
1156
  findings = []
1049
1157
 
@@ -1064,6 +1172,12 @@ def audit_forms(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1064
1172
  suggested_fields = sum(f['suggested'] for f in state['forms'])
1065
1173
  if error_fields > 0 and suggested_fields == 0:
1066
1174
  add('low', '3.3.3', 'form_error_no_suggestion', n=error_fields)
1175
+ elif not touched and state is not None and state['forms']:
1176
+ # alcance declarado (revisión externa, 3ª pasada): un formulario sin
1177
+ # NINGÚN campo rellenable con dato inválido (solo casillas/radios)
1178
+ # devolvía 100 sin haber probado nada — esto es una reseña de alcance,
1179
+ # no una aprobación
1180
+ add('low', '3.3.1', 'form_untestable', n=len(state['forms']))
1067
1181
 
1068
1182
  from .a11yaudit import compute_score
1069
1183
  return {
@@ -1088,77 +1202,87 @@ def sr_transcript(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1088
1202
  structure; this function returns it as prose an agent can READ and
1089
1203
  understand from a blind user's perspective.
1090
1204
  """
1091
- # J4 (ronda 4): el driver de playwright NUNCA se paraba — una fuga
1092
- # de proceso por llamada en un servidor MCP de larga vida
1093
- from playwright.sync_api import sync_playwright
1094
- pw = sync_playwright().start()
1205
+ # J4 (ronda 4): el driver de playwright NUNCA se paraba — una fuga de
1206
+ # proceso por llamada en un servidor MCP de larga vida. Hoy el POOL posee
1207
+ # el driver (browser y playwright mueren juntos en _close_pool, atexit
1208
+ # incluido): esta función solo pide prestado y devuelve la página.
1209
+ nav = _get_browser(preferred=browser)
1210
+ page, close_page = _pooled_page(nav, auth_state)
1095
1211
  try:
1096
- nav = _get_browser(pw, preferred=browser)
1097
- ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1098
- page = ctx.new_page() if auth_state else nav.new_page()
1099
1212
  try:
1100
1213
  page.goto(url, wait_until='load', timeout=timeout * 1000)
1101
1214
  page.wait_for_timeout(400)
1102
1215
  except Exception as e:
1103
- ctx.close()
1104
- _close_pool()
1105
1216
  return {'error': str(e)[:100]}
1106
1217
 
1107
1218
  try:
1108
1219
  tree = page.locator('body').aria_snapshot()
1109
1220
  except Exception:
1110
1221
  tree = None
1111
- try:
1112
- ctx.close()
1113
- except Exception:
1114
- pass
1115
-
1116
- if not tree:
1117
- return {'url': url, 'mode': 'sr-transcript',
1118
- 'error': 'accessibility tree not available (Playwright >= 1.49 required)'}
1119
-
1120
- # parse the YAML-like snapshot into linearized announcements
1121
- import re
1122
- announcements = []
1123
- for line in tree.split('\n'):
1124
- stripped = line.strip()
1125
- if not stripped.startswith('- '):
1126
- continue
1127
- # quitar el guion inicial; el resto es el anuncio
1128
- announcement = stripped[2:].rstrip(':')
1129
- if announcement:
1130
- announcements.append(announcement)
1131
-
1132
- return {
1133
- 'url': url,
1134
- 'mode': 'sr-transcript',
1135
- 'announcements': announcements[:200], # cap
1136
- 'total': len(announcements),
1137
- 'arbol_raw': tree[:5000] if len(tree) > 5000 else tree,
1138
- 'note': ('Linearized announcement order — what a screen reader user hears. '
1139
- 'Roles and names as computed by the browser. Use this to understand '
1140
- 'the page from a blind user\'s perspective.'),
1141
- }
1222
+ finally:
1223
+ close_page()
1224
+
1225
+ if not tree:
1226
+ return {'url': url, 'mode': 'sr-transcript',
1227
+ 'error': 'accessibility tree not available (Playwright >= 1.49 required)'}
1228
+
1229
+ # parse the YAML-like snapshot into linearized announcements
1230
+ import re
1231
+ announcements = []
1232
+ for line in tree.split('\n'):
1233
+ stripped = line.strip()
1234
+ if not stripped.startswith('- '):
1235
+ continue
1236
+ # quitar el guion inicial; el resto es el anuncio
1237
+ announcement = stripped[2:].rstrip(':')
1238
+ if announcement:
1239
+ announcements.append(announcement)
1142
1240
 
1241
+ return {
1242
+ 'url': url,
1243
+ 'mode': 'sr-transcript',
1244
+ 'announcements': announcements[:200], # cap
1245
+ 'total': len(announcements),
1246
+ 'arbol_raw': tree[:5000] if len(tree) > 5000 else tree,
1247
+ 'note': ('Linearized announcement order — what a screen reader user hears. '
1248
+ 'Roles and names as computed by the browser. Use this to understand '
1249
+ 'the page from a blind user\'s perspective.'),
1250
+ }
1251
+ # (6a pasada) identidad de los tooltips visibles AHORA: una sola
1252
+ # definicion para antes/durante/despues, en vez de tres literales
1253
+ _TOOLTIPS_VISIBLE_JS = (
1254
+ "() => [...document.querySelectorAll("
1255
+ "'[role=tooltip], [class*=tooltip], [class*=popover]')]"
1256
+ ".filter(el => {"
1257
+ " if (el.checkVisibility) "
1258
+ " return el.checkVisibility({checkOpacity: true, checkVisibilityCSS: true});"
1259
+ " const s = getComputedStyle(el);"
1260
+ " const box = el.getBoundingClientRect();"
1261
+ " return el.offsetParent !== null && s.visibility !== 'hidden'"
1262
+ " && parseFloat(s.opacity || '1') > 0.01 && box.width > 0;"
1263
+ "})"
1264
+ ".map(el => el.tagName + '#' + (el.id || '') + '.' + (el.className.toString().slice(0, 30)))")
1143
1265
 
1144
- finally:
1145
- try:
1146
- pw.stop()
1147
- except Exception: # noqa: BLE001
1148
- pass
1149
1266
  _JS_HOVER_TEST = r'''() => {
1150
- // find elements that show tooltips/overlays on hover
1267
+ // find elements that show tooltips/overlays on hover. (6a pasada) cada
1268
+ // candidato se SELLA con data-a11yhover=<i>: el hover va a ESTE nodo --
1269
+ // el selector tag/id antiguo probaba el PRIMER nodo homonimo dos veces
1270
+ // y se perdia el tooltip persistente del segundo
1151
1271
  const candidates = [];
1272
+ let n = 0;
1152
1273
  for (const el of document.querySelectorAll('[title], [data-tooltip], [aria-describedby]')) {
1153
1274
  if (candidates.length >= 10) break;
1154
1275
  const r = el.getBoundingClientRect();
1155
1276
  if (r.width > 10 && r.height > 10 && r.top >= 0 && r.top < innerHeight) {
1277
+ el.setAttribute('data-a11yhover', String(n));
1156
1278
  candidates.push({
1157
1279
  tag: el.tagName.toLowerCase(),
1158
1280
  id: el.id || '',
1281
+ idx: n,
1159
1282
  desc: el.getAttribute('aria-describedby') || el.getAttribute('title') || '',
1160
1283
  rect: {x: r.x, y: r.y, w: r.width, h: r.height}
1161
1284
  });
1285
+ n++;
1162
1286
  }
1163
1287
  }
1164
1288
  return candidates;
@@ -1166,64 +1290,47 @@ _JS_HOVER_TEST = r'''() => {
1166
1290
 
1167
1291
  def audit_hover(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1168
1292
  """1.4.13 Content on Hover or Focus: do tooltips dismiss on Escape?"""
1169
- from playwright.sync_api import sync_playwright
1170
- with sync_playwright() as p:
1171
- nav = _get_browser(p, preferred=browser)
1172
- ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1173
- page = ctx.new_page() if auth_state else nav.new_page()
1293
+ nav = _get_browser(preferred=browser)
1294
+ page, close_page = _pooled_page(nav, auth_state)
1295
+ try:
1174
1296
  try:
1175
1297
  page.goto(url, wait_until='load', timeout=timeout * 1000)
1176
1298
  page.wait_for_timeout(400)
1177
1299
  except Exception as e:
1178
- nav.close()
1179
1300
  return {'error': str(e)[:100]}
1301
+ # tooltips visibles ANTES de tocar nada: los preexistentes (ajenos)
1302
+ # jamas se atribuyen a un control por el mero hecho de hoverear
1303
+ _preexisting_tips = page.evaluate(_TOOLTIPS_VISIBLE_JS)
1180
1304
 
1181
1305
  candidates = page.evaluate(_JS_HOVER_TEST)
1182
1306
  no_dismissibles = []
1183
- for c in candidates[:8]:
1184
- try:
1185
- # hover sobre el elemento
1186
- sel = f'{c["tag"]}#{c["id"]}' if c['id'] else c['tag']
1187
- page.hover(sel, timeout=2000)
1188
- page.wait_for_timeout(400)
1189
- # identidad de los tooltips visibles ANTES (por elemento, no
1190
- # por recuento global: other tooltip podía aparecer a la vez y
1191
- # el contador antiguo enmascaraba un cierre correcto)
1192
- before = page.evaluate(
1193
- "() => [...document.querySelectorAll("
1194
- "'[role=tooltip], [class*=tooltip], [class*=popover]')]"
1195
- ".filter(el => {"
1196
- " if (el.checkVisibility) "
1197
- " return el.checkVisibility({checkOpacity: true, checkVisibilityCSS: true});"
1198
- " const s = getComputedStyle(el);"
1199
- " const box = el.getBoundingClientRect();"
1200
- " return el.offsetParent !== null && s.visibility !== 'hidden'"
1201
- " && parseFloat(s.opacity || '1') > 0.01 && box.width > 0;"
1202
- "})"
1203
- ".map(el => el.tagName + '#' + (el.id || '') + '.' + (el.className.toString().slice(0, 30)))")
1204
- if not before:
1205
- continue # nada visible → no aplica
1206
- # Escape
1207
- page.keyboard.press('Escape')
1208
- page.wait_for_timeout(300)
1209
- after = page.evaluate(
1210
- "() => [...document.querySelectorAll("
1211
- "'[role=tooltip], [class*=tooltip], [class*=popover]')]"
1212
- ".filter(el => {"
1213
- " if (el.checkVisibility) "
1214
- " return el.checkVisibility({checkOpacity: true, checkVisibilityCSS: true});"
1215
- " const s = getComputedStyle(el);"
1216
- " const box = el.getBoundingClientRect();"
1217
- " return el.offsetParent !== null && s.visibility !== 'hidden'"
1218
- " && parseFloat(s.opacity || '1') > 0.01 && box.width > 0;"
1219
- "})"
1220
- ".map(el => el.tagName + '#' + (el.id || '') + '.' + (el.className.toString().slice(0, 30)))")
1221
- if set(before) <= set(after):
1222
- # los mismos (o más) siguen visibles: no se cerró con Escape
1223
- no_dismissibles.append(f'{c["tag"]}#{c["id"] or "no-id"}')
1224
- except Exception:
1225
- continue
1226
- nav.close()
1307
+ try:
1308
+ for c in candidates[:8]:
1309
+ try:
1310
+ # (6a pasada) hover sobre ESTE nodo por su sello; y solo
1311
+ # cuentan los tooltips que APARECEN al activarlo -- un
1312
+ # tooltip ajeno ya visible no se atribuye al control
1313
+ page.hover(f'[data-a11yhover="{c["idx"]}"]', timeout=2000)
1314
+ page.wait_for_timeout(400)
1315
+ _during = page.evaluate(_TOOLTIPS_VISIBLE_JS)
1316
+ _new_tips = [t for t in _during if t not in _preexisting_tips]
1317
+ if not _new_tips:
1318
+ continue # este control no mostro nada nuevo: no aplica
1319
+ page.keyboard.press('Escape')
1320
+ page.wait_for_timeout(300)
1321
+ _after_esc = page.evaluate(_TOOLTIPS_VISIBLE_JS)
1322
+ if set(_new_tips) <= set(_after_esc):
1323
+ # los mismos (o mas) siguen visibles: no se cerro
1324
+ no_dismissibles.append(f'{c["tag"]}#{c["id"] or "no-id"}')
1325
+ except Exception:
1326
+ continue
1327
+ finally:
1328
+ # limpiar los sellos: la pagina queda como estaba
1329
+ page.evaluate(
1330
+ "() => document.querySelectorAll('[data-a11yhover]')"
1331
+ ".forEach(el => el.removeAttribute('data-a11yhover'))")
1332
+ finally:
1333
+ close_page()
1227
1334
 
1228
1335
  findings = []
1229
1336
  if no_dismissibles:
@@ -1242,22 +1349,42 @@ def audit_hover(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1242
1349
 
1243
1350
 
1244
1351
  _JS_SPACING = r'''() => {
1245
- // WCAG 1.4.12 Text Spacing: the documented override set, applied globally,
1246
- // then measure which texts get clipped by height-constrained containers.
1352
+ // WCAG 1.4.12 (5a pasada): ANTES y DESPUES de inyectar los overrides, y
1353
+ // el recorte del CONTENEDOR (propio o de cualquier ancestro con overflow
1354
+ // hidden O clip) -- antes: una sola medicion acusaba parrafos ya recortados
1355
+ // de antes y no veia los que empezaban a recortarse con el espaciado.
1356
+ const SEL = 'p, li, h1, h2, h3, h4, h5, h6, a, span, label';
1357
+ const clippedBy = el => {
1358
+ let n = el;
1359
+ while (n && n !== document.body) {
1360
+ const s = getComputedStyle(n);
1361
+ const modes = [s.overflow, s.overflowY, s.overflowX];
1362
+ if (modes.includes('hidden') || modes.includes('clip')) {
1363
+ const rb = n.getBoundingClientRect(), re = el.getBoundingClientRect();
1364
+ if (re.bottom > rb.bottom + 3 || re.right > rb.right + 3) return true;
1365
+ return false; // ancestro recortante y el elemento dentro: no clip
1366
+ }
1367
+ n = n.parentElement;
1368
+ }
1369
+ return false;
1370
+ };
1371
+ const snap = {};
1372
+ document.querySelectorAll(SEL).forEach((el, i) => {
1373
+ if (!el.offsetParent) return;
1374
+ snap[i] = clippedBy(el);
1375
+ });
1247
1376
  const css = document.createElement('style');
1248
1377
  css.id = 'a11y-spacing-1412';
1249
1378
  css.textContent = '*{line-height:1.5!important;letter-spacing:0.12em!important;'
1250
1379
  + 'word-spacing:0.16em!important} p{margin-bottom:2em!important}';
1251
1380
  document.head.appendChild(css);
1252
1381
  const clip = [];
1253
- for (const el of document.querySelectorAll('p, li, h1, h2, h3, h4, h5, h6, a, span, label')) {
1254
- if (clip.length >= 15) break;
1255
- if (!el.offsetParent) continue;
1256
- const s = getComputedStyle(el);
1257
- const clipped = (s.overflow === 'hidden' || s.overflowY === 'hidden')
1258
- && el.scrollHeight > el.clientHeight + 3;
1259
- if (clipped) clip.push(el.tagName.toLowerCase() + (el.id ? '#' + el.id : ''));
1260
- }
1382
+ document.querySelectorAll(SEL).forEach((el, i) => {
1383
+ if (clip.length >= 15) return;
1384
+ if (!el.offsetParent) return;
1385
+ if (!snap[i] && clippedBy(el))
1386
+ clip.push(el.tagName.toLowerCase() + (el.id ? '#' + el.id : ''));
1387
+ });
1261
1388
  css.remove();
1262
1389
  return clip;
1263
1390
  }'''
@@ -1266,6 +1393,7 @@ _JS_HOVER = r'''(i) => {
1266
1393
  const el = document.querySelector('[data-a11yidx="' + i + '"]');
1267
1394
  if (!el) return null;
1268
1395
  const parseCol = c => { const m = /rgba?\(([^)]+)\)/.exec(c || '');
1396
+ if(!m){const m3=/color\(\s*srgb\s+([^)]+)\)/.exec(c||'');if(m3){const ps=m3[1].split('/');const rgb=ps[0].trim().split(/\s+/);const cv=v=>v.endsWith('%')?parseFloat(v)*2.55:parseFloat(v)*255;const al=ps.length>1?(ps[1].trim().endsWith('%')?parseFloat(ps[1])/100:parseFloat(ps[1])):1;if(rgb.length>=3&&isFinite(cv(rgb[0]))&&isFinite(cv(rgb[1]))&&isFinite(cv(rgb[2]))&&isFinite(al))return{r:Math.round(cv(rgb[0])),g:Math.round(cv(rgb[1])),b:Math.round(cv(rgb[2])),a:al};}return null;}
1269
1397
  if (!m) return null;
1270
1398
  const p = m[1].split(',').map(x => parseFloat(x));
1271
1399
  return { r: p[0], g: p[1], b: p[2], a: p.length > 3 ? p[3] : 1 }; };
@@ -1345,21 +1473,23 @@ def audit_reflow(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1345
1473
  un viewport de 320px, no emular zoom con CSS (validado empíricamente:
1346
1474
  el truco de zoom CSS marca en falso páginas sanas porque no re-lleva a cabo
1347
1475
  el layout)."""
1348
- from playwright.sync_api import sync_playwright
1349
- with sync_playwright() as p:
1350
- nav = _get_browser(p, preferred=browser)
1351
- page = nav.new_page(viewport={'width': 1280, 'height': 800})
1476
+ nav = _get_browser(preferred=browser)
1477
+ # auth_state aplica por fin aquí también (la revisión externa lo cazó:
1478
+ # el parámetro existía y se IGNORABA — con la cookie fuera, la pantalla
1479
+ # de login puntuaba 100); con sesión, el viewport viaja en el contexto
1480
+ page, close_page = _pooled_page(nav, auth_state, viewport={'width': 1280, 'height': 800})
1481
+ try:
1352
1482
  try:
1353
1483
  page.goto(url, wait_until='load', timeout=timeout * 1000)
1354
1484
  page.wait_for_timeout(300)
1355
1485
  except Exception as e: # noqa: BLE001
1356
- nav.close()
1357
1486
  return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
1358
1487
 
1359
1488
  page.set_viewport_size({'width': 320, 'height': 800})
1360
1489
  page.wait_for_timeout(500)
1361
1490
  r320 = page.evaluate(_JS_OVERFLOW)
1362
- nav.close()
1491
+ finally:
1492
+ close_page()
1363
1493
 
1364
1494
  findings = []
1365
1495
 
@@ -1467,16 +1597,13 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1467
1597
  ESCAPE libera el ciclo. Un modal que cicla y suelta con Escape es correcto;
1468
1598
  uno que no suelta es trampa — hallazgo 'high'.
1469
1599
  """
1470
- from playwright.sync_api import sync_playwright
1471
- with sync_playwright() as p:
1472
- nav = _get_browser(p, preferred=browser)
1473
- ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1474
- page = ctx.new_page() if auth_state else nav.new_page()
1600
+ nav = _get_browser(preferred=browser)
1601
+ page, close_page = _pooled_page(nav, auth_state)
1602
+ try:
1475
1603
  try:
1476
1604
  page.goto(url, wait_until='load', timeout=timeout * 1000)
1477
1605
  page.wait_for_timeout(400)
1478
1606
  except Exception as e: # noqa: BLE001
1479
- nav.close()
1480
1607
  return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
1481
1608
 
1482
1609
  page.evaluate("document.querySelectorAll('[data-a11ystop]').forEach(e => {"
@@ -1496,9 +1623,14 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1496
1623
  seq.append(stop)
1497
1624
  if stop not in paths:
1498
1625
  paths[stop] = page.evaluate(_STOP_META, stop)
1499
- # detección de ciclo: el final de la secuencia se repite con periodo p
1626
+ # detección de ciclo: el final de la secuencia se repite con periodo p.
1627
+ # El tope de periodo sale de la SECUENCIA OBSERVADA (len/2; con 2
1628
+ # repeticiones completas exigidas ya no puede afirmar un periodo que
1629
+ # no ocurrió dos veces) — el tope fijo de 12 dejaba trampas de 13+
1630
+ # paradas sin hallazgo consumiendo el presupuesto entero (revisión
1631
+ # externa, 3ª pasada)
1500
1632
  cycle = None
1501
- for p_ in range(1, min(12, len(seq) // 2) + 1):
1633
+ for p_ in range(1, len(seq) // 2 + 1):
1502
1634
  if seq[-p_:] == seq[-2 * p_:-p_] and len(set(seq[-p_:])) >= 1:
1503
1635
  # needs al menos 2 repeticiones completas del periodo
1504
1636
  reps = sum(1 for k in range(len(seq) - p_, 0, -p_)
@@ -1506,6 +1638,9 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1506
1638
  if reps >= 2:
1507
1639
  cycle = seq[-p_:]
1508
1640
  break
1641
+ # presupuesto agotado sin círculo completo: el veredicto de trampa es
1642
+ # INDECISO, no «sin trampa» — se declara
1643
+ budget_exhausted = (cycle is None and len(seq) >= max_steps)
1509
1644
 
1510
1645
  # 3.2.1: ¿el foco provocó navegación? (context destroyed = navegación)
1511
1646
  focus_navigated = None
@@ -1515,22 +1650,45 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1515
1650
  except Exception:
1516
1651
  focus_navigated = url_before + ' → (navigated away)'
1517
1652
 
1518
- # 3.2.2: ¿un select provoca navegación al cambiar?
1653
+ # 3.2.2: ¿un select provoca navegación al cambiar? (6a pasada) TODOS
1654
+ # los selects (hasta 3), y el AVISO PREVIO se juzga aparte de la
1655
+ # observación: un aria-describedby que anuncia el cambio EXIME; la
1656
+ # navegación silenciosa se registra por CONTROL — antes solo se
1657
+ # probaba el primer select y uno CON aviso disparaba el hallazgo
1519
1658
  input_navigated = None
1520
1659
  input_elem = None
1660
+ select_observations = []
1521
1661
  if not focus_navigated:
1522
1662
  try:
1523
- sel = page.query_selector('select')
1524
- if sel:
1663
+ url_pre = page.url
1664
+ for sel in page.query_selector_all('select')[:3]:
1525
1665
  opts = sel.query_selector_all('option')
1526
- if len(opts) > 1:
1527
- url_pre = page.url
1666
+ if len(opts) <= 1:
1667
+ continue
1668
+ _advisory = sel.evaluate(
1669
+ 'el => { const db = el.getAttribute("aria-describedby");'
1670
+ ' if (!db) return false;'
1671
+ ' return db.split(/\\s+/).some(id => {'
1672
+ ' const r = document.getElementById(id);'
1673
+ ' return r && (r.innerText || "").trim(); }); }')
1674
+ _name = (sel.get_attribute('aria-label')
1675
+ or sel.get_attribute('id') or 'select')[:40]
1676
+ try:
1528
1677
  sel.select_option(index=1)
1529
- page.wait_for_timeout(600)
1530
- if page.url != url_pre:
1531
- input_navigated = page.url
1532
- input_elem = 'select'
1533
- except Exception:
1678
+ except Exception: # noqa: BLE001
1679
+ continue
1680
+ page.wait_for_timeout(600)
1681
+ if page.url.split('#')[0] != url_pre.split('#')[0]:
1682
+ input_navigated = page.url
1683
+ input_elem = _name
1684
+ select_observations.append(
1685
+ {'control': _name, 'navigated': True,
1686
+ 'prior_advisory': bool(_advisory)})
1687
+ break # la página ya no está: no hay más que probar
1688
+ select_observations.append(
1689
+ {'control': _name, 'navigated': False,
1690
+ 'prior_advisory': bool(_advisory)})
1691
+ except Exception: # noqa: BLE001
1534
1692
  pass
1535
1693
 
1536
1694
  esc_releases = None
@@ -1573,10 +1731,8 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1573
1731
  skip['broken'].append(found['id'])
1574
1732
  except Exception: # noqa: BLE001 — SPA o contexto destruido: sin dato
1575
1733
  pass
1576
- try:
1577
- nav.close()
1578
- except Exception:
1579
- pass
1734
+ finally:
1735
+ close_page()
1580
1736
 
1581
1737
  findings = []
1582
1738
  if focus_navigated:
@@ -1585,7 +1741,9 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1585
1741
  'signal': 'focus_navigates',
1586
1742
  'issue': _t(lang, 'focus_navigates').format(example='un elemento', url=focus_navigated[:60]),
1587
1743
  'remediation': _t(lang, 'focus_navigates_rem')})
1588
- if input_navigated:
1744
+ if input_navigated and not any(o['prior_advisory'] for o in select_observations
1745
+ if o['control'] == input_elem):
1746
+ # navegación REAL sin aviso previo asociado al control que navegó
1589
1747
  findings.append({
1590
1748
  'severity': 'high', 'criterion': CRIT.get(lang, CRIT['es']).get('3.2.2', '3.2.2'),
1591
1749
  'signal': 'input_navigates',
@@ -1615,8 +1773,10 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1615
1773
  'summary': {s_: sum(1 for h in findings if h['severity'] == s_)
1616
1774
  for s_ in ('high', 'medium', 'low')},
1617
1775
  'steps': len(seq),
1776
+ 'select_observations': select_observations,
1618
1777
  'tab_stops': [paths.get(i, f'tab stop {i}') for i in seq],
1619
1778
  'cycle': {'detected': bool(cycle),
1779
+ 'budget_exhausted': budget_exhausted,
1620
1780
  'elements': [paths.get(i, f'tab stop {i}') for i in cycle] if cycle else [],
1621
1781
  'escape_releases': esc_releases},
1622
1782
  'skip_link': {'checked': skip['checked'], 'label': skip.get('label'),
@@ -1759,7 +1919,6 @@ def audit_forced_colors(url, timeout=45, lang='en', auth_state=None, browser='au
1759
1919
  dependen del color del autor pueden quedar invisible_els sobre el fondo
1760
1920
  del sistema), y bordes usados como único indicador visual. Nadie más
1761
1921
  lo automatiza."""
1762
- from playwright.sync_api import sync_playwright
1763
1922
  _JS_FC = r'''() => {
1764
1923
  const invisible_els = [];
1765
1924
  let n = 0;
@@ -1790,10 +1949,9 @@ def audit_forced_colors(url, timeout=45, lang='en', auth_state=None, browser='au
1790
1949
  }'''
1791
1950
  from .a11yaudit import _t as _t_audit, CRIT, compute_score
1792
1951
 
1793
- with sync_playwright() as p:
1794
- nav = _get_browser(p, preferred=browser)
1795
- ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1796
- page = ctx.new_page() if auth_state else nav.new_page()
1952
+ nav = _get_browser(preferred=browser)
1953
+ page, close_page = _pooled_page(nav, auth_state)
1954
+ try:
1797
1955
  try:
1798
1956
  page.goto(url, wait_until='load', timeout=timeout * 1000)
1799
1957
  page.wait_for_timeout(400)
@@ -1802,9 +1960,9 @@ def audit_forced_colors(url, timeout=45, lang='en', auth_state=None, browser='au
1802
1960
  page.wait_for_timeout(400)
1803
1961
  forced = page.evaluate(_JS_FC)
1804
1962
  except Exception as e: # noqa: BLE001
1805
- nav.close()
1806
1963
  return {'error': _t_audit(lang, 'fetch_error').format(e=e)}
1807
- nav.close()
1964
+ finally:
1965
+ close_page()
1808
1966
 
1809
1967
  findings = []
1810
1968
  if forced['coloredSvgs']:
@@ -1835,31 +1993,37 @@ def audit_reduced_motion(url, timeout=45, lang='en', auth_state=None, browser='a
1835
1993
  vez. Si el número NO baja, el sitio ignora la preferencia del usuario
1836
1994
  (2.2.2: pausa/parada/ocultar; 2.3.3 AAA). Nadie más lo automatiza:
1837
1995
  axe lo deja en revisión manual."""
1838
- from playwright.sync_api import sync_playwright
1839
1996
  _JS_RM = r'''() => {
1840
- let n = 0, examples = [];
1997
+ // (5a pasada) por ELEMENTO y con estado de reproduccion: una lista con
1998
+ // una animacion infinita y otra finita no contaba (iterationCount es
1999
+ // una LISTA 'infinite,1'), y pausar por CSS daba 'no respeta' aunque
2000
+ // el movimiento estuviera detenido
2001
+ const out = {};
1841
2002
  for (const el of document.querySelectorAll('*')) {
1842
- if (n >= 40) break;
2003
+ if (Object.keys(out).length >= 40) break;
1843
2004
  const cs = getComputedStyle(el);
1844
- if (cs.animationIterationCount !== 'infinite' || cs.animationName === 'none') continue;
2005
+ const counts = (cs.animationIterationCount || '').split(',');
1845
2006
  const durs = (cs.animationDuration || '0s').split(',').map(
1846
2007
  x => { const v = parseFloat(x) || 0; return x.includes('ms') ? v / 1000 : v; });
1847
- const dur = Math.max(...durs, 0);
1848
- if (dur <= 0.15) continue;
1849
- n++;
1850
- if (examples.length < 6) examples.push(
1851
- el.tagName.toLowerCase() + (el.id ? '#' + el.id : '')
1852
- + '.' + String(el.className).slice(0, 25) + ' (' + cs.animationName.slice(0, 30) + ')');
2008
+ let loops = false;
2009
+ for (let i = 0; i < counts.length; i++)
2010
+ if (counts[i].trim() === 'infinite' && (durs[i] || 0) > 0.15) { loops = true; break; }
2011
+ if (!loops) continue;
2012
+ const paused = (cs.animationPlayState || '').split(',').every(p => p.trim() === 'paused');
2013
+ const key = el.tagName.toLowerCase() + (el.id ? '#' + el.id : '')
2014
+ + ':' + String(cs.animationName).slice(0, 40);
2015
+ if (!(key in out)) out[key] = { paused: paused,
2016
+ example: el.tagName.toLowerCase() + (el.id ? '#' + el.id : '')
2017
+ + ' (' + String(cs.animationName).slice(0, 30) + ')' };
1853
2018
  }
1854
2019
  const videos = document.querySelectorAll('video[autoplay]').length;
1855
- return { anims: n, examples: examples, videos };
2020
+ return { anims: out, videos };
1856
2021
  }'''
1857
2022
  from .a11yaudit import _t as _t_audit, CRIT, compute_score
1858
2023
 
1859
- with sync_playwright() as p:
1860
- nav = _get_browser(p, preferred=browser)
1861
- ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1862
- page = ctx.new_page() if auth_state else nav.new_page()
2024
+ nav = _get_browser(preferred=browser)
2025
+ page, close_page = _pooled_page(nav, auth_state)
2026
+ try:
1863
2027
  try:
1864
2028
  page.goto(url, wait_until='load', timeout=timeout * 1000)
1865
2029
  page.wait_for_timeout(600)
@@ -1868,25 +2032,40 @@ def audit_reduced_motion(url, timeout=45, lang='en', auth_state=None, browser='a
1868
2032
  page.wait_for_timeout(600)
1869
2033
  reduced = page.evaluate(_JS_RM)
1870
2034
  except Exception as e: # noqa: BLE001
1871
- nav.close()
1872
2035
  return {'error': _t_audit(lang, 'fetch_error').format(e=e)}
1873
- nav.close()
1874
-
1875
- respects = reduced['anims'] < normal['anims']
2036
+ finally:
2037
+ close_page()
2038
+
2039
+ # veredicto por ELEMENTO (5a pasada): solo cuentan las que CORREN (las
2040
+ # pausadas por CSS estan controladas); reduccion total, PARCIAL (unas
2041
+ # paran y otras siguen -- antes "respeta" con una viva) y sin datos
2042
+ _norm = {k: v for k, v in (normal.get('anims') or {}).items() if not v.get('paused')}
2043
+ _red = {k for k, v in (reduced.get('anims') or {}).items() if not v.get('paused')}
2044
+ _n, _r = len(_norm), len(_red)
2045
+ _stopped = [k for k in _norm if k not in _red]
2046
+ motion = {'normal': _n, 'reduced': _r, 'stopped': len(_stopped),
2047
+ 'partial': bool(_stopped) and _r > 0,
2048
+ 'paused_css': sum(1 for v in (normal.get('anims') or {}).values() if v.get('paused')),
2049
+ 'still_running': [_norm[k]['example'] for k in _norm if k in _red][:6]}
2050
+ respects = (True if (_n > 0 and _r == 0) else (False if _n > 0 else None))
1876
2051
  findings = []
1877
- if normal['anims'] > 0 and not respects:
2052
+ if _n > 0 and not respects:
1878
2053
  findings.append({
1879
2054
  'severity': 'medium', 'criterion': CRIT.get(lang, CRIT['es']).get('2.2.2', '2.2.2'),
1880
2055
  'signal': 'reduced_motion_ignored',
1881
- 'issue': _t_audit(lang, 'reduced_motion_ignored').format(
1882
- n=normal['anims'], nr=reduced['anims']),
2056
+ 'issue': _t_audit(lang, 'reduced_motion_ignored').format(n=_n, nr=_r),
1883
2057
  'remediation': _t_audit(lang, 'reduced_motion_ignored_rem'),
1884
- 'examples': normal['examples'][:4]})
2058
+ 'examples': (motion['still_running']
2059
+ or [v['example'] for v in _norm.values()])[:4]})
1885
2060
  order = {'high': 0, 'medium': 1, 'low': 2}
1886
2061
  findings.sort(key=lambda h: order[h['severity']])
1887
2062
  return {
1888
2063
  'mode': 'reduced-motion', 'url': url,
1889
- 'normal': normal, 'reduced': reduced,
2064
+ 'normal': {'anims': len(normal.get('anims') or {}),
2065
+ 'videos': normal.get('videos', 0)},
2066
+ 'reduced': {'anims': len(reduced.get('anims') or {}),
2067
+ 'videos': reduced.get('videos', 0)},
2068
+ 'motion': motion,
1890
2069
  'respects': respects,
1891
2070
  'score': compute_score(findings),
1892
2071
  'findings': findings,
@@ -1903,72 +2082,92 @@ def audit_dom_url(url, timeout=45, lang='en', auth_state=None, browser='auto', c
1903
2082
  :hover reales de los primeros controles marcados. auth_state: ruta a un
1904
2083
  storage_state de Playwright (cookies/localStorage exportados con la sesión
1905
2084
  iniciada) para auditar detrás de login."""
1906
- from playwright.sync_api import sync_playwright
1907
- with sync_playwright() as p:
1908
- nav = _get_browser(p, preferred=browser)
1909
- ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1910
- page = ctx.new_page() if auth_state else nav.new_page()
2085
+ nav = _get_browser(preferred=browser)
2086
+ page, close_page = _pooled_page(nav, auth_state)
2087
+ _resp = None
2088
+ page_url_final = None
2089
+ try:
1911
2090
  if color_scheme in ('dark', 'light'):
1912
2091
  # contraste por esquema: los temas oscuros fallan donde el claro
1913
2092
  # pasa — nadie audita ambos (axe tampoco)
1914
2093
  page.emulate_media(color_scheme=color_scheme)
1915
2094
  try:
1916
- page.goto(url, wait_until='load', timeout=timeout * 1000)
2095
+ _resp = page.goto(url, wait_until='load', timeout=timeout * 1000)
1917
2096
  page.wait_for_timeout(400)
1918
2097
  except Exception as e: # noqa: BLE001
1919
2098
  if not page.content() or page.url in ('about:blank', ''):
1920
- nav.close()
1921
2099
  return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
1922
- try:
1923
- data = page.evaluate(_JS, MAX_EXAMPLES)
1924
- # 1.4.12: inject the WCAG spacing overrides, count clipped texts
1925
- data['spacingClipped'] = page.evaluate(_JS_SPACING)
1926
- # 1.4.3 real: captura + muestreo píxel a píxel de las zonas sobre
1927
- # imagen/degradado que el contraste computado no puede calcular
1928
- # (main frame; los iframes quedan como conteo de "revisar")
1929
- measured = []
1930
- for z in (data.get('contrastZones') or [])[:8]:
1931
- try:
1932
- c = parse_color(z['fg'])
1933
- if not c:
1934
- continue
1935
- m = _samples_background(
1936
- page.locator(f'[data-a11ytxt="{z["i"]}"]'),
1937
- {'x': z.get('x', 0), 'y': z.get('y', 0),
1938
- 'width': z.get('w', 1400), 'height': z.get('h', 400)}, c)
1939
- if m:
1940
- measured.append({'example': z['example'], 'fg': z['fg'],
1941
- 'large': bool(z.get('large')),
1942
- 'measured': m})
1943
- except Exception: # noqa: BLE001
1944
- continue
1945
- data['contrastMeasured'] = measured
1946
- # iframes same-origin: mismo colector por frame
1947
- subframes = []
1948
- for fr in page.frames[1:5]:
1949
- try:
1950
- subframes.append(fr.evaluate(_JS, MAX_EXAMPLES))
1951
- except Exception: # noqa: BLE001
1952
- continue # cross-origin o no escaneable
1953
- data['iframes_data'] = subframes
1954
- # hover real sobre los controles marcados
1955
- hover = []
1956
- for i in range(min(10, int(data.get('marks', 0)))):
1957
- try:
1958
- page.hover(f'[data-a11yidx="{i}"]', timeout=1000)
1959
- r = page.evaluate(_JS_HOVER, i)
1960
- if r and r['ratio'] < 3:
1961
- hover.append(dict(r, example=f'hover #{i}'))
1962
- except Exception: # noqa: BLE001
2100
+ data = page.evaluate(_JS, MAX_EXAMPLES)
2101
+ # 1.4.12: inject the WCAG spacing overrides, count clipped texts
2102
+ data['spacingClipped'] = page.evaluate(_JS_SPACING)
2103
+ # 1.4.3 real: captura + muestreo píxel a píxel de las zonas sobre
2104
+ # imagen/degradado que el contraste computado no puede calcular
2105
+ # (main frame; los iframes quedan como conteo de "revisar")
2106
+ measured = []
2107
+ for z in (data.get('contrastZones') or [])[:8]:
2108
+ try:
2109
+ c = parse_color(z['fg'])
2110
+ if not c:
1963
2111
  continue
1964
- data['hover'] = hover
1965
- finally:
2112
+ m = _samples_background(
2113
+ page.locator(f'[data-a11ytxt="{z["i"]}"]'),
2114
+ {'x': z.get('x', 0), 'y': z.get('y', 0),
2115
+ 'width': z.get('w', 1400), 'height': z.get('h', 400)}, c)
2116
+ if m:
2117
+ measured.append({'example': z['example'], 'fg': z['fg'],
2118
+ 'large': bool(z.get('large')),
2119
+ 'measured': m})
2120
+ except Exception: # noqa: BLE001
2121
+ continue
2122
+ data['contrastMeasured'] = measured
2123
+ # iframes same-origin: mismo colector por frame
2124
+ subframes = []
2125
+ for fr in page.frames[1:5]:
1966
2126
  try:
1967
- ctx.close()
1968
- except Exception:
1969
- pass
2127
+ subframes.append(fr.evaluate(_JS, MAX_EXAMPLES))
2128
+ except Exception: # noqa: BLE001
2129
+ continue # cross-origin o no escaneable
2130
+ data['iframes_data'] = subframes
2131
+ # hover real sobre los controles marcados
2132
+ hover = []
2133
+ for i in range(min(10, int(data.get('marks', 0)))):
2134
+ try:
2135
+ page.hover(f'[data-a11yidx="{i}"]', timeout=1000)
2136
+ r = page.evaluate(_JS_HOVER, i)
2137
+ if r and r['ratio'] < 3:
2138
+ hover.append(dict(r, example=f'hover #{i}'))
2139
+ except Exception: # noqa: BLE001
2140
+ continue
2141
+ data['hover'] = hover
2142
+ page_url_final = page.url
2143
+ finally:
2144
+ close_page()
1970
2145
  _merge_iframes(data)
1971
- return audit_dom(data, url, lang=lang, color_scheme=color_scheme)
2146
+ report_out = audit_dom(data, url, lang=lang, color_scheme=color_scheme)
2147
+ # verdad de navegación (revisión externa, 4ª pasada): un 404 con HTML
2148
+ # puntuaba 100 como si fuera la página pedida — el informe declara el
2149
+ # estado HTTP y la URL FINAL para que el consumidor distinga
2150
+ final_url = page_url_final or url
2151
+ try:
2152
+ _st = _resp.status if _resp is not None else None
2153
+ except Exception: # noqa: BLE001 — respuesta ya consumida
2154
+ _st = None
2155
+ if final_url.split('#')[0] != url.split('#')[0]:
2156
+ report_out['requested_url'] = url
2157
+ report_out['redirect_note'] = (
2158
+ 'la URL pedida redirigió: el informe es de la página FINAL'
2159
+ if lang == 'es' else
2160
+ 'the requested URL redirected: this report is for the FINAL page')
2161
+ if _st:
2162
+ report_out['http_status'] = _st
2163
+ if _st >= 400:
2164
+ report_out['http_error_note'] = (
2165
+ f'la página respondió HTTP {_st}: esto es una respuesta de '
2166
+ 'error, no la página pedida'
2167
+ if lang == 'es' else
2168
+ f'the page answered HTTP {_st}: this is an error response, '
2169
+ 'not the requested page')
2170
+ return report_out
1972
2171
 
1973
2172
 
1974
2173
  def contrast_dom(url, selector, text_color=None, sample=4, lang='en', timeout=45,
@@ -1982,58 +2181,52 @@ def contrast_dom(url, selector, text_color=None, sample=4, lang='en', timeout=45
1982
2181
  Para text_ sobre imágenes, degradados, vídeo o cualquier fondo que el
1983
2182
  cálculo CSS no puede resolver. Requiere Playwright.
1984
2183
  """
1985
- from playwright.sync_api import sync_playwright
1986
2184
  from .contrast import T as _TC
1987
2185
  t9 = _TC.get(lang, _TC['es'])
1988
- with sync_playwright() as p:
1989
- nav = _get_browser(p, preferred=browser)
1990
- ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1991
- page = ctx.new_page() if auth_state else nav.new_page()
2186
+ nav = _get_browser(preferred=browser)
2187
+ page, close_page = _pooled_page(nav, auth_state)
2188
+ try:
2189
+ page.goto(url, wait_until='load', timeout=timeout * 1000)
2190
+ page.wait_for_timeout(300)
2191
+ loc = page.locator(selector).first
1992
2192
  try:
1993
- page.goto(url, wait_until='load', timeout=timeout * 1000)
1994
- page.wait_for_timeout(300)
1995
- loc = page.locator(selector).first
1996
- try:
1997
- loc.wait_for(timeout=timeout * 1000)
1998
- except Exception: # noqa: BLE001
1999
- return {'error': t9['selector_missing'].format(s=selector)}
2000
- if text_color:
2001
- c = parse_color(text_color)
2002
- if not c:
2003
- return {'error': t9['invalid_color']}
2004
- else:
2005
- comp = loc.evaluate('el => getComputedStyle(el).color')
2006
- c = parse_color(comp)
2007
- if not c:
2008
- return {'error': f"{t9['invalid_color']} (computed: {comp})"}
2009
- if c.get('a', 1) < 1:
2010
- return {'error': t9['opaque_text']}
2011
- try:
2012
- box = loc.bounding_box()
2013
- if not box or box['width'] < 3 or box['height'] < 3:
2014
- return {'error': t9['no_box'].format(s=selector)}
2015
- m = _samples_background(loc, box, c)
2016
- except Exception: # noqa: BLE001
2193
+ loc.wait_for(timeout=timeout * 1000)
2194
+ except Exception: # noqa: BLE001
2195
+ return {'error': t9['selector_missing'].format(s=selector)}
2196
+ if text_color:
2197
+ c = parse_color(text_color)
2198
+ if not c:
2199
+ return {'error': t9['invalid_color']}
2200
+ else:
2201
+ comp = loc.evaluate('el => getComputedStyle(el).color')
2202
+ c = parse_color(comp)
2203
+ if not c:
2204
+ return {'error': f"{t9['invalid_color']} (computed: {comp})"}
2205
+ if c.get('a', 1) < 1:
2206
+ return {'error': t9['opaque_text']}
2207
+ try:
2208
+ box = loc.bounding_box()
2209
+ if not box or box['width'] < 3 or box['height'] < 3:
2017
2210
  return {'error': t9['no_box'].format(s=selector)}
2018
- if not m:
2019
- return {'error': t9['no_pixels']}
2020
- out = {'url': url, 'selector': selector, 'text_color': hexs(c),
2021
- 'image': f'{selector} ({round(box["width"])}×{round(box["height"])})',
2022
- 'worst_ratio': m['worst_ratio'],
2023
- 'median_ratio': m['median_ratio'],
2024
- 'p95_ratio': m['p95_ratio'],
2025
- 'area_passes_aa_normal_text_4_5': m['area_passes_aa_normal_text_4_5'],
2026
- 'area_passes_aa_min_3_0': m['area_passes_aa_min_3_0'],
2027
- 'sampled_pixels': m['sampled_pixels'],
2028
- 'interpretation': t9['interp']}
2029
- if 'worst_zone' in m:
2030
- out['worst_zone'] = m['worst_zone']
2031
- return out
2032
- finally:
2033
- try:
2034
- ctx.close()
2035
- except Exception: # noqa: BLE001
2036
- pass
2211
+ m = _samples_background(loc, box, c)
2212
+ except Exception: # noqa: BLE001
2213
+ return {'error': t9['no_box'].format(s=selector)}
2214
+ if not m:
2215
+ return {'error': t9['no_pixels']}
2216
+ out = {'url': url, 'selector': selector, 'text_color': hexs(c),
2217
+ 'image': f'{selector} ({round(box["width"])}×{round(box["height"])})',
2218
+ 'worst_ratio': m['worst_ratio'],
2219
+ 'median_ratio': m['median_ratio'],
2220
+ 'p95_ratio': m['p95_ratio'],
2221
+ 'area_passes_aa_normal_text_4_5': m['area_passes_aa_normal_text_4_5'],
2222
+ 'area_passes_aa_min_3_0': m['area_passes_aa_min_3_0'],
2223
+ 'sampled_pixels': m['sampled_pixels'],
2224
+ 'interpretation': t9['interp']}
2225
+ if 'worst_zone' in m:
2226
+ out['worst_zone'] = m['worst_zone']
2227
+ return out
2228
+ finally:
2229
+ close_page()
2037
2230
 
2038
2231
 
2039
2232
  # --- contrast walk: perceptual pass over EVERY rendered text element --------
@@ -2041,7 +2234,13 @@ def contrast_dom(url, selector, text_color=None, sample=4, lang='en', timeout=45
2041
2234
  _JS_WALK = r'''(maxEls) => {
2042
2235
  const visible = el => !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length);
2043
2236
  const directText = el => [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim());
2044
- const parseC = s => { const m = String(s).match(/rgba?\(([\d.]+),\s*([\d.]+),\s*([\d.]+)(?:,\s*([\d.]+))?\)/);
2237
+ const parseC = s => { const m3 = /color\(\s*srgb\s+([^)]+)\)/.exec(String(s));
2238
+ if (m3) { const ps = m3[1].split('/'); const rgb = ps[0].trim().split(/\s+/);
2239
+ const cv = v => v.endsWith('%') ? parseFloat(v) * 2.55 : parseFloat(v) * 255;
2240
+ const al = ps.length > 1 ? (ps[1].trim().endsWith('%') ? parseFloat(ps[1]) / 100 : parseFloat(ps[1])) : 1;
2241
+ if (rgb.length >= 3 && isFinite(cv(rgb[0])) && isFinite(cv(rgb[1])) && isFinite(cv(rgb[2])) && isFinite(al))
2242
+ return {r: Math.round(cv(rgb[0])), g: Math.round(cv(rgb[1])), b: Math.round(cv(rgb[2])), a: al}; }
2243
+ const m = String(s).match(/rgba?\(([\d.]+),\s*([\d.]+),\s*([\d.]+)(?:,\s*([\d.]+))?\)/);
2045
2244
  return m ? {r:+m[1], g:+m[2], b:+m[3], a: m[4] === undefined ? 1 : +m[4]} : null; };
2046
2245
  const effBg = el => {
2047
2246
  const layers = [];
@@ -2081,7 +2280,7 @@ _JS_WALK = r'''(maxEls) => {
2081
2280
  if (!visible(el) || !directText(el)) continue;
2082
2281
  const cs = getComputedStyle(el);
2083
2282
  const color = parseC(cs.color);
2084
- if (!color) continue;
2283
+ if (!color) { out.push({skip: 'unparsed-color', path: path(el)}); continue; }
2085
2284
  if (color.a < 1) { out.push({skip: 'translucent', path: path(el)}); continue; }
2086
2285
  const fs = parseFloat(cs.fontSize) || 16;
2087
2286
  const fw = parseInt(cs.fontWeight) || 400;
@@ -2114,21 +2313,28 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
2114
2313
  Filtro honesto, no veredicto: text_ en shadow DOM, canvas, vídeo y
2115
2314
  pseudo-elementos no se captura; lo no medido se declara, jamás inventado.
2116
2315
  """
2117
- from playwright.sync_api import sync_playwright
2118
2316
  from .contrast import ratio as _ratio, suggest as _suggest, parse_color
2119
2317
 
2120
2318
  def _verdicts(entries):
2121
2319
  for e in entries:
2122
2320
  if e['ratio'] is not None:
2123
- e['verdict'] = 'pass' if e['ratio'] >= e['threshold'] else 'fail'
2321
+ exact = e.pop('_exact', None)
2322
+ value = exact if exact is not None else e['ratio']
2323
+ e['verdict'] = 'pass' if value >= e['threshold'] else 'fail'
2324
+ if exact is not None and (value >= e['threshold']) != \
2325
+ (e['ratio'] >= e['threshold']):
2326
+ e['ratio_exact'] = round(exact, 6) # el redondeo maquilla: declararlo
2124
2327
 
2125
2328
  def _pass(page):
2126
2329
  raw = page.evaluate(_JS_WALK, max_walk)
2127
- entries, shot_jobs, skipped = [], [], 0
2330
+ entries, shot_jobs, skipped, unparsed = [], [], 0, 0
2128
2331
  for row in raw:
2129
2332
  if row.get('skip') == 'translucent':
2130
2333
  skipped += 1
2131
2334
  continue
2335
+ if row.get('skip') == 'unparsed-color':
2336
+ unparsed += 1
2337
+ continue
2132
2338
  fg = {k: row['color'][k] for k in ('r', 'g', 'b')}
2133
2339
  bg = {k: row['bg'][k] for k in ('r', 'g', 'b')}
2134
2340
  large = row['font_px'] >= 24 or (row['font_px'] >= 18.66 and row['bold'])
@@ -2142,7 +2348,12 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
2142
2348
  if row['bg_image']:
2143
2349
  shot_jobs.append((entry, fg))
2144
2350
  else:
2145
- entry['ratio'] = round(_ratio(fg, bg), 2)
2351
+ # umbral sobre el valor EXACTO (revisión externa, 3ª pasada:
2352
+ # 4,4999346 redondeado a 4,50 pasaba por válido); el redondeo
2353
+ # es presentación — _exact viaja interno hasta el veredicto
2354
+ r_exact = _ratio(fg, bg)
2355
+ entry['ratio'] = round(r_exact, 2)
2356
+ entry['_exact'] = r_exact
2146
2357
  entries.append(entry)
2147
2358
  sampled = 0
2148
2359
  for entry, fg in shot_jobs:
@@ -2162,7 +2373,7 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
2162
2373
  except Exception: # noqa: BLE001 — one dead locator must not kill the walk
2163
2374
  continue
2164
2375
  _verdicts(entries)
2165
- return entries, skipped
2376
+ return entries, skipped, unparsed
2166
2377
 
2167
2378
  def _summarize(entries, skipped):
2168
2379
  fails = [e for e in entries if e['verdict'] == 'fail']
@@ -2174,71 +2385,70 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
2174
2385
  'fails_4_5_normal_text': sum(1 for e in fails if e['threshold'] >= 4.5),
2175
2386
  'fails_3_0_large_text': sum(1 for e in fails if e['threshold'] < 4.5),
2176
2387
  'translucent_text_skipped': skipped,
2388
+ 'unparsed_colors': unparsed + (locals().get('_unp_d') or 0),
2177
2389
  'pixel_sampled': sum(1 for e in entries if e['pixel_sampled']),
2178
2390
  'worst_ratio': worst['ratio'] if worst else None,
2179
2391
  'worst_element': worst['path'] if worst else None}
2180
2392
 
2181
- with sync_playwright() as p:
2182
- def _run(scheme):
2183
- nav = _get_browser(p, preferred=browser)
2184
- ctx = (nav.new_context(storage_state=auth_state, color_scheme=scheme)
2185
- if auth_state else nav.new_context(color_scheme=scheme))
2186
- page = ctx.new_page()
2393
+ def _run(scheme):
2394
+ nav = _get_browser(preferred=browser)
2395
+ ctx = (nav.new_context(storage_state=auth_state, color_scheme=scheme)
2396
+ if auth_state else nav.new_context(color_scheme=scheme))
2397
+ page = ctx.new_page()
2398
+ try:
2399
+ page.goto(url, wait_until='load', timeout=timeout * 1000)
2400
+ page.wait_for_timeout(300)
2401
+ return _pass(page)
2402
+ finally:
2187
2403
  try:
2188
- page.goto(url, wait_until='load', timeout=timeout * 1000)
2189
- page.wait_for_timeout(300)
2190
- return _pass(page)
2191
- finally:
2192
- try:
2193
- ctx.close()
2194
- nav.close()
2195
- except Exception: # noqa: BLE001
2196
- pass
2197
-
2198
- entries, skipped = _run('light')
2199
- report = {'mode': 'contrast-walk', 'url': url, 'scheme': 'light',
2200
- 'checked': len(entries),
2201
- 'elements': entries,
2202
- 'summary': _summarize(entries, skipped)}
2203
-
2204
- # suggestions for the worst flat-background fails (pixel zones have no
2205
- # single background to suggest against — honest skip)
2206
- fails = sorted((e for e in entries if e['verdict'] == 'fail' and not e['bg_image']),
2207
- key=lambda e: e['ratio'])
2208
- for e in fails[:8]:
2209
- s = _suggest(parse_color(e['color']), parse_color(e['bg']),
2210
- target=e['threshold'], lang=lang)
2211
- if s:
2212
- e['suggestion'] = s
2213
-
2214
- if dark:
2215
- entries_d, skipped_d = _run('dark')
2216
- report['dark'] = {'scheme': 'dark', 'checked': len(entries_d),
2217
- 'elements': entries_d,
2218
- 'summary': _summarize(entries_d, skipped_d)}
2219
- light_fails = {e['path'] for e in entries if e['verdict'] == 'fail'}
2220
- dark_fails = {e['path'] for e in entries_d if e['verdict'] == 'fail'}
2221
- report['dark_delta'] = {
2222
- 'new_fails': sorted(dark_fails - light_fails)[:20],
2223
- 'resolved': sorted(light_fails - dark_fails)[:20],
2224
- 'note': ('a site that ignores prefers-color-scheme shows a zero '
2225
- 'delta: same colors in both passes')}
2226
-
2227
- report['limits'] = (
2228
- 'Computed ratios cover effective background-color with alpha '
2229
- 'compositing; text over images/gradients is pixel-sampled '
2230
- '(worst-case) up to the cap, the rest is declared unmeasured. Text '
2231
- 'in shadow DOM, canvas, video and pseudo-elements is not captured. '
2232
- 'A fail is a filter finding (1.4.3), not a verdict — judge the '
2233
- 'zone with contrast-dom.'
2234
- if lang == 'en' else
2235
- 'Los ratios computados cubren background-color efectivo con '
2236
- 'composición alfa; el text_ sobre imágenes/gradientes se muestrea '
2237
- 'por píxeles (peor caso) hasta el tope y el resto se declara sin '
2238
- 'medir. El text_ en shadow DOM, canvas, vídeo y pseudo-elementos '
2239
- 'no se captura. Un fallo es un hallazgo de filtro (1.4.3), no un '
2240
- 'veredicto — juzga la zona con contrast-dom.')
2241
- return report
2404
+ ctx.close()
2405
+ except Exception: # noqa: BLE001
2406
+ pass
2407
+
2408
+ entries, skipped, unparsed = _run('light')
2409
+ report = {'mode': 'contrast-walk', 'url': url, 'scheme': 'light',
2410
+ 'checked': len(entries),
2411
+ 'elements': entries,
2412
+ 'summary': _summarize(entries, skipped)}
2413
+
2414
+ # suggestions for the worst flat-background fails (pixel zones have no
2415
+ # single background to suggest against — honest skip)
2416
+ fails = sorted((e for e in entries if e['verdict'] == 'fail' and not e['bg_image']),
2417
+ key=lambda e: e['ratio'])
2418
+ for e in fails[:8]:
2419
+ s = _suggest(parse_color(e['color']), parse_color(e['bg']),
2420
+ target=e['threshold'], lang=lang)
2421
+ if s:
2422
+ e['suggestion'] = s
2423
+
2424
+ if dark:
2425
+ entries_d, skipped_d, _unp_d = _run('dark')
2426
+ report['dark'] = {'scheme': 'dark', 'checked': len(entries_d),
2427
+ 'elements': entries_d,
2428
+ 'summary': _summarize(entries_d, skipped_d)}
2429
+ light_fails = {e['path'] for e in entries if e['verdict'] == 'fail'}
2430
+ dark_fails = {e['path'] for e in entries_d if e['verdict'] == 'fail'}
2431
+ report['dark_delta'] = {
2432
+ 'new_fails': sorted(dark_fails - light_fails)[:20],
2433
+ 'resolved': sorted(light_fails - dark_fails)[:20],
2434
+ 'note': ('a site that ignores prefers-color-scheme shows a zero '
2435
+ 'delta: same colors in both passes')}
2436
+
2437
+ report['limits'] = (
2438
+ 'Computed ratios cover effective background-color with alpha '
2439
+ 'compositing; text over images/gradients is pixel-sampled '
2440
+ '(worst-case) up to the cap, the rest is declared unmeasured. Text '
2441
+ 'in shadow DOM, canvas, video and pseudo-elements is not captured. '
2442
+ 'A fail is a filter finding (1.4.3), not a verdict — judge the '
2443
+ 'zone with contrast-dom.'
2444
+ if lang == 'en' else
2445
+ 'Los ratios computados cubren background-color efectivo con '
2446
+ 'composición alfa; el text_ sobre imágenes/gradientes se muestrea '
2447
+ 'por píxeles (peor caso) hasta el tope y el resto se declara sin '
2448
+ 'medir. El text_ en shadow DOM, canvas, vídeo y pseudo-elementos '
2449
+ 'no se captura. Un fallo es un hallazgo de filtro (1.4.3), no un '
2450
+ 'veredicto — juzga la zona con contrast-dom.')
2451
+ return report
2242
2452
 
2243
2453
 
2244
2454
  def contrast_dom_main(argv):
@@ -2290,7 +2500,7 @@ def main(argv):
2290
2500
  print(json.dumps({'error': str(e)}))
2291
2501
  return 1
2292
2502
  print(json.dumps(res, ensure_ascii=False, indent=1))
2293
- return 0
2503
+ return 1 if isinstance(res, dict) and 'error' in res else 0
2294
2504
 
2295
2505
 
2296
2506
  def reflow_main(argv):
@@ -2298,14 +2508,17 @@ def reflow_main(argv):
2298
2508
  ap.add_argument('url')
2299
2509
  ap.add_argument('--lang', default='en', choices=['en', 'es'])
2300
2510
  ap.add_argument('--timeout', type=int, default=45)
2511
+ ap.add_argument('--auth-state', dest='auth_state',
2512
+ help='Path to a Playwright storage_state JSON to audit behind login')
2301
2513
  a = ap.parse_args(argv)
2302
2514
  try:
2303
- res = audit_reflow(a.url, timeout=a.timeout, lang=a.lang)
2515
+ res = audit_reflow(a.url, timeout=a.timeout, lang=a.lang,
2516
+ auth_state=a.auth_state)
2304
2517
  except ImportError:
2305
2518
  print(json.dumps({'error': 'Playwright not installed'}))
2306
2519
  return 1
2307
2520
  print(json.dumps(res, ensure_ascii=False, indent=1))
2308
- return 0
2521
+ return 1 if isinstance(res, dict) and 'error' in res else 0
2309
2522
 
2310
2523
 
2311
2524
  def forms_main(argv):
@@ -2320,7 +2533,7 @@ def forms_main(argv):
2320
2533
  print(json.dumps({'error': 'Playwright not installed'}))
2321
2534
  return 1
2322
2535
  print(json.dumps(res, ensure_ascii=False, indent=1))
2323
- return 0
2536
+ return 1 if isinstance(res, dict) and 'error' in res else 0
2324
2537
 
2325
2538
 
2326
2539
  def kbd_main(argv):
@@ -2335,7 +2548,7 @@ def kbd_main(argv):
2335
2548
  print(json.dumps({'error': 'Playwright not installed'}))
2336
2549
  return 1
2337
2550
  print(json.dumps(res, ensure_ascii=False, indent=1))
2338
- return 0
2551
+ return 1 if isinstance(res, dict) and 'error' in res else 0
2339
2552
 
2340
2553
 
2341
2554
  def hover_main(argv):
@@ -2354,7 +2567,7 @@ def hover_main(argv):
2354
2567
  print(json.dumps({'error': 'Playwright not installed'}))
2355
2568
  return 1
2356
2569
  print(json.dumps(res, ensure_ascii=False, indent=1))
2357
- return 0
2570
+ return 1 if isinstance(res, dict) and 'error' in res else 0
2358
2571
 
2359
2572
 
2360
2573
  if __name__ == '__main__':