@kinti/a11y-toolkit 5.25.2 → 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.
Files changed (44) hide show
  1. package/README.md +1 -1
  2. package/a11y_toolkit/a11y.py +31 -4
  3. package/a11y_toolkit/a11yact.py +9 -1
  4. package/a11y_toolkit/a11yannotate.py +185 -0
  5. package/a11y_toolkit/a11yaudit.py +903 -186
  6. package/a11y_toolkit/a11ybadge.py +24 -17
  7. package/a11y_toolkit/a11ybudget.py +145 -1
  8. package/a11y_toolkit/a11ycorpus.py +58 -24
  9. package/a11y_toolkit/a11ycrit.py +110 -53
  10. package/a11y_toolkit/a11ydiff.py +104 -34
  11. package/a11y_toolkit/a11ydisprove.py +15 -8
  12. package/a11y_toolkit/a11ydocx.py +8 -6
  13. package/a11y_toolkit/a11ydom.py +451 -96
  14. package/a11y_toolkit/a11yen301549.py +147 -0
  15. package/a11y_toolkit/a11yengines.py +157 -0
  16. package/a11y_toolkit/a11yevidence.py +182 -36
  17. package/a11y_toolkit/a11yfix.py +131 -52
  18. package/a11y_toolkit/a11yinit.py +30 -5
  19. package/a11y_toolkit/a11yjourney.py +110 -4
  20. package/a11y_toolkit/a11yledger.py +119 -12
  21. package/a11y_toolkit/a11ylocate.py +247 -0
  22. package/a11y_toolkit/a11yopenacr.py +28 -7
  23. package/a11y_toolkit/a11ypatches.py +154 -0
  24. package/a11y_toolkit/a11ypatterns.py +344 -0
  25. package/a11y_toolkit/a11ypdf.py +109 -53
  26. package/a11y_toolkit/a11yrgaa.py +60 -0
  27. package/a11y_toolkit/a11yroute.py +34 -12
  28. package/a11y_toolkit/a11ysarif.py +70 -21
  29. package/a11y_toolkit/a11yscope.py +296 -0
  30. package/a11y_toolkit/a11yscroll.py +7 -5
  31. package/a11y_toolkit/a11ystatement.py +30 -6
  32. package/a11y_toolkit/a11ytrace.py +293 -0
  33. package/a11y_toolkit/a11yvalidate.py +21 -15
  34. package/a11y_toolkit/a11yvpat.py +54 -11
  35. package/a11y_toolkit/a11yvtt.py +22 -6
  36. package/a11y_toolkit/a11ywiz.py +121 -0
  37. package/a11y_toolkit/contrast.py +62 -24
  38. package/a11y_toolkit/locales/en.json +222 -24
  39. package/a11y_toolkit/locales/es.json +223 -25
  40. package/a11y_toolkit/rgaa.json +2661 -0
  41. package/a11y_toolkit/server.py +247 -59
  42. package/package.json +2 -2
  43. package/a11y_toolkit/a11yplan.py +0 -214
  44. package/a11y_toolkit/a11ywcagem.py +0 -237
