@kinti/a11y-toolkit 5.35.0 → 5.35.1

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.
package/README.md CHANGED
@@ -16,7 +16,7 @@ As an MCP server (stdio):
16
16
 
17
17
  ```json
18
18
  { "mcpServers": { "a11y-toolkit": {
19
- "command": "npx", "args": ["-y", "@kinti/a11y-toolkit", "a11y-toolkit-mcp"] } } }
19
+ "command": "npx", "args": ["-y", "-p", "@kinti/a11y-toolkit", "a11y-toolkit-mcp"] } } }
20
20
  ```
21
21
 
22
22
  ## Requirements
@@ -1984,10 +1984,21 @@ def page_identity(url):
1984
1984
  def audit_conditions(report):
1985
1985
  """Identify recorded capture conditions that affect comparability."""
1986
1986
  if report.get('mode') == 'rendered':
1987
- return {'color_scheme': report.get('color_scheme') or report.get('scheme')}
1987
+ return {'color_scheme': report.get('color_scheme') or report.get('scheme'),
1988
+ 'authenticated': report.get('authenticated'), 'browser': report.get('browser')}
1988
1989
  return {}
1989
1990
 
1990
1991
 
1992
+ def rendered_conditions_recorded(conditions):
1993
+ return (conditions.get('color_scheme') in ('light', 'dark')
1994
+ and isinstance(conditions.get('authenticated'), bool)
1995
+ and isinstance(conditions.get('browser'), str) and bool(conditions['browser']))
1996
+
1997
+
1998
+ def audit_conditions_match(mode, previous, current):
1999
+ return previous == current and (mode != 'rendered' or rendered_conditions_recorded(current))
2000
+
2001
+
1991
2002
  def completed_report_pages(report):
1992
2003
  """Return measured pages or the reason they cannot support a comparison."""
1993
2004
  if not isinstance(report, dict) or report.get('error'):
@@ -3200,7 +3211,7 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
3200
3211
  continue
3201
3212
  reports.append(report)
3202
3213
  parsers.append(pg)
3203
- if len(reports) < max_pages and not from_sitemap:
3214
+ if len(reports) < max_pages and not urls_sm:
3204
3215
  for new in _internal_links(html_pg, next_final, url):
3205
3216
  if new not in seen:
3206
3217
  queue.append(new)
@@ -44,7 +44,7 @@ import datetime
44
44
  import json
45
45
  from collections import Counter
46
46
 
47
- from .a11yaudit import audit_conditions, completed_report_pages, normalize_signal
47
+ from .a11yaudit import audit_conditions, audit_conditions_match, completed_report_pages, normalize_signal
48
48
  import sys
49
49
 
50
50
  # mensajes CLI bilingües (patrón _labels): el stdin de --init espera el JSON
@@ -145,7 +145,8 @@ def _compare_instances(budget, pages, blocking):
145
145
  prior = base.get(url)
146
146
  if prior and prior['mode'] != page['mode']:
147
147
  return {'error': 'the audit mode changed for a baseline page', 'url': url}
148
- if prior and prior.get('conditions', {}) != page['conditions']:
148
+ if prior and not audit_conditions_match(page['mode'], prior.get('conditions', {}),
149
+ page['conditions']):
149
150
  return {'error': 'the capture conditions changed or were not recorded in the baseline',
150
151
  'url': url}
151
152
  old = prior['findings'] if prior else {}
@@ -198,6 +199,8 @@ def compare(budget, audit, today=None):
198
199
  if budget.get('format') == BUDGET_FORMAT:
199
200
  verdict = _compare_instances(budget, _page_index(pages), blocking)
200
201
  else:
202
+ if any(p.get('mode') == 'rendered' for p in pages):
203
+ return {'error': 'a rendered audit needs a baseline with recorded capture conditions'}
201
204
  verdict = _compare_signals(budget, pages, blocking)
202
205
  except (ValueError, KeyError, TypeError) as err:
203
206
  return {'error': f'invalid budget input: {err}'}
@@ -142,7 +142,12 @@ def snapshot(url, output=None, auth_state=None, engine='chromium'):
142
142
  nav = launch(p)
143
143
  ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
144
144
  page = ctx.new_page() if auth_state else nav.new_page()
145
- page.goto(url, wait_until='networkidle', timeout=45000)
145
+ from .a11ydom import _NavigationHTTPError, _load_page
146
+ try:
147
+ _load_page(page, url, timeout=45000, wait_until='networkidle')
148
+ except _NavigationHTTPError as error:
149
+ nav.close()
150
+ return error.report()
146
151
  elements = page.evaluate(COLLECTOR)
147
152
 
148
153
  # Árbol de accesibilidad REAL (roles/nombres computados, lo que anuncia
