prunelle 0.8.0 → 0.10.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 (209) hide show
  1. package/llms.txt +68 -51
  2. package/package.json +7 -2
  3. package/src/a11y/declaration.ts +10 -17
  4. package/src/a11y/index.ts +69 -125
  5. package/src/animate.ts +127 -0
  6. package/src/build/asides.ts +51 -0
  7. package/src/build/bundle.ts +94 -136
  8. package/src/build/client-entries.ts +6 -6
  9. package/src/build/client-outputs.ts +75 -0
  10. package/src/build/client-plugin.ts +9 -4
  11. package/src/build/ecoindex.ts +4 -2
  12. package/src/build/files.ts +18 -0
  13. package/src/build/graph.ts +14 -6
  14. package/src/build/index.ts +23 -11
  15. package/src/build/island-promote.ts +42 -2
  16. package/src/build/islands.ts +63 -9
  17. package/src/build/key-types.ts +31 -0
  18. package/src/build/manifest.ts +117 -1
  19. package/src/build/plugin-host.ts +13 -1
  20. package/src/build/prerender.ts +8 -3
  21. package/src/build/reach.ts +18 -4
  22. package/src/build/report.ts +1 -1
  23. package/src/build/resolve.ts +5 -1
  24. package/src/build/route-types.ts +16 -0
  25. package/src/build/routes.ts +42 -15
  26. package/src/build/seed-ids.ts +65 -0
  27. package/src/build/seed-writes.ts +111 -0
  28. package/src/build/static-headers.ts +2 -2
  29. package/src/build/static.ts +1 -1
  30. package/src/cli/check-cache.ts +51 -0
  31. package/src/cli/check-consent.ts +95 -0
  32. package/src/cli/check-forms.ts +10 -2
  33. package/src/cli/check-links-patterns.ts +101 -0
  34. package/src/cli/check-links.ts +30 -105
  35. package/src/cli/check-regions.ts +185 -0
  36. package/src/cli/check-security.ts +50 -6
  37. package/src/cli/check.ts +49 -21
  38. package/src/cli/commands.ts +138 -16
  39. package/src/cli/docs.ts +21 -2
  40. package/src/cli/form-opaque-children.ts +40 -0
  41. package/src/cli/index.ts +1 -1
  42. package/src/cli/inspect.ts +2 -0
  43. package/src/cli/mcp-tools.ts +2 -2
  44. package/src/cli/new.ts +9 -5
  45. package/src/cli/upgrade-names.ts +14 -2
  46. package/src/cli/upgrade.ts +3 -0
  47. package/src/compiler/analyze.ts +22 -16
  48. package/src/compiler/cacheability-private.ts +13 -3
  49. package/src/compiler/cacheability.ts +24 -2
  50. package/src/compiler/compliance-contrast.ts +322 -0
  51. package/src/compiler/compliance-empty.ts +24 -0
  52. package/src/compiler/compliance-rgaa-content.ts +95 -0
  53. package/src/compiler/compliance-rgaa-criteria.ts +45 -0
  54. package/src/compiler/compliance-rgaa-pages.ts +140 -0
  55. package/src/compiler/compliance-rgaa.ts +19 -0
  56. package/src/compiler/compliance-rules.ts +72 -0
  57. package/src/compiler/compliance-third-party.ts +59 -0
  58. package/src/compiler/compliance-urls.ts +52 -0
  59. package/src/compiler/compliance.ts +61 -93
  60. package/src/compiler/cookie-inventory.ts +119 -0
  61. package/src/compiler/dom-attrs.ts +178 -22
  62. package/src/compiler/dom.ts +31 -44
  63. package/src/compiler/emit.ts +17 -6
  64. package/src/compiler/expr-context.ts +260 -207
  65. package/src/compiler/foreign-imports.ts +5 -3
  66. package/src/compiler/mistakes.ts +18 -9
  67. package/src/compiler/props-body.ts +263 -21
  68. package/src/compiler/props-pattern.ts +211 -0
  69. package/src/compiler/props.ts +324 -343
  70. package/src/compiler/signal-reads.ts +142 -29
  71. package/src/compiler/spread-handlers.ts +25 -13
  72. package/src/compiler/ssr-emit.ts +510 -0
  73. package/src/compiler/ssr-helpers.ts +165 -121
  74. package/src/compiler/ssr.ts +28 -441
  75. package/src/context.ts +14 -1
  76. package/src/dev/child.ts +1 -1
  77. package/src/dev/host-check.ts +2 -1
  78. package/src/dev/hot-islands.ts +71 -0
  79. package/src/dev/index.ts +31 -18
  80. package/src/dev/protocol.ts +1 -1
  81. package/src/dev/queue.ts +3 -2
  82. package/src/dev/reload.ts +5 -2
  83. package/src/dev/supervisor.ts +3 -1
  84. package/src/dev/watchers.ts +6 -2
  85. package/src/dom/action.ts +97 -14
  86. package/src/dom/attrs.ts +93 -25
  87. package/src/dom/extras.ts +91 -50
  88. package/src/dom/field-marks.ts +32 -0
  89. package/src/dom/hot.ts +9 -0
  90. package/src/dom/index.ts +44 -18
  91. package/src/dom/island-hot.ts +29 -0
  92. package/src/dom/island.ts +13 -2
  93. package/src/dom/loop.ts +259 -188
  94. package/src/dom/prefetch.ts +135 -0
  95. package/src/dom/regions.ts +515 -0
  96. package/src/dom/swap.ts +246 -0
  97. package/src/dom/trusted.ts +22 -0
  98. package/src/dom/upload.ts +44 -0
  99. package/src/eco/declaration.ts +44 -41
  100. package/src/eco/index.ts +8 -5
  101. package/src/href.ts +31 -0
  102. package/src/index.ts +12 -5
  103. package/src/plugins/config.ts +1 -1
  104. package/src/plugins/context.ts +7 -1
  105. package/src/plugins/daily.ts +27 -0
  106. package/src/plugins/index.ts +3 -3
  107. package/src/plugins/order.ts +1 -1
  108. package/src/plugins/public.ts +12 -5
  109. package/src/plugins/services.ts +88 -14
  110. package/src/plugins/types.ts +128 -10
  111. package/src/reactivity/graph.ts +244 -41
  112. package/src/reactivity/hmr.ts +101 -0
  113. package/src/reactivity/index.ts +243 -239
  114. package/src/reactivity/resource.ts +129 -0
  115. package/src/reactivity/seed.ts +141 -0
  116. package/src/reactivity/selector.ts +85 -47
  117. package/src/reactivity/server-seed.ts +202 -0
  118. package/src/reactivity/store.ts +331 -97
  119. package/src/rgpd/draft.ts +171 -0
  120. package/src/rgpd/forms.ts +85 -0
  121. package/src/rgpd/index.ts +57 -0
  122. package/src/server/action-flash.ts +1 -0
  123. package/src/server/action-protect.ts +3 -0
  124. package/src/server/action-registry.ts +11 -9
  125. package/src/server/action.ts +51 -19
  126. package/src/server/app-secret.ts +14 -8
  127. package/src/server/cache-invalidation.ts +97 -0
  128. package/src/server/compress.ts +55 -18
  129. package/src/server/consent.ts +21 -5
  130. package/src/server/cookie-inventory.ts +78 -0
  131. package/src/server/cookies.ts +77 -8
  132. package/src/server/cors.ts +98 -0
  133. package/src/server/csp-report.ts +90 -0
  134. package/src/server/discard.ts +13 -0
  135. package/src/server/document.ts +2 -2
  136. package/src/server/env.ts +1 -1
  137. package/src/server/errors.ts +9 -2
  138. package/src/server/field-errors.ts +91 -0
  139. package/src/server/form-schema.ts +16 -11
  140. package/src/server/health.ts +41 -11
  141. package/src/server/http.ts +28 -11
  142. package/src/server/index.ts +122 -307
  143. package/src/server/loader.ts +2 -0
  144. package/src/server/page.ts +3 -9
  145. package/src/server/plugin-host.ts +66 -16
  146. package/src/server/plugin-route-shadow.ts +24 -0
  147. package/src/server/public.ts +14 -3
  148. package/src/server/rate-limit.ts +49 -10
  149. package/src/server/region.ts +22 -2
  150. package/src/server/request-handler.ts +406 -0
  151. package/src/server/request-log.ts +94 -0
  152. package/src/server/route-cache.ts +55 -8
  153. package/src/server/route-input.ts +54 -0
  154. package/src/server/route-table.ts +53 -27
  155. package/src/server/router.ts +2 -1
  156. package/src/server/routing.ts +104 -45
  157. package/src/server/sanitize-html.ts +4 -2
  158. package/src/server/security.ts +38 -8
  159. package/src/server/serve-handlers.ts +16 -6
  160. package/src/server/served-file.ts +19 -14
  161. package/src/server/shared-store.ts +323 -0
  162. package/src/server/start.ts +12 -5
  163. package/src/server/static-dir.ts +34 -12
  164. package/src/server/stream.ts +2 -1
  165. package/src/server/surface.ts +39 -0
  166. package/src/server/webhook.ts +50 -0
  167. package/src/server/workers.ts +168 -0
  168. package/src/ssr/consent-banner.ts +20 -16
  169. package/src/ssr/consent-texts.ts +40 -0
  170. package/src/ssr/context.ts +174 -53
  171. package/src/ssr/cookie-table.ts +75 -0
  172. package/src/ssr/index.ts +63 -58
  173. package/src/ssr/navigation.ts +161 -14
  174. package/src/ssr/region.ts +9 -3
  175. package/src/style.ts +12 -5
  176. package/src/test/browser.ts +53 -23
  177. package/src/test/build-reuse.ts +85 -0
  178. package/src/test/index.ts +51 -8
  179. package/src/test/mount.ts +53 -0
  180. package/src/test/outside.ts +94 -0
  181. package/src/ts-plugin/diagnostics.ts +56 -18
  182. package/templates/_shared/AGENTS.md +1 -1
  183. package/templates/_shared/Dockerfile +22 -0
  184. package/templates/_shared/dockerignore +9 -0
  185. package/templates/_shared/gitignore +2 -0
  186. package/templates/app/.env.example +3 -1
  187. package/templates/app/compose.yaml +32 -0
  188. package/templates/app/db/migrations/001_notes.sql +7 -0
  189. package/templates/app/db/schema.ts +11 -0
  190. package/templates/app/package.json +1 -0
  191. package/templates/app/prunelle.config.ts +6 -0
  192. package/templates/app/src/actions/notes.ts +26 -0
  193. package/templates/app/src/auth.ts +4 -2
  194. package/templates/app/src/db.ts +5 -0
  195. package/templates/app/src/routes/dashboard/index.tsx +26 -1
  196. package/templates/app/src/routes/privacy.tsx +6 -2
  197. package/templates/app/tests/app.test.ts +14 -3
  198. package/templates/plugin/AGENTS.md +11 -0
  199. package/templates/plugin/CLAUDE.md +1 -0
  200. package/templates/plugin/README.md +27 -0
  201. package/templates/plugin/gitignore +2 -0
  202. package/templates/plugin/llms.txt +19 -0
  203. package/templates/plugin/package.json +33 -0
  204. package/templates/plugin/src/index.ts +40 -0
  205. package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
  206. package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
  207. package/templates/plugin/tests/plugin.test.ts +42 -0
  208. package/templates/plugin/tsconfig.json +19 -0
  209. package/ts-plugin.cjs +4058 -2246