@@ -0,0 +1,293 @@
1
+ #!/usr/bin/env python3
2
+ """a11y_trace — the behavioral trace: what a keyboard user LIVES, step by step.
3
+
4
+ The deterministic core of the journey-replay idea family (replayable journeys,
5
+ screen-reader release gates, behavioral debugging): one walk of the page
6
+ recording, PER TAB STEP, the focused element's stable signature (the same
7
+ key doctrine as the snapshot), the aria-live announcements the step
8
+ triggered, and the url — plus the accessibility tree at the end.
9
+ `trace diff` compares two traces: FOCUS BEHAVIOR IS THE GATE (a forked or
10
+ lost tab sequence blocks, exit 2); announcements are reported, not gated
11
+ (content changes legitimately between builds — a collapsed announcement
12
+ layer is flagged informationally).
13
+
14
+ Honesty: this captures the accessibility-tree / live-region layer — what a
15
+ screen reader would have AVAILABLE, not the synthesized speech of NVDA/JAWS
16
+ (real AT is a different beast; the agent-side complement is
17
+ a11y_journey_verdict). The collector is SILENT (no panel injected): a trace
18
+ must not mutate the page it measures.
19
+
20
+ CLI (infrastructure, not a tool — D17, like corpus/mutants/engines):
21
+ a11ytrace.py https://web [--steps 25] [-o trace.json] # needs Playwright
22
+ a11ytrace.py https://web --script journey.json -o t.json # scripted real journey
23
+ a11ytrace.py diff before.json after.json # exit 0 ok / 2 divergences
24
+
25
+ Script file: a JSON list of actions — {"kind":"click","selector":"#pay"},
26
+ {"kind":"fill","selector":"#email","value":"…"}, {"kind":"select",…},
27
+ {"kind":"press","key":"Enter"}, {"kind":"wait","ms":300}, {"kind":"goto","url":…}.
28
+ """
29
+
30
+ import argparse
31
+ import json
32
+ import sys
33
+ from datetime import datetime, timezone
34
+
35
+ from . import a11ydiff
36
+
37
+ # Silent live-region collector: accumulates announcements and exposes a
38
+ # drain() so each trace step reads EXACTLY the announcements it triggered.
39
+ # Same selector set as the arialive monitor, but no DOM panel — the trace
40
+ # must not mutate the page it measures.
41
+ _COLLECTOR = r'''() => {
42
+ if (window.__a11yTraceDrain) return window.__a11yTraceDrain();
43
+ const SEL = '[aria-live],[role=alert],[role=status],[role=log],[role=marquee],[role=timer]';
44
+ const seen = new WeakSet(); const log = [];
45
+ const politeness = el => el.getAttribute('aria-live') ||
46
+ ({ alert: 'assertive', status: 'polite', log: 'polite',
47
+ marquee: 'off', timer: 'off' })[el.getAttribute('role')] || 'polite';
48
+ const target = el => el.id ? '#' + el.id
49
+ : (el.className && typeof el.className === 'string'
50
+ ? el.tagName.toLowerCase() + '.' + el.className.trim().split(/\s+/).slice(0, 2).join('.')
51
+ : el.tagName.toLowerCase());
52
+ const push = (el, reason) => {
53
+ if (log.length >= 500) return;
54
+ log.push({ politeness: politeness(el),
55
+ role: el.getAttribute('role') || 'aria-live',
56
+ target: target(el),
57
+ text: ((el.innerText || el.textContent || '').trim()
58
+ .replace(/\s+/g, ' ')).slice(0, 220),
59
+ reason: reason || 'update' });
60
+ };
61
+ const watch = el => {
62
+ if (!el || el.nodeType !== 1 || seen.has(el)) return;
63
+ if (!el.matches || !el.matches(SEL)) return;
64
+ seen.add(el);
65
+ if (el.getAttribute('role') === 'alert') push(el, 'inserted');
66
+ new MutationObserver(() => push(el))
67
+ .observe(el, { childList: true, characterData: true, subtree: true });
68
+ };
69
+ document.querySelectorAll(SEL).forEach(watch);
70
+ new MutationObserver(muts => muts.forEach(m => m.addedNodes.forEach(n => {
71
+ if (n.nodeType !== 1) return;
72
+ watch(n);
73
+ if (n.querySelectorAll) n.querySelectorAll(SEL).forEach(watch);
74
+ }))).observe(document.body, { childList: true, subtree: true });
75
+ window.__a11yTraceDrain = () => log.splice(0);
76
+ return [];
77
+ }'''
78
+
79
+ # Drenaje defensivo: un `goto` destruye window.__a11yTraceDrain (navegación =
80
+ # contexto nuevo); pedirlo sin guardia tronaría el paso entero. La expresión
81
+ # es estática (nada del page entra aquí) y devuelve [] cuando el recolector
82
+ # aún no existe — el paso se graba, simplemente sin anuncios de ese instante.
83
+ _DRAIN = '() => window.__a11yTraceDrain ? window.__a11yTraceDrain() : []'
84
+
85
+
86
+ def _run_script_action(page, act):
87
+ """One scripted action → (label, ok). Selector-valued actions target CSS."""
88
+ kind = act.get('kind', '')
89
+ sel = act.get('selector') or act.get('target') or ''
90
+ if kind == 'click':
91
+ loc = page.locator(sel).first
92
+ loc.click(timeout=5000)
93
+ return f'click:{sel}', True
94
+ if kind == 'fill':
95
+ page.locator(sel).first.fill(str(act.get('value', '')), timeout=5000)
96
+ return f'fill:{sel}', True
97
+ if kind == 'select':
98
+ page.locator(sel).first.select_option(str(act.get('value', '')), timeout=5000)
99
+ return f'select:{sel}', True
100
+ if kind == 'press':
101
+ page.keyboard.press(act.get('key', 'Enter'))
102
+ return f'press:{act.get("key", "Enter")}', True
103
+ if kind == 'wait':
104
+ page.wait_for_timeout(int(act.get('ms', 300)))
105
+ return f'wait:{act.get("ms", 300)}', True
106
+ if kind == 'goto':
107
+ page.goto(act.get('url', ''), wait_until='load', timeout=30000)
108
+ # la navegación destruye el recolector (contexto nuevo): re-inyectarlo
109
+ # o el drain de ESTE paso y de los siguientes tronaría/volvería vacío
110
+ page.evaluate(_COLLECTOR)
111
+ return f'goto:{act.get("url", "")}', True
112
+ return f'unknown:{kind or sel}', False
113
+
114
+
115
+ def _run_script(page, script):
116
+ """Scripted actions → (walk, navigations). Factored out of trace() so the
117
+ loop is testable against a fake page (no Playwright needed)."""
118
+ walk = []
119
+ navigations = 0
120
+ url_now = page.url
121
+ for i, act in enumerate(script):
122
+ if not isinstance(act, dict):
123
+ continue
124
+ try:
125
+ label, _ok = _run_script_action(page, act)
126
+ except Exception as e: # noqa: BLE001 — a failed action is a recorded step too
127
+ label = f'{act.get("kind", "?")}:{act.get("selector") or act.get("key") or ""}'
128
+ label += f' (failed: {str(e)[:60]})'
129
+ page.wait_for_timeout(200)
130
+ info = page.evaluate(a11ydiff.FOCUS_KEY_JS)
131
+ anns = page.evaluate(_DRAIN)
132
+ if page.url != url_now:
133
+ navigations += 1
134
+ url_now = page.url
135
+ walk.append({'step': i + 1, 'action': label, 'focus': info,
136
+ 'announcements': anns, 'url': page.url})
137
+ return walk, navigations
138
+
139
+
140
+ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None, browser='auto'):
141
+ """One url → the behavioral trace (replayable JSON).
142
+
143
+ script: optional list of scripted actions (click/fill/select/press/wait/
144
+ goto, each with a CSS selector where applicable) — a REAL journey instead
145
+ of the keyboard walk. Each action becomes a recorded step; the announcement
146
+ collector and the focus signature stay identical, so trace diff works the
147
+ same over scripted traces."""
148
+ from playwright.sync_api import sync_playwright
149
+ from .a11ydom import _get_browser
150
+ with sync_playwright() as p:
151
+ nav = _get_browser(p, preferred=browser)
152
+ ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
153
+ page = ctx.new_page() if auth_state else nav.new_page()
154
+ try:
155
+ page.goto(url, wait_until='load', timeout=timeout * 1000)
156
+ except Exception as e: # noqa: BLE001
157
+ nav.close()
158
+ return {'error': f'could not load: {e}'}
159
+ page.wait_for_timeout(400)
160
+ page.evaluate(_COLLECTOR)
161
+
162
+ walk = []
163
+ navigations = 0
164
+ url_now = page.url
165
+ if script:
166
+ ended_by = 'script_done'
167
+ walk, navigations = _run_script(page, script)
168
+ else:
169
+ ended_by = 'step_cap'
170
+ for i in range(steps):
171
+ page.keyboard.press('Tab')
172
+ info = page.evaluate(a11ydiff.FOCUS_KEY_JS)
173
+ if info is None:
174
+ ended_by = 'no_more_focusables'
175
+ break
176
+ page.wait_for_timeout(150) # let the observers flush
177
+ anns = page.evaluate(_DRAIN)
178
+ if page.url != url_now:
179
+ navigations += 1
180
+ url_now = page.url
181
+ walk.append({'step': i + 1, 'focus': info,
182
+ 'announcements': anns, 'url': page.url})
183
+
184
+ tree = None
185
+ try:
186
+ tree = page.locator('body').aria_snapshot()
187
+ if len(tree) > 60_000:
188
+ tree = tree[:60_000] + '\n… (truncated)'
189
+ except Exception: # noqa: BLE001
190
+ tree = None
191
+ nav.close()
192
+
193
+ data = {'mode': 'trace', 'url': url,
194
+ 'ts': datetime.now(timezone.utc).isoformat(),
195
+ 'steps': walk,
196
+ 'summary': {'steps_taken': len(walk),
197
+ 'announcements': sum(len(s.get('announcements') or [])
198
+ for s in walk),
199
+ 'navigations': navigations,
200
+ 'ended_by': ended_by}}
201
+ if tree is not None:
202
+ data['tree'] = tree
203
+ if output:
204
+ with open(output, 'w', encoding='utf-8') as f:
205
+ json.dump(data, f, ensure_ascii=False, indent=1)
206
+ return data
207
+
208
+
209
+ def trace_diff(a, b):
210
+ """Two traces → verdict. Focus behavior gates; announcements inform."""
211
+ fa = [s.get('focus') for s in a.get('steps', [])]
212
+ fb = [s.get('focus') for s in b.get('steps', [])]
213
+ set_a, set_b = set(fa), set(fb)
214
+ common_a = [x for x in fa if x in set_b]
215
+ common_b = [x for x in fb if x in set_a]
216
+ lost = [x for x in fa if x not in set_b]
217
+ gained = [x for x in fb if x not in set_a]
218
+ reordered = common_a != common_b
219
+ first_divergence = next((i for i, (x, y) in enumerate(zip(common_a, common_b))
220
+ if x != y), None)
221
+ ann_a = sum(len(s.get('announcements', [])) for s in a.get('steps', []))
222
+ ann_b = sum(len(s.get('announcements', [])) for s in b.get('steps', []))
223
+ collapsed = ann_a > 0 and ann_b == 0
224
+ ok = not (lost or reordered)
225
+ return {
226
+ 'ok': ok,
227
+ 'summary': {'steps': {'before': len(fa), 'after': len(fb)},
228
+ 'focus_lost': len(lost), 'focus_gained': len(gained),
229
+ 'reordered': reordered,
230
+ 'announcements': {'before': ann_a, 'after': ann_b,
231
+ 'collapsed': collapsed}},
232
+ 'focus': {'before': fa, 'after': fb, 'lost': lost, 'gained': gained,
233
+ 'first_divergence': first_divergence},
234
+ 'note': ('focus behavior is the gate: a lost or forked tab sequence '
235
+ 'blocks (exit 2). Announcement counts are reported, not '
236
+ 'gated — content changes legitimately between builds; a '
237
+ 'collapsed layer (had announcements, now zero) is flagged '
238
+ 'informationally'),
239
+ }
240
+
241
+
242
+ def main(argv):
243
+ # el hub del CLI pasa el argv SIN el subcomando (['url', …]): el parser
244
+ # exige trace|diff — prepend 'trace' cuando el primer token no es subcmd
245
+ if argv and argv[0] not in ('trace', 'diff') and not argv[0].startswith('-'):
246
+ argv = ['trace'] + argv
247
+ p = argparse.ArgumentParser(description=__doc__)
248
+ sub = p.add_subparsers(dest='cmd', required=True)
249
+ s1 = sub.add_parser('trace')
250
+ s1.add_argument('url')
251
+ s1.add_argument('--steps', type=int, default=25)
252
+ s1.add_argument('--script', help='JSON file: scripted journey (click/fill/select/press/wait/goto)')
253
+ s1.add_argument('--auth-state', help='Playwright storage_state JSON (session)')
254
+ s1.add_argument('--timeout', type=int, default=45)
255
+ s1.add_argument('-o', '--out', default='trace.json')
256
+ s2 = sub.add_parser('diff')
257
+ s2.add_argument('a')
258
+ s2.add_argument('b')
259
+ a = p.parse_args(argv)
260
+
261
+ if a.cmd == 'trace':
262
+ script = None
263
+ if a.script:
264
+ try:
265
+ with open(a.script, encoding='utf-8') as f:
266
+ script = json.load(f)
267
+ except (OSError, json.JSONDecodeError) as e:
268
+ print(json.dumps({'error': f'bad script file: {e}'}))
269
+ return 1
270
+ try:
271
+ d = trace(a.url, steps=a.steps, output=a.out, auth_state=a.auth_state,
272
+ timeout=a.timeout, script=script)
273
+ except ImportError:
274
+ print(json.dumps({'error': 'Playwright not installed: pip install '
275
+ 'playwright && playwright install chromium'}))
276
+ return 1
277
+ if 'error' in d:
278
+ print(json.dumps(d, ensure_ascii=False))
279
+ return 1
280
+ print(json.dumps({'url': d['url'], 'summary': d['summary'],
281
+ 'out': a.out}, ensure_ascii=False, indent=1))
282
+ return 0
283
+ with open(a.a, encoding='utf-8') as f:
284
+ ja = json.load(f)
285
+ with open(a.b, encoding='utf-8') as f:
286
+ jb = json.load(f)
287
+ verdict = trace_diff(ja, jb)
288
+ print(json.dumps(verdict, ensure_ascii=False, indent=1))
289
+ return 0 if verdict['ok'] else 2
290
+
291
+
292
+ if __name__ == '__main__':
293
+ sys.exit(main(sys.argv[1:]))
@@ -22,16 +22,13 @@ import urllib.request
22
22
  from .a11yaudit import compute_score
