@kinti/a11y-toolkit 5.22.0 → 5.22.2
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/__init__.py +5 -0
- package/a11y_toolkit/a11y.py +115 -0
- package/a11y_toolkit/a11yact.py +167 -0
- package/a11y_toolkit/a11yaudit.py +1951 -0
- package/a11y_toolkit/a11ybadge.py +102 -0
- package/a11y_toolkit/a11ybudget.py +122 -0
- package/a11y_toolkit/a11ycrit.py +1017 -0
- package/a11y_toolkit/a11ydiff.py +192 -0
- package/a11y_toolkit/a11ydisprove.py +175 -0
- package/a11y_toolkit/a11ydocx.py +132 -0
- package/a11y_toolkit/a11ydom.py +1831 -0
- package/a11y_toolkit/a11yevidence.py +272 -0
- package/a11y_toolkit/a11yfix.py +330 -0
- package/a11y_toolkit/a11yi18n.py +100 -0
- package/a11y_toolkit/a11yinit.py +113 -0
- package/a11y_toolkit/a11yjourney.py +284 -0
- package/a11y_toolkit/a11yledger.py +210 -0
- package/a11y_toolkit/a11ymutants.py +406 -0
- package/a11y_toolkit/a11yopenacr.py +207 -0
- package/a11y_toolkit/a11ypdf.py +273 -0
- package/a11y_toolkit/a11yroute.py +378 -0
- package/a11y_toolkit/a11ysarif.py +139 -0
- package/a11y_toolkit/a11yscroll.py +212 -0
- package/a11y_toolkit/a11ystatement.py +158 -0
- package/a11y_toolkit/a11yvalidate.py +127 -0
- package/a11y_toolkit/a11yvpat.py +238 -0
- package/a11y_toolkit/a11yvtt.py +136 -0
- package/a11y_toolkit/a11ywcag3.py +262 -0
- package/a11y_toolkit/arialive.js +107 -0
- package/a11y_toolkit/arialive_js.py +113 -0
- package/a11y_toolkit/contrast.py +536 -0
- package/a11y_toolkit/locales/_template.json +468 -0
- package/a11y_toolkit/locales/en.json +525 -0
- package/a11y_toolkit/locales/es.json +525 -0
- package/a11y_toolkit/server.py +1529 -0
- package/bin/a11y-toolkit-mcp.cjs +2 -2
- package/bin/a11y-toolkit.cjs +2 -2
- package/lib/runner.cjs +30 -22
- package/package.json +2 -1
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Infinite-scroll auditor — the documented a11y disaster nobody automates.
|
|
3
|
+
|
|
4
|
+
Sources: Deque's "Infinite Scrolling & Role=Feed Accessibility Issues" and the
|
|
5
|
+
WAI-ARIA APG Feed pattern. NO official W3C failure technique exists
|
|
6
|
+
(verified 2026-09); applicable criteria: 2.4.3 (focus order), 4.1.3 (status
|
|
7
|
+
messages) and 2.2.2 (auto-updating content).
|
|
8
|
+
|
|
9
|
+
What it measures, with real focus and a live-region observer:
|
|
10
|
+
1. Does focus SURVIVE each loading batch? (re-rendering the container
|
|
11
|
+
destroys it — the documented failure)
|
|
12
|
+
2. Is new content ANNOUNCED? (aria-live/status regions receiving text
|
|
13
|
+
during loading; role="feed" container)
|
|
14
|
+
3. Does the feed END or offer an alternative? ("load more" button, footer
|
|
15
|
+
reachability, detectable end)
|
|
16
|
+
4. Structure: role="feed" + role="article" (APG pattern) as positive signal.
|
|
17
|
+
|
|
18
|
+
Requires local Playwright. A filter with honest judgment, not a verdict.
|
|
19
|
+
|
|
20
|
+
CLI:
|
|
21
|
+
a11yscroll.py https://medium.com/section [--max-batches 5] [--lang es]
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
import argparse
|
|
25
|
+
import json
|
|
26
|
+
import sys
|
|
27
|
+
|
|
28
|
+
from .a11yaudit import CRIT, T, compute_score
|
|
29
|
+
|
|
30
|
+
from . import a11yi18n
|
|
31
|
+
_TD = a11yi18n.pair('scroll') # locales/<lang>.json — community-editable
|
|
32
|
+
|
|
33
|
+
_MON = r"""() => {
|
|
34
|
+
window.__a11yscroll = { events: [], n: 0 };
|
|
35
|
+
const esViva = el => el.closest && el.closest('[aria-live], [role="status"], [role="alert"], [role="log"], [role="feed"]');
|
|
36
|
+
const anota = (tipo, texto) => {
|
|
37
|
+
if (window.__a11yscroll.events.length < 50)
|
|
38
|
+
window.__a11yscroll.events.push({ type: tipo, text: (texto || '').trim().slice(0, 80) });
|
|
39
|
+
};
|
|
40
|
+
new MutationObserver(muts => {
|
|
41
|
+
for (const m of muts) {
|
|
42
|
+
if (m.type === 'characterData' || m.type === 'childList') {
|
|
43
|
+
const el = m.target.nodeType === 1 ? m.target : m.target.parentElement;
|
|
44
|
+
if (el && esViva(el)) {
|
|
45
|
+
const vivo = el.closest('[aria-live], [role="status"], [role="alert"], [role="log"], [role="feed"]');
|
|
46
|
+
anota('anuncio', vivo.innerText || vivo.textContent || '');
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}).observe(document.body, { subtree: true, childList: true, characterData: true });
|
|
51
|
+
}"""
|
|
52
|
+
|
|
53
|
+
_STATE = r"""() => {
|
|
54
|
+
const items = document.querySelectorAll('article, [role="article"]').length
|
|
55
|
+
|| document.querySelectorAll('main li').length;
|
|
56
|
+
const feed = document.querySelector('[role="feed"]');
|
|
57
|
+
const activo = document.activeElement;
|
|
58
|
+
const fuera = activo && activo !== document.body
|
|
59
|
+
? (() => { const r = activo.getBoundingClientRect();
|
|
60
|
+
return r.bottom < -8 || r.top > innerHeight + 8 || (r.width === 0 && r.height === 0); })()
|
|
61
|
+
: false;
|
|
62
|
+
const mas = [...document.querySelectorAll('button, a')]
|
|
63
|
+
.some(b => /más|more|cargar|load/i.test((b.innerText || '').trim()) && b.offsetParent);
|
|
64
|
+
return { items, hasFeed: !!feed, hasFooter: !!document.querySelector('footer, [role="contentinfo"]'),
|
|
65
|
+
focus: activo && activo !== document.body
|
|
66
|
+
? (activo.tagName.toLowerCase() + (activo.id ? '#' + activo.id : '')) : null,
|
|
67
|
+
focus_offscreen: !!fuera, hasMore: mas,
|
|
68
|
+
scroll: document.documentElement.scrollHeight,
|
|
69
|
+
events: window.__a11yscroll ? window.__a11yscroll.events : [] };
|
|
70
|
+
}"""
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _add(findings, lang, sev, code, key, **fmt):
|
|
74
|
+
findings.append({
|
|
75
|
+
'severity': sev, 'criterion': CRIT.get(lang, CRIT['es']).get(code, code),
|
|
76
|
+
'signal': key, 'issue': _TD.get(lang, _TD['es'])[key].format(**fmt),
|
|
77
|
+
'remediation': _TD.get(lang, _TD['es'])[key + '_rem'].format(**fmt),
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def audit_scroll(url, max_batches=5, lang='en', timeout=45, auth_state=None):
|
|
82
|
+
from playwright.sync_api import sync_playwright
|
|
83
|
+
with sync_playwright() as p:
|
|
84
|
+
nav = p.chromium.launch()
|
|
85
|
+
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
86
|
+
page = ctx.new_page(viewport={'width': 1280, 'height': 800}) if auth_state \
|
|
87
|
+
else nav.new_page(viewport={'width': 1280, 'height': 800})
|
|
88
|
+
try:
|
|
89
|
+
page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
90
|
+
page.wait_for_timeout(500)
|
|
91
|
+
except Exception as e: # noqa: BLE001
|
|
92
|
+
nav.close()
|
|
93
|
+
return {'error': f'no se pudo cargar: {e}'}
|
|
94
|
+
page.evaluate(_MON)
|
|
95
|
+
page.evaluate("(() => { const c = document.querySelector("
|
|
96
|
+
" 'article a[href], [role=article] a[href], main li a[href]');"
|
|
97
|
+
" if (c) c.focus(); })()")
|
|
98
|
+
before = page.evaluate(_STATE)
|
|
99
|
+
initial_focus = before['focus']
|
|
100
|
+
|
|
101
|
+
batches = []
|
|
102
|
+
end_reached = False
|
|
103
|
+
via_click = False
|
|
104
|
+
for _t in range(max_batches):
|
|
105
|
+
page.evaluate("window.scrollTo(0, document.documentElement.scrollHeight)")
|
|
106
|
+
grew = False
|
|
107
|
+
for _wait in range(6): # hasta ~3 s esperando nueva tanda
|
|
108
|
+
page.wait_for_timeout(500)
|
|
109
|
+
e = page.evaluate(_STATE)
|
|
110
|
+
if e['items'] > (batches[-1]['items'] if batches else before['items']) \
|
|
111
|
+
or e['scroll'] > (batches[-1]['scroll'] if batches else before['scroll']):
|
|
112
|
+
grew = True
|
|
113
|
+
break
|
|
114
|
+
if not grew and not via_click:
|
|
115
|
+
# el scroll no trae nada: ¿hay botón «cargar más»? (la alternativa sana)
|
|
116
|
+
via_click = page.evaluate(
|
|
117
|
+
"() => [...document.querySelectorAll('button, a')].some(b =>"
|
|
118
|
+
" /más|more|cargar|load/i.test((b.innerText || '').trim()) && b.offsetParent)")
|
|
119
|
+
if via_click:
|
|
120
|
+
page.evaluate(
|
|
121
|
+
"() => { const b = [...document.querySelectorAll('button, a')].find("
|
|
122
|
+
"b => /más|more|cargar|load/i.test((b.innerText || '').trim()) && b.offsetParent);"
|
|
123
|
+
" if (b) b.click(); }")
|
|
124
|
+
for _wait in range(6):
|
|
125
|
+
page.wait_for_timeout(500)
|
|
126
|
+
e2 = page.evaluate(_STATE)
|
|
127
|
+
if e2['items'] > (batches[-1]['items'] if batches else before['items']):
|
|
128
|
+
grew = True
|
|
129
|
+
break
|
|
130
|
+
e = page.evaluate(_STATE)
|
|
131
|
+
batches.append(e)
|
|
132
|
+
if not grew:
|
|
133
|
+
end_reached = True
|
|
134
|
+
break
|
|
135
|
+
|
|
136
|
+
nav.close()
|
|
137
|
+
|
|
138
|
+
findings = []
|
|
139
|
+
last = batches[-1] if batches else before
|
|
140
|
+
|
|
141
|
+
# 1. foco (2.4.3): desaparecido o fuera de pantalla tras las tandas
|
|
142
|
+
if initial_focus:
|
|
143
|
+
if last['focus'] is None:
|
|
144
|
+
_add(findings, lang, 'high', '2.4.3', 'scroll_focus',
|
|
145
|
+
where='disappeared', detail=f'was on {initial_focus}')
|
|
146
|
+
elif last['focus_offscreen']:
|
|
147
|
+
_add(findings, lang, 'medium', '2.4.3', 'scroll_focus',
|
|
148
|
+
where='went offscreen', detail=initial_focus)
|
|
149
|
+
|
|
150
|
+
# Guardián de honestidad: sin ítems detectados no hay feed que auditar
|
|
151
|
+
hay_feed_real = before['items'] > 0 or last['items'] > before['items']
|
|
152
|
+
note = None
|
|
153
|
+
if not hay_feed_real:
|
|
154
|
+
note = ('no standard items detected (article, role=article, li in main): the feed is '
|
|
155
|
+
'behind a login/bot wall or uses non-standard markup. Announcement/end signals '
|
|
156
|
+
'are skipped; audit feeds you own with known markup.' if lang == 'en' else
|
|
157
|
+
'no se detectaron ítems con los selectores estándar (article, role=article, '
|
|
158
|
+
'li en main): o el feed está tras login/muro de bots, o usa marcado no estándar. '
|
|
159
|
+
'Las señales de anuncios/fin se omiten; valida feeds propios con marcado conocido.')
|
|
160
|
+
|
|
161
|
+
# 2. anuncios (4.1.3) — solo si hubo feed real
|
|
162
|
+
if hay_feed_real and batches and not last['hasFeed'] and not last['events']:
|
|
163
|
+
_add(findings, lang, 'medium', '4.1.3', 'scroll_no_announce',
|
|
164
|
+
n=len(batches))
|
|
165
|
+
|
|
166
|
+
# 3. fin/alternativa — solo si hubo feed real
|
|
167
|
+
if hay_feed_real and not end_reached and not last['hasMore']:
|
|
168
|
+
_add(findings, lang, 'medium', '2.2.2', 'scroll_no_end', n=len(batches))
|
|
169
|
+
|
|
170
|
+
# 4. patrón APG
|
|
171
|
+
if not last['hasFeed']:
|
|
172
|
+
_add(findings, lang, 'low', '1.3.1', 'scroll_no_feed')
|
|
173
|
+
|
|
174
|
+
order = {'high': 0, 'medium': 1, 'low': 2}
|
|
175
|
+
findings.sort(key=lambda h: order[h['severity']])
|
|
176
|
+
return {
|
|
177
|
+
'url': url,
|
|
178
|
+
'mode': 'scroll',
|
|
179
|
+
'score': compute_score(findings),
|
|
180
|
+
'summary': {s_: sum(1 for h in findings if h['severity'] == s_)
|
|
181
|
+
for s_ in ('high', 'medium', 'low')},
|
|
182
|
+
'items': {'before': before['items'], 'after': last['items']},
|
|
183
|
+
'batches': len(batches),
|
|
184
|
+
'end_reached': end_reached,
|
|
185
|
+
'live_announcements': [e['text'] for e in last['events'][:5]],
|
|
186
|
+
'focus': {'initial': initial_focus, 'final': last['focus'],
|
|
187
|
+
'offscreen': last['focus_offscreen']},
|
|
188
|
+
'load_more_alternative': last['hasMore'],
|
|
189
|
+
'note': note,
|
|
190
|
+
'findings': findings,
|
|
191
|
+
'limits': _TD.get(lang, _TD['es'])['limits'].format(n=len(batches)),
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def main(argv):
|
|
196
|
+
ap = argparse.ArgumentParser(description=__doc__)
|
|
197
|
+
ap.add_argument('url')
|
|
198
|
+
ap.add_argument('--max-batches', type=int, default=5)
|
|
199
|
+
ap.add_argument('--lang', default='en', choices=['en', 'es'])
|
|
200
|
+
ap.add_argument('--timeout', type=int, default=45)
|
|
201
|
+
a = ap.parse_args(argv)
|
|
202
|
+
try:
|
|
203
|
+
res = audit_scroll(a.url, max_batches=a.max_batches, lang=a.lang, timeout=a.timeout)
|
|
204
|
+
except ImportError:
|
|
205
|
+
print(json.dumps({'error': 'Playwright not installed'}))
|
|
206
|
+
return 1
|
|
207
|
+
print(json.dumps(res, ensure_ascii=False, indent=1))
|
|
208
|
+
return 0
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
if __name__ == '__main__':
|
|
212
|
+
sys.exit(main(sys.argv[1:]))
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Accessibility Statement generator (bilingual es/en).
|
|
3
|
+
|
|
4
|
+
- framework 'rd1112': art. 10 of RD 1112/2018 (ES) or Directive (EU)
|
|
5
|
+
2016/2102 / EN 301 549 style statement (EN) — public sector.
|
|
6
|
+
- framework 'eaa': Ley 11/2023 (ES) or the service accessibility information
|
|
7
|
+
under Directive (EU) 2019/882 — European Accessibility Act (EN).
|
|
8
|
+
|
|
9
|
+
The generated HTML is accessible by construction (correct lang, heading
|
|
10
|
+
hierarchy, semantic lists, dates in <time>).
|
|
11
|
+
|
|
12
|
+
Usage:
|
|
13
|
+
declaracion.py --entity "Name" --url "https://…" --status partial \
|
|
14
|
+
--inaccessible "…" --feedback "a@b.gal" [--framework rd1112|eaa] \
|
|
15
|
+
[--lang es|en] [--output decl.html]
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import datetime
|
|
20
|
+
import html
|
|
21
|
+
import json
|
|
22
|
+
import sys
|
|
23
|
+
from . import a11yi18n
|
|
24
|
+
|
|
25
|
+
def TODAY() -> str:
|
|
26
|
+
# computed per call: freezing it at import time produced statements dated
|
|
27
|
+
# with the process START time (long-running processes)
|
|
28
|
+
return datetime.date.today().isoformat()
|
|
29
|
+
|
|
30
|
+
STATES = a11yi18n.pair('statement_states') # locales/<lang>.json — community-editable
|
|
31
|
+
|
|
32
|
+
TXT = a11yi18n.pair('statement_txt') # locales/<lang>.json — community-editable
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# estados canónicos ingleses; los valores españoles pre-5.11 se aceptan como alias
|
|
36
|
+
STATUS_ALIASES = {'plena': 'full', 'parcial': 'partial', 'no_conforme': 'not_conformant'}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def generate(entity, url, status, inaccessible_content=None, method=None,
|
|
40
|
+
evaluation_date=None, review_date=None, feedback=None,
|
|
41
|
+
complaints=None, framework='rd1112', alternative_format=None,
|
|
42
|
+
lang='en'):
|
|
43
|
+
"""Devuelve dict con 'html' y resumen. framework: 'rd1112'|'eaa' · lang: 'es'|'en'."""
|
|
44
|
+
t = TXT.get(lang, TXT['es'])
|
|
45
|
+
status = STATUS_ALIASES.get(status, status)
|
|
46
|
+
if status not in STATES['es']:
|
|
47
|
+
return {'error': t['error_status']}
|
|
48
|
+
inaccessible_content = inaccessible_content or []
|
|
49
|
+
if status == 'full' and inaccessible_content:
|
|
50
|
+
return {'error': t['error_inconsistent']}
|
|
51
|
+
|
|
52
|
+
e = lambda s: html.escape(str(s), quote=True) # noqa: E731
|
|
53
|
+
status_title, status_text = STATES.get(lang, STATES['es'])[status]
|
|
54
|
+
evaluation_date = evaluation_date or TODAY()
|
|
55
|
+
review_date = review_date or TODAY()
|
|
56
|
+
method = method or t['method_default']
|
|
57
|
+
feedback = feedback or t['feedback_default']
|
|
58
|
+
|
|
59
|
+
if inaccessible_content:
|
|
60
|
+
items = '\n'.join(f' <li>{e(x)}</li>' for x in inaccessible_content)
|
|
61
|
+
no_acc = f'''
|
|
62
|
+
<h2>{t['h_inaccessible']}</h2>
|
|
63
|
+
<p>{t['inaccessible_intro']}</p>
|
|
64
|
+
<ul>
|
|
65
|
+
{items}
|
|
66
|
+
</ul>'''
|
|
67
|
+
else:
|
|
68
|
+
no_acc = f'''
|
|
69
|
+
<h2>{t['h_inaccessible']}</h2>
|
|
70
|
+
<p>{t['inaccessible_empty']}</p>'''
|
|
71
|
+
|
|
72
|
+
disalt = ''
|
|
73
|
+
if alternative_format:
|
|
74
|
+
disalt = f'''
|
|
75
|
+
<h2>{t['h_alt_access']}</h2>
|
|
76
|
+
<p>{e(alternative_format)}</p>'''
|
|
77
|
+
|
|
78
|
+
doc_title = t['title'][framework]
|
|
79
|
+
doc = f'''<!doctype html>
|
|
80
|
+
<html lang="{html.escape(str(lang), quote=True)}">
|
|
81
|
+
<head>
|
|
82
|
+
<meta charset="utf-8">
|
|
83
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
84
|
+
<title>{doc_title} · {e(entity)}</title>
|
|
85
|
+
<meta name="robots" content="noindex">
|
|
86
|
+
</head>
|
|
87
|
+
<body>
|
|
88
|
+
<main>
|
|
89
|
+
<h1>{doc_title} · {e(entity)}</h1>
|
|
90
|
+
<p>{t['intro'][framework].format(e=e(entity), u=e(url))}</p>
|
|
91
|
+
<p>{t['standard_note']}</p>
|
|
92
|
+
|
|
93
|
+
<h2>{t['h_status']} · {status_title}</h2>
|
|
94
|
+
<p>{status_text}</p>
|
|
95
|
+
{no_acc}
|
|
96
|
+
|
|
97
|
+
<h2>{t['h_preparation']}</h2>
|
|
98
|
+
<ul>
|
|
99
|
+
<li>{t['l_evaluation']}: <time datetime="{e(evaluation_date)}">{e(evaluation_date)}</time></li>
|
|
100
|
+
<li>{t['l_declared']} <time datetime="{e(TODAY())}">{e(TODAY())}</time></li>
|
|
101
|
+
<li>{t['l_method']}: {e(method)}</li>
|
|
102
|
+
<li>{t['l_review']}: <time datetime="{e(review_date)}">{e(review_date)}</time></li>
|
|
103
|
+
</ul>
|
|
104
|
+
|
|
105
|
+
<h2>{t['h_contact']}</h2>
|
|
106
|
+
<p>{t['contact'].format(f=e(feedback))}</p>
|
|
107
|
+
<p>{e(complaints) if complaints else t['complaints'][framework]}</p>
|
|
108
|
+
{disalt}
|
|
109
|
+
</main>
|
|
110
|
+
</body>
|
|
111
|
+
</html>
|
|
112
|
+
'''
|
|
113
|
+
return {
|
|
114
|
+
'html': doc,
|
|
115
|
+
'summary': {
|
|
116
|
+
'entity': entity, 'url': url, 'framework': framework, 'lang': lang,
|
|
117
|
+
'status': status_title,
|
|
118
|
+
'inaccessible_items': len(inaccessible_content),
|
|
119
|
+
'dates': {'evaluation': evaluation_date, 'declaration': TODAY(),
|
|
120
|
+
'review': review_date},
|
|
121
|
+
},
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def main(argv):
|
|
126
|
+
p = argparse.ArgumentParser(description=__doc__)
|
|
127
|
+
p.add_argument('--entity', required=True)
|
|
128
|
+
p.add_argument('--url', required=True)
|
|
129
|
+
p.add_argument('--status', required=True,
|
|
130
|
+
choices=['full', 'partial', 'not_conformant', 'plena', 'parcial', 'no_conforme'])
|
|
131
|
+
p.add_argument('--inaccessible', action='append', default=[])
|
|
132
|
+
p.add_argument('--method')
|
|
133
|
+
p.add_argument('--evaluation-date')
|
|
134
|
+
p.add_argument('--review-date')
|
|
135
|
+
p.add_argument('--feedback')
|
|
136
|
+
p.add_argument('--complaints')
|
|
137
|
+
p.add_argument('--alternative-format')
|
|
138
|
+
p.add_argument('--framework', default='rd1112', choices=['rd1112', 'eaa'])
|
|
139
|
+
p.add_argument('--lang', default='en', choices=['en', 'es'])
|
|
140
|
+
p.add_argument('--output')
|
|
141
|
+
a = p.parse_args(argv)
|
|
142
|
+
res = generate(a.entity, a.url, a.status, a.inaccessible, a.method,
|
|
143
|
+
a.evaluation_date, a.review_date, a.feedback,
|
|
144
|
+
a.complaints, a.framework, a.alternative_format, a.lang)
|
|
145
|
+
if 'error' in res:
|
|
146
|
+
print(res['error'], file=sys.stderr)
|
|
147
|
+
return 1
|
|
148
|
+
if a.output:
|
|
149
|
+
with open(a.output, 'w', encoding='utf-8') as f:
|
|
150
|
+
f.write(res['html'])
|
|
151
|
+
print(json.dumps(res['summary'], ensure_ascii=False, indent=1))
|
|
152
|
+
else:
|
|
153
|
+
print(res['html'])
|
|
154
|
+
return 0
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
if __name__ == '__main__':
|
|
158
|
+
sys.exit(main(sys.argv[1:]))
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""W3C Nu Html Checker integration — the W3C's own parser as a toolkit mode.
|
|
3
|
+
|
|
4
|
+
validar_url / validar_html call the public Nu validator
|
|
5
|
+
(https://validator.w3.org/nu/) REST API and map its messages to toolkit
|
|
6
|
+
findings. PRIVACY: validar_html POSTs the document content to the W3C
|
|
7
|
+
service; validar_url only shares the URL (same as a11y_audit_url).
|
|
8
|
+
Self-hosting (docker ghcr.io/validator/validator) is supported via
|
|
9
|
+
base_url for sensitive content.
|
|
10
|
+
|
|
11
|
+
CLI:
|
|
12
|
+
a11yvalidate.py --url https://example.com
|
|
13
|
+
a11yvalidate.py --file page.html
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import json
|
|
18
|
+
import sys
|
|
19
|
+
import urllib.parse
|
|
20
|
+
import urllib.request
|
|
21
|
+
|
|
22
|
+
from .a11yaudit import compute_score
|
|
23
|
+
|
|
24
|
+
BASE = 'https://validator.w3.org/nu/'
|
|
25
|
+
UA = 'a11y-toolkit/3.16 (WCAG audit; github.com/kinti/a11y-toolkit)'
|
|
26
|
+
|
|
27
|
+
# known Nu messages → WCAG criteria (the honest subset; the rest are
|
|
28
|
+
# plain HTML validity findings, reported under their own label)
|
|
29
|
+
_MAPPING = (
|
|
30
|
+
('must have an "alt" attribute', '1.1.1'),
|
|
31
|
+
('"lang" attribute', '3.1.1'),
|
|
32
|
+
('Bad value' and 'role', None), # placeholder, refined below
|
|
33
|
+
('duplicate id', None),
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _criterion_for(message):
|
|
38
|
+
m = message.lower()
|
|
39
|
+
if 'alt' in m and 'img' in m:
|
|
40
|
+
return '1.1.1'
|
|
41
|
+
if 'lang' in m and ('html' in m or 'language' in m):
|
|
42
|
+
return '3.1.1'
|
|
43
|
+
if 'role' in m and ('bad value' in m or 'must not' in m):
|
|
44
|
+
return '4.1.2'
|
|
45
|
+
return None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _call(data=None, url=None, timeout=60, base_url=None):
|
|
49
|
+
target = (base_url or BASE).rstrip('/') + '/'
|
|
50
|
+
if url:
|
|
51
|
+
target += '?' + urllib.parse.urlencode({'doc': url, 'out': 'json'})
|
|
52
|
+
req = urllib.request.Request(target, headers={'User-Agent': UA})
|
|
53
|
+
else:
|
|
54
|
+
target += '?out=json'
|
|
55
|
+
req = urllib.request.Request(target, data=data.encode('utf-8'),
|
|
56
|
+
headers={'User-Agent': UA,
|
|
57
|
+
'Content-Type': 'text/html; charset=utf-8'},
|
|
58
|
+
method='POST')
|
|
59
|
+
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
60
|
+
return json.load(r)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _process(resp, origin, lang='en'):
|
|
64
|
+
findings = []
|
|
65
|
+
for m in resp.get('messages', []):
|
|
66
|
+
kind = m.get('type', 'info')
|
|
67
|
+
if kind == 'info':
|
|
68
|
+
continue
|
|
69
|
+
crit = _criterion_for(m.get('message', ''))
|
|
70
|
+
findings.append({
|
|
71
|
+
'severity': 'medium' if kind == 'error' else 'low',
|
|
72
|
+
'criterion': crit or 'HTML validity (W3C Nu)',
|
|
73
|
+
'signal': 'html_invalid',
|
|
74
|
+
'issue': (m.get('message', '') or '')[:220],
|
|
75
|
+
'remediation': 'Fix the HTML error reported by the W3C validator'
|
|
76
|
+
if lang == 'en' else 'Corrige el error HTML reportado por el validador W3C',
|
|
77
|
+
'line': m.get('lastLine'),
|
|
78
|
+
})
|
|
79
|
+
order = {'high': 0, 'medium': 1, 'low': 2}
|
|
80
|
+
findings.sort(key=lambda h: order[h['severity']])
|
|
81
|
+
return {
|
|
82
|
+
'url': origin,
|
|
83
|
+
'mode': 'w3c-nu',
|
|
84
|
+
'score': compute_score(findings),
|
|
85
|
+
'summary': {s_: sum(1 for h in findings if h['severity'] == s_)
|
|
86
|
+
for s_ in ('high', 'medium', 'low')},
|
|
87
|
+
'findings': findings,
|
|
88
|
+
'notice': ('Report from the W3C Nu validator (validator.w3.org/nu). Complements the '
|
|
89
|
+
'toolkit audits with the W3C parser view: doctype, encoding, structural '
|
|
90
|
+
'validity. HTML validity is not WCAG by itself; mapped criteria where they '
|
|
91
|
+
'overlap are labeled.'),
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def validate_url(url, timeout=60, lang='en', base_url=None):
|
|
96
|
+
resp = _call(url=url, timeout=timeout, base_url=base_url)
|
|
97
|
+
return _process(resp, url, lang)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def validate_html(html_text, timeout=60, lang='en', base_url=None):
|
|
101
|
+
resp = _call(data=html_text, timeout=timeout, base_url=base_url)
|
|
102
|
+
return _process(resp, '(html posted)', lang)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def main(argv):
|
|
106
|
+
ap = argparse.ArgumentParser(description='W3C Nu validator integration')
|
|
107
|
+
g = ap.add_mutually_exclusive_group(required=True)
|
|
108
|
+
g.add_argument('--url')
|
|
109
|
+
g.add_argument('--file')
|
|
110
|
+
ap.add_argument('--lang', default='en', choices=['en', 'es'])
|
|
111
|
+
ap.add_argument('--self-hosted', help='base URL of a self-hosted vnu instance')
|
|
112
|
+
a = ap.parse_args(argv)
|
|
113
|
+
try:
|
|
114
|
+
if a.url:
|
|
115
|
+
res = validate_url(a.url, lang=a.lang, base_url=a.self_hosted)
|
|
116
|
+
else:
|
|
117
|
+
with open(a.file, encoding='utf-8', errors='replace') as f:
|
|
118
|
+
res = validate_html(f.read(), lang=a.lang, base_url=a.self_hosted)
|
|
119
|
+
except Exception as e: # noqa: BLE001
|
|
120
|
+
print(json.dumps({'error': f'validator call failed: {e}'}))
|
|
121
|
+
return 1
|
|
122
|
+
print(json.dumps(res, ensure_ascii=False, indent=1))
|
|
123
|
+
return 0
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
if __name__ == '__main__':
|
|
127
|
+
sys.exit(main(sys.argv[1:]))
|