package/src/a11y/index.ts CHANGED
@@ -1,13 +1,13 @@
1
- // Built-in `a11y()` plugin, axe-core + Chromium route auditor, RGAA 4.1 reporting, and accessibility declaration drafter.
1
+ // Built-in `prunelle a11y` axe-core + Chromium route auditor, RGAA 4.1 reporting, and accessibility declaration drafter.
2
2
 
3
3
  import type { RouteManifestEntry } from '../build/manifest'
4
4
  import type { PrunellePlugin } from '../plugins/types'
5
5
  import type { BrowserTest, BrowserTestOptions } from '../test/browser'
6
+ import type { AccessibilityDeclarationResult, ManualAudit } from './declaration'
6
7
  import type { RgaaCriterion } from './rgaa-map'
7
8
  import { existsSync } from 'node:fs'
8
9
  import { resolve } from 'node:path'
9
10
  import { relPosix } from '../build/files'
10
- import { definePlugin } from '../plugins/config'
11
11
  import { loadConfig } from '../plugins/load'
12
12
  import { DEFAULT_DECLARATION_PATH, draftAccessibilityStatement } from './declaration'
13
13
  import { rgaaCriteriaForAxeRule } from './rgaa-map'
@@ -53,6 +53,8 @@ export interface A11yAuditReport {
53
53
  axeVersion?: string | undefined
54
54
  tags: string[]
55
55
  routes: A11yRouteReport[]
56
+ /** Routes of the build the audit did not open (dynamic routes with no prerendered URL, pages left out for want of `--all-static`, non-HTML responses): pass them with `--routes` to cover them. */
57
+ skipped: string[]
56
58
  totalViolations: number
57
59
  totalNodes: number
58
60
  ok: boolean
@@ -79,29 +81,9 @@ export interface A11yAuditOptions {
79
81
  plugins?: PrunellePlugin[] | undefined
80
82
  }
81
83
 
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
84
  export const DEFAULT_AXE_TAGS: readonly string[] = ['RGAAv4', 'wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa']
102
85
 
103
86
  const AXE_SPECIFIER = 'axe-core'
104
- const CLI_KIT_SPECIFIER = '@kaynooo/cli-kit'
105
87
 
106
88
  interface LoadedAxe {
107
89
  source: string
@@ -192,19 +174,25 @@ async function discoverRoutesToAudit(
192
174
  browser: BrowserTest,
193
175
  explicitRoutes: readonly string[] | undefined,
194
176
  includeAllStatic: boolean,
195
- ): Promise<string[]> {
177
+ ): Promise<{ routes: string[], skipped: string[] }> {
196
178
  if (explicitRoutes !== undefined && explicitRoutes.length > 0)
197
- return sortRoutes(explicitRoutes)
179
+ return { routes: sortRoutes(explicitRoutes), skipped: [] }
198
180
 
199
181
  const manifestRoutes = browser.app.manifest?.routes ?? []
200
182
  const prerendered = collectPrerenderedHtmlRoutes(manifestRoutes)
183
+ const covered = new Set(manifestRoutes.filter(r => collectPrerenderedHtmlRoutes([r]).length > 0).map(r => r.path))
201
184
  if (prerendered.length > 0 && !includeAllStatic)
202
- return prerendered
185
+ return { routes: prerendered, skipped: sortRoutes(manifestRoutes.map(r => r.path).filter(path => !covered.has(path))) }
203
186
 
204
187
  const discovered = new Set<string>(prerendered)
188
+ const skipped: string[] = []
205
189
  for (const route of manifestRoutes) {
206
- if (route.path.includes(':') || route.path.includes('*'))
190
+ if (covered.has(route.path))
207
191
  continue
192
+ if (route.path.includes(':') || route.path.includes('*')) {
193
+ skipped.push(route.path)
194
+ continue
195
+ }
208
196
  const normalized = normalizeRoutePath(route.path)
209
197
  if (discovered.has(normalized))
210
198
  continue
@@ -212,8 +200,10 @@ async function discoverRoutesToAudit(
212
200
  const contentType = (probe.headers.get('content-type') ?? '').toLowerCase()
213
201
  if (probe.status < 400 && contentType.includes('text/html'))
214
202
  discovered.add(normalized)
203
+ else
204
+ skipped.push(route.path)
215
205
  }
216
- return sortRoutes(discovered)
206
+ return { routes: sortRoutes(discovered), skipped: sortRoutes(skipped) }
217
207
  }
218
208
 
219
209
  function normalizeImpact(raw: string | null | undefined): A11yImpact {
@@ -298,7 +288,7 @@ export async function auditAccessibility(options: A11yAuditOptions): Promise<A11
298
288
  })
299
289
 
300
290
  try {
301
- const routes = await discoverRoutesToAudit(browser, options.routes, options.includeAllStatic === true)
291
+ const { routes, skipped } = await discoverRoutesToAudit(browser, options.routes, options.includeAllStatic === true)
302
292
  const results: A11yRouteReport[] = []
303
293
  for (const route of routes)
304
294
  results.push(await auditRoute(browser, route, axe.source, tags))
@@ -317,6 +307,7 @@ export async function auditAccessibility(options: A11yAuditOptions): Promise<A11
317
307
  axeVersion: axe.version,
318
308
  tags,
319
309
  routes: results,
310
+ skipped,
320
311
  totalViolations,
321
312
  totalNodes,
322
313
  ok: totalViolations === 0,
@@ -333,8 +324,11 @@ export function formatA11yReport(report: A11yAuditReport): string {
333
324
  const routeWord = report.routes.length === 1 ? 'route' : 'routes'
334
325
  lines.push(`prunelle a11y: audited ${report.routes.length} ${routeWord} (${report.tags.join(', ')})`)
335
326
 
327
+ const skippedLine = (): string => ` not audited: ${report.skipped.join(', ')} (pass them with --routes to audit them)`
336
328
  if (report.routes.length === 0) {
337
329
  lines.push(' No prerendered or static HTML routes were found to audit. Pass --routes /path to target specific routes.')
330
+ if (report.skipped.length > 0)
331
+ lines.push(skippedLine())
338
332
  return lines.join('\n')
339
333
  }
340
334
 
@@ -364,8 +358,19 @@ export function formatA11yReport(report: A11yAuditReport): string {
364
358
  lines.push(` to check by hand: ${v.id}${rgaaOf(v)}, ${elements(v.nodes.length)}`)
365
359
  details(v)
366
360
  }
361
+ for (const error of r.pageErrors)
362
+ lines.push(` page error: ${error}`)
367
363
  }
368
364
 
365
+ const toCheck = report.routes.reduce((sum, r) => sum + r.incomplete, 0)
366
+ if (toCheck > 0)
367
+ lines.push(` ${toCheck} ${toCheck === 1 ? 'check' : 'checks'} axe could not decide: to check by hand.`)
368
+ const pageErrors = report.routes.reduce((sum, r) => sum + r.pageErrors.length, 0)
369
+ if (pageErrors > 0)
370
+ lines.push(` ${pageErrors} JavaScript ${pageErrors === 1 ? 'error' : 'errors'} on the audited pages: a broken page may hide what axe would flag.`)
371
+ if (report.skipped.length > 0)
372
+ lines.push(skippedLine())
373
+
369
374
  if (report.ok) {
370
375
  lines.push(`✓ 0 accessibility violations across ${report.routes.length} ${routeWord}.`)
371
376
  }
@@ -376,109 +381,48 @@ export function formatA11yReport(report: A11yAuditReport): string {
376
381
  return lines.join('\n')
377
382
  }
378
383
 
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 rawRate = values.rate?.trim()
414
- const manualAudit = values['audit-date'] !== undefined && rawRate !== undefined
415
- ? { date: new Date(`${values['audit-date']}T00:00:00Z`), rate: rawRate === '' ? Number.NaN : Number(rawRate) }
416
- : undefined
417
- if (manualAudit !== undefined) {
418
- if (Number.isNaN(manualAudit.date.getTime()))
419
- return badUsage('--audit-date must be a valid YYYY-MM-DD date, e.g. --audit-date 2026-03-31')
420
- if (!(manualAudit.rate >= 0 && manualAudit.rate <= 100))
421
- return badUsage(`--rate must be a percentage from 0 to 100, got "${values.rate}"`)
422
- }
384
+ export interface RunA11yOptions {
385
+ root: string
386
+ routes?: readonly string[] | undefined
387
+ includeAllStatic?: boolean | undefined
388
+ draft?: string | undefined
389
+ force?: boolean | undefined
390
+ audit?: ManualAudit | undefined
391
+ organization?: string | undefined
392
+ contactEmail?: string | undefined
393
+ }
423
394
 
424
- const wantDraft = values.draft !== undefined
425
- const force = values.force === true
426
- const draftDest = values.out
427
- ?? (values.draft !== undefined && values.draft !== '' ? values.draft : undefined)
428
- ?? positionals[0]
429
- ?? pluginOptions.declarationPath
430
- ?? DEFAULT_DECLARATION_PATH
395
+ export interface RunA11yResult {
396
+ report: A11yAuditReport
397
+ drafted?: AccessibilityDeclarationResult | undefined
398
+ }
431
399
 
432
- if (wantDraft && !force) {
400
+ /** Runs `prunelle a11y`: audits rendered routes with axe-core + RGAA 4.1 and optionally drafts the accessibility declaration. */
401
+ export async function runA11y(options: RunA11yOptions): Promise<RunA11yResult> {
402
+ const root = resolve(options.root)
403
+ const wantDraft = options.draft !== undefined
404
+ const draftDest = options.draft !== undefined && options.draft !== '' ? options.draft : DEFAULT_DECLARATION_PATH
405
+ if (wantDraft && options.force !== true) {
433
406
  const dest = resolve(root, draftDest)
434
407
  if (existsSync(dest))
435
- throw new Exit(`${relPosix(root, dest)} already exists: pass --force to overwrite it`, 1)
408
+ throw new Error(`prunelle a11y: ${relPosix(root, dest)} already exists: pass --force to overwrite it`)
436
409
  }
437
-
438
410
  const report = await auditAccessibility({
439
411
  root,
440
- routes: rawRoutes,
441
- includeAllStatic: values['all-static'] === true || pluginOptions.includeAllStatic === true,
442
- tags: pluginOptions.tags,
443
- browserPath: pluginOptions.browserPath,
444
- timeout: pluginOptions.timeout,
445
- })
446
-
447
- let drafted: ReturnType<typeof draftAccessibilityStatement> | undefined
448
- if (wantDraft) {
449
- drafted = draftAccessibilityStatement({
450
- root,
451
- outPath: draftDest,
452
- report,
453
- organization: values.org ?? pluginOptions.organization,
454
- contactEmail: values.contact ?? pluginOptions.contactEmail,
455
- siteUrl: (await loadConfig(root)).site,
456
- audit: manualAudit,
457
- force,
458
- })
459
- }
460
-
461
- if (values.json === true) {
462
- console.log(JSON.stringify(drafted !== undefined ? { ...report, declaration: { path: drafted.relativePath, status: drafted.status } } : report, null, 2))
463
- if (!report.ok && !wantDraft && values['no-fail'] !== true)
464
- process.exitCode = 1
465
- return
466
- }
467
-
468
- console.log(formatA11yReport(report))
469
- if (drafted !== undefined)
470
- console.log(`prunelle a11y: drafted RGAA 4.1.2 accessibility declaration at ${drafted.relativePath} (${drafted.status})`)
471
-
472
- if (!report.ok && !wantDraft && values['no-fail'] !== true)
473
- throw new Exit(`found ${report.totalViolations} accessibility violation${report.totalViolations === 1 ? '' : 's'}`, 1)
474
- }
475
-
476
- /** Built-in accessibility plugin: registers `prunelle a11y` (axe-core Chromium audit + RGAA 4.1 mapping + declaration draft). */
477
- export function a11y(options: A11yPluginOptions = {}): PrunellePlugin {
478
- return definePlugin({
479
- name: 'prunelle:a11y',
480
- commands: {
481
- a11y: (args, root) => runA11yCommand(args, root, options),
482
- },
412
+ routes: options.routes,
413
+ includeAllStatic: options.includeAllStatic === true,
483
414
  })
415
+ const drafted = wantDraft
416
+ ? draftAccessibilityStatement({
417
+ root,
418
+ outPath: draftDest,
419
+ report,
420
+ organization: options.organization,
421
+ contactEmail: options.contactEmail,
422
+ siteUrl: (await loadConfig(root)).site,
423
+ audit: options.audit,
424
+ force: options.force === true,
425
+ })
426
+ : undefined
427
+ return { report, drafted }
484
428
  }
package/src/animate.ts ADDED
@@ -0,0 +1,127 @@
1
+ // `ref={animate()}`: an element fades (or slides, scales, collapses) in when an island adds it and out before the DOM drops it. The code stays in this module, so a page that never imports it pays 0 B; the first call patches `removeChild` once to hold a leaving element until its animation ends.
2
+
3
+ import { isHydrating, isMounting } from './dom/index'
4
+
5
+ export type AnimateEffect = 'fade' | 'slide' | 'scale' | 'collapse' | Keyframe[] | ((el: Element) => Keyframe[])
6
+ export interface AnimateOptions {
7
+ /** Milliseconds, 200 by default. */
8
+ duration?: number
9
+ /** A CSS timing function, `ease` by default. */
10
+ easing?: string
11
+ }
12
+
13
+ const PRESETS: Record<string, (el: Element) => Keyframe[]> = {
14
+ fade: () => [{ opacity: 0 }, { opacity: 1 }],
15
+ slide: () => [{ opacity: 0, transform: 'translateY(0.5rem)' }, { opacity: 1, transform: 'none' }],
16
+ scale: () => [{ opacity: 0, transform: 'scale(0.95)' }, { opacity: 1, transform: 'none' }],
17
+ collapse: el => [
18
+ { opacity: 0, height: '0px', marginBlock: '0px', paddingBlock: '0px', overflow: 'hidden' },
19
+ { opacity: 1, height: `${(el as HTMLElement).offsetHeight}px`, overflow: 'hidden' },
20
+ ],
21
+ }
22
+
23
+ interface Config { frames: (el: Element) => Keyframe[], timing: { duration: number, easing: string } }
24
+
25
+ const configs = new WeakMap<Node, Config>()
26
+ // The elements held by a leave animation, each with the call that lets it go now.
27
+ const leaving = new Map<Node, () => void>()
28
+ let patched = false
29
+
30
+ const reduced = (): boolean => typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches
31
+
32
+ // Starts the leave animation of `child` and drops it from `parent` when it ends. False when it must go at once.
33
+ function leave(parent: Node, child: Node, drop: (child: Node) => void): boolean {
34
+ const config = configs.get(child)
35
+ // A hidden tab pauses its animations, so a row removed there would be held for good.
36
+ if (config === undefined || child.parentNode !== parent || child.nodeType !== 1 || typeof (child as Element).animate !== 'function' || reduced() || document.hidden)
37
+ return false
38
+ if (leaving.has(child))
39
+ return true
40
+ const el = child as Element
41
+ el.setAttribute('inert', '')
42
+ const done = () => {
43
+ if (!leaving.delete(child))
44
+ return
45
+ clearTimeout(timer)
46
+ if (child.parentNode === parent)
47
+ drop(child)
48
+ else
49
+ el.removeAttribute('inert')
50
+ run.cancel()
51
+ }
52
+ const run = el.animate(config.frames(el), { ...config.timing, direction: 'reverse', fill: 'forwards' })
53
+ // Throttled timers still fire when the animation clock does not.
54
+ const timer = setTimeout(done, config.timing.duration + 100)
55
+ leaving.set(child, done)
56
+ run.onfinish = done
57
+ run.oncancel = done
58
+ return true
59
+ }
60
+
61
+ // A row or a panel that comes back while its previous element still leaves: the old one goes at once, so no id appears twice.
62
+ function dismissLeaving(el: Element): void {
63
+ for (const [old, done] of leaving) {
64
+ const same = el.id === '' ? (old as Element).id === '' && (old === el.previousSibling || old === el.nextSibling) : (old as Element).id === el.id
65
+ if (old.parentNode === el.parentNode && (old as Element).localName === el.localName && same)
66
+ done()
67
+ }
68
+ }
69
+
70
+ function patch(): void {
71
+ if (patched)
72
+ return
73
+ patched = true
74
+ const { removeChild } = Node.prototype
75
+ Node.prototype.removeChild = function <T extends Node>(this: Node, child: T): T {
76
+ if (!leave(this, child, c => removeChild.call(this, c)))
77
+ removeChild.call(this, child)
78
+ return child
79
+ }
80
+ // `parent.textContent = ''` is how a list clears itself, which would skip the animations of its rows.
81
+ const text = Object.getOwnPropertyDescriptor(Node.prototype, 'textContent')
82
+ if (text?.set === undefined)
83
+ return
84
+ const { set } = text
85
+ Object.defineProperty(Node.prototype, 'textContent', {
86
+ ...text,
87
+ set(this: Node, value: string | null) {
88
+ if ((value === '' || value === null) && this.nodeType === 1) {
89
+ for (let n = this.firstChild; n !== null; n = n.nextSibling) {
90
+ if (!configs.has(n))
91
+ continue
92
+ for (let child = this.firstChild, next: ChildNode | null; child !== null; child = next) {
93
+ next = child.nextSibling
94
+ this.removeChild(child)
95
+ }
96
+ return
97
+ }
98
+ }
99
+ set.call(this, value)
100
+ },
101
+ })
102
+ }
103
+
104
+ /**
105
+ * A ref callback: `<li key={t.id} ref={animate('slide')}>`. The element animates in when an island adds it after hydration and out when a conditional or a list row removes it; with `prefers-reduced-motion: reduce` it appears and goes at once. `effect` is a preset, the keyframes of the enter (the leave plays them backwards), or a function of the element returning them.
106
+ */
107
+ export function animate(effect: AnimateEffect = 'fade', options: AnimateOptions = {}): (el: Element) => void {
108
+ const frames = typeof effect === 'string' ? PRESETS[effect] : typeof effect === 'function' ? effect : () => effect
109
+ if (frames === undefined)
110
+ throw new TypeError(`prunelle: animate() got the unknown effect ${JSON.stringify(effect)}: use 'fade', 'slide', 'scale', 'collapse', keyframes or a function returning them.`)
111
+ const timing = { duration: options.duration ?? 200, easing: options.easing ?? 'ease' }
112
+ return (el) => {
113
+ patch()
114
+ configs.set(el, { frames, timing })
115
+ // What the page rendered, or an island's first mount, does not animate in.
116
+ if (isHydrating() || isMounting() || typeof el.animate !== 'function')
117
+ return
118
+ // The reconciler attaches the element right after its ref ran.
119
+ queueMicrotask(() => {
120
+ if (!el.isConnected)
121
+ return
122
+ dismissLeaving(el)
123
+ if (!reduced())
124
+ el.animate(frames(el), timing)
125
+ })
126
+ }
127
+ }
@@ -0,0 +1,51 @@
1
+ // Modules an island imports only when a page needs them, each built on its own so the importing chunk names it through a define: a literal `import('./x')` would make Bun add its preload helper, 400 B, to every chunk that has one.
2
+
3
+ import type { BundleEnv } from './bundle'
4
+ import { join } from 'node:path'
5
+ import { relPosix, runBunBuild } from './files'
6
+ import { PRUNELLE_SRC_ROOT } from './resolve'
7
+
8
+ const ASIDE_MODULES = {
9
+ /** The prop revivers, for an island whose props hold a Date, Map, Set or another tagged value. */
10
+ PRUNELLE_REVIVE: 'dom/revive.ts',
11
+ /** `useAction`'s field error marks, for a submit that failed with field errors. */
12
+ PRUNELLE_FIELD_MARKS: 'dom/field-marks.ts',
13
+ /** `useAction`'s XHR sender, for a submit holding a `File`, which reports upload progress. */
14
+ PRUNELLE_UPLOAD: 'dom/upload.ts',
15
+ }
16
+
17
+ export interface Asides {
18
+ reviveScript: string | undefined
19
+ /** Relative to the client dir. */
20
+ files: string[]
21
+ external: string[]
22
+ define: Record<string, string>
23
+ }
24
+
25
+ async function buildAside(env: BundleEnv, path: string): Promise<{ url: string, file: string }> {
26
+ const built = await runBunBuild('client', env.root, () => {}, {
27
+ entrypoints: [join(PRUNELLE_SRC_ROOT, path)],
28
+ outdir: env.clientDir,
29
+ target: 'browser',
30
+ format: 'esm',
31
+ minify: env.minify,
32
+ naming: '[name]-[hash].[ext]',
33
+ })
34
+ const file = relPosix(env.clientDir, built.outputs[0]!.path)
35
+ return { url: `${env.assetPrefix}/${file}`, file }
36
+ }
37
+
38
+ /** Builds them when the app has islands, with what the client build needs to leave them out of its chunks and name them. */
39
+ export async function buildAsides(env: BundleEnv, hasIslands: boolean): Promise<Asides> {
40
+ const asides: Asides = { reviveScript: undefined, files: [], external: [], define: {} }
41
+ if (!hasIslands)
42
+ return asides
43
+ const built = await Promise.all(Object.entries(ASIDE_MODULES).map(async ([name, path]) => ({ name, ...await buildAside(env, path) })))
44
+ for (const { name, url, file } of built) {
45
+ asides.files.push(file)
46
+ asides.external.push(url)
47
+ asides.define[name] = JSON.stringify(url)
48
+ }
49
+ asides.reviveScript = built.find(b => b.name === 'PRUNELLE_REVIVE')?.url
50
+ return asides
51
+ }