23
23
 
24
24
  BASE = 'https://validator.w3.org/nu/'
25
- UA = 'a11y-toolkit/3.16 (WCAG audit; github.com/kinti/a11y-toolkit)'
26
25
 
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
- )
26
+
27
+ def _ua():
28
+ # lazy: server importa este módulo arriba; la versión vive en un solo
29
+ # sitio (antes: UA hardcodeado dos majors atrás)
30
+ from .server import VERSION
31
+ return f'a11y-toolkit/{VERSION} (WCAG audit; github.com/kinti/a11y-toolkit)'
35
32
 
36
33
 
37
34
  def _criterion_for(message):
@@ -49,11 +46,11 @@ def _call(data=None, url=None, timeout=60, base_url=None):
49
46
  target = (base_url or BASE).rstrip('/') + '/'
50
47
  if url:
51
48
  target += '?' + urllib.parse.urlencode({'doc': url, 'out': 'json'})
52
- req = urllib.request.Request(target, headers={'User-Agent': UA})
49
+ req = urllib.request.Request(target, headers={'User-Agent': _ua()})
53
50
  else:
54
51
  target += '?out=json'
55
52
  req = urllib.request.Request(target, data=data.encode('utf-8'),
56
- headers={'User-Agent': UA,
53
+ headers={'User-Agent': _ua(),
57
54
  'Content-Type': 'text/html; charset=utf-8'},
58
55
  method='POST')
59
56
  with urllib.request.urlopen(req, timeout=timeout) as r:
@@ -85,13 +82,22 @@ def _process(resp, origin, lang='en'):
85
82
  'summary': {s_: sum(1 for h in findings if h['severity'] == s_)
86
83
  for s_ in ('high', 'medium', 'low')},
87
84
  '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.'),
