prunelle 0.1.1 → 0.7.2

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