@@ -177,6 +182,9 @@ _NOTE = {
177
182
 
178
183
 
179
184
  def diff(a, b, lang='en'):
185
+ for capture in (a, b):
186
+ if 'error' in capture:
187
+ return {**capture, 'ok': False}
180
188
  # multiset por firma: dos controles con el MISMO nombre (Edit por fila,
181
189
  # botones-icono sin name) son dos elementos — un dict por clave los
182
190
  # colapsaba y el diff decía «sin cambios» ante una duplicación
@@ -258,6 +266,9 @@ def main(argv):
258
266
  except ImportError:
259
267
  print(json.dumps({'error': 'Playwright not installed: pip install playwright && playwright install chromium'}))
260
268
  return 1
269
+ if 'error' in d:
270
+ print(json.dumps(d, ensure_ascii=False))
271
+ return 1
261
272
  print(json.dumps({'url': d['url'], 'elements': len(d['elements']),
262
273
  'focus_steps': len(d['focus_order']), 'out': a.out},
263
274
  ensure_ascii=False, indent=1))
@@ -266,8 +277,10 @@ def main(argv):
266
277
  ja = json.load(f)
267
278
  with open(a.b, encoding='utf-8') as f:
268
279
  jb = json.load(f)
269
- print(json.dumps(diff(ja, jb), ensure_ascii=False, indent=1))
270
280
  verdict = diff(ja, jb)
281
+ print(json.dumps(verdict, ensure_ascii=False, indent=1))
282
+ if 'error' in verdict:
283
+ return 1
271
284
  return 0 if verdict['ok'] else 2
272
285
 
273
286
 
@@ -26,16 +26,18 @@ import json
26
26
 
27
27
  import sys
28
28
 
29
- from .a11yaudit import audit_url, normalize_signal, page_identity
29
+ from .a11yaudit import (audit_conditions, audit_conditions_match, audit_url, normalize_signal,
30
+ page_identity, rendered_conditions_recorded)
30
31
 
31
32
 
32
- def _recheck(url, expected_url, timeout, lang, color_scheme=None):
33
+ def _recheck(url, expected_url, timeout, lang, color_scheme=None, auth_state=None, browser='auto'):
33
34
  """Obtain a successful measurement of the same page."""
34
35
  if color_scheme is None:
35
36
  fresh = audit_url(url, timeout=timeout, lang=lang)
36
37
  else:
37
38
  from .a11ydom import audit_dom_url
38
- fresh = audit_dom_url(url, timeout=timeout, lang=lang, color_scheme=color_scheme)
39
+ fresh = audit_dom_url(url, timeout=timeout, lang=lang, color_scheme=color_scheme,
40
+ auth_state=auth_state, browser=browser)
39
41
  if 'error' in fresh:
40
42
  return None, fresh['error']
41
43
  if page_identity(fresh.get('url')) != page_identity(expected_url):
@@ -87,12 +89,21 @@ def _classify_findings(previous, current, lang):
87
89
  return current, historical
88
90
 
89
91
 
90
- def disprove(url, report=None, timeout=30, lang='en'):
92
+ def _unverified(report, reason):
93
+ findings = [dict(h, disprover_status='not-rechecked') for h in report.get('findings', [])]
94
+ return dict(report, findings=findings, disprover={'executed': False, 'reason': reason})
95
+
96
+
97
+ def disprove(url, report=None, timeout=30, lang='en', auth_state=None):
91
98
  """Audit a URL and disprove findings, or verify an existing report.
92
99
 
93
100
  Return the fresh measurement and the outcomes of prior findings."""
94
101
  if report is None:
95
- report = audit_url(url, timeout=timeout, lang=lang)
102
+ if auth_state:
103
+ from .a11ydom import audit_dom_url
104
+ report = audit_dom_url(url, timeout=timeout, lang=lang, auth_state=auth_state)
105
+ else:
106
+ report = audit_url(url, timeout=timeout, lang=lang)
96
107
  if report.get('error'):
97
108
  return report
98
109
  mode_name = report.get('mode', 'static')
@@ -116,35 +127,35 @@ def disprove(url, report=None, timeout=30, lang='en'):
116
127
  return res
117
128
 
118
129
  if mode_name == 'static':
130
+ if auth_state:
131
+ return _unverified(report, 'El informe estático no admite una sesión de navegador.'
132
+ if lang == 'es' else
133
+ 'The static report does not support a browser session.')
119
134
  fresh, err = _recheck(url, expected_url, timeout, lang)
120
135
  elif mode_name == 'rendered':
121
- # condición necesaria: el esquema de color bajo el que se auditó. Sin
122
- # él no se reverifica (rechazar un contrast_fail de dark mode tras
123
- # mirar la página en claro es exactamente el falso «arreglado» que
124
- # este patrón existe para impedir)
125
- scheme = report.get('color_scheme') or report.get('scheme')
126
- if scheme not in ('light', 'dark'):
127
- res = dict(report)
128
- res['findings'] = [dict(h, disprover_status='not-rechecked') for h in findings]
129
- res['disprover'] = {
130
- 'executed': False,
131
- 'reason': ('the rendered report does not record its color_scheme '
132
- '— re-verifying under a different condition could reject '
133
- 'real findings (a dark-only contrast fail looks fixed '
134
- 'under light); re-audit with a11y_audit_dom and disprove '
135
- 'THAT report')}
136
- return res
137
- fresh, err = _recheck(url, expected_url, timeout, lang, color_scheme=scheme)
136
+ conditions = audit_conditions(report)
137
+ if not rendered_conditions_recorded(conditions):
138
+ return _unverified(report, ('El informe no registra todas las condiciones de captura. '
139
+ 'Vuelve a auditar con a11y_audit_dom.' if lang == 'es' else
140
+ 'Capture conditions are missing. Re-audit with a11y_audit_dom.'))
141
+ if bool(auth_state) != conditions['authenticated']:
142
+ return _unverified(report, ('La reauditoría necesita el mismo tipo de sesión que la captura. '
143
+ 'Usa auth_state para una captura con sesión.' if lang == 'es' else
144
+ 'Re-audit with the same session type as the capture. '
145
+ 'Use auth_state for an authenticated capture.'))
146
+ scheme = conditions['color_scheme']
147
+ fresh, err = _recheck(url, expected_url, timeout, lang, color_scheme=scheme,
148
+ auth_state=auth_state, browser=conditions['browser'])
149
+ if not err and not audit_conditions_match(mode_name, conditions, audit_conditions(fresh)):
150
+ return _unverified(report, 'La reauditoría cambió las condiciones de captura.'
151
+ if lang == 'es' else 'Capture conditions changed during re-audit.')
138
152
  else:
139
153
  # no re-verifier for this mode: report not-rechecked, never a proxy
140
154
  # audit (a keyboard finding must not vanish just because the wrong
141
155
  # method ran). `rejected` is reserved for an equivalent check that
142
156
  # actually disproves the original finding.
143
- res = dict(report)
144
- res['findings'] = [dict(h, disprover_status='not-rechecked') for h in findings]
145
- res['disprover'] = {'executed': False,
146
- 'reason': f"no re-verifier for mode {mode_name!r}"}
147
- return res
157
+ return _unverified(report, (f'No hay reauditoría para el modo {mode_name!r}.' if lang == 'es'
158
+ else f'No re-verifier for mode {mode_name!r}.'))
148
159
 
149
160
  if err:
150
161
  return dict(report, error=err, disprover={'executed': False, 'reason': err})
@@ -170,6 +181,7 @@ def main(argv):
170
181
  ap = argparse.ArgumentParser(description='Disprover: re-verify findings against the live page')
171
182
  ap.add_argument('--url', required=True, help='URL to audit and disprove')
172
183
  ap.add_argument('--file', help='existing report JSON (optional; if absent, audits first)')
184
+ ap.add_argument('--auth-state', help='local Playwright session for the original capture')
173
185
  ap.add_argument('--lang', default='en', choices=['en', 'es'])
174
186
  ap.add_argument('--timeout', type=int, default=30)
175
187
  ap.add_argument('-o', '--out', help='save result JSON here')
@@ -178,7 +190,7 @@ def main(argv):
178
190
  if a.file:
179
191
  with open(a.file, encoding='utf-8') as f:
180
192
  report = json.load(f)
181
- res = disprove(a.url, report=report, timeout=a.timeout, lang=a.lang)
193
+ res = disprove(a.url, report=report, timeout=a.timeout, lang=a.lang, auth_state=a.auth_state)
182
194
  if 'error' in res:
183
195
  print(json.dumps(res))
184
196
  return 1
@@ -26,6 +26,32 @@ from .contrast import parse_color, decode_png, sample_rgb, hexs, luminance, rati
26
26
  # carga y limits): bilingües aquí, igual que el catálogo (invariante es/en)
27
27
  _LOAD_ERR = {'es': 'no se pudo cargar: {e}',
28
28
  'en': 'could not load: {e}'}
29
+
30
+
31
+ class _NavigationHTTPError(RuntimeError):
32
+ def __init__(self, status, url):
33
+ super().__init__(f'HTTP {status}: could not load the requested page')
34
+ self.status = status
35
+ self.url = url
36
+
37
+ def report(self, lang='en'):
38
+ message = (f'HTTP {self.status}: no se pudo cargar la página solicitada'
39
+ if lang == 'es' else str(self))
40
+ return {'error': message, 'url': self.url, 'http_status': self.status}
41
+
42
+
43
+ def _load_page(page, url, timeout, wait_until='load'):
44
+ response = page.goto(url, wait_until=wait_until, timeout=timeout)
45
+ if response is not None and response.status >= 400:
46
+ raise _NavigationHTTPError(response.status, page.url)
47
+
48
+
49
+ def _load_error(error, lang, template='{e}'):
50
+ if isinstance(error, _NavigationHTTPError):
51
+ return error.report(lang)
52
+ return {'error': template.format(e=error)}
53
+
54
+
29
55
  _LIMITS_HCM = {
30
56
  'es': ('Heurística de revisión (1.4.3/1.4.11 en HCM): los fills '
31
57
  'coloreados hardcoded en SVG suelen caer al heredado con '
@@ -155,7 +181,7 @@ class _NoPoolBrowser:
155
181
  def __init__(self, headless, preferred):
156
182
  from playwright.sync_api import sync_playwright
157
183
  self._pw = sync_playwright().start()
158
- self._nav, kind = _detect_browser(self._pw, preferred)
184
+ self._nav, self.kind = _detect_browser(self._pw, preferred)
159
185
  self._live_pages = 0
160
186
 
161
187
  def new_context(self, **kw):
@@ -1185,10 +1211,10 @@ def audit_forms(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1185
1211
  page, close_page = _pooled_page(nav, auth_state)
1186
1212
  try:
1187
1213
  try:
1188
- page.goto(url, wait_until='load', timeout=timeout * 1000)
1214
+ _load_page(page, url, timeout * 1000)
1189
1215
  page.wait_for_timeout(400)
1190
1216
  except Exception as e: # noqa: BLE001
1191
- return {'error': _t(lang, 'fetch_error').format(e=e)}
1217
+ return _load_error(e, lang, _t(lang, 'fetch_error'))
1192
1218
  url_before = page.url
1193
1219
  pre = page.evaluate(_JS_FORM_PRE)
1194
1220
  try:
@@ -1259,10 +1285,10 @@ def sr_transcript(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1259
1285
  page, close_page = _pooled_page(nav, auth_state)
1260
1286
  try:
1261
1287
  try:
1262
- page.goto(url, wait_until='load', timeout=timeout * 1000)
1288
+ _load_page(page, url, timeout * 1000)
1263
1289
  page.wait_for_timeout(400)
1264
1290
  except Exception as e:
1265
- return {'error': str(e)[:100]}
1291
+ return _load_error(e, lang, '{e!s:.100}')
1266
1292
 
1267
1293
  try:
1268
1294
  tree = page.locator('body').aria_snapshot()
@@ -1343,10 +1369,10 @@ def audit_hover(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1343
1369
  page, close_page = _pooled_page(nav, auth_state)
1344
1370
  try:
1345
1371
  try:
1346
- page.goto(url, wait_until='load', timeout=timeout * 1000)
1372
+ _load_page(page, url, timeout * 1000)
1347
1373
  page.wait_for_timeout(400)
1348
1374
  except Exception as e:
1349
- return {'error': str(e)[:100]}
1375
+ return _load_error(e, lang, '{e!s:.100}')
1350
1376
  # tooltips visibles ANTES de tocar nada: los preexistentes (ajenos)
1351
1377
  # jamas se atribuyen a un control por el mero hecho de hoverear
1352
1378
  _preexisting_tips = page.evaluate(_TOOLTIPS_VISIBLE_JS)
@@ -1538,10 +1564,10 @@ def audit_reflow(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1538
1564
  page, close_page = _pooled_page(nav, auth_state, viewport={'width': 1280, 'height': 800})
1539
1565
  try:
1540
1566
  try:
1541
- page.goto(url, wait_until='load', timeout=timeout * 1000)
1567
+ _load_page(page, url, timeout * 1000)
1542
1568
  page.wait_for_timeout(300)
1543
1569
  except Exception as e: # noqa: BLE001
1544
- return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
1570
+ return _load_error(e, lang, _LOAD_ERR.get(lang, _LOAD_ERR['en']))
1545
1571
 
1546
1572
  page.set_viewport_size({'width': 320, 'height': 800})
1547
1573
  page.wait_for_timeout(500)
@@ -1659,10 +1685,10 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1659
1685
  page, close_page = _pooled_page(nav, auth_state)
1660
1686
  try:
1661
1687
  try:
1662
- page.goto(url, wait_until='load', timeout=timeout * 1000)
1688
+ _load_page(page, url, timeout * 1000)
1663
1689
  page.wait_for_timeout(400)
1664
1690
  except Exception as e: # noqa: BLE001
1665
- return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
1691
+ return _load_error(e, lang, _LOAD_ERR.get(lang, _LOAD_ERR['en']))
1666
1692
 
1667
1693
  page.evaluate("document.querySelectorAll('[data-a11ystop]').forEach(e => {"
1668
1694
  " e.removeAttribute('data-a11ystop'); e.removeAttribute('data-a11yruta'); })")
@@ -2015,14 +2041,14 @@ def audit_forced_colors(url, timeout=45, lang='en', auth_state=None, browser='au
2015
2041
  page, close_page = _pooled_page(nav, auth_state)
2016
2042
  try:
2017
2043
  try:
2018
- page.goto(url, wait_until='load', timeout=timeout * 1000)
2044
+ _load_page(page, url, timeout * 1000)
2019
2045
  page.wait_for_timeout(400)
2020
2046
  normal = page.evaluate(_JS_FC)
2021
2047
  page.emulate_media(forced_colors='active')
2022
2048
  page.wait_for_timeout(400)
2023
2049
  forced = page.evaluate(_JS_FC)
2024
2050
  except Exception as e: # noqa: BLE001
2025
- return {'error': _t_audit(lang, 'fetch_error').format(e=e)}
2051
+ return _load_error(e, lang, _t_audit(lang, 'fetch_error'))
2026
2052
  finally:
2027
2053
  close_page()
2028
2054
 
@@ -2087,14 +2113,14 @@ def audit_reduced_motion(url, timeout=45, lang='en', auth_state=None, browser='a
2087
2113
  page, close_page = _pooled_page(nav, auth_state)
2088
2114
  try:
2089
2115
  try:
2090
- page.goto(url, wait_until='load', timeout=timeout * 1000)
2116
+ _load_page(page, url, timeout * 1000)
2091
2117
  page.wait_for_timeout(600)
2092
2118
  normal = page.evaluate(_JS_RM)
2093
2119
  page.emulate_media(reduced_motion='reduce')
2094
2120
  page.wait_for_timeout(600)
2095
2121
  reduced = page.evaluate(_JS_RM)
2096
2122
  except Exception as e: # noqa: BLE001
2097
- return {'error': _t_audit(lang, 'fetch_error').format(e=e)}
2123
+ return _load_error(e, lang, _t_audit(lang, 'fetch_error'))
2098
2124
  finally:
2099
2125
  close_page()
2100
2126
 
@@ -2145,6 +2171,7 @@ def audit_dom_url(url, timeout=45, lang='en', auth_state=None, browser='auto', c
2145
2171
  storage_state de Playwright (cookies/localStorage exportados con la sesión
2146
2172
  iniciada) para auditar detrás de login."""
2147
2173
  nav = _get_browser(preferred=browser)
2174
+ browser_kind = nav.kind if isinstance(nav, _NoPoolBrowser) else _POOL['type']
2148
2175
  page, close_page = _pooled_page(nav, auth_state)
2149
2176
  _resp = None
2150
2177
  page_url_final = None
@@ -2157,8 +2184,7 @@ def audit_dom_url(url, timeout=45, lang='en', auth_state=None, browser='auto', c
2157
2184
  _resp = page.goto(url, wait_until='load', timeout=timeout * 1000)
2158
2185
  page.wait_for_timeout(400)
2159
2186
  except Exception as e: # noqa: BLE001
2160
- if not page.content() or page.url in ('about:blank', ''):
2161
- return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
2187
+ return _load_error(e, lang, _LOAD_ERR.get(lang, _LOAD_ERR['en']))
2162
2188
  data = page.evaluate(_JS, MAX_EXAMPLES)
2163
2189
  # 1.4.12: inject the WCAG spacing overrides, count clipped texts
2164
2190
  data['spacingClipped'] = page.evaluate(_JS_SPACING)
@@ -2209,6 +2235,8 @@ def audit_dom_url(url, timeout=45, lang='en', auth_state=None, browser='auto', c
2209
2235
  # /account redirigió — antes conservaba /account y solo añadía la nota
2210
2236
  final_url = (page_url_final or url).split('#')[0]
2211
2237
  report_out = audit_dom(data, final_url, lang=lang, color_scheme=color_scheme)
2238
+ report_out['authenticated'] = bool(auth_state)
2239
+ report_out['browser'] = browser_kind
2212
2240
  try:
2213
2241
  _st = _resp.status if _resp is not None else None
2214
2242
  except Exception: # noqa: BLE001 — respuesta ya consumida
@@ -2253,7 +2281,10 @@ def contrast_dom(url, selector, text_color=None, sample=4, lang='en', timeout=45
2253
2281
  nav = _get_browser(preferred=browser)
2254
2282
  page, close_page = _pooled_page(nav, auth_state)
2255
2283
  try:
2256
- page.goto(url, wait_until='load', timeout=timeout * 1000)
2284
+ try:
2285
+ _load_page(page, url, timeout * 1000)
2286
+ except Exception as e: # noqa: BLE001
2287
+ return _load_error(e, lang, _LOAD_ERR.get(lang, _LOAD_ERR['en']))
2257
2288
  page.wait_for_timeout(300)
2258
2289
  loc = page.locator(selector).first
2259
2290
  try:
@@ -2463,7 +2494,7 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
2463
2494
  if auth_state else nav.new_context(color_scheme=scheme))
2464
2495
  page = ctx.new_page()
2465
2496
  try:
2466
- page.goto(url, wait_until='load', timeout=timeout * 1000)
2497
+ _load_page(page, url, timeout * 1000)
2467
2498
  page.wait_for_timeout(300)
2468
2499
  return _pass(page)
2469
2500
  finally:
@@ -2472,7 +2503,10 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
2472
2503
  except Exception: # noqa: BLE001
2473
2504
  pass
2474
2505
 
2475
- entries, skipped, unparsed = _run('light')
2506
+ try:
2507
+ entries, skipped, unparsed = _run('light')
2508
+ except _NavigationHTTPError as error:
2509
+ return error.report(lang)
2476
2510
  report = {'mode': 'contrast-walk', 'url': url, 'scheme': 'light',
2477
2511
  'checked': len(entries),
2478
2512
  'elements': entries,
@@ -2489,7 +2523,10 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
2489
2523
  e['suggestion'] = s
2490
2524
 
2491
2525
  if dark:
2492
- entries_d, skipped_d, _unp_d = _run('dark')
2526
+ try:
2527
+ entries_d, skipped_d, _unp_d = _run('dark')
2528
+ except _NavigationHTTPError as error:
2529
+ return error.report(lang)
2493
2530
  report['dark'] = {'scheme': 'dark', 'checked': len(entries_d),
2494
2531
  'elements': entries_d,
2495
2532
  'summary': _summarize(entries_d, skipped_d, _unp_d)}
@@ -41,7 +41,7 @@ DEFAULT_ENGINES = ('chromium', 'firefox', 'webkit')
41
41
 
42
42
 
43
43
  def _capture(url, engine, auth_state=None):
44
- """One engine's snapshot; raises on engine failure (caller records it)."""
44
+ """Capture one engine's snapshot."""
45
45
  return a11ydiff.snapshot(url, engine=engine, auth_state=auth_state)
46
46
 
47
47
 
@@ -90,8 +90,11 @@ def matrix(url, engines=None, auth_state=None, capture=None):
90
90
  failed.append({'engine': name, 'error': f'unknown engine (known: {", ".join(ENGINES)})'})
91
91
  continue
92
92
  try:
93
- snaps[name] = capture(url, name, auth_state)
94
- s = snaps[name]
93
+ s = capture(url, name, auth_state)
94
+ if 'error' in s:
95
+ failed.append({**s, 'engine': name})
96
+ continue
97
+ snaps[name] = s
95
98
  ok.append({'engine': name, 'elements': len(s.get('elements', [])),
96
99
  'focus_steps': len(s.get('focus_order', [])),
97
100
  'tree': 'accessibility_tree' in s or 'arbol_accesible' in s})
@@ -127,9 +130,8 @@ def matrix(url, engines=None, auth_state=None, capture=None):
127
130
  'conformance claim.'),
128
131
  }
129
132
  if not enough:
130
- report['note'] = ('fewer than 2 engines launched: install them with '
131
- '`playwright install firefox webkit` — a matrix of one '
132
- 'engine cannot see cross-engine behavior')
133
+ report['note'] = ('fewer than 2 engines captured the page. Check the reported '
134
+ 'errors. Install missing engines with `playwright install firefox webkit`.')
133
135
  return report
134
136
 
135
137
 
@@ -27,6 +27,7 @@ CLI:
27
27
  import argparse
28
28
  import hashlib
29
29
  import json
30
+ import re
30
31
 
31
32
  from .a11yaudit import normalize_report # noqa: E402 (compat 5.10)
32
33
  import sys
@@ -193,10 +194,11 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
193
194
  # matriz de criterios: los que tocamos (estado según hallazgos) + manuales
194
195
  from .a11ycrit import _C as _CAT, effort
195
196
  codes_aa = sorted(k for k, v in _CAT.items() if v[0] in ('A', 'AA'))
196
- touched = {}
197
+ touched, values = {}, {}
197
198
  for inf in pages:
198
199
  for h in inf.get('findings', []):
199
- if h.get('status') == 'rejected' or h.get('disprover_status') == 'rejected':
200
+ if (not isinstance(h, dict) or h.get('status') == 'rejected'
201
+ or h.get('disprover_status') == 'rejected'):
200
202
  continue
201
203
  crit = h.get('criterion')
202
204
  if not crit or not isinstance(crit, str): # informe malformado: saltar
@@ -210,8 +212,23 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
210
212
  and h.get('disprover_status') != 'not-rechecked'
211
213
  else 'automated-review')
212
214
  # el peor estado gana: fail > review
213
- if touched.get(code) != 'automated-fail':
215
+ previous = touched.get(code)
216
+ if previous != 'automated-fail':
214
217
  touched[code] = state
218
+ if previous != state:
219
+ values.pop(code, None)
220
+ if touched[code] == state and code not in values:
221
+ value = {}
222
+ issue = str(h.get('issue') or '')
223
+ if 'ratio' in issue.lower() or ':' in issue:
224
+ match = re.search(r'([\d.]+):1', issue)
225
+ if match:
226
+ value['measured'] = f'{match.group(1)}:1'
227
+ examples = h.get('examples')
228
+ if isinstance(examples, list) and examples:
229
+ value['example'] = str(examples[0])[:80]
230
+ if value:
231
+ values[code] = value
215
232
 
216
233
  verified = {v.split(' ')[0] for v in (verified or [])}
217
234
 
@@ -232,25 +249,6 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
232
249
  continue
233
250
  reason = row.get('reason')
234
251
  excluded[crit.split(' ')[0]] = reason if isinstance(reason, str) else ''
235
- # extraer valores medidos clave de los hallazgos (ratio, ejemplos)
236
- values = {}
237
- for inf in pages:
238
- for h in inf.get('findings', []):
239
- code = str(h.get('criterion') or '').split(' ')[0]
240
- if code not in values:
241
- val = {}
242
- issue_txt = str(h.get('issue') or '')
243
- if 'ratio' in issue_txt.lower() or ':' in issue_txt:
244
- import re as _re
245
- m = _re.search(r'([\d.]+):1', issue_txt)
246
- if m:
247
- val['measured'] = f'{m.group(1)}:1'
248
- _ex_list = h.get('examples', [])
249
- if isinstance(_ex_list, list) and _ex_list:
250
- val['example'] = str(_ex_list[0])[:80]
251
- if val:
252
- values[code] = val
253
-
254
252
  # criterios que requieren modos que este pack no incluye → not-run con el
255
253
  # nombre de la herramienta que falta (canónico en a11ycrit, re-derivado)
256
254
  from .a11ycrit import MODES_BY_CRITERION as _MODES_BY
@@ -30,7 +30,8 @@ from datetime import datetime, timezone
30
30
 
31
31
  import tempfile
32
32
 
33
- from .a11yaudit import audit_conditions, completed_report_pages, normalize_signal, page_identity
33
+ from .a11yaudit import (audit_conditions, audit_conditions_match, completed_report_pages,
34
+ normalize_signal, page_identity)
34
35
 
35
36
  # per-path lock: always multi-thread; multi-process on POSIX (fcntl).
36
37
  # Without it, two concurrent writes left a truncated JSON (external review
@@ -154,8 +155,9 @@ def _record(url, report, ledger=None, path='a11y-ledger.json', lang='en'):
154
155
  'Use a different ledger for a different scope.')}
155
156
  current_conditions = {page_identity(page): value for page, value in page_conditions.items()}
156
157
  previous_conditions = prev.get('page_conditions', {})
157
- if prev and any(previous_conditions.get(page, {}) != current_conditions.get(page_identity(page), {})
158
- for page in previous_pages):
158
+ if prev and any(not audit_conditions_match(page_mode, previous_conditions.get(page, {}),
159
+ current_conditions.get(page_identity(page), {}))
160
+ for page, page_mode in previous_pages.items()):
159
161
  return {'error': ('Cambiaron las condiciones de captura o el historial antiguo no las registra.'
160
162
  if lang == 'es' else
161
163
  'Capture conditions changed or were not recorded in the old ledger.')}
@@ -356,16 +356,16 @@ def _test_sliders(page, findings, lang, cap=3):
356
356
 
357
357
  def audit_patterns(url, timeout=45, lang='en', auth_state=None, browser='auto'):
358
358
  """One url → widget patterns found + contract findings (filter, not verdict)."""
359
- from .a11ydom import _get_browser, _pooled_page
359
+ from .a11ydom import _get_browser, _load_error, _load_page, _pooled_page
360
360
  lang = 'es' if lang == 'es' else 'en'
361
361
  nav = _get_browser(preferred=browser)
362
362
  page, close_page = _pooled_page(nav, auth_state)
363
363
  try:
364
364
  try:
365
- page.goto(url, wait_until='load', timeout=timeout * 1000)
365
+ _load_page(page, url, timeout * 1000)
366
366
  page.wait_for_timeout(400)
367
367
  except Exception as e: # noqa: BLE001
368
- return {'error': f'could not load: {e}'}
368
+ return _load_error(e, lang, 'could not load: {e}')
369
369
 
370
370
  counts = page.evaluate(_COUNTS)
371
371
  findings = []
@@ -80,17 +80,17 @@ def _add(findings, lang, sev, code, key, **fmt):
80
80
 
81
81
  def audit_scroll(url, max_batches=5, lang='en', timeout=45, auth_state=None, browser='auto',
82
82
  interactive=False, load_more=None):
83
- from .a11ydom import _get_browser, _pooled_page
83
+ from .a11ydom import _get_browser, _load_error, _load_page, _pooled_page
84
84
  nav = _get_browser(preferred=browser)
85
85
  # BrowserContext.new_page() NO acepta viewport: _pooled_page lo manda al
86
86
  # new_context cuando hay auth_state
87
87
  page, close_page = _pooled_page(nav, auth_state, viewport={'width': 1280, 'height': 800})
88
88
  try:
89
89
  try:
90
- page.goto(url, wait_until='load', timeout=timeout * 1000)
90
+ _load_page(page, url, timeout * 1000)
91
91
  page.wait_for_timeout(500)
92
92
  except Exception as e: # noqa: BLE001
93
- return {'error': f'no se pudo cargar: {e}'}
93
+ return _load_error(e, lang, 'no se pudo cargar: {e}')
94
94
  page.evaluate(_MON)
95
95
  page.evaluate("(() => { const c = document.querySelector("
96
96
  " 'article a[href], [role=article] a[href], main li a[href]');"
@@ -33,6 +33,7 @@ import sys
33
33
  from datetime import datetime, timezone
34
34
 
35
35
  from . import a11ydiff
36
+ from .a11ydom import _NavigationHTTPError, _load_page
36
37
 
37
38
  # Silent live-region collector: accumulates announcements and exposes a
38
39
  # drain() so each trace step reads EXACTLY the announcements it triggered.
@@ -97,19 +98,6 @@ _DIALOG_STATE_JS = '''() => {
97
98
  }'''
98
99
 
99
100
 
100
- class _TraceHttpError(Exception):
101
- def __init__(self, status, url):
102
- super().__init__(f'HTTP {status}: could not capture the requested page')
103
- self.status = status
104
- self.url = url
105
-
106
-
107
- def _goto(page, url, timeout):
108
- response = page.goto(url, wait_until='load', timeout=timeout)
109
- if response is not None and response.status >= 400:
110
- raise _TraceHttpError(response.status, page.url)
111
-
112
-
113
101
  def _run_script_action(page, act):
114
102
  """One scripted action → (label, ok). Selector-valued actions target CSS."""
115
103
  kind = act.get('kind', '')
@@ -131,7 +119,7 @@ def _run_script_action(page, act):
131
119
  page.wait_for_timeout(int(act.get('ms', 300)))
132
120
  return f'wait:{act.get("ms", 300)}', True
133
121
  if kind == 'goto':
134
- _goto(page, act.get('url', ''), timeout=30000)
122
+ _load_page(page, act.get('url', ''), timeout=30000)
135
123
  # la navegación destruye el recolector (contexto nuevo): re-inyectarlo
136
124
  # o el drain de ESTE paso y de los siguientes tronaría/volvería vacío
137
125
  page.evaluate(_COLLECTOR)
@@ -146,15 +134,17 @@ def _run_script(page, script, dialog_state=False, check_navigation=None):
146
134
  navigations = 0
147
135
  url_now = page.url
148
136
  for i, act in enumerate(script):
149
- if not isinstance(act, dict):
150
- continue
151
137
  try:
152
- label, _ok = _run_script_action(page, act)
153
- except _TraceHttpError:
138
+ if isinstance(act, dict):
139
+ label, succeeded = _run_script_action(page, act)
140
+ else:
141
+ label, succeeded = 'invalid action', False
142
+ except _NavigationHTTPError:
154
143
  raise
155
144
  except Exception as e: # noqa: BLE001 — a failed action is a recorded step too
156
145
  label = f'{act.get("kind", "?")}:{act.get("selector") or act.get("key") or ""}'
157
146
  label += f' (failed: {str(e)[:60]})'
147
+ succeeded = False
158
148
  page.wait_for_timeout(200)
159
149
  if check_navigation is not None:
160
150
  check_navigation()
@@ -163,7 +153,7 @@ def _run_script(page, script, dialog_state=False, check_navigation=None):
163
153
  if page.url != url_now:
164
154
  navigations += 1
165
155
  url_now = page.url
166
- step = {'step': i + 1, 'action': label, 'focus': info,
156
+ step = {'step': i + 1, 'action': label, 'action_succeeded': succeeded, 'focus': info,
167
157
  'announcements': anns, 'url': page.url}
168
158
  if dialog_state:
169
159
  try:
@@ -190,6 +180,8 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
190
180
  el foco al opener pero DEJA el modal abierto es una divergencia de
191
181
  estado que el foco solo no ve."""
192
182
  from .a11ydom import _get_browser, _pooled_page
183
+ if script is not None and (not isinstance(script, list) or not script):
184
+ return {'error': 'the trace script must be a non-empty list of actions'}
193
185
  nav = _get_browser(preferred=browser)
194
186
  page, close_page = _pooled_page(nav, auth_state)
195
187
  navigation_error = None
@@ -199,7 +191,7 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
199
191
  request = response.request
200
192
  if (navigation_error is None and response.status >= 400
201
193
  and request.is_navigation_request() and request.frame == page.main_frame):
202
- navigation_error = _TraceHttpError(response.status, response.url)
194
+ navigation_error = _NavigationHTTPError(response.status, response.url)
203
195
 
204
196
  def check_navigation():
205
197
  if navigation_error is not None:
@@ -208,8 +200,8 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
208
200
  try:
209
201
  page.on('response', observe_response)
210
202
  try:
211
- _goto(page, url, timeout=timeout * 1000)
212
- except _TraceHttpError:
203
+ _load_page(page, url, timeout=timeout * 1000)
204
+ except _NavigationHTTPError:
213
205
  raise
214
206
  except Exception as e: # noqa: BLE001
215
207
  return {'error': f'could not load: {e}'}
@@ -256,8 +248,8 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
256
248
  except Exception: # noqa: BLE001
257
249
  tree = None
258
250
  check_navigation()
259
- except _TraceHttpError as e:
260
- return {'error': str(e), 'url': e.url, 'http_status': e.status}
251
+ except _NavigationHTTPError as e:
252
+ return e.report()
261
253
  finally:
262
254
  close_page()
263
255
 
@@ -266,6 +258,7 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
266
258
  **({'dialog_state_captured': True} if capture_dialog_state else {}),
267
259
  'steps': walk,
268
260
  'summary': {'steps_taken': len(walk),
261
+ 'failed_actions': sum(s.get('action_succeeded') is False for s in walk),
269
262
  'announcements': sum(len(s.get('announcements') or [])
270
263
  for s in walk),
271
264
  'navigations': navigations,
@@ -339,17 +332,25 @@ def _trace_error(trace):
339
332
  or (step.get('announcements') is not None
340
333
  and not isinstance(step['announcements'], list))):
341
334
  return f'invalid step {index}'
335
+ succeeded = step.get('action_succeeded')
336
+ if 'action_succeeded' in step and type(succeeded) is not bool:
337
+ return f'invalid action status at step {index}'
338
+ action = step.get('action')
339
+ legacy_failure = (succeeded is None and isinstance(action, str)
340
+ and (action.startswith('unknown:') or ' (failed:' in action))
341
+ if succeeded is False or legacy_failure:
342
+ return f'script action failed at step {index}'
342
343
  return None
343
344
 
344
345
 
345
346
  def trace_diff(a, b, gate_dialog_state=False):
346
- """Two traces → verdict. Focus behavior gates; announcements inform.
347
+ """Two traces → verdict. Failed actions invalidate a capture.
347
348
 
348
349
  gate_dialog_state (issue #16): OPT-IN — compara también el estado de
349
350
  diálogo capturado (trace --capture-dialog-state). Sin foco perdido ni
350
351
  reordenado pero con el modal ABIERTO donde antes cerraba: regresión.
351
352
  Evidencia faltante o acciones distintas → INCONCLUSIVE, nunca un falso
352
- PASS. El foco sigue siendo el único gate por defecto."""
353
+ PASS. El foco se compara después de validar la ejecución."""
353
354
  for label, capture in (('reference', a), ('candidate', b)):
354
355
  error = _trace_error(capture)
355
356
  if error:
@@ -382,7 +383,8 @@ def trace_diff(a, b, gate_dialog_state=False):
382
383
  'focus': {'before': fa, 'after': fb, 'lost': lost, 'gained': gained,
383
384
  'first_divergence': first_divergence},
384
385
  **({'dialog_gate': gate} if gate_dialog_state else {}),
385
- 'note': ('focus behavior is the gate: a lost or forked tab sequence '
386
+ 'note': ('failed scripted actions invalidate the capture (exit 1); '
387
+ 'a lost or forked tab sequence '
386
388
  'blocks (exit 2). Announcement counts are reported, not '
387
389
  'gated — content changes legitimately between builds; a '
388
390
  'collapsed layer (had announcements, now zero) is flagged '
@@ -97,7 +97,7 @@ try:
97
97
  except ImportError:
98
98
  ARIALIVE_JS = None # repo checkout: read the file
99
99
 
100
- VERSION = '5.35.0'
100
+ VERSION = '5.35.1'
101
101
 
102
102
  # Params renombrados a inglés en 5.11.0; se aceptan los nombres previos.
103
103
  PARAM_ALIASES = {
@@ -558,12 +558,13 @@ TOOLS = [
558
558
  'name': 'a11y_disprove',
559
559
  'description': ('Re-audits the original live page and returns its current findings, '
560
560
  'score and coverage. Rendered reports are rechecked under their '
561
- 'recorded color scheme. Matching findings are confirmed, disappeared '
561
+ 'recorded browser, color scheme and session type. Matching findings are confirmed, disappeared '
562
562
  'findings are rejected, and ambiguous historical matches are kept '
563
563
  'for review. — Use a11y_evidence to seal the fresh measurement.'),
564
564
  'inputSchema': {'type': 'object', 'properties': {
565
565
  'url': {'type': 'string', 'description': 'URL to re-verify against'},
566
566
  'report': {'type': 'object', 'description': 'existing audit report (optional; if absent, audits first)'},
567
+ 'auth_state': {'type': 'string', 'description': 'Local Playwright session for the original authenticated capture'},
567
568
  'lang': {'type': 'string', 'enum': ['es', 'en'], 'description': 'Output language (en default)'},
568
569
  'timeout': {'type': 'number', 'description': 'Timeout seconds (30 default)'},
569
570
  }, 'required': ['url']},
@@ -1016,6 +1017,7 @@ _PARAM_DOCS = {
1016
1017
  ('a11y_forced_colors', 'timeout'): 'Page load timeout seconds (45 default)',
1017
1018
  ('a11y_disprove', 'url'): 'URL to re-verify findings against',
1018
1019
  ('a11y_disprove', 'report'): 'Existing audit report to verify (optional; audits first if absent)',
1020
+ ('a11y_disprove', 'auth_state'): 'Local Playwright session file for the original authenticated capture',
1019
1021
  ('a11y_disprove', 'timeout'): 'Fetch timeout seconds (default 30)',
1020
1022
  ('a11y_ledger', 'action'): 'record (add audit), gaps (what is missing), or summary (overview)',
1021
1023
  ('a11y_ledger', 'url'): 'URL being audited (for record/gaps)',
@@ -1501,7 +1503,7 @@ def invoke(name, args):
1501
1503
  try:
1502
1504
  return _content(disprove_fn(args['url'], report=args.get('report'),
1503
1505
  timeout=args.get('timeout', 30),
1504
- lang=args.get('lang', 'en')))
1506
+ lang=args.get('lang', 'en'), auth_state=args.get('auth_state')))
1505
1507
  except Exception as e:
1506
1508
  return {'content': [{'type': 'text', 'text': f'error: {e}'}], 'isError': True}
1507
1509
  if name == 'a11y_ledger':
package/lib/_bootstrap.py CHANGED
@@ -16,8 +16,8 @@ _ENGINE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
16
16
  sys.path.insert(0, _ENGINE)
17
17
 
18
18
  _ENTRY = {
19
- 'a11y_toolkit.a11y': 'main',
20
- 'a11y_toolkit.server': 'main',
19
+ 'a11y_toolkit.a11y',
20
+ 'a11y_toolkit.server',
21
21
  }
22
22
 
23
23
 
@@ -25,8 +25,10 @@ def _run(entry, args):
25
25
  if entry not in _ENTRY:
26
26
  print(f'unknown entry: {entry}', file=sys.stderr)
27
27
  return 2
28
- module = __import__(entry, fromlist=[_ENTRY[entry]])
29
- return getattr(module, _ENTRY[entry])(args)
28
+ module = __import__(entry, fromlist=['main'])
29
+ if entry == 'a11y_toolkit.server':
30
+ return module.main()
31
+ return module.main(args)
30
32
 
31
33
 
32
34
  if __name__ == '__main__':
package/lib/runner.cjs CHANGED
@@ -35,7 +35,7 @@ function run(entry) {
35
35
  return;
36
36
  }
37
37
  const SCRIPTS = { 'a11y_toolkit.a11y': 'a11ytoolkit', 'a11y_toolkit.server': 'a11y-toolkit-mcp' };
38
- const child = spawn(UVX, ['--from', `a11y-toolkit==${VERSION}`, SCRIPTS[entry] || entry], { stdio: 'inherit' });
38
+ const child = spawn(UVX, ['--from', `a11y-toolkit==${VERSION}`, SCRIPTS[entry] || entry, ...args], { stdio: 'inherit' });
39
39
  child.on('error', (e) => {
40
40
  if (e.code === 'ENOENT') {
41
41
  console.error('a11y-toolkit: needs python3 (>=3.9) or uv.');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kinti/a11y-toolkit",
3
- "version": "5.35.0",
3
+ "version": "5.35.1",
4
4
  "mcpName": "io.github.kinti/a11y-toolkit",
5
5
  "description": "Zero-dependency WCAG 2.2 accessibility engine (37 MCP tools + CLI): audits, contrast fixing, SHA-256-sealed evidence packs, SARIF, EARL/ACT, CI ratchet. Self-contained: the pure-stdlib Python engine ships inside and runs via python3 \u2014 no downloads, no installs.",
6
6
  "license": "MIT",