85
+ 'notice': _NOTICE.get(lang, _NOTICE['en']),
92
86
  }
93
87
 
94
88
 
89
+ _NOTICE = {
90
+ 'es': ('Informe del validador Nu del W3C (validator.w3.org/nu). Complementa las '
91
+ 'auditorías del toolkit con la vista del parser del W3C: doctype, '
92
+ 'codificación, validez estructural. La validez HTML no es WCAG por sí '
93
+ 'misma; los criterios mapeados donde se solapan van etiquetados.'),
94
+ 'en': ('Report from the W3C Nu validator (validator.w3.org/nu). Complements the '
95
+ 'toolkit audits with the W3C parser view: doctype, encoding, structural '
96
+ 'validity. HTML validity is not WCAG by itself; mapped criteria where they '
97
+ 'overlap are labeled.'),
98
+ }
99
+
100
+
95
101
  def validate_url(url, timeout=60, lang='en', base_url=None):
96
102
  resp = _call(url=url, timeout=timeout, base_url=base_url)
97
103
  return _process(resp, url, lang)
@@ -6,9 +6,11 @@ or raw audit reports (the pack is built here). Output: an accessible HTML
6
6
  VPAT with the full 55-criterion WCAG 2.2 A/AA table.
7
7
 
8
8
  Honesty rule (non-negotiable, mirrors the pack): the machine fills Remarks,
