@kinti/a11y-toolkit 5.26.0 → 5.27.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 +27 -4
- package/a11y_toolkit/a11yact.py +9 -1
- package/a11y_toolkit/a11yannotate.py +185 -0
- package/a11y_toolkit/a11yaudit.py +853 -193
- 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 +110 -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 +425 -95
- 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/a11yinit.py +30 -5
- 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 +177 -20
- package/a11y_toolkit/locales/es.json +178 -21
- package/a11y_toolkit/rgaa.json +2661 -0
- package/a11y_toolkit/server.py +149 -50
- package/package.json +2 -2
- package/a11y_toolkit/a11yplan.py +0 -214
- package/a11y_toolkit/a11ywcagem.py +0 -237
|
@@ -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')
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""a11y_patches — the sealed record of an autofix run: what changed, on what
|
|
3
|
+
page, reproducible or stale.
|
|
4
|
+
|
|
5
|
+
The doctrine this serves: fixing the ORIGINAL web is the client's job (their
|
|
6
|
+
agent, their CI, their credentials). The engine never touches the real web;
|
|
7
|
+
what it hands over is a patch-set — a versioned, sha-keyed artifact listing
|
|
8
|
+
the deterministic fixes that were applied to a copy, so anyone can repeat
|
|
9
|
+
them upstream and PROVE they did the right thing.
|
|
10
|
+
|
|
11
|
+
The honesty rules, same as everywhere:
|
|
12
|
+
- A patch-set is keyed by the source page's SHA-256. Hand it a different
|
|
13
|
+
page and it declares itself `stale` — patches never blind-apply.
|
|
14
|
+
- `verify` re-runs the deterministic autofix and cross-checks: same engine,
|
|
15
|
+
same page → the same fixes must reproduce, patch for patch. Anything else
|
|
16
|
+
is reported as a mismatch, never silently accepted.
|
|
17
|
+
- Fixes that autofix declined to apply travel in the set too (`not_applied`),
|
|
18
|
+
so the record matches the run.
|
|
19
|
+
|
|
20
|
+
Artifact (format a11y-patches/1):
|
|
21
|
+
{'format': 'a11y-patches/1', 'source_sha256': str, 'engine_version': str,
|
|
22
|
+
'created_at': iso8601, 'params': {lang, title, form_errors}, 'count': int,
|
|
23
|
+
'fixes': [{signal, fix}, ...], 'not_applied': [{signal, criterion, ...}]}
|
|
24
|
+
|
|
25
|
+
`params` are SEALED in the set: `verify` repeats the autofix with exactly the
|
|
26
|
+
arguments of the build (an older set without `params` verifies with the build
|
|
27
|
+
defaults). Without them, every set carrying the form-error layer verified as
|
|
28
|
+
`mismatch` — the replay silently dropped lang/title/form_errors.
|
|
29
|
+
|
|
30
|
+
CLI:
|
|
31
|
+
a11ytoolkit patches --file page.html -o patches.json # build
|
|
32
|
+
a11ytoolkit patches --file page.html --verify patches.json # verify
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
import argparse
|
|
36
|
+
import datetime
|
|
37
|
+
import hashlib
|
|
38
|
+
import json
|
|
39
|
+
import sys
|
|
40
|
+
|
|
41
|
+
from .a11yfix import autofix as _autofix
|
|
42
|
+
from . import a11yi18n
|
|
43
|
+
|
|
44
|
+
FORMAT = 'a11y-patches/1'
|
|
45
|
+
|
|
46
|
+
T = a11yi18n.pair('patches')
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _t(lang, key):
|
|
50
|
+
return T.get(lang, T['en']).get(key, key)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _sha(text):
|
|
54
|
+
return hashlib.sha256(text.encode('utf-8', 'replace')).hexdigest()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def build(html_text, lang=None, title=None, form_errors=True):
|
|
58
|
+
"""Run the deterministic autofix once; return its sealed patch-set and
|
|
59
|
+
the fixed html. The record is a fact about this run, not a promise."""
|
|
60
|
+
from .server import VERSION # lazy: server importa este módulo arriba
|
|
61
|
+
res = _autofix(html_text, lang=lang, title=title, form_errors=form_errors)
|
|
62
|
+
patch_set = {
|
|
63
|
+
'format': FORMAT,
|
|
64
|
+
'source_sha256': _sha(html_text),
|
|
65
|
+
'engine_version': VERSION,
|
|
66
|
+
'created_at': datetime.datetime.now(
|
|
67
|
+
datetime.timezone.utc).isoformat(timespec='seconds'),
|
|
68
|
+
# params sellados: verify repite el autofix CON ESTOS argumentos
|
|
69
|
+
'params': {'lang': lang, 'title': title, 'form_errors': form_errors},
|
|
70
|
+
'count': len(res['applied']),
|
|
71
|
+
'fixes': res['applied'],
|
|
72
|
+
'not_applied': res['not_applied'],
|
|
73
|
+
}
|
|
74
|
+
return {'patch_set': patch_set, 'fixed_html': res['fixed_html'],
|
|
75
|
+
'result': res}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def apply_patches(html_text, patch_set, lang='en'):
|
|
79
|
+
"""Verify-and-repeat: the patch-set is reproduced on the SAME page.
|
|
80
|
+
|
|
81
|
+
Returns {'status': 'reproduced'|'stale'|'mismatch', ...}. `stale` means
|
|
82
|
+
the page is not the one the set was built from (sha mismatch) — the set
|
|
83
|
+
invalidates itself rather than blind-applying. `mismatch` means the same
|
|
84
|
+
page no longer produces the same fixes (engine drift or tampered set)."""
|
|
85
|
+
if not isinstance(patch_set, dict) or patch_set.get('format') != FORMAT:
|
|
86
|
+
return {'status': 'mismatch', 'note': _t(lang, 'pat_bad_format')}
|
|
87
|
+
sha = _sha(html_text)
|
|
88
|
+
if sha != patch_set.get('source_sha256'):
|
|
89
|
+
return {'status': 'stale', 'source_sha256': sha,
|
|
90
|
+
'expected_sha256': patch_set.get('source_sha256'),
|
|
91
|
+
'note': _t(lang, 'pat_stale')}
|
|
92
|
+
# replay with the SEALED build params (build defaults for pre-params sets):
|
|
93
|
+
# re-running with different arguments invents a mismatch that is not there
|
|
94
|
+
params = patch_set.get('params') or {}
|
|
95
|
+
res = _autofix(html_text,
|
|
96
|
+
lang=params.get('lang'),
|
|
97
|
+
title=params.get('title'),
|
|
98
|
+
form_errors=params.get('form_errors', True))
|
|
99
|
+
if res['applied'] != patch_set.get('fixes'):
|
|
100
|
+
return {'status': 'mismatch', 'source_sha256': sha,
|
|
101
|
+
'reproduced': res['applied'],
|
|
102
|
+
'recorded': patch_set.get('fixes'),
|
|
103
|
+
'note': _t(lang, 'pat_mismatch')}
|
|
104
|
+
return {'status': 'reproduced', 'source_sha256': sha,
|
|
105
|
+
'count': len(res['applied']), 'fixed_html': res['fixed_html'],
|
|
106
|
+
'note': _t(lang, 'pat_reproduced')}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def main(argv):
|
|
110
|
+
ap = argparse.ArgumentParser(
|
|
111
|
+
description='Build or verify a sealed patch-set of deterministic fixes')
|
|
112
|
+
ap.add_argument('html_file', nargs='?', help='the HTML file')
|
|
113
|
+
ap.add_argument('--file', dest='html_opt', help='the HTML file (alt form)')
|
|
114
|
+
ap.add_argument('-o', '--out', help='write the patch-set JSON here (build)')
|
|
115
|
+
ap.add_argument('--verify', metavar='PATCHSET',
|
|
116
|
+
help='verify this patch-set against the HTML instead')
|
|
117
|
+
ap.add_argument('--fixed', dest='fixed_out',
|
|
118
|
+
help='write the fixed html here (build)')
|
|
119
|
+
ap.add_argument('--lang', default='en', choices=['es', 'en'])
|
|
120
|
+
a = ap.parse_args(argv)
|
|
121
|
+
path = a.html_file or a.html_opt
|
|
122
|
+
if not path:
|
|
123
|
+
ap.error('an HTML file is required (positional or --file)')
|
|
124
|
+
html_text = open(path, encoding='utf-8', errors='replace').read()
|
|
125
|
+
if a.verify:
|
|
126
|
+
patch_set = json.load(open(a.verify, encoding='utf-8'))
|
|
127
|
+
res = apply_patches(html_text, patch_set)
|
|
128
|
+
# JSON SIEMPRE válido: el fixed_html completo no se imprime (una
|
|
129
|
+
# salida cortada a [:2000] partía escapes y dejaba JSON roto) —
|
|
130
|
+
# quien quiera la copia arreglada usa --fixed
|
|
131
|
+
out = {k: v for k, v in res.items() if k != 'fixed_html'}
|
|
132
|
+
print(json.dumps(out, ensure_ascii=False, indent=1))
|
|
133
|
+
if a.fixed_out and res.get('status') == 'reproduced':
|
|
134
|
+
with open(a.fixed_out, 'w', encoding='utf-8') as f:
|
|
135
|
+
f.write(res['fixed_html'])
|
|
136
|
+
return 0 if res['status'] in ('reproduced', 'stale') else 1
|
|
137
|
+
res = build(html_text)
|
|
138
|
+
payload = json.dumps(res['patch_set'], ensure_ascii=False, indent=1)
|
|
139
|
+
if a.out:
|
|
140
|
+
with open(a.out, 'w', encoding='utf-8') as f:
|
|
141
|
+
f.write(payload)
|
|
142
|
+
print(json.dumps({'out': a.out, 'count': res['patch_set']['count'],
|
|
143
|
+
'source_sha256': res['patch_set']['source_sha256']},
|
|
144
|
+
ensure_ascii=False))
|
|
145
|
+
else:
|
|
146
|
+
print(payload)
|
|
147
|
+
if a.fixed_out:
|
|
148
|
+
with open(a.fixed_out, 'w', encoding='utf-8') as f:
|
|
149
|
+
f.write(res['fixed_html'])
|
|
150
|
+
return 0
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
if __name__ == '__main__':
|
|
154
|
+
sys.exit(main(sys.argv[1:]))
|