prunelle 0.1.1 → 0.7.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 (173) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +369 -0
  5. package/src/a11y/index.ts +466 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +88 -40
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +230 -0
  15. package/src/build/files.ts +6 -0
  16. package/src/build/first-load.ts +83 -11
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +218 -113
  19. package/src/build/island-promote.ts +229 -0
  20. package/src/build/islands.ts +11 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +2 -2
  23. package/src/build/plugin-host.ts +113 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +173 -38
  26. package/src/build/reach.ts +136 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +42 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +93 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +610 -0
  36. package/src/cli/check-imports.ts +25 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +107 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -18
  49. package/src/compiler/analyze.ts +68 -14
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability.ts +636 -0
  52. package/src/compiler/compliance-eco.ts +71 -0
  53. package/src/compiler/compliance-rgaa.ts +614 -0
  54. package/src/compiler/compliance-urls.ts +145 -0
  55. package/src/compiler/compliance.ts +355 -351
  56. package/src/compiler/data-keys.ts +199 -192
  57. package/src/compiler/dev-source.ts +87 -0
  58. package/src/compiler/dom-attrs.ts +138 -65
  59. package/src/compiler/dom.ts +517 -442
  60. package/src/compiler/expr-context.ts +167 -57
  61. package/src/compiler/foreign-imports.ts +88 -0
  62. package/src/compiler/mistakes.ts +23 -2
  63. package/src/compiler/props-body.ts +52 -0
  64. package/src/compiler/props.ts +87 -36
  65. package/src/compiler/scope.ts +400 -333
  66. package/src/compiler/server-only.ts +190 -151
  67. package/src/compiler/shared.ts +42 -14
  68. package/src/compiler/signal-reads.ts +6 -2
  69. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  70. package/src/compiler/ssr.ts +220 -89
  71. package/src/context.ts +34 -0
  72. package/src/dev/error-log.ts +177 -0
  73. package/src/dev/host-check.ts +26 -0
  74. package/src/dev/index.ts +91 -34
  75. package/src/dev/open-editor.ts +208 -0
  76. package/src/dev/protocol.ts +3 -0
  77. package/src/dev/reload.ts +5 -3
  78. package/src/dev/supervisor.ts +50 -25
  79. package/src/dev/watchers.ts +74 -13
  80. package/src/dom/action.ts +47 -21
  81. package/src/dom/attrs.ts +15 -3
  82. package/src/dom/extras.ts +29 -14
  83. package/src/dom/index.ts +39 -10
  84. package/src/dom/island.ts +54 -35
  85. package/src/dom/loop.ts +33 -23
  86. package/src/eco/declaration.ts +257 -0
  87. package/src/eco/index.ts +65 -0
  88. package/src/index.ts +2 -2
  89. package/src/jsx-runtime.ts +2 -2
  90. package/src/plugins/config.ts +8 -7
  91. package/src/plugins/context.ts +16 -1
  92. package/src/plugins/index.ts +2 -2
  93. package/src/plugins/load.ts +30 -10
  94. package/src/plugins/order.ts +38 -1
  95. package/src/plugins/public.ts +6 -3
  96. package/src/plugins/services.ts +84 -0
  97. package/src/plugins/types.ts +51 -2
  98. package/src/reactivity/graph.ts +10 -0
  99. package/src/reactivity/index.ts +24 -16
  100. package/src/reactivity/selector.ts +31 -4
  101. package/src/reactivity/store.ts +45 -13
  102. package/src/server/action-flash.ts +158 -0
  103. package/src/server/action-protect.ts +199 -0
  104. package/src/server/action-registry.ts +1 -1
  105. package/src/server/action.ts +56 -117
  106. package/src/server/app-secret.ts +63 -0
  107. package/src/server/assets.ts +34 -2
  108. package/src/server/compress.ts +96 -10
  109. package/src/server/consent.ts +59 -22
  110. package/src/server/cookies.ts +16 -2
  111. package/src/server/document.ts +25 -10
  112. package/src/server/env.ts +14 -0
  113. package/src/server/errors.ts +305 -65
  114. package/src/server/form-schema.ts +343 -0
  115. package/src/server/health.ts +275 -0
  116. package/src/server/http.ts +177 -38
  117. package/src/server/index.ts +264 -272
  118. package/src/server/loader.ts +11 -2
  119. package/src/server/param-matchers.ts +112 -0
  120. package/src/server/plugin-host.ts +125 -88
  121. package/src/server/public.ts +6 -5
  122. package/src/server/rate-limit.ts +102 -36
  123. package/src/server/request-body.ts +1 -1
  124. package/src/server/route-cache.ts +445 -0
  125. package/src/server/route-table.ts +344 -9
  126. package/src/server/router.ts +125 -40
  127. package/src/server/routing.ts +112 -63
  128. package/src/server/sanitize-html.ts +309 -0
  129. package/src/server/security.ts +277 -50
  130. package/src/server/serve-handlers.ts +31 -7
  131. package/src/server/start.ts +60 -16
  132. package/src/server/static-dir.ts +87 -11
  133. package/src/server/stream.ts +68 -27
  134. package/src/ssr/consent-banner.ts +58 -0
  135. package/src/ssr/context.ts +105 -7
  136. package/src/ssr/index.ts +148 -3
  137. package/src/ssr/navigation.ts +2 -2
  138. package/src/ssr/region.ts +31 -19
  139. package/src/style.ts +32 -1
  140. package/src/test/browser.ts +28 -13
  141. package/src/test/index.ts +97 -12
  142. package/src/ts-plugin/diagnostics.ts +505 -0
  143. package/src/ts-plugin/fixes.ts +364 -0
  144. package/src/ts-plugin/index.ts +194 -0
  145. package/templates/_shared/AGENTS.md +2 -2
  146. package/templates/_shared/gitignore +5 -0
  147. package/templates/_shared/mcp.json +11 -0
  148. package/templates/_shared/src/routes/legal.tsx +15 -1
  149. package/templates/_shared/tsconfig.json +5 -0
  150. package/templates/app/.env.example +4 -0
  151. package/templates/app/package.json +2 -1
  152. package/templates/app/prunelle.config.ts +2 -0
  153. package/templates/app/src/auth.ts +4 -6
  154. package/templates/app/src/mail.ts +4 -0
  155. package/templates/app/src/routes/_layout.tsx +9 -1
  156. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  157. package/templates/app/src/routes/login.tsx +49 -30
  158. package/templates/app/src/routes/privacy.tsx +25 -0
  159. package/templates/app/src/styles/app.css +8 -1
  160. package/templates/app/tests/app.test.ts +44 -3
  161. package/templates/blog/package.json +1 -1
  162. package/templates/blog/prunelle.config.ts +1 -1
  163. package/templates/blog/src/routes/_layout.tsx +6 -1
  164. package/templates/blog/src/routes/index.tsx +5 -1
  165. package/templates/blog/src/styles/app.css +6 -1
  166. package/templates/fullstack/package.json +1 -1
  167. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  168. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  169. package/templates/fullstack/src/styles/app.css +11 -1
  170. package/templates/minimal/package.json +1 -1
  171. package/templates/minimal/src/routes/_layout.tsx +4 -0
  172. package/templates/minimal/src/styles/app.css +11 -1
  173. package/ts-plugin.cjs +4277 -0