9
- never the Conformance Level. Every row starts at 'Not Evaluated' unless an
10
- automated fail forces 'Does Not Support' (or 'Partially Supports' for
11
- review-level signals). A qualified human sets the final level via `overrides`
9
+ never the Conformance Level. Every row starts at 'Not Evaluated'; the only
10
+ machine-set level is 'Does Not Support', forced by an automated fail.
11
+ Review-level signals stay 'Not Evaluated' with the evidence in Remarks —
12
+ the machine never prints a conformance claim from review-level evidence.
13
+ A qualified human sets the final level via `overrides`
12
14
  and signs; until then the document is a DRAFT and says so. The signature
13
15
  statement must reference the evidence pack's sha256 — same tamper-evidence
14
16
  rule as the pack itself. VPAT is a vendor self-declaration, not a certificate.
@@ -17,6 +19,11 @@ CLI:
17
19
  a11yvpat.py pack.json --product "Acme App" --contact a11y@acme.example \
18
20
  --overrides '{"1.1.1": "does_not_support", "1.2.2": "not_applicable"}' \
19
21
  -o vpat.html
22
+
23
+ FROZEN LAYER (2026-11-04, founder decision "freeze the docs"): this
24
+ module stays public as an HONEST DRAFT generator (the machine fills
25
+ Remarks/texts, never the claim). Maintenance fixes only; new
26
+ capabilities live in the SaaS (a11y.es / Lince).
20
27
  """
21
28
 
22
29
  import argparse
@@ -25,17 +32,23 @@ import html
25
32
  import json
26
33
  import sys
27
34
  from . import a11yi18n
35
+ from .a11yact import _NOT_DEAD
28
36
 
29
37
  LEVELS = a11yi18n.pair('vpat_levels') # locales/<lang>.json — community-editable
30
38
 
31
39
  _STATUS_TO_LEVEL = {
32
40
  'automated-fail': 'does_not_support',
33
- 'automated-review': 'partially_supports',
41
+ # review-level evidence is NOT a conformance claim: it stays not-evaluated
42
+ # and the finding travels in the Remarks (evidence, never conformance —
43
+ # only a human sets a level above does-not-support)
44
+ 'automated-review': 'not_evaluated',
34
45
  # not-flagged ≠ pass; agent-verified no es una firma humana
35
46
  'not-flagged': 'not_evaluated',
36
47
  'not-run': 'not_evaluated',
37
48
  'manual-only': 'not_evaluated',
38
49
  'agent-verified': 'not_evaluated',
50
+ # exclusión de aplicabilidad confirmada por humano (pack con scope)
51
+ 'not-applicable': 'not_applicable',
39
52
  }
40
53
 
41
54
  TXT = a11yi18n.pair('vpat_txt') # locales/<lang>.json — community-editable
@@ -46,11 +59,27 @@ def _t(lang):
46
59
 
47
60
 
48
61
  def _findings_by_code(pack):
49
- """Código de criterio → primer hallazgo con issue+remediation (de los artefactos)."""
62
+ """Código de criterio → primer hallazgo VIVO con issue+remediation (de los artefactos).
63
+
64
+ Un hallazgo muerto (el disprover lo marcó rejected, o quedó not-rechecked)
65
+ NO es evidencia: se salta — mismo filtro que a11yact (EARL) y build_pack.
66
+ Si existe otro hallazgo vivo del mismo código, ese es el que se cita; el
67
+ muerto nunca enmascara al vivo (ni viceversa)."""
50
68
  by_code = {}
51
69
  for art in pack.get('artifacts', []):
52
70
  body = art.get('body') or {}
53
- for h in body.get('findings', []):
71
+ # artifacts de site-crawl anidan los hallazgos en reports[] — sin
72
+ # este descenso TODOS los Remarks de un pack de crawl salían sin cita
73
+ _hls = body.get('findings')
74
+ if not _hls and isinstance(body.get('reports'), list):
75
+ _hls = [h for sub in body['reports']
76
+ if isinstance(sub, dict) for h in sub.get('findings', [])
77
+ if isinstance(h, dict)]
78
+ for h in (_hls or []):
79
+ if not isinstance(h, dict):
80
+ continue # artefacto hostil: sin crash
81
+ if h.get('status') in _NOT_DEAD or h.get('disprover_status') in _NOT_DEAD:
82
+ continue
54
83
  code = (h.get('criterion') or '').split(' ')[0]
55
84
  if code and code not in by_code:
56
85
  by_code[code] = h
@@ -80,7 +109,7 @@ def _remarks(t, row, finding, level, pack_sha):
80
109
  if chunks:
81
110
  parts.append('; '.join(chunks))
82
111
  if finding:
83
- parts.append(f"issue: {finding.get('issue', '')[:220]}")
112
+ parts.append(f"issue: {str(finding.get('issue') or '')[:220]}")
84
113
  if finding.get('remediation'):
85
114
  parts.append(f"remediation: {finding['remediation'][:220]}")
86
115
  ef = row.get('effort')
@@ -100,18 +129,29 @@ def _wcag_order(code):
100
129
  def generate_vpat(pack=None, reports=None, product='', product_version=None,
101
130
  report_date=None, description=None, contact=None, methods=None,
102
131
  notes=None, overrides=None, reviewer=None, lang='en',
103
- verified=None, output_path=None):
132
+ verified=None, scope=None, output_path=None):
104
133
  """Pack (o informes) → HTML VPAT 2.5 accesible + resumen.
