@kinti/a11y-toolkit 5.28.0 → 5.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/a11y_toolkit/a11yact.py +17 -8
- package/a11y_toolkit/a11yaudit.py +255 -79
- package/a11y_toolkit/a11ybudget.py +21 -1
- package/a11y_toolkit/a11ycorpus.py +8 -1
- package/a11y_toolkit/a11ycrit.py +74 -0
- package/a11y_toolkit/a11ydiff.py +24 -11
- package/a11y_toolkit/a11ydisprove.py +27 -4
- package/a11y_toolkit/a11ydocx.py +28 -4
- package/a11y_toolkit/a11ydom.py +618 -370
- package/a11y_toolkit/a11yengines.py +19 -6
- package/a11y_toolkit/a11yevidence.py +34 -11
- package/a11y_toolkit/a11yfingerprints.py +8 -5
- package/a11y_toolkit/a11yfix.py +21 -2
- package/a11y_toolkit/a11yinit.py +24 -5
- package/a11y_toolkit/a11yjourney.py +7 -0
- package/a11y_toolkit/a11yledger.py +9 -0
- package/a11y_toolkit/a11ylocate.py +7 -1
- package/a11y_toolkit/a11yopenacr.py +16 -1
- package/a11y_toolkit/a11ypatterns.py +133 -43
- package/a11y_toolkit/a11ypdf.py +26 -5
- package/a11y_toolkit/a11ysarif.py +10 -2
- package/a11y_toolkit/a11yscope.py +19 -0
- package/a11y_toolkit/a11yscroll.py +48 -23
- package/a11y_toolkit/a11ytrace.py +6 -8
- package/a11y_toolkit/a11yvpat.py +11 -1
- package/a11y_toolkit/a11yvtt.py +33 -3
- package/a11y_toolkit/arialive.js +17 -7
- package/a11y_toolkit/contrast.py +12 -5
- package/a11y_toolkit/locales/_template.json +9 -3
- package/a11y_toolkit/locales/en.json +13 -0
- package/a11y_toolkit/locales/es.json +13 -0
- package/a11y_toolkit/server.py +39 -12
- package/lib/_bootstrap.py +36 -0
- package/lib/runner.cjs +12 -4
- package/package.json +1 -1
package/a11y_toolkit/a11ydom.py
CHANGED
|
@@ -44,7 +44,16 @@ _LIMITS_MOTION = {
|
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
from . import a11yi18n
|
|
47
|
-
|
|
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(
|
|
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
|
|
106
|
-
|
|
107
|
-
|
|
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
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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);
|
|
@@ -988,28 +1098,60 @@ _JS_FORM_STATE = r'''(pre) => {
|
|
|
988
1098
|
return out;
|
|
989
1099
|
}'''
|
|
990
1100
|
|
|
1101
|
+
# 18-nov: label→foco. Click en un <label> asociado debe enfocar su campo:
|
|
1102
|
+
# es comportamiento nativo del spec, así que si falla solo puede ser JS
|
|
1103
|
+
# saboteándolo (preventDefault de date-pickers y amigos). DATO, no hallazgo:
|
|
1104
|
+
# hasta calibrar la prevalencia real, la honesty manda (filter, not verdict).
|
|
1105
|
+
_JS_LABEL_FOCUS = r'''() => {
|
|
1106
|
+
const out = {checked: 0, failures: []};
|
|
1107
|
+
for (const lb of document.querySelectorAll('label')) {
|
|
1108
|
+
if (out.checked >= 8) break;
|
|
1109
|
+
const ctl = lb.control
|
|
1110
|
+
|| (lb.getAttribute('for') ? document.getElementById(lb.getAttribute('for')) : null);
|
|
1111
|
+
if (!ctl) continue;
|
|
1112
|
+
const tag = ctl.tagName.toLowerCase();
|
|
1113
|
+
const type = (ctl.getAttribute('type') || '').toLowerCase();
|
|
1114
|
+
if (tag === 'button' || tag === 'a'
|
|
1115
|
+
|| (tag === 'input' && ['submit', 'button', 'reset', 'image'].includes(type)))
|
|
1116
|
+
continue; // click podría ENVIAR: fuera del alcance
|
|
1117
|
+
if (ctl.disabled) continue;
|
|
1118
|
+
if (!ctl.offsetParent && getComputedStyle(ctl).display === 'none'
|
|
1119
|
+
&& getComputedStyle(ctl).visibility === 'hidden') continue;
|
|
1120
|
+
out.checked++;
|
|
1121
|
+
const sel = 'label' + (lb.htmlFor ? '[for="' + lb.htmlFor + '"]' : ':nth-of-type(1)');
|
|
1122
|
+
lb.click();
|
|
1123
|
+
const ae = document.activeElement;
|
|
1124
|
+
if (!(ae === ctl || (ae && ctl.contains(ae))))
|
|
1125
|
+
out.failures.push(sel + ' → ' + tag + (type ? '[type=' + type + ']' : ''));
|
|
1126
|
+
try { ctl.blur(); } catch (e) {}
|
|
1127
|
+
}
|
|
1128
|
+
return out;
|
|
1129
|
+
}'''
|
|
1130
|
+
|
|
991
1131
|
def audit_forms(url, timeout=45, lang='en', auth_state=None, browser='auto'):
|
|
992
1132
|
"""3.3.1 Error Identification / 3.3.3 Error Suggestion — the guided flow:
|
|
993
1133
|
fill every validatable field with INVALID data, really submit, then judge
|
|
994
1134
|
how errors are identified and announced in the post-submit DOM."""
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
999
|
-
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:
|
|
1000
1138
|
try:
|
|
1001
1139
|
page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
1002
1140
|
page.wait_for_timeout(400)
|
|
1003
1141
|
except Exception as e: # noqa: BLE001
|
|
1004
|
-
nav.close()
|
|
1005
1142
|
return {'error': _t(lang, 'fetch_error').format(e=e)}
|
|
1006
1143
|
url_before = page.url
|
|
1007
1144
|
pre = page.evaluate(_JS_FORM_PRE)
|
|
1145
|
+
try:
|
|
1146
|
+
label_focus = page.evaluate(_JS_LABEL_FOCUS)
|
|
1147
|
+
except Exception: # noqa: BLE001 — página hostil: sin dato, sin excusa
|
|
1148
|
+
label_focus = {'checked': 0, 'failures': []}
|
|
1008
1149
|
touched = page.evaluate(_JS_FORM_FILL)
|
|
1009
1150
|
page.wait_for_timeout(900)
|
|
1010
1151
|
navigated = page.url.split('#')[0] != url_before.split('#')[0]
|
|
1011
1152
|
state = None if navigated else page.evaluate(_JS_FORM_STATE, pre)
|
|
1012
|
-
|
|
1153
|
+
finally:
|
|
1154
|
+
close_page()
|
|
1013
1155
|
|
|
1014
1156
|
findings = []
|
|
1015
1157
|
|
|
@@ -1030,17 +1172,24 @@ def audit_forms(url, timeout=45, lang='en', auth_state=None, browser='auto'):
|
|
|
1030
1172
|
suggested_fields = sum(f['suggested'] for f in state['forms'])
|
|
1031
1173
|
if error_fields > 0 and suggested_fields == 0:
|
|
1032
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']))
|
|
1033
1181
|
|
|
1034
1182
|
from .a11yaudit import compute_score
|
|
1035
1183
|
return {
|
|
1036
1184
|
'url': url, 'mode': 'forms',
|
|
1037
1185
|
'invalid_fields': len(touched),
|
|
1186
|
+
'label_focus': label_focus,
|
|
1038
1187
|
'detail': touched[:10],
|
|
1039
1188
|
'score': compute_score(findings),
|
|
1040
1189
|
'summary': {s_: sum(1 for h in findings if h['severity'] == s_)
|
|
1041
1190
|
for s_ in ('high', 'medium', 'low')},
|
|
1042
1191
|
'findings': findings,
|
|
1043
|
-
'limits': _t(lang, 'limits'),
|
|
1192
|
+
'limits': _t(lang, 'limits') + ' ' + _t(lang, 'label_focus_note'),
|
|
1044
1193
|
}
|
|
1045
1194
|
|
|
1046
1195
|
|
|
@@ -1053,77 +1202,87 @@ def sr_transcript(url, timeout=45, lang='en', auth_state=None, browser='auto'):
|
|
|
1053
1202
|
structure; this function returns it as prose an agent can READ and
|
|
1054
1203
|
understand from a blind user's perspective.
|
|
1055
1204
|
"""
|
|
1056
|
-
# J4 (ronda 4): el driver de playwright NUNCA se paraba — una fuga
|
|
1057
|
-
#
|
|
1058
|
-
|
|
1059
|
-
|
|
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)
|
|
1060
1211
|
try:
|
|
1061
|
-
nav = _get_browser(pw, preferred=browser)
|
|
1062
|
-
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
1063
|
-
page = ctx.new_page() if auth_state else nav.new_page()
|
|
1064
1212
|
try:
|
|
1065
1213
|
page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
1066
1214
|
page.wait_for_timeout(400)
|
|
1067
1215
|
except Exception as e:
|
|
1068
|
-
ctx.close()
|
|
1069
|
-
_close_pool()
|
|
1070
1216
|
return {'error': str(e)[:100]}
|
|
1071
1217
|
|
|
1072
1218
|
try:
|
|
1073
1219
|
tree = page.locator('body').aria_snapshot()
|
|
1074
1220
|
except Exception:
|
|
1075
1221
|
tree = None
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
if announcement:
|
|
1095
|
-
announcements.append(announcement)
|
|
1096
|
-
|
|
1097
|
-
return {
|
|
1098
|
-
'url': url,
|
|
1099
|
-
'mode': 'sr-transcript',
|
|
1100
|
-
'announcements': announcements[:200], # cap
|
|
1101
|
-
'total': len(announcements),
|
|
1102
|
-
'arbol_raw': tree[:5000] if len(tree) > 5000 else tree,
|
|
1103
|
-
'note': ('Linearized announcement order — what a screen reader user hears. '
|
|
1104
|
-
'Roles and names as computed by the browser. Use this to understand '
|
|
1105
|
-
'the page from a blind user\'s perspective.'),
|
|
1106
|
-
}
|
|
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)
|
|
1107
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)))")
|
|
1108
1265
|
|
|
1109
|
-
finally:
|
|
1110
|
-
try:
|
|
1111
|
-
pw.stop()
|
|
1112
|
-
except Exception: # noqa: BLE001
|
|
1113
|
-
pass
|
|
1114
1266
|
_JS_HOVER_TEST = r'''() => {
|
|
1115
|
-
// 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
|
|
1116
1271
|
const candidates = [];
|
|
1272
|
+
let n = 0;
|
|
1117
1273
|
for (const el of document.querySelectorAll('[title], [data-tooltip], [aria-describedby]')) {
|
|
1118
1274
|
if (candidates.length >= 10) break;
|
|
1119
1275
|
const r = el.getBoundingClientRect();
|
|
1120
1276
|
if (r.width > 10 && r.height > 10 && r.top >= 0 && r.top < innerHeight) {
|
|
1277
|
+
el.setAttribute('data-a11yhover', String(n));
|
|
1121
1278
|
candidates.push({
|
|
1122
1279
|
tag: el.tagName.toLowerCase(),
|
|
1123
1280
|
id: el.id || '',
|
|
1281
|
+
idx: n,
|
|
1124
1282
|
desc: el.getAttribute('aria-describedby') || el.getAttribute('title') || '',
|
|
1125
1283
|
rect: {x: r.x, y: r.y, w: r.width, h: r.height}
|
|
1126
1284
|
});
|
|
1285
|
+
n++;
|
|
1127
1286
|
}
|
|
1128
1287
|
}
|
|
1129
1288
|
return candidates;
|
|
@@ -1131,64 +1290,47 @@ _JS_HOVER_TEST = r'''() => {
|
|
|
1131
1290
|
|
|
1132
1291
|
def audit_hover(url, timeout=45, lang='en', auth_state=None, browser='auto'):
|
|
1133
1292
|
"""1.4.13 Content on Hover or Focus: do tooltips dismiss on Escape?"""
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
1138
|
-
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:
|
|
1139
1296
|
try:
|
|
1140
1297
|
page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
1141
1298
|
page.wait_for_timeout(400)
|
|
1142
1299
|
except Exception as e:
|
|
1143
|
-
nav.close()
|
|
1144
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)
|
|
1145
1304
|
|
|
1146
1305
|
candidates = page.evaluate(_JS_HOVER_TEST)
|
|
1147
1306
|
no_dismissibles = []
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
"() => [...document.querySelectorAll("
|
|
1176
|
-
"'[role=tooltip], [class*=tooltip], [class*=popover]')]"
|
|
1177
|
-
".filter(el => {"
|
|
1178
|
-
" if (el.checkVisibility) "
|
|
1179
|
-
" return el.checkVisibility({checkOpacity: true, checkVisibilityCSS: true});"
|
|
1180
|
-
" const s = getComputedStyle(el);"
|
|
1181
|
-
" const box = el.getBoundingClientRect();"
|
|
1182
|
-
" return el.offsetParent !== null && s.visibility !== 'hidden'"
|
|
1183
|
-
" && parseFloat(s.opacity || '1') > 0.01 && box.width > 0;"
|
|
1184
|
-
"})"
|
|
1185
|
-
".map(el => el.tagName + '#' + (el.id || '') + '.' + (el.className.toString().slice(0, 30)))")
|
|
1186
|
-
if set(before) <= set(after):
|
|
1187
|
-
# los mismos (o más) siguen visibles: no se cerró con Escape
|
|
1188
|
-
no_dismissibles.append(f'{c["tag"]}#{c["id"] or "no-id"}')
|
|
1189
|
-
except Exception:
|
|
1190
|
-
continue
|
|
1191
|
-
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()
|
|
1192
1334
|
|
|
1193
1335
|
findings = []
|
|
1194
1336
|
if no_dismissibles:
|
|
@@ -1207,22 +1349,42 @@ def audit_hover(url, timeout=45, lang='en', auth_state=None, browser='auto'):
|
|
|
1207
1349
|
|
|
1208
1350
|
|
|
1209
1351
|
_JS_SPACING = r'''() => {
|
|
1210
|
-
// WCAG 1.4.12
|
|
1211
|
-
//
|
|
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
|
+
});
|
|
1212
1376
|
const css = document.createElement('style');
|
|
1213
1377
|
css.id = 'a11y-spacing-1412';
|
|
1214
1378
|
css.textContent = '*{line-height:1.5!important;letter-spacing:0.12em!important;'
|
|
1215
1379
|
+ 'word-spacing:0.16em!important} p{margin-bottom:2em!important}';
|
|
1216
1380
|
document.head.appendChild(css);
|
|
1217
1381
|
const clip = [];
|
|
1218
|
-
|
|
1219
|
-
if (clip.length >= 15)
|
|
1220
|
-
if (!el.offsetParent)
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
if (clipped) clip.push(el.tagName.toLowerCase() + (el.id ? '#' + el.id : ''));
|
|
1225
|
-
}
|
|
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
|
+
});
|
|
1226
1388
|
css.remove();
|
|
1227
1389
|
return clip;
|
|
1228
1390
|
}'''
|
|
@@ -1231,6 +1393,7 @@ _JS_HOVER = r'''(i) => {
|
|
|
1231
1393
|
const el = document.querySelector('[data-a11yidx="' + i + '"]');
|
|
1232
1394
|
if (!el) return null;
|
|
1233
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;}
|
|
1234
1397
|
if (!m) return null;
|
|
1235
1398
|
const p = m[1].split(',').map(x => parseFloat(x));
|
|
1236
1399
|
return { r: p[0], g: p[1], b: p[2], a: p.length > 3 ? p[3] : 1 }; };
|
|
@@ -1310,21 +1473,23 @@ def audit_reflow(url, timeout=45, lang='en', auth_state=None, browser='auto'):
|
|
|
1310
1473
|
un viewport de 320px, no emular zoom con CSS (validado empíricamente:
|
|
1311
1474
|
el truco de zoom CSS marca en falso páginas sanas porque no re-lleva a cabo
|
|
1312
1475
|
el layout)."""
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
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:
|
|
1317
1482
|
try:
|
|
1318
1483
|
page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
1319
1484
|
page.wait_for_timeout(300)
|
|
1320
1485
|
except Exception as e: # noqa: BLE001
|
|
1321
|
-
nav.close()
|
|
1322
1486
|
return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
|
|
1323
1487
|
|
|
1324
1488
|
page.set_viewport_size({'width': 320, 'height': 800})
|
|
1325
1489
|
page.wait_for_timeout(500)
|
|
1326
1490
|
r320 = page.evaluate(_JS_OVERFLOW)
|
|
1327
|
-
|
|
1491
|
+
finally:
|
|
1492
|
+
close_page()
|
|
1328
1493
|
|
|
1329
1494
|
findings = []
|
|
1330
1495
|
|
|
@@ -1432,16 +1597,13 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
|
|
|
1432
1597
|
ESCAPE libera el ciclo. Un modal que cicla y suelta con Escape es correcto;
|
|
1433
1598
|
uno que no suelta es trampa — hallazgo 'high'.
|
|
1434
1599
|
"""
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
1439
|
-
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:
|
|
1440
1603
|
try:
|
|
1441
1604
|
page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
1442
1605
|
page.wait_for_timeout(400)
|
|
1443
1606
|
except Exception as e: # noqa: BLE001
|
|
1444
|
-
nav.close()
|
|
1445
1607
|
return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
|
|
1446
1608
|
|
|
1447
1609
|
page.evaluate("document.querySelectorAll('[data-a11ystop]').forEach(e => {"
|
|
@@ -1461,9 +1623,14 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
|
|
|
1461
1623
|
seq.append(stop)
|
|
1462
1624
|
if stop not in paths:
|
|
1463
1625
|
paths[stop] = page.evaluate(_STOP_META, stop)
|
|
1464
|
-
# 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)
|
|
1465
1632
|
cycle = None
|
|
1466
|
-
for p_ in range(1,
|
|
1633
|
+
for p_ in range(1, len(seq) // 2 + 1):
|
|
1467
1634
|
if seq[-p_:] == seq[-2 * p_:-p_] and len(set(seq[-p_:])) >= 1:
|
|
1468
1635
|
# needs al menos 2 repeticiones completas del periodo
|
|
1469
1636
|
reps = sum(1 for k in range(len(seq) - p_, 0, -p_)
|
|
@@ -1471,6 +1638,9 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
|
|
|
1471
1638
|
if reps >= 2:
|
|
1472
1639
|
cycle = seq[-p_:]
|
|
1473
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)
|
|
1474
1644
|
|
|
1475
1645
|
# 3.2.1: ¿el foco provocó navegación? (context destroyed = navegación)
|
|
1476
1646
|
focus_navigated = None
|
|
@@ -1480,22 +1650,45 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
|
|
|
1480
1650
|
except Exception:
|
|
1481
1651
|
focus_navigated = url_before + ' → (navigated away)'
|
|
1482
1652
|
|
|
1483
|
-
# 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
|
|
1484
1658
|
input_navigated = None
|
|
1485
1659
|
input_elem = None
|
|
1660
|
+
select_observations = []
|
|
1486
1661
|
if not focus_navigated:
|
|
1487
1662
|
try:
|
|
1488
|
-
|
|
1489
|
-
|
|
1663
|
+
url_pre = page.url
|
|
1664
|
+
for sel in page.query_selector_all('select')[:3]:
|
|
1490
1665
|
opts = sel.query_selector_all('option')
|
|
1491
|
-
if len(opts)
|
|
1492
|
-
|
|
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:
|
|
1493
1677
|
sel.select_option(index=1)
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
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
|
|
1499
1692
|
pass
|
|
1500
1693
|
|
|
1501
1694
|
esc_releases = None
|
|
@@ -1538,10 +1731,8 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
|
|
|
1538
1731
|
skip['broken'].append(found['id'])
|
|
1539
1732
|
except Exception: # noqa: BLE001 — SPA o contexto destruido: sin dato
|
|
1540
1733
|
pass
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
except Exception:
|
|
1544
|
-
pass
|
|
1734
|
+
finally:
|
|
1735
|
+
close_page()
|
|
1545
1736
|
|
|
1546
1737
|
findings = []
|
|
1547
1738
|
if focus_navigated:
|
|
@@ -1550,7 +1741,9 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
|
|
|
1550
1741
|
'signal': 'focus_navigates',
|
|
1551
1742
|
'issue': _t(lang, 'focus_navigates').format(example='un elemento', url=focus_navigated[:60]),
|
|
1552
1743
|
'remediation': _t(lang, 'focus_navigates_rem')})
|
|
1553
|
-
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ó
|
|
1554
1747
|
findings.append({
|
|
1555
1748
|
'severity': 'high', 'criterion': CRIT.get(lang, CRIT['es']).get('3.2.2', '3.2.2'),
|
|
1556
1749
|
'signal': 'input_navigates',
|
|
@@ -1580,8 +1773,10 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
|
|
|
1580
1773
|
'summary': {s_: sum(1 for h in findings if h['severity'] == s_)
|
|
1581
1774
|
for s_ in ('high', 'medium', 'low')},
|
|
1582
1775
|
'steps': len(seq),
|
|
1776
|
+
'select_observations': select_observations,
|
|
1583
1777
|
'tab_stops': [paths.get(i, f'tab stop {i}') for i in seq],
|
|
1584
1778
|
'cycle': {'detected': bool(cycle),
|
|
1779
|
+
'budget_exhausted': budget_exhausted,
|
|
1585
1780
|
'elements': [paths.get(i, f'tab stop {i}') for i in cycle] if cycle else [],
|
|
1586
1781
|
'escape_releases': esc_releases},
|
|
1587
1782
|
'skip_link': {'checked': skip['checked'], 'label': skip.get('label'),
|
|
@@ -1724,7 +1919,6 @@ def audit_forced_colors(url, timeout=45, lang='en', auth_state=None, browser='au
|
|
|
1724
1919
|
dependen del color del autor pueden quedar invisible_els sobre el fondo
|
|
1725
1920
|
del sistema), y bordes usados como único indicador visual. Nadie más
|
|
1726
1921
|
lo automatiza."""
|
|
1727
|
-
from playwright.sync_api import sync_playwright
|
|
1728
1922
|
_JS_FC = r'''() => {
|
|
1729
1923
|
const invisible_els = [];
|
|
1730
1924
|
let n = 0;
|
|
@@ -1755,10 +1949,9 @@ def audit_forced_colors(url, timeout=45, lang='en', auth_state=None, browser='au
|
|
|
1755
1949
|
}'''
|
|
1756
1950
|
from .a11yaudit import _t as _t_audit, CRIT, compute_score
|
|
1757
1951
|
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
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:
|
|
1762
1955
|
try:
|
|
1763
1956
|
page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
1764
1957
|
page.wait_for_timeout(400)
|
|
@@ -1767,9 +1960,9 @@ def audit_forced_colors(url, timeout=45, lang='en', auth_state=None, browser='au
|
|
|
1767
1960
|
page.wait_for_timeout(400)
|
|
1768
1961
|
forced = page.evaluate(_JS_FC)
|
|
1769
1962
|
except Exception as e: # noqa: BLE001
|
|
1770
|
-
nav.close()
|
|
1771
1963
|
return {'error': _t_audit(lang, 'fetch_error').format(e=e)}
|
|
1772
|
-
|
|
1964
|
+
finally:
|
|
1965
|
+
close_page()
|
|
1773
1966
|
|
|
1774
1967
|
findings = []
|
|
1775
1968
|
if forced['coloredSvgs']:
|
|
@@ -1800,31 +1993,37 @@ def audit_reduced_motion(url, timeout=45, lang='en', auth_state=None, browser='a
|
|
|
1800
1993
|
vez. Si el número NO baja, el sitio ignora la preferencia del usuario
|
|
1801
1994
|
(2.2.2: pausa/parada/ocultar; 2.3.3 AAA). Nadie más lo automatiza:
|
|
1802
1995
|
axe lo deja en revisión manual."""
|
|
1803
|
-
from playwright.sync_api import sync_playwright
|
|
1804
1996
|
_JS_RM = r'''() => {
|
|
1805
|
-
|
|
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 = {};
|
|
1806
2002
|
for (const el of document.querySelectorAll('*')) {
|
|
1807
|
-
if (
|
|
2003
|
+
if (Object.keys(out).length >= 40) break;
|
|
1808
2004
|
const cs = getComputedStyle(el);
|
|
1809
|
-
|
|
2005
|
+
const counts = (cs.animationIterationCount || '').split(',');
|
|
1810
2006
|
const durs = (cs.animationDuration || '0s').split(',').map(
|
|
1811
2007
|
x => { const v = parseFloat(x) || 0; return x.includes('ms') ? v / 1000 : v; });
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
if (
|
|
1816
|
-
|
|
1817
|
-
|
|
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) + ')' };
|
|
1818
2018
|
}
|
|
1819
2019
|
const videos = document.querySelectorAll('video[autoplay]').length;
|
|
1820
|
-
return { anims:
|
|
2020
|
+
return { anims: out, videos };
|
|
1821
2021
|
}'''
|
|
1822
2022
|
from .a11yaudit import _t as _t_audit, CRIT, compute_score
|
|
1823
2023
|
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
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:
|
|
1828
2027
|
try:
|
|
1829
2028
|
page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
1830
2029
|
page.wait_for_timeout(600)
|
|
@@ -1833,25 +2032,40 @@ def audit_reduced_motion(url, timeout=45, lang='en', auth_state=None, browser='a
|
|
|
1833
2032
|
page.wait_for_timeout(600)
|
|
1834
2033
|
reduced = page.evaluate(_JS_RM)
|
|
1835
2034
|
except Exception as e: # noqa: BLE001
|
|
1836
|
-
nav.close()
|
|
1837
2035
|
return {'error': _t_audit(lang, 'fetch_error').format(e=e)}
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
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))
|
|
1841
2051
|
findings = []
|
|
1842
|
-
if
|
|
2052
|
+
if _n > 0 and not respects:
|
|
1843
2053
|
findings.append({
|
|
1844
2054
|
'severity': 'medium', 'criterion': CRIT.get(lang, CRIT['es']).get('2.2.2', '2.2.2'),
|
|
1845
2055
|
'signal': 'reduced_motion_ignored',
|
|
1846
|
-
'issue': _t_audit(lang, 'reduced_motion_ignored').format(
|
|
1847
|
-
n=normal['anims'], nr=reduced['anims']),
|
|
2056
|
+
'issue': _t_audit(lang, 'reduced_motion_ignored').format(n=_n, nr=_r),
|
|
1848
2057
|
'remediation': _t_audit(lang, 'reduced_motion_ignored_rem'),
|
|
1849
|
-
'examples':
|
|
2058
|
+
'examples': (motion['still_running']
|
|
2059
|
+
or [v['example'] for v in _norm.values()])[:4]})
|
|
1850
2060
|
order = {'high': 0, 'medium': 1, 'low': 2}
|
|
1851
2061
|
findings.sort(key=lambda h: order[h['severity']])
|
|
1852
2062
|
return {
|
|
1853
2063
|
'mode': 'reduced-motion', 'url': url,
|
|
1854
|
-
'normal':
|
|
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,
|
|
1855
2069
|
'respects': respects,
|
|
1856
2070
|
'score': compute_score(findings),
|
|
1857
2071
|
'findings': findings,
|
|
@@ -1868,72 +2082,92 @@ def audit_dom_url(url, timeout=45, lang='en', auth_state=None, browser='auto', c
|
|
|
1868
2082
|
:hover reales de los primeros controles marcados. auth_state: ruta a un
|
|
1869
2083
|
storage_state de Playwright (cookies/localStorage exportados con la sesión
|
|
1870
2084
|
iniciada) para auditar detrás de login."""
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
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:
|
|
1876
2090
|
if color_scheme in ('dark', 'light'):
|
|
1877
2091
|
# contraste por esquema: los temas oscuros fallan donde el claro
|
|
1878
2092
|
# pasa — nadie audita ambos (axe tampoco)
|
|
1879
2093
|
page.emulate_media(color_scheme=color_scheme)
|
|
1880
2094
|
try:
|
|
1881
|
-
page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
2095
|
+
_resp = page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
1882
2096
|
page.wait_for_timeout(400)
|
|
1883
2097
|
except Exception as e: # noqa: BLE001
|
|
1884
2098
|
if not page.content() or page.url in ('about:blank', ''):
|
|
1885
|
-
nav.close()
|
|
1886
2099
|
return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
if not c:
|
|
1899
|
-
continue
|
|
1900
|
-
m = _samples_background(
|
|
1901
|
-
page.locator(f'[data-a11ytxt="{z["i"]}"]'),
|
|
1902
|
-
{'x': z.get('x', 0), 'y': z.get('y', 0),
|
|
1903
|
-
'width': z.get('w', 1400), 'height': z.get('h', 400)}, c)
|
|
1904
|
-
if m:
|
|
1905
|
-
measured.append({'example': z['example'], 'fg': z['fg'],
|
|
1906
|
-
'large': bool(z.get('large')),
|
|
1907
|
-
'measured': m})
|
|
1908
|
-
except Exception: # noqa: BLE001
|
|
1909
|
-
continue
|
|
1910
|
-
data['contrastMeasured'] = measured
|
|
1911
|
-
# iframes same-origin: mismo colector por frame
|
|
1912
|
-
subframes = []
|
|
1913
|
-
for fr in page.frames[1:5]:
|
|
1914
|
-
try:
|
|
1915
|
-
subframes.append(fr.evaluate(_JS, MAX_EXAMPLES))
|
|
1916
|
-
except Exception: # noqa: BLE001
|
|
1917
|
-
continue # cross-origin o no escaneable
|
|
1918
|
-
data['iframes_data'] = subframes
|
|
1919
|
-
# hover real sobre los controles marcados
|
|
1920
|
-
hover = []
|
|
1921
|
-
for i in range(min(10, int(data.get('marks', 0)))):
|
|
1922
|
-
try:
|
|
1923
|
-
page.hover(f'[data-a11yidx="{i}"]', timeout=1000)
|
|
1924
|
-
r = page.evaluate(_JS_HOVER, i)
|
|
1925
|
-
if r and r['ratio'] < 3:
|
|
1926
|
-
hover.append(dict(r, example=f'hover #{i}'))
|
|
1927
|
-
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:
|
|
1928
2111
|
continue
|
|
1929
|
-
|
|
1930
|
-
|
|
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]:
|
|
1931
2126
|
try:
|
|
1932
|
-
|
|
1933
|
-
except Exception:
|
|
1934
|
-
|
|
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()
|
|
1935
2145
|
_merge_iframes(data)
|
|
1936
|
-
|
|
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
|
|
1937
2171
|
|
|
1938
2172
|
|
|
1939
2173
|
def contrast_dom(url, selector, text_color=None, sample=4, lang='en', timeout=45,
|
|
@@ -1947,58 +2181,52 @@ def contrast_dom(url, selector, text_color=None, sample=4, lang='en', timeout=45
|
|
|
1947
2181
|
Para text_ sobre imágenes, degradados, vídeo o cualquier fondo que el
|
|
1948
2182
|
cálculo CSS no puede resolver. Requiere Playwright.
|
|
1949
2183
|
"""
|
|
1950
|
-
from playwright.sync_api import sync_playwright
|
|
1951
2184
|
from .contrast import T as _TC
|
|
1952
2185
|
t9 = _TC.get(lang, _TC['es'])
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
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
|
|
1957
2192
|
try:
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
return {'error': t9['
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
if
|
|
1975
|
-
return {'error': t9['opaque_text']}
|
|
1976
|
-
try:
|
|
1977
|
-
box = loc.bounding_box()
|
|
1978
|
-
if not box or box['width'] < 3 or box['height'] < 3:
|
|
1979
|
-
return {'error': t9['no_box'].format(s=selector)}
|
|
1980
|
-
m = _samples_background(loc, box, c)
|
|
1981
|
-
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:
|
|
1982
2210
|
return {'error': t9['no_box'].format(s=selector)}
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
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()
|
|
2002
2230
|
|
|
2003
2231
|
|
|
2004
2232
|
# --- contrast walk: perceptual pass over EVERY rendered text element --------
|
|
@@ -2006,7 +2234,13 @@ def contrast_dom(url, selector, text_color=None, sample=4, lang='en', timeout=45
|
|
|
2006
2234
|
_JS_WALK = r'''(maxEls) => {
|
|
2007
2235
|
const visible = el => !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length);
|
|
2008
2236
|
const directText = el => [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim());
|
|
2009
|
-
const parseC = s => { const
|
|
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.]+))?\)/);
|
|
2010
2244
|
return m ? {r:+m[1], g:+m[2], b:+m[3], a: m[4] === undefined ? 1 : +m[4]} : null; };
|
|
2011
2245
|
const effBg = el => {
|
|
2012
2246
|
const layers = [];
|
|
@@ -2046,7 +2280,7 @@ _JS_WALK = r'''(maxEls) => {
|
|
|
2046
2280
|
if (!visible(el) || !directText(el)) continue;
|
|
2047
2281
|
const cs = getComputedStyle(el);
|
|
2048
2282
|
const color = parseC(cs.color);
|
|
2049
|
-
if (!color) continue;
|
|
2283
|
+
if (!color) { out.push({skip: 'unparsed-color', path: path(el)}); continue; }
|
|
2050
2284
|
if (color.a < 1) { out.push({skip: 'translucent', path: path(el)}); continue; }
|
|
2051
2285
|
const fs = parseFloat(cs.fontSize) || 16;
|
|
2052
2286
|
const fw = parseInt(cs.fontWeight) || 400;
|
|
@@ -2079,21 +2313,28 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
|
|
|
2079
2313
|
Filtro honesto, no veredicto: text_ en shadow DOM, canvas, vídeo y
|
|
2080
2314
|
pseudo-elementos no se captura; lo no medido se declara, jamás inventado.
|
|
2081
2315
|
"""
|
|
2082
|
-
from playwright.sync_api import sync_playwright
|
|
2083
2316
|
from .contrast import ratio as _ratio, suggest as _suggest, parse_color
|
|
2084
2317
|
|
|
2085
2318
|
def _verdicts(entries):
|
|
2086
2319
|
for e in entries:
|
|
2087
2320
|
if e['ratio'] is not None:
|
|
2088
|
-
|
|
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
|
|
2089
2327
|
|
|
2090
2328
|
def _pass(page):
|
|
2091
2329
|
raw = page.evaluate(_JS_WALK, max_walk)
|
|
2092
|
-
entries, shot_jobs, skipped = [], [], 0
|
|
2330
|
+
entries, shot_jobs, skipped, unparsed = [], [], 0, 0
|
|
2093
2331
|
for row in raw:
|
|
2094
2332
|
if row.get('skip') == 'translucent':
|
|
2095
2333
|
skipped += 1
|
|
2096
2334
|
continue
|
|
2335
|
+
if row.get('skip') == 'unparsed-color':
|
|
2336
|
+
unparsed += 1
|
|
2337
|
+
continue
|
|
2097
2338
|
fg = {k: row['color'][k] for k in ('r', 'g', 'b')}
|
|
2098
2339
|
bg = {k: row['bg'][k] for k in ('r', 'g', 'b')}
|
|
2099
2340
|
large = row['font_px'] >= 24 or (row['font_px'] >= 18.66 and row['bold'])
|
|
@@ -2107,7 +2348,12 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
|
|
|
2107
2348
|
if row['bg_image']:
|
|
2108
2349
|
shot_jobs.append((entry, fg))
|
|
2109
2350
|
else:
|
|
2110
|
-
|
|
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
|
|
2111
2357
|
entries.append(entry)
|
|
2112
2358
|
sampled = 0
|
|
2113
2359
|
for entry, fg in shot_jobs:
|
|
@@ -2127,7 +2373,7 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
|
|
|
2127
2373
|
except Exception: # noqa: BLE001 — one dead locator must not kill the walk
|
|
2128
2374
|
continue
|
|
2129
2375
|
_verdicts(entries)
|
|
2130
|
-
return entries, skipped
|
|
2376
|
+
return entries, skipped, unparsed
|
|
2131
2377
|
|
|
2132
2378
|
def _summarize(entries, skipped):
|
|
2133
2379
|
fails = [e for e in entries if e['verdict'] == 'fail']
|
|
@@ -2139,71 +2385,70 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
|
|
|
2139
2385
|
'fails_4_5_normal_text': sum(1 for e in fails if e['threshold'] >= 4.5),
|
|
2140
2386
|
'fails_3_0_large_text': sum(1 for e in fails if e['threshold'] < 4.5),
|
|
2141
2387
|
'translucent_text_skipped': skipped,
|
|
2388
|
+
'unparsed_colors': unparsed + (locals().get('_unp_d') or 0),
|
|
2142
2389
|
'pixel_sampled': sum(1 for e in entries if e['pixel_sampled']),
|
|
2143
2390
|
'worst_ratio': worst['ratio'] if worst else None,
|
|
2144
2391
|
'worst_element': worst['path'] if worst else None}
|
|
2145
2392
|
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
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:
|
|
2152
2403
|
try:
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
|
|
2165
|
-
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
if
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
'composición alfa; el text_ sobre imágenes/gradientes se muestrea '
|
|
2202
|
-
'por píxeles (peor caso) hasta el tope y el resto se declara sin '
|
|
2203
|
-
'medir. El text_ en shadow DOM, canvas, vídeo y pseudo-elementos '
|
|
2204
|
-
'no se captura. Un fallo es un hallazgo de filtro (1.4.3), no un '
|
|
2205
|
-
'veredicto — juzga la zona con contrast-dom.')
|
|
2206
|
-
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
|
|
2207
2452
|
|
|
2208
2453
|
|
|
2209
2454
|
def contrast_dom_main(argv):
|
|
@@ -2255,7 +2500,7 @@ def main(argv):
|
|
|
2255
2500
|
print(json.dumps({'error': str(e)}))
|
|
2256
2501
|
return 1
|
|
2257
2502
|
print(json.dumps(res, ensure_ascii=False, indent=1))
|
|
2258
|
-
return 0
|
|
2503
|
+
return 1 if isinstance(res, dict) and 'error' in res else 0
|
|
2259
2504
|
|
|
2260
2505
|
|
|
2261
2506
|
def reflow_main(argv):
|
|
@@ -2263,14 +2508,17 @@ def reflow_main(argv):
|
|
|
2263
2508
|
ap.add_argument('url')
|
|
2264
2509
|
ap.add_argument('--lang', default='en', choices=['en', 'es'])
|
|
2265
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')
|
|
2266
2513
|
a = ap.parse_args(argv)
|
|
2267
2514
|
try:
|
|
2268
|
-
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)
|
|
2269
2517
|
except ImportError:
|
|
2270
2518
|
print(json.dumps({'error': 'Playwright not installed'}))
|
|
2271
2519
|
return 1
|
|
2272
2520
|
print(json.dumps(res, ensure_ascii=False, indent=1))
|
|
2273
|
-
return 0
|
|
2521
|
+
return 1 if isinstance(res, dict) and 'error' in res else 0
|
|
2274
2522
|
|
|
2275
2523
|
|
|
2276
2524
|
def forms_main(argv):
|
|
@@ -2285,7 +2533,7 @@ def forms_main(argv):
|
|
|
2285
2533
|
print(json.dumps({'error': 'Playwright not installed'}))
|
|
2286
2534
|
return 1
|
|
2287
2535
|
print(json.dumps(res, ensure_ascii=False, indent=1))
|
|
2288
|
-
return 0
|
|
2536
|
+
return 1 if isinstance(res, dict) and 'error' in res else 0
|
|
2289
2537
|
|
|
2290
2538
|
|
|
2291
2539
|
def kbd_main(argv):
|
|
@@ -2300,7 +2548,7 @@ def kbd_main(argv):
|
|
|
2300
2548
|
print(json.dumps({'error': 'Playwright not installed'}))
|
|
2301
2549
|
return 1
|
|
2302
2550
|
print(json.dumps(res, ensure_ascii=False, indent=1))
|
|
2303
|
-
return 0
|
|
2551
|
+
return 1 if isinstance(res, dict) and 'error' in res else 0
|
|
2304
2552
|
|
|
2305
2553
|
|
|
2306
2554
|
def hover_main(argv):
|
|
@@ -2319,7 +2567,7 @@ def hover_main(argv):
|
|
|
2319
2567
|
print(json.dumps({'error': 'Playwright not installed'}))
|
|
2320
2568
|
return 1
|
|
2321
2569
|
print(json.dumps(res, ensure_ascii=False, indent=1))
|
|
2322
|
-
return 0
|
|
2570
|
+
return 1 if isinstance(res, dict) and 'error' in res else 0
|
|
2323
2571
|
|
|
2324
2572
|
|
|
2325
2573
|
if __name__ == '__main__':
|