@@ -0,0 +1,466 @@
1
+ // Built-in `a11y()` plugin, axe-core + Chromium route auditor, RGAA 4.1 reporting, and accessibility declaration drafter.
2
+
3
+ import type { RouteManifestEntry } from '../build/manifest'
4
+ import type { PrunellePlugin } from '../plugins/types'
5
+ import type { BrowserTest, BrowserTestOptions } from '../test/browser'
6
+ import type { RgaaCriterion } from './rgaa-map'
7
+ import { resolve } from 'node:path'
8
+ import { definePlugin } from '../plugins/config'
9
+ import { loadConfig } from '../plugins/load'
10
+ import { DEFAULT_DECLARATION_PATH, draftAccessibilityStatement } from './declaration'
11
+ import { rgaaCriteriaForAxeRule } from './rgaa-map'
12
+
13
+ export { DEFAULT_DECLARATION_PATH, draftAccessibilityStatement, inferComplianceStatus } from './declaration'
14
+ export type { AccessibilityDeclarationOptions, AccessibilityDeclarationResult, ComplianceStatus, ManualAudit } from './declaration'
15
+ export { AXE_TO_RGAA, RGAA_CRITERIA, rgaaCriteriaForAxeRule } from './rgaa-map'
16
+ export type { RgaaCriterion } from './rgaa-map'
17
+
18
+ export type A11yImpact = 'minor' | 'moderate' | 'serious' | 'critical'
19
+
20
+ export interface A11yViolationNode {
21
+ target: string[]
22
+ html: string
23
+ failureSummary?: string | undefined
24
+ }
25
+
26
+ export interface A11yViolation {
27
+ id: string
28
+ impact: A11yImpact
29
+ description: string
30
+ help: string
31
+ helpUrl: string
32
+ tags: string[]
33
+ rgaa: RgaaCriterion[]
34
+ nodes: A11yViolationNode[]
35
+ }
36
+
37
+ export interface A11yRouteReport {
38
+ route: string
39
+ url: string
40
+ violations: A11yViolation[]
41
+ passes: number
42
+ incomplete: number
43
+ /** What axe could not decide (axe's `incomplete`), to check by hand: same shape as a violation. */
44
+ toCheck: A11yViolation[]
45
+ pageErrors: string[]
46
+ }
47
+
48
+ export interface A11yAuditReport {
49
+ root: string
50
+ auditedAt: string
51
+ axeVersion?: string | undefined
52
+ tags: string[]
53
+ routes: A11yRouteReport[]
54
+ totalViolations: number
55
+ totalNodes: number
56
+ ok: boolean
57
+ }
58
+
59
+ export interface A11yAuditOptions {
60
+ /** Application root directory. */
61
+ root: string
62
+ /** Explicit route paths to audit (overrides manifest discovery). */
63
+ routes?: readonly string[] | undefined
64
+ /** Include static non-dynamic HTML routes even when prerendered routes exist. */
65
+ includeAllStatic?: boolean | undefined
66
+ /** Axe tags to evaluate (default: `['RGAAv4', 'wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa']`, axe's RGAA rules plus WCAG 2.1 A and AA). */
67
+ tags?: readonly string[] | undefined
68
+ /** Chrome or Chromium executable path (forwarded to `testBrowser`). */
69
+ browserPath?: string | undefined
70
+ /** Per-page navigation/evaluation timeout in milliseconds (default: 10000). */
71
+ timeout?: number | undefined
72
+ /** Optional custom `routesDir` (forwarded to `testBrowser`). */
73
+ routesDir?: string | undefined
74
+ /** Optional custom `outDir` (forwarded to `testBrowser`). */
75
+ outDir?: string | undefined
76
+ /** Optional plugin override (forwarded to `testBrowser`). */
77
+ plugins?: PrunellePlugin[] | undefined
78
+ }
79
+
80
+ export interface A11yPluginOptions {
81
+ /** Default routes to audit when `--routes` is not given on the CLI. */
82
+ routes?: readonly string[] | undefined
83
+ /** Include static non-dynamic HTML routes alongside prerendered routes (default: `false`). */
84
+ includeAllStatic?: boolean | undefined
85
+ /** Axe tags to evaluate (default: `['RGAAv4', 'wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa']`, axe's RGAA rules plus WCAG 2.1 A and AA). */
86
+ tags?: readonly string[] | undefined
87
+ /** Default destination path for `prunelle a11y --draft` (default: `'src/routes/accessibilite.tsx'`). */
88
+ declarationPath?: string | undefined
89
+ /** Organization name pre-filled in `--draft` declarations. */
90
+ organization?: string | undefined
91
+ /** Contact email pre-filled in `--draft` declarations. */
92
+ contactEmail?: string | undefined
93
+ /** Chrome or Chromium executable path. */
94
+ browserPath?: string | undefined
95
+ /** Per-page timeout in milliseconds. */
96
+ timeout?: number | undefined
97
+ }
98
+
99
+ export const DEFAULT_AXE_TAGS: readonly string[] = ['RGAAv4', 'wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa']
100
+
101
+ const AXE_SPECIFIER = 'axe-core'
102
+ const CLI_KIT_SPECIFIER = '@kaynooo/cli-kit'
103
+
104
+ interface LoadedAxe {
105
+ source: string
106
+ version?: string | undefined
107
+ }
108
+
109
+ interface RawAxeNode {
110
+ target?: unknown[] | undefined
111
+ html?: string | undefined
112
+ failureSummary?: string | undefined
113
+ }
114
+
115
+ interface RawAxeViolation {
116
+ id: string
117
+ impact?: string | null | undefined
118
+ description: string
119
+ help: string
120
+ helpUrl: string
121
+ tags: string[]
122
+ nodes: RawAxeNode[]
123
+ }
124
+
125
+ interface RawAxeRunResult {
126
+ violations: RawAxeViolation[]
127
+ passes: number
128
+ incomplete: RawAxeViolation[]
129
+ }
130
+
131
+ interface TestBrowserModule {
132
+ testBrowser: (options: BrowserTestOptions) => Promise<BrowserTest>
133
+ }
134
+
135
+ // Keep axe-core and testBrowser dynamically resolved so neither axe-core nor playwright-core enters any client or server bundle.
136
+ async function loadAxe(): Promise<LoadedAxe> {
137
+ try {
138
+ const mod = await import(AXE_SPECIFIER) as { source?: unknown, version?: unknown, default?: { source?: unknown, version?: unknown } }
139
+ const source = typeof mod.source === 'string' ? mod.source : mod.default?.source
140
+ const version = typeof mod.version === 'string' ? mod.version : typeof mod.default?.version === 'string' ? mod.default.version : undefined
141
+ if (typeof source !== 'string' || source.length === 0)
142
+ throw new Error('axe-core did not expose a `source` script string')
143
+ return { source, version }
144
+ }
145
+ catch (error) {
146
+ if (error instanceof Error && error.message.startsWith('axe-core did not'))
147
+ throw new Error(`prunelle: ${error.message}.`, { cause: error })
148
+ throw new Error('prunelle: a11y audit needs axe-core, and it is not installed: run `bun add -d axe-core`.', { cause: error })
149
+ }
150
+ }
151
+
152
+ async function loadTestBrowser(): Promise<TestBrowserModule['testBrowser']> {
153
+ const url = new URL('../test/browser.ts', import.meta.url).href
154
+ const mod = await import(url) as TestBrowserModule
155
+ return mod.testBrowser
156
+ }
157
+
158
+ function normalizeRoutePath(raw: string): string {
159
+ const trimmed = raw.trim()
160
+ if (trimmed === '' || trimmed === '/')
161
+ return '/'
162
+ const withSlash = trimmed.startsWith('/') ? trimmed : `/${trimmed}`
163
+ return withSlash.length > 1 && withSlash.endsWith('/') ? withSlash.slice(0, -1) : withSlash
164
+ }
165
+
166
+ function sortRoutes(routes: Iterable<string>): string[] {
167
+ return [...new Set([...routes].map(normalizeRoutePath))].sort((a, b) => {
168
+ if (a === '/')
169
+ return -1
170
+ if (b === '/')
171
+ return 1
172
+ return a.localeCompare(b)
173
+ })
174
+ }
175
+
176
+ function collectPrerenderedHtmlRoutes(routes: readonly RouteManifestEntry[]): string[] {
177
+ const urls: string[] = []
178
+ for (const route of routes) {
179
+ if (route.prerendered === undefined)
180
+ continue
181
+ for (const [url, relFile] of Object.entries(route.prerendered)) {
182
+ if (relFile.endsWith('.html') || relFile.endsWith('.htm'))
183
+ urls.push(url)
184
+ }
185
+ }
186
+ return sortRoutes(urls)
187
+ }
188
+
189
+ async function discoverRoutesToAudit(
190
+ browser: BrowserTest,
191
+ explicitRoutes: readonly string[] | undefined,
192
+ includeAllStatic: boolean,
193
+ ): Promise<string[]> {
194
+ if (explicitRoutes !== undefined && explicitRoutes.length > 0)
195
+ return sortRoutes(explicitRoutes)
196
+
197
+ const manifestRoutes = browser.app.manifest?.routes ?? []
198
+ const prerendered = collectPrerenderedHtmlRoutes(manifestRoutes)
199
+ if (prerendered.length > 0 && !includeAllStatic)
200
+ return prerendered
201
+
202
+ const discovered = new Set<string>(prerendered)
203
+ for (const route of manifestRoutes) {
204
+ if (route.path.includes(':') || route.path.includes('*'))
205
+ continue
206
+ const normalized = normalizeRoutePath(route.path)
207
+ if (discovered.has(normalized))
208
+ continue
209
+ const probe = await browser.app.get(normalized)
210
+ const contentType = (probe.headers.get('content-type') ?? '').toLowerCase()
211
+ if (probe.status < 400 && contentType.includes('text/html'))
212
+ discovered.add(normalized)
213
+ }
214
+ return sortRoutes(discovered)
215
+ }
216
+
217
+ function normalizeImpact(raw: string | null | undefined): A11yImpact {
218
+ if (raw === 'minor' || raw === 'moderate' || raw === 'serious' || raw === 'critical')
219
+ return raw
220
+ return 'moderate'
221
+ }
222
+
223
+ function mapAxeViolations(rawViolations: readonly RawAxeViolation[]): A11yViolation[] {
224
+ return rawViolations.map(v => ({
225
+ id: v.id,
226
+ impact: normalizeImpact(v.impact),
227
+ description: v.description,
228
+ help: v.help,
229
+ helpUrl: v.helpUrl,
230
+ tags: Array.isArray(v.tags) ? v.tags.map(String) : [],
231
+ rgaa: rgaaCriteriaForAxeRule(v.id, Array.isArray(v.tags) ? v.tags : []),
232
+ nodes: (Array.isArray(v.nodes) ? v.nodes : []).map(n => ({
233
+ target: Array.isArray(n.target) ? n.target.map(String) : [],
234
+ html: typeof n.html === 'string' ? n.html : '',
235
+ failureSummary: typeof n.failureSummary === 'string' && n.failureSummary.length > 0 ? n.failureSummary : undefined,
236
+ })),
237
+ }))
238
+ }
239
+
240
+ async function auditRoute(browser: BrowserTest, route: string, axeSource: string, tags: readonly string[]): Promise<A11yRouteReport> {
241
+ const page = await browser.open(route)
242
+ try {
243
+ await page.evaluate(`${axeSource};\nvoid 0`)
244
+ const runExpr = `(() => {
245
+ if (!window.axe || typeof window.axe.run !== 'function')
246
+ throw new Error('axe-core failed to initialize in page');
247
+ const toPlain = (v) => ({
248
+ id: v.id,
249
+ impact: v.impact || 'moderate',
250
+ description: v.description,
251
+ help: v.help,
252
+ helpUrl: v.helpUrl,
253
+ tags: v.tags,
254
+ nodes: v.nodes.map((n) => ({
255
+ target: Array.isArray(n.target) ? n.target.map(String) : [],
256
+ html: n.html || '',
257
+ failureSummary: n.failureSummary || undefined,
258
+ })),
259
+ });
260
+ return window.axe.run(document, ${JSON.stringify({ runOnly: { type: 'tag', values: tags } })}).then((res) => ({
261
+ violations: res.violations.map(toPlain),
262
+ passes: res.passes.length,
263
+ incomplete: res.incomplete.map(toPlain),
264
+ }));
265
+ })()`
266
+ const raw = await page.evaluate<RawAxeRunResult>(runExpr)
267
+ return {
268
+ route,
269
+ url: page.url,
270
+ violations: mapAxeViolations(raw.violations),
271
+ passes: raw.passes,
272
+ incomplete: raw.incomplete.length,
273
+ toCheck: mapAxeViolations(raw.incomplete),
274
+ pageErrors: [...page.errors],
275
+ }
276
+ }
277
+ finally {
278
+ await page.close()
279
+ }
280
+ }
281
+
282
+ /** Builds the app, serves it in Chromium via `testBrowser`, and runs `axe-core` on every discovered route. */
283
+ export async function auditAccessibility(options: A11yAuditOptions): Promise<A11yAuditReport> {
284
+ const root = resolve(options.root)
285
+ const tags = options.tags !== undefined && options.tags.length > 0 ? [...options.tags] : [...DEFAULT_AXE_TAGS]
286
+ const axe = await loadAxe()
287
+ const runBrowser = await loadTestBrowser()
288
+
289
+ const browser = await runBrowser({
290
+ root,
291
+ routesDir: options.routesDir,
292
+ outDir: options.outDir,
293
+ plugins: options.plugins,
294
+ browserPath: options.browserPath,
295
+ timeout: options.timeout,
296
+ })
297
+
298
+ try {
299
+ const routes = await discoverRoutesToAudit(browser, options.routes, options.includeAllStatic === true)
300
+ const results: A11yRouteReport[] = []
301
+ for (const route of routes)
302
+ results.push(await auditRoute(browser, route, axe.source, tags))
303
+
304
+ let totalViolations = 0
305
+ let totalNodes = 0
306
+ for (const r of results) {
307
+ totalViolations += r.violations.length
308
+ for (const v of r.violations)
309
+ totalNodes += v.nodes.length
310
+ }
311
+
312
+ return {
313
+ root,
314
+ auditedAt: new Date().toISOString(),
315
+ axeVersion: axe.version,
316
+ tags,
317
+ routes: results,
318
+ totalViolations,
319
+ totalNodes,
320
+ ok: totalViolations === 0,
321
+ }
322
+ }
323
+ finally {
324
+ await browser.close()
325
+ }
326
+ }
327
+
328
+ /** Formats an `A11yAuditReport` into a human-readable CLI report grouped by route with RGAA 4.1 criteria. */
329
+ export function formatA11yReport(report: A11yAuditReport): string {
330
+ const lines: string[] = []
331
+ const routeWord = report.routes.length === 1 ? 'route' : 'routes'
332
+ lines.push(`prunelle a11y: audited ${report.routes.length} ${routeWord} (${report.tags.join(', ')})`)
333
+
334
+ if (report.routes.length === 0) {
335
+ lines.push(' No prerendered or static HTML routes were found to audit. Pass --routes /path to target specific routes.')
336
+ return lines.join('\n')
337
+ }
338
+
339
+ const rgaaOf = (v: A11yViolation): string => v.rgaa.length > 0 ? ` (RGAA ${v.rgaa.map(c => c.id).join(', ')})` : ''
340
+ const elements = (count: number): string => `${count} ${count === 1 ? 'element' : 'elements'}`
341
+ const details = (v: A11yViolation): void => {
342
+ lines.push(` ${v.help}`)
343
+ const firstSelector = v.nodes[0]?.target.join(' > ')
344
+ if (firstSelector)
345
+ lines.push(` Selector: ${firstSelector}`)
346
+ lines.push(` Help: ${v.helpUrl}`)
347
+ }
348
+ for (const r of report.routes) {
349
+ if (r.violations.length === 0) {
350
+ lines.push(` ✓ ${r.route} (0 violations, ${r.passes} passes)`)
351
+ }
352
+ else {
353
+ const routeNodes = r.violations.reduce((sum, v) => sum + v.nodes.length, 0)
354
+ lines.push(` ✗ ${r.route} (${r.violations.length} ${r.violations.length === 1 ? 'violation' : 'violations'}, ${elements(routeNodes)})`)
355
+ }
356
+ for (const v of r.violations) {
357
+ lines.push(` [${v.impact}] ${v.id}${rgaaOf(v)} — ${elements(v.nodes.length)}`)
358
+ details(v)
359
+ }
360
+ // axe's `incomplete`: it found the elements but cannot tell whether they pass.
361
+ for (const v of r.toCheck) {
362
+ lines.push(` to check by hand: ${v.id}${rgaaOf(v)}, ${elements(v.nodes.length)}`)
363
+ details(v)
364
+ }
365
+ }
366
+
367
+ if (report.ok) {
368
+ lines.push(`✓ 0 accessibility violations across ${report.routes.length} ${routeWord}.`)
369
+ }
370
+ else {
371
+ const failedRoutes = report.routes.filter(r => r.violations.length > 0).length
372
+ lines.push(`✗ ${report.totalViolations} violation${report.totalViolations === 1 ? '' : 's'} across ${report.totalNodes} element${report.totalNodes === 1 ? '' : 's'} on ${failedRoutes} ${failedRoutes === 1 ? 'route' : 'routes'}.`)
373
+ }
374
+ return lines.join('\n')
375
+ }
376
+
377
+ async function runA11yCommand(args: string[], root: string, pluginOptions: A11yPluginOptions): Promise<void> {
378
+ const { badUsage, Exit, parse } = await import(CLI_KIT_SPECIFIER) as typeof import('@kaynooo/cli-kit')
379
+ const { values, positionals } = parse(args, 'prunelle a11y [options]: audits rendered routes with axe-core + RGAA 4.1 and drafts an accessibility declaration', {
380
+ 'routes': { type: 'string', description: 'comma-separated routes to audit (e.g. /,/about)' },
381
+ 'all-static': { type: 'boolean', description: 'include static non-dynamic HTML routes alongside prerendered routes' },
382
+ 'json': { type: 'boolean', description: 'print the audit report as JSON on stdout' },
383
+ 'draft': { type: 'string', optional: { bare: '' }, description: 'write an editable RGAA 4.1.2 accessibility declaration page (default: src/routes/accessibilite.tsx)' },
384
+ 'out': { type: 'string', description: 'destination path for --draft (default: src/routes/accessibilite.tsx)' },
385
+ 'audit-date': { type: 'string', description: 'day the manual RGAA audit ended (YYYY-MM-DD), written into --draft with --rate' },
386
+ 'rate': { type: 'string', description: 'applicable RGAA criteria the manual audit found met, in percent: 100 is totally, 50 or more partially compliant' },
387
+ 'status': { type: 'string', description: 'removed: the level now follows --audit-date and --rate' },
388
+ 'org': { type: 'string', description: 'organization name written into --draft' },
389
+ 'contact': { type: 'string', description: 'contact email written into --draft' },
390
+ 'no-fail': { type: 'boolean', description: 'exit 0 even when accessibility violations are found' },
391
+ }, {
392
+ positionals: ['[dest]'],
393
+ exits: [
394
+ [0, 'no accessibility violations found (or --draft / --no-fail)'],
395
+ [1, 'one or more accessibility violations found, or audit failed'],
396
+ [2, 'a usage error'],
397
+ ],
398
+ })
399
+
400
+ const rawRoutes = values.routes !== undefined
401
+ ? values.routes.split(',').map(s => s.trim()).filter(Boolean)
402
+ : pluginOptions.routes
403
+ if (values.routes !== undefined && (rawRoutes === undefined || rawRoutes.length === 0))
404
+ return badUsage('--routes requires at least one route path, e.g. --routes /,/about')
405
+
406
+ if (values.status !== undefined)
407
+ return badUsage('--status is gone: the compliance level follows the manual audit, so pass --audit-date YYYY-MM-DD and --rate <percent> (100 is totally, 50 or more partially compliant)')
408
+ if ((values['audit-date'] === undefined) !== (values.rate === undefined))
409
+ return badUsage('--audit-date and --rate go together: pass the day the manual RGAA audit ended and the percentage of criteria it found met')
410
+ const manualAudit = values['audit-date'] !== undefined && values.rate !== undefined
411
+ ? { date: new Date(`${values['audit-date']}T00:00:00Z`), rate: Number(values.rate) }
412
+ : undefined
413
+
414
+ const wantDraft = values.draft !== undefined
415
+ const draftDest = values.out
416
+ ?? (values.draft !== undefined && values.draft !== '' ? values.draft : undefined)
417
+ ?? positionals[0]
418
+ ?? pluginOptions.declarationPath
419
+ ?? DEFAULT_DECLARATION_PATH
420
+
421
+ const report = await auditAccessibility({
422
+ root,
423
+ routes: rawRoutes,
424
+ includeAllStatic: values['all-static'] === true || pluginOptions.includeAllStatic === true,
425
+ tags: pluginOptions.tags,
426
+ browserPath: pluginOptions.browserPath,
427
+ timeout: pluginOptions.timeout,
428
+ })
429
+
430
+ let drafted: ReturnType<typeof draftAccessibilityStatement> | undefined
431
+ if (wantDraft) {
432
+ drafted = draftAccessibilityStatement({
433
+ root,
434
+ outPath: draftDest,
435
+ report,
436
+ organization: values.org ?? pluginOptions.organization,
437
+ contactEmail: values.contact ?? pluginOptions.contactEmail,
438
+ siteUrl: (await loadConfig(root)).site,
439
+ audit: manualAudit,
440
+ })
441
+ }
442
+
443
+ if (values.json === true) {
444
+ console.log(JSON.stringify(drafted !== undefined ? { ...report, declaration: { path: drafted.relativePath, status: drafted.status } } : report, null, 2))
445
+ if (!report.ok && !wantDraft && values['no-fail'] !== true)
446
+ process.exitCode = 1
447
+ return
448
+ }
449
+
450
+ console.log(formatA11yReport(report))
451
+ if (drafted !== undefined)
452
+ console.log(`prunelle a11y: drafted RGAA 4.1.2 accessibility declaration at ${drafted.relativePath} (${drafted.status})`)
453
+
454
+ if (!report.ok && !wantDraft && values['no-fail'] !== true)
455
+ throw new Exit(`found ${report.totalViolations} accessibility violation${report.totalViolations === 1 ? '' : 's'}`, 1)
456
+ }
457
+
458
+ /** Built-in accessibility plugin: registers `prunelle a11y` (axe-core Chromium audit + RGAA 4.1 mapping + declaration draft). */
459
+ export function a11y(options: A11yPluginOptions = {}): PrunellePlugin {
460
+ return definePlugin({
461
+ name: 'prunelle:a11y',
462
+ commands: {
463
+ a11y: (args, root) => runA11yCommand(args, root, options),
464
+ },
465
+ })
466
+ }