105
134
 
106
135
  overrides: {'1.1.1': 'supports', …} — niveles fijados por una persona
107
- cualificada; ganan sobre la derivación automática."""
136
+ cualificada; ganan sobre la derivación automática (scope incluido:
137
+ una exclusion confirmada puede revertirse a mano si el humano lo decide).
138
+
139
+ scope: salida de a11y_scope — las exclusiones CONFIRMADAS por humano
140
+ salen como Not Applicable con su razón; las propuestas nunca."""
108
141
  t = _t(lang)
109
142
  if pack is None:
110
143
  if not reports:
111
144
  return {'error': t['error_no_pack']}
112
145
  from .a11yevidence import build_pack
113
146
  pack = build_pack(reports, verified=verified,
114
- reviewer=reviewer)
147
+ reviewer=reviewer, scope=scope)
148
+ elif scope is not None:
149
+ # pack ya construido + scope: aplicar las exclusiones confirmadas
150
+ # (jamás silencio — el CLI lo promete)
151
+ if not isinstance(scope, dict):
152
+ return {'error': t['error_scope']}
153
+ from .a11yevidence import apply_scope
154
+ pack = apply_scope(pack, scope, lang=lang)
115
155
  if not isinstance(pack, dict) or 'criteria' not in pack:
116
156
  return {'error': t['error_no_pack']}
