@kinti/a11y-toolkit 5.26.0 → 5.28.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/README.md +1 -1
- package/a11y_toolkit/a11y.py +30 -4
- package/a11y_toolkit/a11yact.py +9 -1
- package/a11y_toolkit/a11yannotate.py +185 -0
- package/a11y_toolkit/a11yaudit.py +924 -196
- package/a11y_toolkit/a11ybadge.py +24 -17
- package/a11y_toolkit/a11ybudget.py +145 -1
- package/a11y_toolkit/a11ycorpus.py +58 -24
- package/a11y_toolkit/a11ycrit.py +114 -53
- package/a11y_toolkit/a11ydiff.py +104 -34
- package/a11y_toolkit/a11ydisprove.py +15 -8
- package/a11y_toolkit/a11ydocx.py +8 -6
- package/a11y_toolkit/a11ydom.py +567 -97
- package/a11y_toolkit/a11yen301549.py +53 -1
- package/a11y_toolkit/a11yengines.py +157 -0
- package/a11y_toolkit/a11yevidence.py +81 -33
- package/a11y_toolkit/a11yfix.py +131 -52
- package/a11y_toolkit/a11ygate.py +225 -0
- package/a11y_toolkit/a11yinit.py +73 -7
- package/a11y_toolkit/a11yjourney.py +110 -4
- package/a11y_toolkit/a11yledger.py +119 -12
- package/a11y_toolkit/a11ylocate.py +247 -0
- package/a11y_toolkit/a11yopenacr.py +10 -3
- package/a11y_toolkit/a11ypatches.py +154 -0
- package/a11y_toolkit/a11ypatterns.py +344 -0
- package/a11y_toolkit/a11ypdf.py +109 -53
- package/a11y_toolkit/a11yrgaa.py +60 -0
- package/a11y_toolkit/a11yroute.py +34 -12
- package/a11y_toolkit/a11ysarif.py +45 -18
- package/a11y_toolkit/a11yscope.py +67 -15
- package/a11y_toolkit/a11yscroll.py +7 -5
- package/a11y_toolkit/a11ystatement.py +30 -6
- package/a11y_toolkit/a11ytrace.py +293 -0
- package/a11y_toolkit/a11yvalidate.py +21 -15
- package/a11y_toolkit/a11yvpat.py +34 -7
- package/a11y_toolkit/a11yvtt.py +22 -6
- package/a11y_toolkit/a11ywiz.py +121 -0
- package/a11y_toolkit/contrast.py +62 -24
- package/a11y_toolkit/locales/en.json +185 -20
- package/a11y_toolkit/locales/es.json +186 -21
- package/a11y_toolkit/rgaa.json +2661 -0
- package/a11y_toolkit/server.py +157 -54
- package/package.json +2 -2
- package/a11y_toolkit/a11yplan.py +0 -214
- package/a11y_toolkit/a11ywcagem.py +0 -237
|
@@ -19,6 +19,11 @@ user is not an AI agent (different strategies, habits, patience).
|
|
|
19
19
|
|
|
20
20
|
CLI:
|
|
21
21
|
a11yjourney.py friction.json [-o verdict.json] [--lang en]
|
|
22
|
+
|
|
23
|
+
Recommended task kinds (free-form by design; these make baselines comparable):
|
|
24
|
+
sign-up, checkout, password-reset, search, onboarding, settings, data-export.
|
|
25
|
+
The friction catalogue lives in locales/<lang>.json (journey_* keys) —
|
|
26
|
+
community-editable, parity-tested.
|
|
22
27
|
"""
|
|
23
28
|
|
|
24
29
|
import argparse
|
|
@@ -47,19 +52,28 @@ def _validate_friction(item, crits, lang='en'):
|
|
|
47
52
|
if 'pattern' in item:
|
|
48
53
|
pat = item['pattern']
|
|
49
54
|
if pat not in cat:
|
|
50
|
-
|
|
55
|
+
_msg = ('patrón desconocido: {p} — disponibles: {d}'
|
|
56
|
+
if lang == 'es' else
|
|
57
|
+
'unknown pattern: {p} — available: {d}')
|
|
58
|
+
return None, _msg.format(p=pat, d=sorted(cat))
|
|
51
59
|
crit, sev, issue, rem = cat[pat]
|
|
52
60
|
return {'signal': pat, 'criterion': crit, 'severity': sev,
|
|
53
61
|
'issue': issue, 'remediation': rem}, None
|
|
54
62
|
crit = str(item.get('criterion', '')).strip()
|
|
55
63
|
if crit not in crits:
|
|
56
|
-
|
|
64
|
+
_msg = ('criterio fuera del conjunto A/AA 2.2: {c!r}'
|
|
65
|
+
if lang == 'es' else 'criterion outside the A/AA 2.2 set: {c!r}')
|
|
66
|
+
return None, _msg.format(c=crit)
|
|
57
67
|
sev = item.get('severity', 'medium')
|
|
58
68
|
if sev not in ('high', 'medium', 'low'):
|
|
59
|
-
|
|
69
|
+
_msg = ('severidad inválida: {s!r} (high|medium|low)'
|
|
70
|
+
if lang == 'es' else 'invalid severity: {s!r} (high|medium|low)')
|
|
71
|
+
return None, _msg.format(s=sev)
|
|
60
72
|
issue = str(item.get('issue', '')).strip()
|
|
61
73
|
if not issue:
|
|
62
|
-
return None, 'fricción sin issue (describe la estructura, nunca cites contenido)'
|
|
74
|
+
return None, ('fricción sin issue (describe la estructura, nunca cites contenido)'
|
|
75
|
+
if lang == 'es' else
|
|
76
|
+
'friction without issue (describe the structure, never quote content)')
|
|
63
77
|
return {'signal': item.get('signal', 'journey_custom'), 'criterion': crit,
|
|
64
78
|
'severity': sev, 'issue': issue,
|
|
65
79
|
'remediation': str(item.get('remediation', '')).strip()}, None
|
|
@@ -158,6 +172,98 @@ def verdict(task, steps, outcome, url='', lang='en'):
|
|
|
158
172
|
}
|
|
159
173
|
|
|
160
174
|
|
|
175
|
+
JOURNEY_FORMAT = 'a11y-journey/1'
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def seal_record(task, steps, outcome, url='', lang='en', trace=None):
|
|
179
|
+
"""Verdict → the sealed journey record (format `a11y-journey/1`).
|
|
180
|
+
|
|
181
|
+
The open artifact the market keeps describing ("replayable traces" in
|
|
182
|
+
every journey-monitoring pitch) and nobody owns: the walk AND the
|
|
183
|
+
judgment in one envelope — the agent's steps as walked, the outcome,
|
|
184
|
+
the deterministic verdict, and an optional a11ytrace capture — sealed
|
|
185
|
+
with a SHA-256 over the canonical payload. Honesty twice over: the sha
|
|
186
|
+
makes the record tamper-evident, and the scoring is deterministic, so
|
|
187
|
+
`record_verify` can RE-DERIVE the verdict from the stored steps and
|
|
188
|
+
demand it matches. A record is evidence, never conformance."""
|
|
189
|
+
import hashlib
|
|
190
|
+
lang = 'es' if lang == 'es' else 'en'
|
|
191
|
+
v = verdict(task, steps, outcome, url=url, lang=lang)
|
|
192
|
+
if 'error' in v:
|
|
193
|
+
return v
|
|
194
|
+
from .server import VERSION # lazy: server imports this module
|
|
195
|
+
record = {
|
|
196
|
+
'format': JOURNEY_FORMAT,
|
|
197
|
+
'engine_version': VERSION,
|
|
198
|
+
'created_at': datetime.now(timezone.utc).isoformat(timespec='seconds'),
|
|
199
|
+
'lang': lang,
|
|
200
|
+
'task': v['task'],
|
|
201
|
+
'url': v['url'],
|
|
202
|
+
'steps': steps,
|
|
203
|
+
'outcome': v['outcome'],
|
|
204
|
+
'verdict': {'verdict': v['verdict'], 'score': v['score'],
|
|
205
|
+
'summary': v['summary'], 'findings': v['findings']},
|
|
206
|
+
'trace': trace,
|
|
207
|
+
'rules': v['rules'],
|
|
208
|
+
'score_note': v['score_note'],
|
|
209
|
+
}
|
|
210
|
+
payload = json.dumps(record, sort_keys=True, ensure_ascii=False,
|
|
211
|
+
default=str).encode('utf-8')
|
|
212
|
+
record['sha256'] = hashlib.sha256(payload).hexdigest()
|
|
213
|
+
return record
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _canonical_findings(findings):
|
|
217
|
+
"""Language-independent projection of a findings list: the sealed verdict
|
|
218
|
+
must re-derive identically regardless of the VERIFIER's lang — issue and
|
|
219
|
+
remediation are localized catalog text, signal/criterion/severity/step
|
|
220
|
+
are the stable contract."""
|
|
221
|
+
return [(f.get('signal'), f.get('criterion'), f.get('severity'),
|
|
222
|
+
f.get('step')) for f in (findings or [])]
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def record_verify(record, lang='en'):
|
|
226
|
+
"""Re-derive the verdict from the stored steps and demand it matches.
|
|
227
|
+
|
|
228
|
+
Returns {'status': 'verified'|'tampered'|'invalid', ...}: `tampered`
|
|
229
|
+
means the sha no longer covers the payload OR the deterministic scoring
|
|
230
|
+
of the stored steps no longer produces the stored verdict — either way
|
|
231
|
+
the record cannot be trusted. `invalid` means it is not a record.
|
|
232
|
+
|
|
233
|
+
The record's sealed `lang` wins over the param (a record sealed in es
|
|
234
|
+
verifies from an en session without false 'tampered'); legacy records
|
|
235
|
+
without lang fall back to the param."""
|
|
236
|
+
import hashlib
|
|
237
|
+
lang = 'es' if lang == 'es' else 'en'
|
|
238
|
+
if not isinstance(record, dict) or record.get('format') != JOURNEY_FORMAT \
|
|
239
|
+
or not record.get('sha256'):
|
|
240
|
+
_JR = a11yi18n.pair('journeyrec')
|
|
241
|
+
return {'status': 'invalid',
|
|
242
|
+
'note': _JR.get(lang, _JR['en']).get('bad_format')}
|
|
243
|
+
eff_lang = record.get('lang') if record.get('lang') in ('es', 'en') else lang
|
|
244
|
+
body = {k: v for k, v in record.items() if k != 'sha256'}
|
|
245
|
+
payload = json.dumps(body, sort_keys=True, ensure_ascii=False,
|
|
246
|
+
default=str).encode('utf-8')
|
|
247
|
+
sha_ok = hashlib.sha256(payload).hexdigest() == record['sha256']
|
|
248
|
+
re_v = verdict(record.get('task', {}), record.get('steps', []),
|
|
249
|
+
record.get('outcome', {}), url=record.get('url', ''),
|
|
250
|
+
lang=eff_lang)
|
|
251
|
+
derived_ok = ('error' not in re_v and isinstance(record.get('verdict'), dict)
|
|
252
|
+
and re_v['verdict'] == record['verdict'].get('verdict')
|
|
253
|
+
and re_v['score'] == record['verdict'].get('score')
|
|
254
|
+
and _canonical_findings(re_v.get('findings'))
|
|
255
|
+
== _canonical_findings(record['verdict'].get('findings')))
|
|
256
|
+
if sha_ok and derived_ok:
|
|
257
|
+
return {'status': 'verified', 'sha256': record['sha256'],
|
|
258
|
+
'verdict': record['verdict'].get('verdict'),
|
|
259
|
+
'score': record['verdict'].get('score')}
|
|
260
|
+
return {'status': 'tampered',
|
|
261
|
+
'sha_intact': sha_ok, 'verdict_reproducible': derived_ok,
|
|
262
|
+
'recomputed': None if 'error' in re_v
|
|
263
|
+
else {'verdict': re_v['verdict'], 'score': re_v['score'],
|
|
264
|
+
'findings': re_v['findings']}}
|
|
265
|
+
|
|
266
|
+
|
|
161
267
|
def budget_init(verdict, url=''):
|
|
162
268
|
"""Verdict → baseline del journey (para comparar tras cada deploy).
|
|
163
269
|
|
|
@@ -17,6 +17,7 @@ CLI:
|
|
|
17
17
|
a11yledger.py record --url https://x --audit report.json [--ledger ledger.json]
|
|
18
18
|
a11yledger.py gaps --url https://x [--ledger ledger.json]
|
|
19
19
|
a11yledger.py summary [--ledger ledger.json]
|
|
20
|
+
a11yledger.py recurrence [--ledger ledger.json]
|
|
20
21
|
"""
|
|
21
22
|
|
|
22
23
|
import argparse
|
|
@@ -66,6 +67,7 @@ def _load(path='a11y-ledger.json'):
|
|
|
66
67
|
for e in ledger.get('entries', {}).values():
|
|
67
68
|
e['active_signals'] = sorted(normalize_signal(x) for x in e.get('active_signals', []))
|
|
68
69
|
e['resolved_signals'] = sorted(normalize_signal(x) for x in e.get('resolved_signals', []))
|
|
70
|
+
e['resolutions'] = {normalize_signal(k): v for k, v in (e.get('resolutions') or {}).items()}
|
|
69
71
|
# renames de claves 5.11.0 (por si un proceso antiguo reescribe después)
|
|
70
72
|
e['last_audit'] = e.pop('ultimo_audit') if 'ultimo_audit' in e else e.get('last_audit')
|
|
71
73
|
return ledger
|
|
@@ -116,16 +118,39 @@ def _record(url, report, ledger=None, path='a11y-ledger.json'):
|
|
|
116
118
|
# señales activas y score
|
|
117
119
|
signals = sorted({normalize_signal(h.get('signal', '')) for h in report.get('findings', [])})
|
|
118
120
|
score = report.get('score')
|
|
121
|
+
prev = ledger['entries'].get(entry_key, {})
|
|
122
|
+
|
|
123
|
+
# resoluciones PERSISTENTES (señal→{resolved_on, seen_count}): antes se
|
|
124
|
+
# recalculaban solo contra el audit anterior y la resolución se olvidaba
|
|
125
|
+
# tras UN audit limpio más (la evidencia de cuándo se arregló se evaporaba).
|
|
126
|
+
# Ahora: señal ausente del último audit pero presente en el historial
|
|
127
|
+
# sigue «resolved» con su resolved_on ORIGINAL.
|
|
128
|
+
resolutions = {normalize_signal(s): (dict(v) if isinstance(v, dict)
|
|
129
|
+
else {'resolved_on': v, 'seen_count': 1})
|
|
130
|
+
for s, v in (prev.get('resolutions') or {}).items()}
|
|
131
|
+
if not resolutions and prev.get('resolved_signals'):
|
|
132
|
+
# ledger legado sin dict: sembrar desde la lista (fecha más antigua
|
|
133
|
+
# disponible = el último audit registrado antes de esta llamada)
|
|
134
|
+
resolutions = {s: {'resolved_on': prev.get('last_audit')
|
|
135
|
+
or prev.get('ultimo_audit'), 'seen_count': 1}
|
|
136
|
+
for s in prev['resolved_signals']}
|
|
137
|
+
for s in signals: # volvió a estar activa → la resolución caduca
|
|
138
|
+
resolutions.pop(s, None)
|
|
139
|
+
ever_seen = set(resolutions) | set(prev.get('active_signals', []))
|
|
140
|
+
for s in ever_seen - set(signals):
|
|
141
|
+
if s in resolutions: # sigue ausente: la resolución original aguanta
|
|
142
|
+
resolutions[s]['seen_count'] = int(resolutions[s].get('seen_count', 1)) + 1
|
|
143
|
+
else:
|
|
144
|
+
resolutions[s] = {'resolved_on': now, 'seen_count': 1}
|
|
119
145
|
|
|
120
146
|
entry = {
|
|
121
147
|
'url': url,
|
|
122
148
|
'last_audit': now,
|
|
123
149
|
'score': score,
|
|
124
|
-
'previous_score':
|
|
150
|
+
'previous_score': prev.get('score'),
|
|
125
151
|
'active_signals': signals,
|
|
126
|
-
'resolved_signals': sorted(
|
|
127
|
-
|
|
128
|
-
),
|
|
152
|
+
'resolved_signals': sorted(resolutions),
|
|
153
|
+
'resolutions': resolutions,
|
|
129
154
|
'mode': report.get('mode', 'static'),
|
|
130
155
|
'disprover': report.get('disprover'),
|
|
131
156
|
}
|
|
@@ -141,8 +166,42 @@ def _record(url, report, ledger=None, path='a11y-ledger.json'):
|
|
|
141
166
|
return entry
|
|
142
167
|
|
|
143
168
|
|
|
144
|
-
|
|
145
|
-
|
|
169
|
+
|
|
170
|
+
_NOTES = {
|
|
171
|
+
'reaudit': {
|
|
172
|
+
'en': ('re-audit this URL if its content changed since {d}. '
|
|
173
|
+
'criteria_without_signal = A/AA criteria with no engine signal '
|
|
174
|
+
'(active or resolved) ever recorded here — many are manual-only '
|
|
175
|
+
'by nature; they are targets, not failures'),
|
|
176
|
+
'es': ('re-audita esta URL si su contenido cambió desde {d}. '
|
|
177
|
+
'criteria_without_signal = criterios A/AA sin ninguna señal del '
|
|
178
|
+
'motor (activa o resuelta) jamás registrada aquí — muchos son '
|
|
179
|
+
'manual-only por naturaleza; son objetivos, no fallos'),
|
|
180
|
+
},
|
|
181
|
+
'empty': {
|
|
182
|
+
'en': 'ledger empty — run your first audit',
|
|
183
|
+
'es': 'ledger vacío — ejecuta tu primera auditoría',
|
|
184
|
+
},
|
|
185
|
+
'chronic': {
|
|
186
|
+
'en': ('deterministic: chronic = active on many urls, or resolved '
|
|
187
|
+
'somewhere and still active elsewhere (recurring). The review '
|
|
188
|
+
'queue starts at hot_urls — fix at the template level, '
|
|
189
|
+
're-audit, and the chronic row drops out'),
|
|
190
|
+
'es': ('determinista: crónica = activa en muchas URLs, o resuelta en '
|
|
191
|
+
'unas y aún activa en otras (recurrente). La cola de revisión '
|
|
192
|
+
'empieza en hot_urls — arregla a nivel de plantilla, re-audita '
|
|
193
|
+
'y la fila crónica cae'),
|
|
194
|
+
},
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
def gaps(url, ledger=None, path='a11y-ledger.json', lang='en'):
|
|
198
|
+
"""What has never been checked on this URL?
|
|
199
|
+
|
|
200
|
+
For an audited URL the ledger knows every signal that EVER fired on it
|
|
201
|
+
(active now or resolved in history): mapped through the signal→criterion
|
|
202
|
+
table that is the complement against the A/AA catalog — the honest
|
|
203
|
+
target list for the next pass. A signal we cannot map (unknown id) is
|
|
204
|
+
skipped, never guessed."""
|
|
146
205
|
if ledger is None:
|
|
147
206
|
ledger = _load(path)
|
|
148
207
|
from .a11yaudit import CRIT
|
|
@@ -151,25 +210,31 @@ def gaps(url, ledger=None, path='a11y-ledger.json'):
|
|
|
151
210
|
if not entry:
|
|
152
211
|
return {'url': url, 'status': 'never_audited',
|
|
153
212
|
'criteria_without_signal': len(CRIT['en'])}
|
|
154
|
-
|
|
213
|
+
from .a11ycrit import _C, _SIGNAL_CRIT # read-only: el mapa señal→criterio
|
|
214
|
+
ever_signaled = set(entry.get('active_signals', [])) \
|
|
215
|
+
| set(entry.get('resolutions') or {})
|
|
216
|
+
checked = {_SIGNAL_CRIT[s] for s in ever_signaled if s in _SIGNAL_CRIT}
|
|
217
|
+
aa = {code for code, v in _C.items() if v[0] in ('A', 'AA')}
|
|
155
218
|
return {
|
|
156
219
|
'url': url,
|
|
157
220
|
'status': 'audited',
|
|
158
221
|
'last_audit': entry.get('last_audit') or entry.get('ultimo_audit'),
|
|
159
222
|
'score': entry['score'],
|
|
160
223
|
'resolved_signals': entry.get('resolved_signals', []),
|
|
161
|
-
'
|
|
162
|
-
|
|
224
|
+
'criteria_with_signal': sorted(checked),
|
|
225
|
+
'criteria_without_signal': sorted(aa - checked),
|
|
226
|
+
'note': _NOTES['reaudit'].get(lang, _NOTES['reaudit']['en']).format(
|
|
227
|
+
d=(entry.get('last_audit') or entry.get('ultimo_audit'))),
|
|
163
228
|
}
|
|
164
229
|
|
|
165
230
|
|
|
166
|
-
def summary(ledger=None, path='a11y-ledger.json'):
|
|
231
|
+
def summary(ledger=None, path='a11y-ledger.json', lang='en'):
|
|
167
232
|
"""Summary of the ledger."""
|
|
168
233
|
if ledger is None:
|
|
169
234
|
ledger = _load(path)
|
|
170
235
|
entries = ledger['entries']
|
|
171
236
|
if not entries:
|
|
172
|
-
return {'total_urls': 0, 'note': '
|
|
237
|
+
return {'total_urls': 0, 'note': _NOTES['empty'].get(lang, _NOTES['empty']['en'])}
|
|
173
238
|
scores = [e.get('score', 0) for e in entries.values() if e.get('score') is not None]
|
|
174
239
|
return {
|
|
175
240
|
'total_urls': len(entries),
|
|
@@ -181,6 +246,44 @@ def summary(ledger=None, path='a11y-ledger.json'):
|
|
|
181
246
|
}
|
|
182
247
|
|
|
183
248
|
|
|
249
|
+
def recurrence(ledger=None, path='a11y-ledger.json', lang='en'):
|
|
250
|
+
"""Chronic signals across urls + hot urls + review queue.
|
|
251
|
+
|
|
252
|
+
The deterministic core of "predictive guardrails" — no ML: the ledger
|
|
253
|
+
itself IS the model. A signal active on many urls, or resolved somewhere
|
|
254
|
+
and still active elsewhere, is CHRONIC: it comes back with every build,
|
|
255
|
+
and a template-level fix beats page-by-page whack-a-mole."""
|
|
256
|
+
if ledger is None:
|
|
257
|
+
ledger = _load(path)
|
|
258
|
+
entries = ledger['entries']
|
|
259
|
+
if not entries:
|
|
260
|
+
return {'total_urls': 0, 'note': 'ledger empty — record audits first'}
|
|
261
|
+
active, resolved = {}, {}
|
|
262
|
+
for e in entries.values():
|
|
263
|
+
for s in e.get('active_signals', []):
|
|
264
|
+
active.setdefault(s, []).append(e.get('url', ''))
|
|
265
|
+
for s in e.get('resolved_signals', []):
|
|
266
|
+
resolved.setdefault(s, []).append(e.get('url', ''))
|
|
267
|
+
chronic = sorted(
|
|
268
|
+
({'signal': s, 'active_on': len(urls),
|
|
269
|
+
'resolved_on': len(resolved.get(s, [])),
|
|
270
|
+
'recurring': s in resolved and s in active}
|
|
271
|
+
for s, urls in active.items()),
|
|
272
|
+
key=lambda x: (-x['active_on'], -x['resolved_on'], x['signal']))[:10]
|
|
273
|
+
urls_ranked = sorted(
|
|
274
|
+
({'url': e.get('url', ''), 'score': e.get('score'),
|
|
275
|
+
'active_signals': len(e.get('active_signals', []))}
|
|
276
|
+
for e in entries.values()),
|
|
277
|
+
key=lambda x: (x['score'] if x['score'] is not None else 101,
|
|
278
|
+
-x['active_signals'], x['url']))
|
|
279
|
+
return {
|
|
280
|
+
'total_urls': len(entries),
|
|
281
|
+
'signals_chronic': chronic,
|
|
282
|
+
'hot_urls': urls_ranked[:5],
|
|
283
|
+
'note': _NOTES['chronic'].get(lang, _NOTES['chronic']['en']),
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
|
|
184
287
|
def main(argv):
|
|
185
288
|
ap = argparse.ArgumentParser(description='Coverage ledger')
|
|
186
289
|
sub = ap.add_subparsers(dest='cmd', required=True)
|
|
@@ -193,6 +296,8 @@ def main(argv):
|
|
|
193
296
|
s2.add_argument('--ledger', default='a11y-ledger.json')
|
|
194
297
|
s3 = sub.add_parser('summary')
|
|
195
298
|
s3.add_argument('--ledger', default='a11y-ledger.json')
|
|
299
|
+
s4 = sub.add_parser('recurrence')
|
|
300
|
+
s4.add_argument('--ledger', default='a11y-ledger.json')
|
|
196
301
|
a = ap.parse_args(argv)
|
|
197
302
|
if a.cmd == 'record':
|
|
198
303
|
with open(a.audit, encoding='utf-8') as f:
|
|
@@ -200,9 +305,11 @@ def main(argv):
|
|
|
200
305
|
r = record(a.url, report, path=a.ledger)
|
|
201
306
|
print(json.dumps(r, ensure_ascii=False, indent=1))
|
|
202
307
|
elif a.cmd == 'gaps':
|
|
203
|
-
print(json.dumps(gaps(a.url, path=a.ledger), ensure_ascii=False, indent=1))
|
|
308
|
+
print(json.dumps(gaps(a.url, path=a.ledger, lang=a.lang), ensure_ascii=False, indent=1))
|
|
204
309
|
elif a.cmd == 'summary':
|
|
205
310
|
print(json.dumps(summary(path=a.ledger), ensure_ascii=False, indent=1))
|
|
311
|
+
elif a.cmd == 'recurrence':
|
|
312
|
+
print(json.dumps(recurrence(path=a.ledger), ensure_ascii=False, indent=1))
|
|
206
313
|
return 0
|
|
207
314
|
|
|
208
315
|
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""a11y_locate — find an element by its accessible name, or refuse honestly.
|
|
3
|
+
|
|
4
|
+
Given raw HTML and a query, returns the deterministic element route (the same
|
|
5
|
+
`tag:nth-of-type(n)` identity the auditor and annotate() share) of the element
|
|
6
|
+
whose accessible name matches, with a confidence — and the honesty rule of the
|
|
7
|
+
house: when several elements share the name, it refuses to pick one
|
|
8
|
+
(`ambiguous: true` + the full candidate list). What has no accessible name is
|
|
9
|
+
never indexed, so a match is never invented.
|
|
10
|
+
|
|
11
|
+
Indexed surfaces (only what the engine computes with full fidelity):
|
|
12
|
+
controls (button, link, area, input:*, role:*) · headings h1-h6 ·
|
|
13
|
+
images with alt · iframes with title · fields with an explicit accessible
|
|
14
|
+
name (aria-label, aria-labelledby, title, name-from-content roles).
|
|
15
|
+
|
|
16
|
+
Output:
|
|
17
|
+
{'query': str, 'role': str|None, 'found': bool, 'ambiguous': bool,
|
|
18
|
+
'selector': str|None, # deterministic route — annotate()-compatible
|
|
19
|
+
'confidence': 'high'|'medium'|None,
|
|
20
|
+
'count': int, # total candidates before the cap
|
|
21
|
+
'matches': [{path, tag, id, role, name, match}], # capped at 10
|
|
22
|
+
'note': str} # honest explanation, in the requested language
|
|
23
|
+
|
|
24
|
+
CLI:
|
|
25
|
+
a11ytoolkit locate --file page.html --query "Submit" [--role button] [-o r.json]
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
import argparse
|
|
29
|
+
import json
|
|
30
|
+
import sys
|
|
31
|
+
|
|
32
|
+
from . import a11yi18n
|
|
33
|
+
from .a11yaudit import MAX_HTML, _Auditor
|
|
34
|
+
|
|
35
|
+
T = a11yi18n.pair('locate') # locales/<lang>.json — community-editable
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _t(lang, key, n=None):
|
|
39
|
+
value = T.get(lang, T['en']).get(key, key)
|
|
40
|
+
return a11yi18n.plural_entry(value, lang, n) if n is not None else value
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# aliases accepted by the `role` filter → the raw kinds the auditor records
|
|
44
|
+
_ROLE_ALIASES = {
|
|
45
|
+
'button': {'button', 'input:submit', 'input:button', 'input:reset',
|
|
46
|
+
'input:image', 'role:button'},
|
|
47
|
+
'link': {'a', 'area', 'link', 'role:link'},
|
|
48
|
+
'textbox': {'input:text', 'input:search', 'input:email', 'input:tel',
|
|
49
|
+
'input:url', 'input:number', 'input:password', 'textarea',
|
|
50
|
+
'search', 'role:textbox', 'role:searchbox', 'spinbutton'},
|
|
51
|
+
'checkbox': {'input:checkbox', 'role:checkbox', 'role:menuitemcheckbox',
|
|
52
|
+
'role:option'},
|
|
53
|
+
'radio': {'input:radio', 'role:radio', 'role:menuitemradio'},
|
|
54
|
+
'combobox': {'select', 'role:combobox', 'role:listbox'},
|
|
55
|
+
'image': {'img', 'role:img', 'input:image'},
|
|
56
|
+
'heading': {'h1', 'h2', 'h3', 'h4', 'h5', 'h6'},
|
|
57
|
+
}
|
|
58
|
+
# roles whose name may come from content (mirrors the auditor's set)
|
|
59
|
+
_NAME_FROM_CONTENT = {'checkbox', 'radio', 'switch', 'option', 'menuitem',
|
|
60
|
+
'menuitemcheckbox', 'menuitemradio', 'tab', 'treeitem'}
|
|
61
|
+
_MATCH_CAP = 10
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _norm(text):
|
|
65
|
+
return ' '.join((text or '').split()).casefold()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _tag_of(path):
|
|
69
|
+
return (path or '').split('>')[-1].split(':nth')[0]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _allowed_roles(role):
|
|
73
|
+
"""Set of raw kinds the `role` filter admits (None → no filter)."""
|
|
74
|
+
if not role:
|
|
75
|
+
return None
|
|
76
|
+
rl = role.strip().lower()
|
|
77
|
+
if rl in _ROLE_ALIASES:
|
|
78
|
+
return set(_ROLE_ALIASES[rl])
|
|
79
|
+
return {rl, '*' + rl, 'input:' + rl, 'role:' + rl, 'h' + rl if rl.isdigit() else rl}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _role_allowed(item_role, allowed):
|
|
83
|
+
if allowed is None:
|
|
84
|
+
return True
|
|
85
|
+
if item_role in allowed:
|
|
86
|
+
return True
|
|
87
|
+
# 'button' también admite 'role:button' sin alias explícito, etc.
|
|
88
|
+
tail = item_role.split(':', 1)[-1]
|
|
89
|
+
return tail in allowed
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _index(p):
|
|
93
|
+
"""Named elements from the auditor's records, in document order."""
|
|
94
|
+
items, seen = [], set()
|
|
95
|
+
|
|
96
|
+
def _name_sources(a):
|
|
97
|
+
lb = ' '.join((p._id_texts.get(i, '') or '').strip()
|
|
98
|
+
for i in (a.get('aria-labelledby') or '').split()).strip()
|
|
99
|
+
return lb, (a.get('aria-label') or '').strip(), (a.get('title') or '').strip()
|
|
100
|
+
|
|
101
|
+
def _add(a, role, name, match_extra=None, route=None):
|
|
102
|
+
if not name or id(a) in seen:
|
|
103
|
+
return
|
|
104
|
+
path = route or p._elem_paths.get(id(a))
|
|
105
|
+
if not path:
|
|
106
|
+
return
|
|
107
|
+
seen.add(id(a))
|
|
108
|
+
it = {'path': path, 'tag': _tag_of(path), 'id': (a.get('id') or '').strip(),
|
|
109
|
+
'role': role, 'name': ' '.join(name.split())[:120]}
|
|
110
|
+
if match_extra:
|
|
111
|
+
it.update(match_extra)
|
|
112
|
+
items.append(it)
|
|
113
|
+
|
|
114
|
+
for kind, a, text, img_attrs, hidden in p.controls_raw:
|
|
115
|
+
if hidden or 'disabled' in a:
|
|
116
|
+
continue
|
|
117
|
+
lb, al, ti = _name_sources(a)
|
|
118
|
+
if kind.startswith('input:'):
|
|
119
|
+
# el value de un input NO es su nombre accesible (solo en botones
|
|
120
|
+
# reales lo es el texto): aquí solo nombran aria/title/labelledby
|
|
121
|
+
_add(a, kind, al or lb or ti)
|
|
122
|
+
continue
|
|
123
|
+
img_names = []
|
|
124
|
+
for ia in img_attrs:
|
|
125
|
+
ilb, ial, iti = _name_sources(ia)
|
|
126
|
+
img_names.append((ia.get('alt') or '').strip() or ial or ilb or iti)
|
|
127
|
+
# orden accname de la spec: labelledby → aria-label → contenido
|
|
128
|
+
# (texto, imgs internas, alt) → title
|
|
129
|
+
_add(a, kind, lb or al or text.strip()
|
|
130
|
+
or ' '.join(x for x in img_names if x).strip()
|
|
131
|
+
or (a.get('alt') or '').strip() or ti)
|
|
132
|
+
|
|
133
|
+
for level, a, text, hidden, route in p.headings_raw:
|
|
134
|
+
if hidden:
|
|
135
|
+
continue
|
|
136
|
+
lb, al, _ti = _name_sources(a)
|
|
137
|
+
_add(a, f'h{level}', lb or al or text.strip(), route=route)
|
|
138
|
+
|
|
139
|
+
for a, hidden in p.imgs_all:
|
|
140
|
+
if hidden:
|
|
141
|
+
continue
|
|
142
|
+
lb, al, ti = _name_sources(a)
|
|
143
|
+
_add(a, 'img', (a.get('alt') or '').strip() or al or lb or ti)
|
|
144
|
+
|
|
145
|
+
for a, hidden in p.iframes_all:
|
|
146
|
+
if hidden:
|
|
147
|
+
continue
|
|
148
|
+
lb, al, ti = _name_sources(a)
|
|
149
|
+
_add(a, 'iframe', (a.get('title') or '').strip() or al or lb)
|
|
150
|
+
|
|
151
|
+
direct_text = {tid: ' '.join(buf).strip()
|
|
152
|
+
for tid, buf in getattr(p, '_field_buffers', {}).items()}
|
|
153
|
+
for tag, kind, a, _en_label, hidden in p.fields_raw:
|
|
154
|
+
if hidden:
|
|
155
|
+
continue
|
|
156
|
+
lb, al, ti = _name_sources(a)
|
|
157
|
+
content_name = direct_text.get(a.get('id') or '', '') \
|
|
158
|
+
if kind.split(':', 1)[-1] in _NAME_FROM_CONTENT else ''
|
|
159
|
+
# el kind de un input es su type ('email'): normalizo al formato
|
|
160
|
+
# 'input:email' que usan los aliases de rol
|
|
161
|
+
role_kind = f'input:{kind}' if tag == 'input' else kind
|
|
162
|
+
_add(a, role_kind, lb or al or ti or content_name)
|
|
163
|
+
|
|
164
|
+
return items
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def locate(html_text, query, role=None, multiple=False, lang='en'):
|
|
168
|
+
"""Localiza por nombre accesible; se niega si la elección es ambigua."""
|
|
169
|
+
if not isinstance(query, str) or not query.strip():
|
|
170
|
+
return {'query': query, 'role': role, 'found': False, 'ambiguous': False,
|
|
171
|
+
'selector': None, 'confidence': None, 'count': 0, 'matches': [],
|
|
172
|
+
'note': _t(lang, 'loc_no_query')}
|
|
173
|
+
allowed = _allowed_roles(role)
|
|
174
|
+
p = _Auditor()
|
|
175
|
+
try:
|
|
176
|
+
p.feed((html_text or '')[:MAX_HTML])
|
|
177
|
+
p.close()
|
|
178
|
+
except Exception as e: # noqa: BLE001 — html hostil: sin índice, sin caída
|
|
179
|
+
return {'query': query, 'role': role, 'found': False, 'ambiguous': False,
|
|
180
|
+
'selector': None, 'confidence': None, 'count': 0, 'matches': [],
|
|
181
|
+
'error': f'unparseable HTML: {e}'}
|
|
182
|
+
|
|
183
|
+
for _id, _parts in p._id_text_parts.items():
|
|
184
|
+
p._id_texts[_id] = ' '.join(_parts).strip()
|
|
185
|
+
|
|
186
|
+
items = [it for it in _index(p) if _role_allowed(it['role'], allowed)]
|
|
187
|
+
qn = _norm(query)
|
|
188
|
+
exact = [it for it in items if _norm(it['name']) == qn]
|
|
189
|
+
partial = [it for it in items if it not in exact and qn and qn in _norm(it['name'])]
|
|
190
|
+
|
|
191
|
+
def _out(found, ambiguous, selector, confidence, matches, total, note):
|
|
192
|
+
return {'query': query, 'role': role, 'found': found, 'ambiguous': ambiguous,
|
|
193
|
+
'selector': selector, 'confidence': confidence, 'count': total,
|
|
194
|
+
'matches': matches[:_MATCH_CAP], 'note': note}
|
|
195
|
+
|
|
196
|
+
if exact:
|
|
197
|
+
if len(exact) == 1:
|
|
198
|
+
return _out(True, False, exact[0]['path'], 'high',
|
|
199
|
+
exact, len(exact), '')
|
|
200
|
+
if multiple:
|
|
201
|
+
return _out(True, False, None, 'high', exact, len(exact),
|
|
202
|
+
_t(lang, 'loc_multiple'))
|
|
203
|
+
return _out(True, True, None, None, exact, len(exact),
|
|
204
|
+
_t(lang, 'loc_ambiguous', n=len(exact)).format(n=len(exact), q=query))
|
|
205
|
+
if partial:
|
|
206
|
+
if len(partial) == 1:
|
|
207
|
+
return _out(True, False, partial[0]['path'], 'medium',
|
|
208
|
+
partial, 1, _t(lang, 'loc_partial').format(q=query))
|
|
209
|
+
return _out(True, True, None, None, partial, len(partial),
|
|
210
|
+
_t(lang, 'loc_partial_ambiguous', n=len(partial)).format(
|
|
211
|
+
n=len(partial), q=query))
|
|
212
|
+
return _out(False, False, None, None, [], 0,
|
|
213
|
+
_t(lang, 'loc_no_match').format(q=query.strip()))
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def main(argv):
|
|
217
|
+
ap = argparse.ArgumentParser(
|
|
218
|
+
description='Locate an element by its accessible name — honest '
|
|
219
|
+
'refusal when the match is ambiguous')
|
|
220
|
+
ap.add_argument('html_file', nargs='?', help='the HTML to search')
|
|
221
|
+
ap.add_argument('--file', dest='html_opt', help='the HTML to search (alt form)')
|
|
222
|
+
ap.add_argument('--query', '-q', required=True, help='accessible name to find')
|
|
223
|
+
ap.add_argument('--role', help='filter: button, link, textbox, heading, h1, image…')
|
|
224
|
+
ap.add_argument('--multiple', action='store_true',
|
|
225
|
+
help='list every exact match instead of refusing')
|
|
226
|
+
ap.add_argument('--lang', default='en', choices=['es', 'en'])
|
|
227
|
+
ap.add_argument('-o', '--out', help='write the result JSON here')
|
|
228
|
+
a = ap.parse_args(argv)
|
|
229
|
+
path = a.html_file or a.html_opt
|
|
230
|
+
if not path:
|
|
231
|
+
ap.error('an HTML file is required (positional or --file)')
|
|
232
|
+
html_text = open(path, encoding='utf-8', errors='replace').read()
|
|
233
|
+
res = locate(html_text, a.query, role=a.role, multiple=a.multiple, lang=a.lang)
|
|
234
|
+
payload = json.dumps(res, ensure_ascii=False, indent=1)
|
|
235
|
+
if a.out:
|
|
236
|
+
with open(a.out, 'w', encoding='utf-8') as f:
|
|
237
|
+
f.write(payload)
|
|
238
|
+
print(json.dumps({'out': a.out, 'found': res['found'],
|
|
239
|
+
'selector': res['selector'],
|
|
240
|
+
'confidence': res['confidence']}, ensure_ascii=False))
|
|
241
|
+
else:
|
|
242
|
+
print(payload)
|
|
243
|
+
return 0
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
if __name__ == '__main__':
|
|
247
|
+
sys.exit(main(sys.argv[1:]))
|
|
@@ -9,8 +9,10 @@ success_criteria_level_a / _aa, one `web` component per criterion.
|
|
|
9
9
|
|
|
10
10
|
Honesty rule (non-negotiable, mirrors the pack and the VPAT): the machine
|
|
11
11
|
fills the adherence `notes`, never the level. Every criterion starts at
|
|
12
|
-
`not-evaluated
|
|
13
|
-
|
|
12
|
+
`not-evaluated`; the only machine-set level is `does-not-support`, forced
|
|
13
|
+
by an automated fail. Review-level signals stay `not-evaluated` with the
|
|
14
|
+
evidence in the notes — the machine never prints a conformance claim from
|
|
15
|
+
review-level evidence. A qualified human sets the
|
|
14
16
|
final level via `overrides` — same vocabulary as a11y_generate_vpat
|
|
15
17
|
(supports, partially_supports, …); the hyphenated forms of the OpenACR
|
|
16
18
|
format itself are accepted too. Every remark references the evidence
|
|
@@ -25,6 +27,11 @@ never break the document structure.
|
|
|
25
27
|
CLI:
|
|
26
28
|
a11yopenacr.py pack.json --product "Acme App" -o openacr.yaml
|
|
27
29
|
a11ytoolkit openacr pack.json --product "Acme App" -o openacr.yaml
|
|
30
|
+
|
|
31
|
+
FROZEN LAYER (2026-11-04, founder decision "freeze the docs"): this
|
|
32
|
+
module stays public as an HONEST DRAFT generator (the machine fills
|
|
33
|
+
Remarks/texts, never the claim). Maintenance fixes only; new
|
|
34
|
+
capabilities live in the SaaS (a11y.es / Lince).
|
|
28
35
|
"""
|
|
29
36
|
|
|
30
37
|
import argparse
|
|
@@ -63,7 +70,7 @@ def _remarks(row, finding, pack_sha):
|
|
|
63
70
|
chunks.append('e.g. ' + str(val['example']))
|
|
64
71
|
parts.append('; '.join(chunks))
|
|
65
72
|
if finding:
|
|
66
|
-
parts.append('issue: ' + str(finding.get('issue'
|
|
73
|
+
parts.append('issue: ' + str(finding.get('issue') or '')[:220])
|
|
67
74
|
if finding.get('remediation'):
|
|
68
75
|
parts.append('remediation: ' + str(finding['remediation'])[:220])
|
|
69
76
|
ef = row.get('effort')
|