117
157
  overrides = overrides or {}
@@ -215,16 +255,19 @@ def main(argv):
215
255
  ap.add_argument('--notes', help='notes')
216
256
  ap.add_argument('--overrides', help='JSON: {"1.1.1": "does_not_support", …}')
217
257
  ap.add_argument('--reviewer', help='JSON: {"name":…, "credential":…, "review_date":…}')
258
+ ap.add_argument('--scope', help='a11y_scope output JSON: confirmed exclusions '
259
+ 'become Not Applicable (proposals never)')
218
260
  ap.add_argument('--lang', default='en', choices=['en', 'es'])
219
261
  ap.add_argument('-o', '--out')
220
262
  a = ap.parse_args(argv)
221
263
  pack = json.load(open(a.pack, encoding='utf-8')) if a.pack else None
222
264
  reports = [json.load(open(f, encoding='utf-8')) for f in a.reports] if a.reports else None
265
+ scope = json.load(open(a.scope, encoding='utf-8')) if a.scope else None
223
266
  res = generate_vpat(pack=pack, reports=reports, product=a.product, report_date=a.report_date,
224
267
  description=a.description, contact=a.contact, methods=a.methods,
225
268
  notes=a.notes, overrides=json.loads(a.overrides) if a.overrides else None,
226
269
  reviewer=json.loads(a.reviewer) if a.reviewer else None,
227
- lang=a.lang, output_path=a.out)
270
+ scope=scope, lang=a.lang, output_path=a.out)
228
271
  if 'error' in res:
229
272
  print(res['error'])
230
273
  return 1
@@ -22,6 +22,10 @@ from . import a11yi18n
22
22
  _RE_TIME = re.compile(
23
23
  r'(?:(\d{2,}):)?(\d{2}):(\d{2})[.,](\d{3})\s*-->\s*(?:(\d{2,}):)?(\d{2}):(\d{2})[.,](\d{3})')
24
24
 
25
+ # etiquetas de marcado WebVTT — <v>, <i>, <b>, <c.cls>, anclas/timestamps
26
+ # <00:00:01.000>: no se leen en voz alta, no cuentan como caracteres de lectura
27
+ _RE_TAG = re.compile(r'<[^>]+>')
28
+
25
29
  T = a11yi18n.pair('vtt') # locales/<lang>.json — community-editable
26
30
 
27
31
 
@@ -51,7 +55,8 @@ def vtt_check(url, duration=None, lang='en'):
51
55
  'signal': key, 'issue': _t(lang, key).format(**fmt),
52
56
  'remediation': _t(lang, key + '_rem').format(**fmt)})
53
57
 
54
- if not text.lstrip().startswith('WEBVTT'):
58
+ # un BOM UTF-8 (U+FEFF) delante de WEBVTT es válido — lstrip() no lo quita
59
+ if not text.removeprefix('\ufeff').lstrip().startswith('WEBVTT'):
55
60
  return {'error': 'does not declare WEBVTT (is it .srt or another format?)',
56
61
  'primeros_bytes': text[:40]}
57
62
 
@@ -87,9 +92,15 @@ def vtt_check(url, duration=None, lang='en'):
87
92
  if overlaps:
88
93
  add('low', 'vtt_overlap', n=overlaps)
89
94
 
90
- too_fast = [{'t': c['text'][:30], 'cps': round(len(c['text']) / max(c['end'] - c['start'], 0.1), 1)}
91
- for c in cues if not c['text'].startswith('<') and c['text']
92
- and len(c['text']) / max(c['end'] - c['start'], 0.1) > 21]
95
+ # cps sobre el texto VISIBLE: las etiquetas (<v>, <i>, <c.cls>, anclas)
96
+ # no se leen en voz alta — se miden TODAS las cues, incluidas las que
97
+ # empiezan con etiqueta de voz
98
+ too_fast = []
99
+ for c in cues:
100
+ visible = _RE_TAG.sub('', c['text']).strip()
101
+ dur = max(c['end'] - c['start'], 0.1)
102
+ if visible and len(visible) / dur > 21:
103
+ too_fast.append({'t': visible[:30], 'cps': round(len(visible) / dur, 1)})
93
104
  if too_fast:
94
105
  add('medium', 'vtt_too_fast', n=len(too_fast),
95
106
  example=', '.join(f"{r['t']}… ({r['cps']}cps)" for r in too_fast[:3]))
@@ -127,8 +138,13 @@ def main(argv):
127
138
  ap.add_argument('--duration', type=float, help='media duration in seconds (coverage check)')
128
139
  ap.add_argument('--lang', default='en', choices=['en', 'es'])
129
140
  a = ap.parse_args(argv)
130
- print(json.dumps(vtt_check(a.url, duration=a.duration, lang=a.lang),
131
- ensure_ascii=False, indent=1))
141
+ try:
142
+ res = vtt_check(a.url, duration=a.duration, lang=a.lang)
143
+ except ValueError as e: # _FetchError incluido (descarga/scheme/HTML-size)
144
+ print(json.dumps({'error': str(e)}, ensure_ascii=False))
145
+ return 1
146
+ print(json.dumps(res, ensure_ascii=False, indent=1))
147
+ return 0
132
148
  return 0
133
149
 
134
150