prunelle 0.1.1 → 0.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/llms.txt +23 -19
- package/package.json +8 -2
- package/src/a11y/declaration.ts +335 -0
- package/src/a11y/index.ts +446 -0
- package/src/a11y/rgaa-map.ts +184 -0
- package/src/attrs.ts +11 -3
- package/src/build/bundle.ts +80 -36
- package/src/build/client-entries.ts +3 -2
- package/src/build/client-plugin.ts +8 -4
- package/src/build/client-prune.ts +56 -6
- package/src/build/compile.ts +11 -9
- package/src/build/ecoindex.ts +229 -0
- package/src/build/index.ts +174 -108
- package/src/build/islands.ts +2 -2
- package/src/build/manifest.ts +66 -5
- package/src/build/output.ts +2 -2
- package/src/build/plugin-host.ts +91 -33
- package/src/build/precompress.ts +15 -2
- package/src/build/prerender.ts +128 -46
- package/src/build/report.ts +23 -2
- package/src/build/resolve.ts +8 -6
- package/src/build/routes.ts +175 -10
- package/src/build/static.ts +137 -39
- package/src/build/status-pages.ts +127 -0
- package/src/build/style-bundles.ts +526 -0
- package/src/cli/check-forms.ts +561 -0
- package/src/cli/check-links.ts +632 -0
- package/src/cli/check.ts +75 -20
- package/src/cli/commands.ts +85 -4
- package/src/cli/docs.ts +402 -0
- package/src/cli/inspect.ts +103 -14
- package/src/cli/mcp-tools.ts +490 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +2 -2
- package/src/cli/render.ts +421 -0
- package/src/cli/upgrade-names.ts +73 -13
- package/src/cli/upgrade.ts +137 -16
- package/src/compiler/analyze.ts +42 -9
- package/src/compiler/browser-globals.ts +140 -17
- package/src/compiler/cacheability.ts +636 -0
- package/src/compiler/compliance-rgaa.ts +508 -0
- package/src/compiler/compliance.ts +241 -289
- package/src/compiler/data-keys.ts +199 -192
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +138 -65
- package/src/compiler/dom.ts +517 -442
- package/src/compiler/expr-context.ts +167 -57
- package/src/compiler/mistakes.ts +4 -1
- package/src/compiler/props.ts +87 -36
- package/src/compiler/scope.ts +400 -333
- package/src/compiler/server-only.ts +190 -151
- package/src/compiler/shared.ts +40 -12
- package/src/compiler/signal-reads.ts +6 -2
- package/src/compiler/ssr-prunelle-tags.ts +27 -14
- package/src/compiler/ssr.ts +218 -87
- package/src/dev/error-log.ts +151 -0
- package/src/dev/index.ts +84 -34
- package/src/dev/open-editor.ts +204 -0
- package/src/dev/protocol.ts +1 -0
- package/src/dev/reload.ts +5 -3
- package/src/dev/supervisor.ts +42 -25
- package/src/dev/watchers.ts +47 -11
- package/src/dom/action.ts +43 -20
- package/src/dom/attrs.ts +15 -3
- package/src/dom/extras.ts +28 -12
- package/src/dom/index.ts +26 -8
- package/src/dom/island.ts +35 -28
- package/src/dom/loop.ts +10 -9
- package/src/plugins/config.ts +8 -7
- package/src/plugins/index.ts +2 -2
- package/src/plugins/load.ts +26 -7
- package/src/plugins/order.ts +38 -1
- package/src/plugins/public.ts +5 -2
- package/src/plugins/services.ts +62 -0
- package/src/plugins/types.ts +32 -0
- package/src/reactivity/graph.ts +10 -0
- package/src/reactivity/index.ts +24 -16
- package/src/reactivity/selector.ts +31 -4
- package/src/reactivity/store.ts +45 -13
- package/src/server/action-protect.ts +198 -0
- package/src/server/action-registry.ts +1 -1
- package/src/server/action.ts +82 -27
- package/src/server/assets.ts +34 -2
- package/src/server/compress.ts +91 -9
- package/src/server/document.ts +25 -10
- package/src/server/errors.ts +303 -65
- package/src/server/form-schema.ts +343 -0
- package/src/server/health.ts +244 -0
- package/src/server/http.ts +128 -31
- package/src/server/index.ts +230 -260
- package/src/server/loader.ts +5 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +123 -88
- package/src/server/public.ts +3 -3
- package/src/server/rate-limit.ts +58 -35
- package/src/server/request-body.ts +1 -1
- package/src/server/route-cache.ts +423 -0
- package/src/server/route-table.ts +339 -8
- package/src/server/router.ts +125 -40
- package/src/server/routing.ts +196 -63
- package/src/server/security.ts +208 -32
- package/src/server/serve-handlers.ts +21 -7
- package/src/server/start.ts +60 -16
- package/src/server/static-dir.ts +61 -8
- package/src/server/stream.ts +41 -22
- package/src/ssr/context.ts +85 -3
- package/src/ssr/index.ts +130 -3
- package/src/ssr/region.ts +31 -19
- package/src/test/browser.ts +28 -13
- package/src/test/index.ts +97 -12
- package/src/ts-plugin/diagnostics.ts +505 -0
- package/src/ts-plugin/fixes.ts +364 -0
- package/src/ts-plugin/index.ts +194 -0
- package/templates/_shared/AGENTS.md +2 -2
- package/templates/_shared/mcp.json +11 -0
- package/templates/_shared/src/routes/legal.tsx +5 -0
- package/templates/_shared/tsconfig.json +5 -0
- package/templates/blog/prunelle.config.ts +1 -1
- package/templates/blog/src/routes/index.tsx +4 -0
- package/ts-plugin.cjs +4277 -0
package/llms.txt
CHANGED
|
@@ -4,43 +4,47 @@
|
|
|
4
4
|
|
|
5
5
|
## Core Rules (everything fits on one page)
|
|
6
6
|
|
|
7
|
-
- **Imports**: `prunelle` (signals, `Head`, `Suspense`, `Catch`, `Region`, `ConsentGate`, `createContext`, `provideContext`, `useContext`, `useId`, `useAction`), `prunelle/server` (`action`, `getActionError`, `notFound`, `defineEnv`, `nodeEnv`, `raw`, `esc`, `escAttr`, `escJson` (JSON text for a `<script>`), `getClientIp`, `isHttpsRequest`, `isTrustedOrigin`, `verifyOrigin`, `safeRedirect`, `safeEqual` (constant-time secret compare), `wantsJson`, `readStringFields` (a body's string fields, on a null-prototype record), `createRateLimitStore({ maxKeys?, maxHits? })` (a standalone sliding-window store: `.limiter({ max, windowMs }).hit(key)` returns 0 or the seconds to wait; plugins use `api.rateLimiter()`), `validateSchema`, `validateSchemaSync`, `formatSchemaIssues`, `formatIssuePath`, route types, `createServer({ root })` to run a built app inside another program), `prunelle/config` (`defineConfig`, `definePlugin`, `serviceKey`, `isInside(dir, target, { orSame })`, plugin types), `prunelle/test` (`testApp`, `testBrowser`). An `@kayjs/*` import, prunelle's name when it was kay v2, fails the compile (`prunelle upgrade` rewrites them); `prunelle/internal/*` is compiler output, outside semver.
|
|
8
|
-
- **Standard TSX & compiler guardrails**: `.tsx` files with `jsxImportSource: "prunelle"`. Use `class` or `className` (never both). Standard `.map()` (with `key={...}`), `&&`, ternaries, `{...spread}`, SVG elements, style strings or objects (`style={{ color: 'red' }}`), and CSS / `*.module.css` imports work natively. Compiler/runtime refuse common React/Solid/Astro habits: `innerHTML={html}` takes a string or `raw(html)` (never `{ __html }`, never `dangerouslySetInnerHTML`, never on void elements or with children); events are camelCase DOM names (`onClick`, `onDblClick`, `onKeyDown` — never lowercase `onclick`, `on:click`, `onDoubleClick`, `*Capture`, string handlers, or render-time assignments); `ref` is always a callback `ref={el => ...}` (never `{ current }`); SVG attrs use kebab-case (`stroke-width`, `fill-opacity`); entities in string attrs and props decode like text (`title="a & b"` is `a & b`; an `innerHTML` string stays as written); use `value`/`checked` (not `defaultValue`/`defaultChecked`) and boolean `{false}` (not `"false"`); no `client:*`/`use:*`/`class:list`/`set:html` directives and no `'use client'`/`'use server'`; no Promises, functions, signals, or plain objects in JSX text/attrs.
|
|
7
|
+
- **Imports**: `prunelle` (signals, `Head`, `Suspense`, `Catch`, `Region`, `ConsentGate`, `createContext`, `provideContext`, `useContext`, `useId`, `useAction`), `prunelle/server` (`action`, `getActionError`, `notFound`, `defineEnv`, `nodeEnv`, `raw`, `esc`, `escAttr`, `escJson` (JSON text for a `<script>`), `DEFAULT_CSP`, `extendCsp`, `getClientIp`, `isHttpsRequest`, `isTrustedOrigin`, `verifyOrigin`, `safeRedirect`, `safeEqual` (constant-time secret compare), `wantsJson`, `readStringFields` (a body's string fields, on a null-prototype record), `createRateLimitStore({ maxKeys?, maxHits? })` (a standalone sliding-window store: `.limiter({ max, windowMs }).hit(key)` returns 0 or the seconds to wait; plugins use `api.rateLimiter()`), `validateSchema`, `validateSchemaSync`, `formatSchemaIssues`, `formatIssuePath`, route types, `PrunelleLocals` (`declare module 'prunelle/server' { interface PrunelleLocals { ... } }` to type `ctx.locals`), `createServer({ root })` to run a built app inside another program), `prunelle/config` (`defineConfig`, `definePlugin`, `serviceKey`, `I18N_CONFIG_SERVICE`, `CONTENT_IMAGE_RESOLVER_SERVICE`, `CONTENT_COLLECTIONS_SERVICE`, `JOBS_SERVICE`, `isInside(dir, target, { orSame })`, `firstLoadUrls`, `distLocator`, `measureFirstLoad`, `brotliSize`, `minifyCss`, `a11y`, `auditAccessibility`, `draftAccessibilityStatement`, `formatA11yReport`, `rgaaCriteriaForAxeRule`, plugin types), `prunelle/build` (programmatic `build`, `createBuildCache`, `analyzeBundleWeights`, `computeEcoIndex`), `prunelle/test` (`testApp`, `testBrowser`), `prunelle/ts-plugin` (TS language-service plugin). An `@kayjs/*` import, prunelle's name when it was kay v2, fails the compile (`prunelle upgrade` rewrites them); `prunelle/internal/*` is compiler output, outside semver.
|
|
8
|
+
- **Standard TSX & compiler guardrails**: `.tsx` files with `jsxImportSource: "prunelle"`. Use `class` or `className` (never both). Standard `.map()` (with `key={...}`), `&&`, ternaries, `{...spread}`, SVG elements, style strings or objects (`style={{ color: 'red' }}`), and CSS / `*.module.css` imports work natively. Compiler/runtime refuse common React/Solid/Astro habits: `innerHTML={html}` takes a string or `raw(html)` (never `{ __html }`, never `dangerouslySetInnerHTML`, never on void elements or with children); events are camelCase DOM names (`onClick`, `onDblClick`, `onKeyDown` — never lowercase `onclick`, `on:click`, `onDoubleClick`, `*Capture`, string handlers, or render-time assignments; `onChange` on text `<input>`/`<textarea>` fires on blur and warns to use `onInput` for every keystroke; `onFocus`/`onBlur` do not bubble — use `onFocusIn`/`onFocusOut`); `ref` is always a callback `ref={el => ...}` (never `{ current }`); SVG attrs use kebab-case (`stroke-width`, `fill-opacity`); entities in string attrs and props decode like text (`title="a & b"` is `a & b`; an `innerHTML` string stays as written); use `value`/`checked` (not `defaultValue`/`defaultChecked`) and boolean `{false}` (not `"false"`); no `client:*`/`use:*`/`class:list`/`set:html` directives and no `'use client'`/`'use server'`; no Promises, functions, signals, or plain objects in JSX text/attrs. Literal `javascript:`/`vbscript:`/non-image `data:` URLs warn and are stripped; spreads drop `on*`, `innerHTML`, `srcdoc`, and `javascript:`/`vbscript:` URLs.
|
|
9
9
|
- **Signals, Context & IDs (`prunelle`)**: `const count = signal(0)` (`.value` read/write, `.peek()` untracked), `computed(() => ...)`, `effect(() => ...)` (return cleanup, never `async`; skipped while an island renders on the server, so derive values with `computed`; a local signal read without `.value` in JSX, an `if`/ternary/loop test or `!`, and `const { value } = count`, fail compile), `batch(() => ...)`, `untrack(() => ...)`, `root(dispose => ...)`, `onMount(() => ...)` (runs after DOM attach; return cleanup), `onCleanup(() => ...)`, `getOwner()`, `selector(() => id.value)` (O(1) selection), `store(obj)` + `snapshot(s)`. Context: `const Ctx = createContext(defaultValue)`, `<Ctx.Provider value={v}>` or `provideContext(Ctx, v, fn)`, `useContext(Ctx)`. Deterministic hydration-safe IDs: `useId(prefix = 'k')` (scoped per island or SSR request). To let a child mutate parent state, pass the signal directly (`<Modal open={isOpen} />`).
|
|
10
10
|
- **Reactive props**: Destructuring props (`function Badge({ count = 0, ...rest }: Props)`) stays reactive in client components, and a default beyond a literal or a name (`items = []`, `id = useId()`) runs once per call; server-rendered children inside islands are preserved via `<pru-slot>`.
|
|
11
|
-
- **Automatic islands**: Any component using reactive primitives (`signal`, `computed`, `effect`, `onMount`, `store`, `selector`), DOM `on*` handlers/`ref`, or imported reactive module state becomes an island automatically, decided per component: a static export beside an island stays static, a component that needs the browser is an island of its own wherever server code renders it as a tag, same file included (the page around it stays static; its chunk keeps only the code of the file it reaches, so an async page importing server code can render a local widget; its props cross the island boundary), a same-file helper that needs the browser makes each component calling it an island, and a primitive called at a file's top level makes every component of it one. Control hydration per call site with `$hydrate="load" | "visible" | "idle" | "interaction" | "media(...)" | "client"`, or the component file's default `export const hydrate = 'visible'` (unknown modes and `$hydrate` on non-islands fail compile); the loader carries only the strategies the app's islands can use, and a page modulepreloads its eager islands with every chunk they
|
|
11
|
+
- **Automatic islands**: Any component using reactive primitives (`signal`, `computed`, `effect`, `onMount`, `store`, `selector`), DOM `on*` handlers/`ref`, or imported reactive module state becomes an island automatically, decided per component: a static export beside an island stays static, a component that needs the browser is an island of its own wherever server code renders it as a tag, same file included (the page around it stays static; its chunk keeps only the code of the file it reaches, so an async page importing server code can render a local widget; its props cross the island boundary), a same-file helper that needs the browser makes each component calling it an island, and a primitive called at a file's top level makes every component of it one. Control hydration per call site with `$hydrate="load" | "visible" | "idle" | "interaction" | "media(...)" | "client"`, or the component file's default `export const hydrate = 'visible'` (unknown modes and `$hydrate` on non-islands fail compile); the loader carries only the strategies the app's islands can use, and a page modulepreloads its eager islands with every chunk they import (a streamed page its route's eager islands only), and a page whose islands all hydrate later downloads the loader alone (about 1 KB gzip) until the first one does, each island bringing the DOM runtime. `<Head>`/`<Suspense>` in an island fail compile (`<Catch>` works in both); an island reading a context provided outside it throws in SSR (pass the value as a prop); server children handed to an island render before it, in the page's scope. Hydration steps over a node an extension injected and redraws a part whose tag differs from the server's and drops the server rows past a list's last row, in production too (dev also warns). Island props crossing the server boundary must be serializable (JSON primitives + `Date`, `Map`, `Set`, `URL`, `RegExp` — functions, signals and JSX in a prop other than `children` are refused; only a page whose props hold one of those classes loads, and preloads, the small file that revives them); an `on*` function passed from server code to a component that is not an island fails build and check too, since it would never run. A browser global (`window`, `document`, `localStorage`, ...) read while a component renders or its module loads warns, since the server has none: read it in `onMount()`, an effect or a handler, or behind `typeof window !== 'undefined'`. Islands cannot import server-only modules (`bun:sqlite`, `node:*`, `prunelle/server`) or read `process.env` other than `process.env.PUBLIC_*` (inlined at build time); action files are stubbed on the client (non-action exports from them cannot be imported by islands).
|
|
12
12
|
- **Routes (`src/routes/`)**:
|
|
13
13
|
- `export default async function Page({ params, locals, url })`: strictly server-only (`0 KB` JS; cannot use signals/handlers directly).
|
|
14
14
|
- Sync `export default function Page({ data, params, locals, url }: PageProps<typeof load>)`: static or auto-island; optional `export async function load(ctx)` runs server-only and returns data, `notFound()` (from `prunelle/server` — return or throw to render `_404.tsx` with HTTP `404`), or a `Response` (e.g. redirect).
|
|
15
|
-
- Special files: `_layout.tsx` (nested outer→inner, receives `{ children, params, locals, url }`, server-only), `_middleware.ts` (`(ctx, next) => Response`, outer→inner), `_error.tsx` (receives `{ error }`, server-only,
|
|
16
|
-
- Params: `[slug].tsx` → `params.slug`; `[...path].tsx` → `params.path` (segments joined by `/`). Params arrive percent-decoded; a segment holding an encoded `/`, `\` or NUL, or a `.`/`..` segment, matches no dynamic route (404), so a param is safe to join into a path; static pages, `public/` files and `prunelle start --static` decode by the same rule (`/a%2fb.txt` never serves `a/b.txt`).
|
|
17
|
-
- API routes: `.ts` files exporting `GET`, `POST`, `PUT`, `PATCH`, `DELETE` receiving `RequestContext` (`request`, `url`, `params`, `cookies`, `locals`, `ip`, `region`, `json()`, `text()`, `redirect()`, `deny()`). Optional `export const csrf = false` opts out of origin checks (e.g. webhooks/bearer APIs).
|
|
18
|
-
- Prerendering: `export const prerender = true` (+ `export function paths() { return ['/posts/a'] }` required for dynamic routes, and for every dynamic page under `--static`, or `prunelle build` fails; unlisted params return `404`). Skipped in `prunelle dev`.
|
|
15
|
+
- Special files: `_layout.tsx` (nested outer→inner, receives `{ children, params, locals, url }`, server-only), `_middleware.ts` (`(ctx, next) => Response`, outer→inner), `_error.tsx` (receives `{ error }`, server-only), `_404.tsx` (server-only; also emitted as `404.html` and `<folder>/404.html` for static non-group folders in `--static`), and status pages `_401.tsx`, `_403.tsx`, `_429.tsx`, `_503.tsx` (receive `{ status, message, url, params, locals }`). `_404.tsx`, `_error.tsx`, and status pages may live in any subfolder (including `(group)/`) and win over the root one for routes under that folder, wrapped in that folder's layouts. `ctx.deny(status, message, fieldErrors?)` renders the nearest status page (falling back to nearest `_error.tsx`, then clean HTML) when the request accepts HTML (`Accept: text/html`), and JSON otherwise (actions keep JSON for JS and flash + 303 for zero-JS forms). An unsupported `_NNN.tsx` (e.g. `_418.tsx`) fails `prunelle check` and `prunelle build`. Each special file needs a default export. Any other file under `src/routes/` must export a page, a method handler or an action (guarded by its folder's `_middleware.ts`), else `prunelle build`/`prunelle check` fail: prefix helpers or their folder with `_`.
|
|
16
|
+
- Params, groups, optionals & matchers: `(name)/` groups routes under its `_layout.tsx` and `_middleware.ts` without adding a URL segment; `[[lang]]/about.tsx` matches both `/about` and `/fr/about` (`params.lang` typed `string | undefined`); `[slug].tsx` → `params.slug`; `[...path].tsx` → `params.path` (segments joined by `/`); `[id=integer].tsx` and `[...path=slug].tsx` match only accepted values and fall through on mismatch (built-ins: `integer` → `` `${number}` ``, `uuid` → `` `${string}-${string}-${string}-${string}-${string}` ``, `slug` → `string`; custom matchers live in `src/params/<name>.ts` exporting `match` or `default`; unknown matchers or conflicting route patterns fail build and check naming both files; precedence: `static > matched param > param > optional > catch-all`). Params arrive percent-decoded; a segment holding an encoded `/`, `\` or NUL, or a `.`/`..` segment, matches no dynamic route (404), unless a plugin catch-all route sets `encodedSlashes`, so a param is safe to join into a path; static pages, `public/` files and `prunelle start --static` decode by the same rule (`/a%2fb.txt` never serves `a/b.txt`).
|
|
17
|
+
- API routes: `.ts` files exporting standard `HTTP_METHOD_EXPORTS` (`GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS`) receiving `RequestContext` (`request`, `url`, `params`, `cookies`, `locals`, `ip`, `requestId`, `region`, `json()`, `text()`, `redirect()`, `deny()`). CSRF checks run on every method outside the safe allowlist (`GET`, `HEAD`, `OPTIONS`), trusting only the forwarded origin when `trustProxy` resolves one (or `trustedOrigins`). Optional `export const csrf = false` opts out of origin checks (e.g. webhooks/bearer APIs).
|
|
18
|
+
- Prerendering & Route caching: `export const prerender = true` (+ `export function paths() { return ['/posts/a'] }` required for dynamic routes, and for every dynamic page under `--static`, or `prunelle build` fails; unlisted params return `404`). Skipped in `prunelle dev`. `export const cache = '1h'` (or `{ maxAge: '1h', staleWhileRevalidate?: '1d' }`) serves a bounded in-memory LRU render (configurable via `routeCache: { maxEntries?, maxBytes? } | false`), re-renders in the background once stale, and sends `cache-control: public, s-maxage=..., stale-while-revalidate=...`; a cached route (or its layout `load()` or imported local modules) reading `ctx.cookies`, `ctx.locals`, `ctx.consent`, `ctx.ip`, `Cookie`/`Authorization` headers, `getActionError()`, or `<ConsentGate>` fails `prunelle check` and `prunelle build` naming the read. Static pages that read nothing from the request or clock are reported as `cacheable` by `prunelle inspect` and prerender automatically with `autoPrerender: true` in `prunelle.config.ts` or `prunelle build --auto-prerender`.
|
|
19
19
|
- **Streaming & Head**: `<Head><title>...</title></Head>` (innermost `<title>` wins); `<Suspense fallback={<p>Loading</p>} error={<p>Failed</p>}><AsyncComp /></Suspense>` streams resolved HTML inline with 0 KB external JS (takes exactly one child; an async component anywhere but as the only child of `<Suspense>` fails build and check, even inside an async page; nested boundaries supported; times out after `streamTimeout`, default `30000` ms; errors also fire `onError`). `<Catch fallback={<p>Failed</p> | (error, retry) => ...}>` renders its fallback in place of children that throw or an awaited child that rejects, on the server (firing `onError`; nothing streams) and in an island, where it also catches a child effect's later throw and `retry()` renders the children again (there it is written as a tag: calling `Catch()` as a function throws); errors thrown by event handlers are not caught.
|
|
20
20
|
- **Regions** (`@prunellejs/spa`, `regions()`): `<Region name="pane" as="section" ...attrs>children</Region>` (from `prunelle`, server-only like `Head`) renders `<div data-pru-region="pane">`; its children are read only when the page or the requested region needs them. `<a href data-pru-target="pane">` swaps that region in place: the browser sends `x-pru-region: pane`, the server answers with the region's inner HTML alone (no layouts, no document; `ctx.region` tells `load()` which, `vary: x-pru-region`), history is pushed and back/forward re-fetch it, focus moves to the region, its `aria-label` is announced, `aria-busy="true"` is set after 150 ms and cleared on swap or failure. Add `data-pru-append` and the response is appended and the clicked link removed (Load more; the history entry is replaced, not pushed). `<form method="get" data-pru-target="results">` swaps on submit; with `data-pru-live` also on input (debounced 200 ms; one history entry per typing burst, a 1 s pause ends it). `data-pru-sync="q icon"` on a link, or on an input/select (its `name`), copies those params of the current URL after every swap so links outside the region stay in step. A link inside `[data-pru-prefetch]` prefetches its region on hover/focus through the cache `spa()` shares. A region may sit inside another (give each its own name): asking for the inner one renders it alone (header `x-pru-region: results/sets`, the path outermost first, which the client computes), asking for the outer renders it with a fresh inner, and an outer swap drops in-flight fetches of the regions inside it. Every region swap also sets `document.title` from the page's `<Head><title>` at that URL (title template applied; the server sends it in `x-pru-title`), and back/forward restore it. `await refreshRegion(name)` from `@prunellejs/spa/regions` redraws a region of the current address from script (after a background `fetch` to an action): no history entry, focus left alone, prefetch cache skipped, `pru:region` fired; it rejects when the page has no such region, the fetch fails or the answer lacks it. `<form method="post" data-pru-target="x">` posts through fetch, follows the redirect and swaps region x (without JS it posts normally); empty fields are dropped from a GET form's URL. A swap runs in a view transition where supported and not under reduced motion; each history entry remembers the window's and the regions' scroll, a pushed swap resets the region's own scroll unless it has `data-pru-keep-scroll="<key>"`; links to the new URL get `aria-current="page"`; a `#hash` link to an element on the page scrolls with no fetch when its page and query are the ones shown or appended by Load more. The regions client ships only on routes whose tree renders a `<Region>`. Without JS, or when a fetch fails or the response lacks the region, the link loads the whole page. Mistakes: `<Region>` without `name`, `data-pru-target` off `<a>`/`<form>`, `data-pru-live` on a non-GET form, `data-pru-append`/`data-pru-live` without their target, a region inside a region of the same name (compile errors); a target naming no `<Region>` in `src/` (`prunelle check`); two regions of one name, a requested region the route does not render (runtime throws).
|
|
21
|
-
- **Actions (`prunelle/server` & `useAction` from `prunelle`)**: `export const fn = action(standardSchema, async (input, ctx) => ..., options?)` or `action(async (ctx) => ...)` — must be a top-level named export so Prunelle can assign a URL. Works as zero-JS `<form action={fn} method="post">` (array fields auto-coerced from checkboxes/multi-selects; validation failures set an `HttpOnly` flash cookie readable via `getActionError(ctx.locals)` with sensitive fields stripped or `flashFields` allowlisted and `303` redirect to trusted Referer; `
|
|
22
|
-
- **Config, Security & Server Helpers (`prunelle.config.ts`, `prunelle/config`, `prunelle/server`)**: `defineConfig({ lang, port, routesDir, outDir, publicDir, assetPrefix, security, trustedOrigins, trustProxy, maxRequestBodySize, streamTimeout, consent, compliance, compress, onError, plugins })`. Default security headers (`security: false` to disable, or override `csp`, `hsts`, `frameOptions`, `referrerPolicy`, `contentTypeOptions`) attach strict `DEFAULT_CSP` (style attributes allowed) with automatic SHA-256 hashes for island/Suspense styles, the app's own `<style>` blocks and stream scripts, plus `HSTS` on HTTPS requests. `trustProxy: true | number` trusts that many right-most proxy hops for `X-Forwarded-*`. `maxRequestBodySize` defaults to `1 MiB`. `prunelle/server` also exports `defineEnv(standardSchema)` (validates env vars at startup), `nodeEnv()` (safe in `--compile`; server code reads it, never `process.env.NODE_ENV`, which `prunelle build` leaves unset for a prerendered page, and build and `prunelle check` warn on such a read outside island code), HTML escaping (`raw`, `esc`, `escAttr`), HTTP security helpers (`getClientIp`, `isHttpsRequest`, `isTrustedOrigin`, `verifyOrigin`, and `safeRedirect(target, fallback = '/')`, which returns the trimmed target only when it is a path on this site, refusing absolute and protocol-relative URLs, backslashes and control characters, and which `@prunellejs/auth` and the consent endpoint use), and Standard Schema helpers (`validateSchema`, `validateSchemaSync`, `formatSchemaIssues`, `formatIssuePath`).
|
|
23
|
-
- **French web law & Consent (RGPD, CNIL, RGAA, LCEN — 0 B client JS)**: `prunelle check` and production `prunelle build` emit actionable warnings (never hard errors): `rgaa/img-alt` (`<img>` without `alt`), `rgaa/form-label` (unlabelled `<input>`/`<select>`/`<textarea>`), `rgaa/accessible-name` (empty or icon-only `<button>`/`<a>`), `rgpd/third-party-url` (third-party `<script src>`, `<link rel="stylesheet|preload|preconnect|dns-prefetch">`, `<iframe src>`, and CSS `@import`/`url(...)` outside `<ConsentGate>` or `site`), `lcen/legal-notice` (page app missing `/mentions-legales
|
|
21
|
+
- **Actions (`prunelle/server` & `useAction` from `prunelle`)**: `export const fn = action(standardSchema, async (input, ctx) => ..., options?)` or `action(async (ctx) => ...)` — must be a top-level named export so Prunelle can assign a URL. Works as zero-JS `<form action={fn} method="post">` (array fields auto-coerced from checkboxes/multi-selects; SSR automatically adds `required`, `minlength`/`maxlength`, `min`/`max`/`step`, `pattern`, and `type="email"|"url"|"number"` to `<input>`/`<select>`/`<textarea>` from the action's Standard Schema JSON Schema unless the app wrote that attribute — 0 B client JS, no implicit `<option>` tags; validation failures set an `HttpOnly` flash cookie readable via `getActionError(ctx.locals)` with sensitive fields stripped or `flashFields` allowlisted and `303` redirect to trusted Referer; `protect: { rateLimit?: { max, windowMs, key? }, honeypot?: boolean | string, minTime?: number }` — or top-level `rateLimit` — enforces `rateLimit` (`429` + `Retry-After` / flash+303) before body parsing, honeypot/`minTime`, and schema validation, renders a hidden honeypot and action-URL-bound HMAC-signed `_pru_ts` timestamp into `<form action={fn}>` automatically (set `PRUNELLE_FORM_SECRET` or `AUTH_SECRET` in production when using `minTime`, else Prunelle logs a one-time production warning), and refuses bots/fast submits with `400` before the handler runs; `prunelle check` and `prunelle build` report unknown form fields with closest name, missing required fields, invalid `<select>` enum options, unsupported schema libraries once per vendor, and unguarded public form actions without `protect`) and as typed island RPC `const res = await fn(data)` (always resolves to `{ ok: true, data }` or `{ ok: false, status, error, fieldErrors?, issues? }`; accepts `FormData` for files; redirects navigate the page). In islands, `const form = useAction(fn, { reset?, onSuccess?, onError? })` returns `{ pending, error, fieldErrors, data, action, onSubmit, submit, reset }` (`pending`/`error`/`fieldErrors`/`data` are `ReadonlySignal`s; wire `<form action={form.action} method="post" onSubmit={form.onSubmit}>` for progressive enhancement, inheriting SSR protection fields and HTML5 constraints). A route, `load()`, middleware or another action may also call it: it runs in that request, schema and folder `_middleware.ts` included, and resolves to the same result; called outside a request it throws. Server code is stripped from client bundles; CSRF `Origin`/`Sec-Fetch-Site` is checked before middleware and body parsing; folder `_middleware.ts` runs before the handler. `ctx` provides `redirect()` and `deny(status, message, fieldErrors?)`.
|
|
22
|
+
- **Config, Security & Server Helpers (`prunelle.config.ts`, `prunelle/config`, `prunelle/server`)**: `defineConfig({ site, lang, port, routesDir, outDir, publicDir, assetPrefix, security, trustedOrigins, trustProxy, maxRequestBodySize, navigation, routeCache, autoPrerender, streamTimeout, consent, compliance, compress, healthCheck, onError, plugins })`. Default security headers (`security: false` to disable, or override `csp`, `hsts`, `frameOptions`, `referrerPolicy`, `contentTypeOptions`) attach strict `DEFAULT_CSP` (style attributes allowed) with automatic SHA-256 hashes for island/Suspense styles, the app's own `<style>` blocks and stream scripts, plus `HSTS` on HTTPS requests; pass `security: { csp: { 'style-src': [...], 'font-src': [...] } }` (or `extendCsp()` / `DEFAULT_CSP` from `prunelle/server`) to add sources to individual directives without copying the whole policy (new `*-src` directives inherit `default-src`, and automatic hashes still land in the extended directives). A `--static` export embeds each page's and `404.html`'s hashed CSP in `<meta http-equiv="Content-Security-Policy">` with `frame-ancestors`, `report-uri` and `sandbox` stripped (browsers ignore them in `<meta>`); configure the static host to send `Content-Security-Policy: frame-ancestors 'self'` and response headers (`X-Content-Type-Options`, `Referrer-Policy`, `HSTS`). Observability: `/_pru/health` (at `${assetPrefix}/health`) answers `200 { ok: true }` (`503` when an app `healthCheck` or plugin `api.healthCheck(name, fn)` fails; `./app --health` probes it for container `HEALTHCHECK`), every request gets `ctx.requestId` (honoring safe incoming `x-request-id` when `trustProxy` is truthy), returned in `x-request-id` and passed to `onError` (`info.requestId`), and `prunelle dev` sends `Server-Timing` (`middleware`, `load`, `render`, `stream`; zero overhead in production). `trustProxy: true | number` trusts that many right-most proxy hops for `X-Forwarded-*`. `maxRequestBodySize` defaults to `1 MiB`. `prunelle/server` also exports `defineEnv(standardSchema)` (validates env vars at startup), `nodeEnv()` (safe in `--compile`; server code reads it, never `process.env.NODE_ENV`, which `prunelle build` leaves unset for a prerendered page, and build and `prunelle check` warn on such a read outside island code), HTML escaping (`raw`, `esc`, `escAttr`), HTTP security helpers (`getClientIp`, `isHttpsRequest`, `isTrustedOrigin`, `verifyOrigin`, and `safeRedirect(target, fallback = '/')`, which returns the trimmed target only when it is a path on this site, refusing absolute and protocol-relative URLs, backslashes and control characters, and which `@prunellejs/auth` and the consent endpoint use), and Standard Schema helpers (`validateSchema`, `validateSchemaSync`, `formatSchemaIssues`, `formatIssuePath`).
|
|
23
|
+
- **French web law & Consent (RGPD, CNIL, RGAA, LCEN — 0 B client JS)**: `prunelle check` and production `prunelle build` emit actionable warnings (never hard errors): `rgaa/img-alt` (`<img>` without `alt`, or `alt={undefined}`/`alt={false}`), `rgaa/form-label` (unlabelled `<input>`/`<select>`/`<textarea>`), `rgaa/accessible-name` (empty or icon-only `<button>`/`<a>`), `rgaa/duplicate-id` (duplicate literal `id` in one component or static `id` inside `.map()`), `rgaa/positive-tabindex` (`tabindex > 0`), `rgaa/nested-control` (interactive element inside `<a>`/`<button>`/`<summary>`), `rgaa/link-as-button` (`<a>` without `href` with `onClick`), `rgaa/unknown-role`, `rgaa/unknown-aria`, `rgaa/invalid-aria-value`, `rgaa/skipped-heading` (downward heading jump > 1 in one component), `rgaa/table-without-header` (`<table>` without `<th>`), `rgaa/fieldset-without-legend`, `rgaa/click-without-key` (`onClick` on non-interactive element without key handler), `rgaa/autofocus`, `rgaa/meta-refresh`, `rgpd/third-party-url` (third-party `<script src>`, `<link rel="stylesheet|preload|preconnect|dns-prefetch|modulepreload|icon">`, `<iframe src>`, `<img src/srcset>`, `<video>`, `<audio>`, `<source>`, `<object data>`, `<embed>`, and CSS `@import`/`url(...)` outside `<ConsentGate>` or `site`), `lcen/legal-notice` (page app missing `/mentions-legales`, `/legal`, or localized variants like `/fr/mentions-legales` / `/[lang]/mentions-legales`), and `rgaa/accessibility-statement` (when `compliance: { publicBody: true }`, missing `/accessibilite`). Silence explicitly per rule via `compliance: { ignore: [...], legalNotice?: string | false, publicBody?: boolean }` in `prunelle.config.ts`, or `// prunelle-ignore <rule>` / `/* prunelle-ignore <rule> */` / `// prunelle-ignore-file <rule>`. One-declaration consent: configure `consent: { categories: ['analytics', 'media'], cookieName?: 'pru_consent', maxAge?: 15552000, endpoint?: '/_pru/consent' }` in `prunelle.config.ts` — Prunelle wires a CSRF-protected `POST /_pru/consent` endpoint (works with zero-JS HTML `<form method="post" action="/_pru/consent">` via `action="accept-all"|"reject-all"` or category checkboxes -> `303`, and JSON -> `200`), exposes `ctx.consent` (`decided`, `categories`, `has(cat)`, `all()`), refuses `ctx.cookies.set(name, val, { category })` before consent is granted, and exports server-only `<ConsentGate category="media" fallback={...}>` (0 KB browser JS, refused inside islands).
|
|
24
24
|
- **Page changes (plain multi-page navigation, 0 B of JS)**: every page carries inline, CSP-hashed `@view-transition { navigation: auto }` (inside `@media (prefers-reduced-motion: no-preference)`) and a `<script type="speculationrules">` prefetching same-origin links on hover (`eagerness: moderate`); never links to another origin, `/_pru/*` (actions included), `[download]`, `[rel~=nofollow]`, nor a link or ancestor with `data-pru-no-prefetch`. Name an element that stays still with CSS `view-transition-name`. `defineConfig({ navigation: { viewTransitions?: boolean (true), prefetch?: 'conservative' | 'moderate' | 'eager' | false ('moderate'), prerender?: 'conservative' | 'moderate' | 'eager' | boolean (false; true is 'moderate'; it runs `load()` of pages nobody opens) } })`; a bad value throws `prunelle: navigation.<key> is ...`. `data-pru-keep-scroll="<key>"` on a scrolling element keeps its `scrollTop` across page loads (restored before first paint when the next page has the same key; per history entry on back/forward/reload; `sessionStorage` blocked = no-op): the page gets one inline hashed script at the end of `<body>` only when it uses the attribute. The key is a literal string without `"<>&` (compile error otherwise, also for a nested panel of the same key); the same key on two elements of one rendered page throws `prunelle: data-pru-keep-scroll="..." is on two elements of one page`. `@prunellejs/spa` keeps the same attribute across its swaps.
|
|
25
|
-
- **Static files & CSS**: Files in `public/` are served at `/` with ETag/`304` (and `Cache-Control: no-cache` in `prunelle dev`; embedded in `--static` and `--compile`); prerendered pages and hashed assets answer an ETag, a `304` and a `HEAD` length too. `prunelle build` compresses hashed assets, `public/` files and prerendered pages of 256 B or more into `.br` and `.gz` files beside them, kept when smaller, and the server sends those as they are; it compresses on the fly (zstd, gzip) only what has none, such as pages rendered per request, and flushes a page streamed past `<Suspense>` with each part. A `public/x.css.br` the app ships is kept and sent as `x.css` in brotli. `prunelle start` on a `--static` export lists its files at startup (`x` serves `x.html` or `x/index.html`, a miss `404.html`), re-lists them when one changes in place, and loads a new export with no restart. Import `.css` or `*.module.css` directly from any component or layout.
|
|
26
|
-
- **CLI**: `prunelle new <dir> [--template minimal|fullstack|blog|app] [--force]` (its `AGENTS.md` points agents at
|
|
27
|
-
- **
|
|
25
|
+
- **Static files & CSS**: Files in `public/` are served at `/` with ETag/`304` (and `Cache-Control: no-cache` in `prunelle dev`; embedded in `--static` and `--compile`); prerendered pages and hashed assets answer an ETag, a `304` and a `HEAD` length too. `prunelle build` consolidates local stylesheets into at most one site-wide hashed immutable sheet (cached across pages) plus one per-route sheet when needed, preserving `@layer` and plugin-before-app cascade order, and compresses hashed assets, `public/` files and prerendered pages of 256 B or more into `.br` and `.gz` files beside them, kept when smaller, and the server sends those as they are; it compresses on the fly (zstd, gzip) only what has none, such as pages rendered per request, and flushes a page streamed past `<Suspense>` with each part. A `public/x.css.br` the app ships is kept and sent as `x.css` in brotli. `prunelle start` on a `--static` export lists its files at startup (`x` serves `x.html` or `x/index.html`, a miss `404.html`), re-lists them when one changes in place, and loads a new export with no restart. Import `.css` or `*.module.css` directly from any component or layout.
|
|
26
|
+
- **CLI (scaffold, check, build, start & upgrade)**: `prunelle new <dir> [--template minimal|fullstack|blog|app] [--force]` (its `AGENTS.md` points agents at `node_modules/prunelle/llms.txt`; writes `.mcp.json` registering `prunelle mcp` and `tsconfig.json` with `prunelle/ts-plugin`; `.gitignore` lists `node_modules/`, `dist/` and `.prunelle-cache/`), `prunelle check [dir] [--no-typecheck] [--json] [--strict]` (every compiler mistake at `file:line:col: error:`, warnings at `file:line:col: warning:` — RGAA/RGPD/LCEN compliance, broken internal links `[link/broken]` across JSX, `ctx.redirect()`, and Markdown content bodies (`// prunelle-ignore` silences one), cached-route private-read errors, form-vs-schema field/option/protection checks, and plugin `check(ctx)` hooks such as `@prunellejs/seo`; `--json` prints `{ ok, checkedFiles, typecheck, errors, warnings }`; `--strict` exits 1 on a warning; `prunelle build` refuses the same mistakes and form-schema errors without the typecheck), `prunelle inspect [dir] [--json]` (fast static report of routes with groups/optional params/matchers/`cache`/accurate `autoPrerender` `cacheable`, `statusPages`, `paramMatchers`, islands with interactivity `reason` and `hydrate` mode, actions with URLs and guarding `_middleware.ts`, and active plugins in resolved order without bundling; `--json` prints `{ routes, statusPages, paramMatchers, islands, actions, plugins }`), `prunelle build [dir] [--static] [--compile [out]] [--auto-prerender] [--analyze] [--json] [--max-js <size>]` (`--analyze` lists each route's eager JS, CSS, fonts, first load (brotli), EcoIndex grade/score/inputs for prerendered routes, and its islands with why each is one; `firstLoadUrls`, `distLocator` and `measureFirstLoad` from `prunelle/config` give plugins the same figure and `await brotliSize(html)` reads the brotli cache; `--analyze --json` outputs `BundleReport` JSON; `--max-js 40kb` fails on a route whose gzipped eager JS is over it), `prunelle start [dir] [--port 3000] [--host [addr]]`, `prunelle upgrade [dir] [--no-install]` (moves a kay v2 app or workspace onto prunelle; kay v1 left untouched; `sqliteAuthStore()` preserves accounts), plus plugin commands (`prunelle a11y [--draft [dest]] [--json] [--routes /a,/b]` via `a11y()` from `prunelle/config`, `prunelle ui-eject <grammar> [dest]`, `prunelle mcp-footprint`, `prunelle i18n-check`, `prunelle icons-find <words> [--set <prefix>] [--limit <n>]`). `--help` and `--completions fish|bash|zsh` come from `@kaynooo/cli-kit`. Exit codes: `0` done, `1` finding/failure, `2` usage error. Plugin commands load from `prunelle.config.ts` only when the first word is no built-in, and take `--root <dir>` and `--help`.
|
|
27
|
+
- **CLI (dev, editor & agent tooling)**: `prunelle dev [dir] [--port 3000] [--host [addr]]` (loopback `127.0.0.1` default; marks rendered elements with `data-pru-src="file:line:col"` in dev only — production output is byte-identical — and Alt-click opens `$PRUNELLE_EDITOR` or `$VISUAL` in VS Code, Cursor, Zed, JetBrains, Sublime, Helix or `{file}:{line}:{col}` templates; records dev build, crash and runtime errors in `.prunelle-dev/last-errors.json`; runs the app in a child process recycled on `prunelle.config.ts` edits or past 2 GB; edits in `public/` reload without rebuilding), `prunelle render <url> [--method|-X <m>] [--body|-d <data>] [--header|-H "K: V"] [--cookie|-b "k=v"] [-i|--include] [--fresh]` (built on `testApp()`: builds or reuses `.prunelle-cache/render-build` with no port bound and without touching `dist/`, printing body or status+headers+body with `-i`; exit `0` for `2xx`/`3xx`, `1` otherwise), `prunelle docs <words...> [--json] [--limit <n>]` (searches `llms.txt` of `prunelle` and every installed `@prunellejs/*` package at the installed versions; `--json` prints `{ query, words, packages, matches }`), `prunelle mcp [dir] [--allow-write]` (stdio MCP server for coding agents exposing `check`, `inspect`, `build_analyze`, `build` (requires `--allow-write`), `render`, `docs` and `dev_errors` tools, plus `prunelle://llms/<pkg>` resources; reloads `prunelle.config.ts` fresh on every tool call; paths stay inside the project), and `prunelle/ts-plugin` (added to `tsconfig.json` `compilerOptions.plugins` as `{ "name": "prunelle/ts-plugin", "site"?: "...", "compliance"?: {...} }`; surfaces compiler mistakes, compliance warnings and 18 mechanical quick fixes in `tsserver` editors — select the workspace TypeScript version in VS Code; `tsserver`-only until `tsgo` supports plugins).
|
|
28
|
+
- **Testing (`prunelle/test`)**: `const app = await testApp({ root, prebuilt?, outDir? })` (builds into its own `.prunelle-cache/test-*` folder, removed at exit, never into `dist/`; `prebuilt: true` reuses the latest testApp build of that root in the process, else `dist/`) — in-process `app.get()`, `app.post()`, `app.import(path)` (the app's bundled copy of a route, action file or `prunelle.config.ts`), `app.submit(action | url, fields)` (automatically sends empty honeypot and aged signed timestamp for `protect`ed `ServerAction`s unless overridden), `app.fetch()`, `app.cookies`, `app.clearCookies()`, `app.dispose()` (`await using app = await testApp(...)`) with persistent cookie jar and zero port binding; `app.errors` lists unhandled route/action/plugin errors (`route GET /p: message`), and `testApp({ dev: true })` shows them in the 500 like `prunelle dev` does. Unhandled errors in routes, actions, plugin routes and streamed `<Suspense>` boundaries log their source, method, path and stack to stderr (`console.error`) in both `prunelle start` and `prunelle dev` whenever no `onError` hook is configured (configuring `onError` handles them without doubling; `testApp()` without `dev: true` captures them in `app.errors` silently). With `dev` (`prunelle dev`, `testApp({ dev: true })`), the 500 also carries message and stack, each frame at its `src/` file and line (under `prunelle start` too, through the source maps `prunelle build` writes; a `--compile` binary names its own code) (JSON `{ ok: false, status: 500, error, stack }` when the request wants JSON, else text; `_error.tsx` still renders); production stays `Internal Server Error`. `prunelle dev` build errors also answer JSON/text per `Accept`. Islands: `const b = await testBrowser({ root, timeout?, browserPath? })` (needs `playwright-core` as a dev dependency and Chrome/Chromium; production build served on `b.origin`, a free 127.0.0.1 port) then `const page = await b.open(path)` (resolves once the page has loaded and its `load`/`client` islands have hydrated; `visible`, `idle`, `interaction` and `media(...)` ones are the test's to trigger) (`b.open(path, { reducedMotion: true })` opens it for a visitor asking for less motion) with live `page.url`, `page.click(sel)`, `page.hover(sel)`, `page.fill(sel, value)`, `page.press(key)`, `page.text(sel)`, `page.waitFor(sel | fn)`, `page.evaluate(fn)`, `page.errors` (page errors, console errors, 4xx/5xx responses), `page.close()`, and `await b.close()` at the end.
|
|
28
29
|
- **Plugins (`prunelle.config.ts`)**: `export default defineConfig({ plugins: [...] })` / `definePlugin(...)`. Order with `enforce: 'pre' | 'post'` and `after: ['@prunellejs/i18n']` (a name no plugin has is an optional dependency, unless it is one typo from one that is, which fails). Two plugins sharing a `name` fail, and so does an unknown config key, naming the closest one.
|
|
29
30
|
- A stateful plugin's `createX()` returns the plugin and the app's handle in one object: `plugins: [auth, mail, rooms]`, with `auth.guard()`, `mail.send()`, `rooms.publish()` in routes. Stateless plugins are `x()`.
|
|
30
|
-
- Hooks: `server(api)` (`use(mw, { scope? })` (`'all'` default, prerendered pages included; `'rendered'` skips prerendered pages, for middleware that only feeds rendering such as a session; `'dynamic'` also skips pages with no `load`; or a path prefix), `rewrite` (also run once per prerendered page at start, on an anonymous GET: no side effects), `route(method, path, handler, { csrf?, trustedOrigins?, trustProxy?, rateLimit? })` (`rateLimit: { max, windowMs, key? }` answers `429` with `Retry-After` before the handler past `max` per window, per `ctx.ip` or `key(ctx)`; responses get the security headers; an HTML one without its own CSP gets the app's, its `<style>` blocks hashed), `provide(key, value)`/`inject(key)` typed by `serviceKey<T>(name)` from `prunelle/config`, `getBuildData`), `onError(info)
|
|
31
|
+
- Hooks: `server(api)` (`use(mw, { scope? })` (`'all'` default, prerendered pages included; `'rendered'` skips prerendered pages, for middleware that only feeds rendering such as a session; `'dynamic'` also skips pages with no `load`; or a path prefix), `rewrite` (also run once per prerendered page at start, on an anonymous GET: no side effects), `route(method, path, handler, { csrf?, trustedOrigins?, trustProxy?, rateLimit?, encodedSlashes? })` (`rateLimit: { max, windowMs, key? }` answers `429` with `Retry-After` before the handler past `max` per window, per `ctx.ip` or `key(ctx)`; `encodedSlashes: true` lets a `*name` catch-all take a segment holding `%2F`, `%5C` or `%00`, left encoded in the param, for text such as a URL, never a file path; on a path with no catch-all it throws; responses get the security headers; an HTML one without its own CSP gets the app's, its `<style>` blocks hashed), `healthCheck(name, fn)` (contributes to `/_pru/health`; returning `false` or throwing turns it `503`), `provide(key, value)`/`inject(key)` typed by `serviceKey<T>(name)` from `prunelle/config`, `getBuildData`), `onError(info)` (`{ error, request, source, requestId }`), `build(ctx)` (`emitAsset`, `emitPublic`, `addStyle`, `addRouteStyle`, `addHead`, `addRouteHead`, `provide`, `inject`, `setData`, `routes`), `afterPrerender(ctx)` (`routes`, `publicFiles`, `emitAsset`, `emitPublic`, `setData`), `transform`, `bunPlugins` (array or `({ root, assetPrefix, minify, target }) => [...]`), `css`, `head(head, ctx)`, `transformHtml`, `inlineScripts` (the inline scripts the plugin writes into pages, each as it stands between its tags: the CSP of every page allows them by hash, since prunelle never hashes a script it finds in a page), `prerenderPaths`, `clientEntry`, `regionClientEntry`, `check(ctx)`, `requires({ root, site })` (one message per setting the plugin needs in production, naming it and its fix: a production start (`NODE_ENV=production`, not `prunelle dev`) refuses while any is unmet, listing them all; `prunelle dev`, tests and `prunelle check` warn once each; a throwing `requires` counts as unmet; first-party: auth refuses an in-memory store, mail a missing transport or `from`, mcp a missing `token`, seo and a content feed a missing `site`), `watchPaths`, `commands`.
|
|
31
32
|
- `api.rateLimiter({ max, windowMs })` returns a limiter in the server's store (bounded to 10 000 keys and 1 000 000 hits, swept every minute, dropped with the server) for a limit a route option cannot key, such as per email: `hit(key)` returns 0, or the whole seconds to wait.
|
|
32
33
|
- Runtime state (timers, connections, caches) is created in `server(api)` and released in `api.onShutdown()`, never in the plugin factory (a throwing `onShutdown` or `onError` hook is logged with its plugin's name; the others still run): `prunelle dev` starts the next server on the same instance before shutting the last one down, and a new process on a `prunelle.config.ts` edit.
|
|
33
|
-
- First-party packages (
|
|
34
|
-
- `@prunellejs/ui` (`node_modules/@prunellejs/ui/llms.txt`): Zero-JS layout/form primitives (`Stack`, `Cluster`, `Grid`, `Sidebar`, `Split`, `Button`, `Card`, `Badge`, `Notice`, `Field`, `Switch`, `Checkbox`, `RadioGroup`, `Progress`, `Accordion`, `Popover`), island widgets (`
|
|
34
|
+
- First-party packages (16 total with `prunelle`; each ships its full reference at `node_modules/@prunellejs/<name>/llms.txt`):
|
|
35
|
+
- `@prunellejs/ui` (`node_modules/@prunellejs/ui/llms.txt`): Zero-JS layout/form/overlay primitives (`Stack`, `Cluster`, `Grid`, `Sidebar`, `Split`, `Button`, `Card`, `Badge`, `Notice`, `Field`, `Switch`, `Checkbox`, `RadioGroup`, `Progress`, `Accordion`, `Popover`, `Dialog`, `Drawer`), island widgets (`ControlledDialog`, `ControlledDrawer`, `Tabs`, `Menu`, `Select`, `CommandPalette` (with lazy `source`), `DataTable`, `Toaster` + `toast()`), `@layer kui` Style Grammars (`prunelle`, `orbit`, `editorial`, `workshop`, `console`, `soft`, `bare`), `prunelle ui-eject`.
|
|
35
36
|
- `@prunellejs/auth` (`node_modules/@prunellejs/auth/llms.txt`): Argon2id passwords, hashed sessions, email verification (`requireEmailVerification: true`), magic links, OAuth 2.0 + PKCE, `auth.guard()`, RGPD helpers (`listSessions`, `exportUser`, `deleteUser`), `memoryAuthStore()` & `sqliteAuthStore()`.
|
|
36
|
-
- `@prunellejs/content` (`node_modules/@prunellejs/content/llms.txt`): Zero-dep `Bun.markdown` + `Bun.YAML` collections, Standard Schema
|
|
37
|
+
- `@prunellejs/content` (`node_modules/@prunellejs/content/llms.txt`): Zero-dep `Bun.markdown` + `Bun.YAML` file (`dir`) and headless CMS/API (`load`) collections, Standard Schema validation, lazy `entry.render()` (`highlight`, MDX-lite `components`, `headingLinks`), auto-wired `@prunellejs/images`, build/per-request caching, localized collections, TOC, and RSS feeds (`content({ feeds })`, `renderRss`, `renderRssAsync`).
|
|
38
|
+
- `@prunellejs/cms` (`node_modules/@prunellejs/cms/llms.txt`): Schema-driven, dev-only CMS (`cms({ guard, inline })`) with both full-page admin at `/_pru/cms` (working without JS) and automatic Shadow DOM in-page editing (click-to-edit frontmatter strings, docked schema drawer, live in-page Markdown body preview), reading `@prunellejs/content` collections via `CONTENT_COLLECTIONS_SERVICE` and shipping 0 B in production or `--static`.
|
|
39
|
+
- `@prunellejs/search` (`node_modules/@prunellejs/search/llms.txt`): First-party per-locale build-time site search (`search()`) indexing prerendered pages and `@prunellejs/content` entries, zero-JS `GET /search` page, and lazy `@prunellejs/search/client` (`searchSite()`, `createSearchSource()` for `CommandPalette`, `highlightMatches()`).
|
|
40
|
+
- `@prunellejs/analytics` (`node_modules/@prunellejs/analytics/llms.txt`): First-party CNIL-compliant server-side audience measurement (`analytics({ provider: plausible() | umami() | matomo() | custom() })`) with 0 B JS for page views, daily-rotating cookie-free visitor hashes, consent-aware first-party event endpoint (`trackEvent()` in `@prunellejs/analytics/client`), and optional Web Vitals.
|
|
37
41
|
- `@prunellejs/live` (`node_modules/@prunellejs/live/llms.txt`): Typed SSE rooms (`createRooms()`), `publish()`, microtask `coalesce()`, `rooms.stream()`, and browser `useLive()` hook (`@prunellejs/live/client`).
|
|
38
42
|
- `@prunellejs/mcp` (`node_modules/@prunellejs/mcp/llms.txt`): MCP Streamable HTTP (`2025-03-26`) exposing `action()`/handlers & compacted Standard JSON Schemas at `/mcp/tools` with bearer auth, `schemas`/`schemaRef`, `resources`, `formatLines`/`formatTable`, `budget`, and `prunelle mcp-footprint`.
|
|
39
43
|
- `@prunellejs/images` (`node_modules/@prunellejs/images/llms.txt`): Build-time AVIF/WebP pipeline + disk cache (`images()`, `image()`, `<Picture>`, `optimizeImageFile()`) and 1200×630 PNG OG `shareCard()`.
|
|
40
|
-
- `@prunellejs/seo` (`node_modules/@prunellejs/seo/llms.txt`): `titleTemplate`, localized `description`, canonical URLs, OG/Twitter/`jsonLd()`, i18n-aware `sitemap.xml`, redirects, manifest, favicons,
|
|
44
|
+
- `@prunellejs/seo` (`node_modules/@prunellejs/seo/llms.txt`): `titleTemplate`, localized `description`, canonical URLs, OG/Twitter/`jsonLd()`, i18n-aware `sitemap.xml`, redirects, manifest, favicons, self-hosted fonts, and `prunelle check` SEO validations (missing/duplicate/long title & description, `noindex` in sitemap, missing share image, missing `site`).
|
|
41
45
|
- `@prunellejs/i18n` (`node_modules/@prunellejs/i18n/llms.txt`): Locale URL rewriting (`ctx.locals.locale`/`t`/`localize`/`alternates`), `<html lang>` + internal link prefixing (`data-no-localize`), `prerenderPaths`, `hreflang`, `Intl` formatters, `prunelle i18n-check`.
|
|
42
46
|
- `@prunellejs/icons` (`node_modules/@prunellejs/icons/llms.txt`): Virtual `~icons/<set>/<name>` & `src/icons` (`~icons/local/<name>`) inline SVG imports + accessible `<Icon>`, `icons()` from `@prunellejs/icons/plugin`, `prunelle icons-find`, and server-only `@prunellejs/icons/search`.
|
|
43
|
-
- `@prunellejs/mail` (`node_modules/@prunellejs/mail/llms.txt`): `createMailer()`, `
|
|
47
|
+
- `@prunellejs/mail` (`node_modules/@prunellejs/mail/llms.txt`): `createMailer()`, TSX email components (`Email`, `Section`, `Heading`, `Text`, `Button`, `Divider`, `Footer`, `Link`, `renderMail()`), `MAIL_URL` (`smtp://`, `smtps://`, `resend://`, `postmark://`) with zero-dep Bun socket SMTP, `@prunellejs/jobs` retry integration, and dev-only `/_pru/mail` outbox + template previews.
|
|
44
48
|
- `@prunellejs/tailwind` (`node_modules/@prunellejs/tailwind/llms.txt`): Tailwind v4 via `tailwind()` (auto-loads `bun-plugin-tailwind`, defaults `css: 'src/app.css'`).
|
|
45
49
|
- `@prunellejs/spa` (`node_modules/@prunellejs/spa/llms.txt`): `regions()` (`refreshRegion()` from `@prunellejs/spa/regions`) for `<Region>` swaps and opt-in `spa()` full-page navigation with `[data-persist]` islands and `[data-pru-prefetch]`.
|
|
46
50
|
- **Server builds & `--compile`**: `prunelle build` writes a stage folder beside `outDir` and renames it in only once every step (bundles, plugin hooks, prerender, `--compile`) passed, so a failed build leaves the previous `outDir` byte-identical and a running `prunelle start` keeps serving it; once a build lands, `prunelle start` loads it in-process with no restart (requests arriving meanwhile wait for it, plugin `server()` runs again and the old build's `api.onShutdown()` hooks run, a build that fails to load is logged and the old one keeps answering, a new port/host/`maxRequestBodySize` needs a restart), and a file it can no longer read answers `404` `no-store`; the hashed client files the previous build made and this one dropped are hard-linked in (`manifest.carriedAssets`, never linked from a page) and served one more deploy, by `prunelle start`, a `--static` export and `--compile`, so a page loaded before the deploy still loads its deferred island chunks; each build is marked with `.prunelle-output`, and a folder holding files prunelle did not build is refused by name (an empty one or an unmarked older prunelle build is replaced). Server `Bun.build` keeps npm dependencies external (`packages: 'external'`) while compiling `@prunellejs/*` TSX packages; `prunelle build --compile` bundles everything + `public/` assets (`with { type: "file" }`) into one standalone Bun executable (`NODE_ENV` defaults to `production`). `prunelle start` and compiled binaries stop gracefully on `SIGTERM`/`SIGINT`/`SIGHUP`: no new connections, `api.onShutdown()` hooks run (`@prunellejs/live` ends its streams), exit 0 once in-flight requests answer, exit 1 after 10 s.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "prunelle",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.3",
|
|
4
4
|
"description": "Bun-native TSX web framework with zero-directive automatic islands, fine-grained signals, and single-binary deploys",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://prunelle.kaynooo.fr",
|
|
@@ -12,7 +12,8 @@
|
|
|
12
12
|
"files": [
|
|
13
13
|
"src",
|
|
14
14
|
"templates",
|
|
15
|
-
"llms.txt"
|
|
15
|
+
"llms.txt",
|
|
16
|
+
"ts-plugin.cjs"
|
|
16
17
|
],
|
|
17
18
|
"exports": {
|
|
18
19
|
".": "./src/index.ts",
|
|
@@ -20,6 +21,7 @@
|
|
|
20
21
|
"./config": "./src/plugins/public.ts",
|
|
21
22
|
"./test": "./src/test/index.ts",
|
|
22
23
|
"./build": "./src/build/index.ts",
|
|
24
|
+
"./ts-plugin": "./ts-plugin.cjs",
|
|
23
25
|
"./jsx-runtime": "./src/jsx-runtime.ts",
|
|
24
26
|
"./jsx-dev-runtime": "./src/jsx-runtime.ts",
|
|
25
27
|
"./internal/dom": "./src/dom/index.ts",
|
|
@@ -45,9 +47,13 @@
|
|
|
45
47
|
"oxc-parser": "^0.155.0"
|
|
46
48
|
},
|
|
47
49
|
"peerDependencies": {
|
|
50
|
+
"axe-core": "^4.14.0",
|
|
48
51
|
"playwright-core": "^1.64.0"
|
|
49
52
|
},
|
|
50
53
|
"peerDependenciesMeta": {
|
|
54
|
+
"axe-core": {
|
|
55
|
+
"optional": true
|
|
56
|
+
},
|
|
51
57
|
"playwright-core": {
|
|
52
58
|
"optional": true
|
|
53
59
|
}
|
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
// Generates an editable French RGAA 4.1.2 accessibility declaration page (Décret n° 2019-768).
|
|
2
|
+
|
|
3
|
+
import type { A11yAuditReport } from './index'
|
|
4
|
+
import { mkdirSync, writeFileSync } from 'node:fs'
|
|
5
|
+
import { dirname, resolve } from 'node:path'
|
|
6
|
+
import { relPosix } from '../build/files'
|
|
7
|
+
|
|
8
|
+
export type ComplianceStatus = 'full' | 'partial' | 'none'
|
|
9
|
+
|
|
10
|
+
export interface AccessibilityDeclarationOptions {
|
|
11
|
+
/** Application root directory. */
|
|
12
|
+
root: string
|
|
13
|
+
/** Destination path relative to `root` (or absolute). Default: `'src/routes/accessibilite.tsx'`. */
|
|
14
|
+
outPath?: string | undefined
|
|
15
|
+
/** Optional audit report from `auditAccessibility()` used to pre-fill test results and non-conformities. */
|
|
16
|
+
report?: A11yAuditReport | undefined
|
|
17
|
+
/** Organization or publisher name (editable placeholder by default). */
|
|
18
|
+
organization?: string | undefined
|
|
19
|
+
/** Public site URL (editable placeholder by default). */
|
|
20
|
+
siteUrl?: string | undefined
|
|
21
|
+
/** Contact email for accessibility feedback (editable placeholder by default). */
|
|
22
|
+
contactEmail?: string | undefined
|
|
23
|
+
/** Explicit compliance level override; inferred from `report` when omitted. */
|
|
24
|
+
status?: ComplianceStatus | undefined
|
|
25
|
+
/** Declaration date (defaults to today). */
|
|
26
|
+
date?: Date | undefined
|
|
27
|
+
/** Write the generated TSX page to disk (default: `true`). */
|
|
28
|
+
write?: boolean | undefined
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface AccessibilityDeclarationResult {
|
|
32
|
+
/** Absolute path of the target declaration file. */
|
|
33
|
+
path: string
|
|
34
|
+
/** Root-relative POSIX path (e.g. `'src/routes/accessibilite.tsx'`). */
|
|
35
|
+
relativePath: string
|
|
36
|
+
/** Compliance status written into the declaration. */
|
|
37
|
+
status: ComplianceStatus
|
|
38
|
+
/** Generated TSX source code. */
|
|
39
|
+
content: string
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export const DEFAULT_DECLARATION_PATH = 'src/routes/accessibilite.tsx'
|
|
43
|
+
|
|
44
|
+
const STATUS_LABELS: Readonly<Record<ComplianceStatus, string>> = {
|
|
45
|
+
full: 'totalement conforme',
|
|
46
|
+
partial: 'partiellement conforme',
|
|
47
|
+
none: 'non conforme',
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Infers RGAA compliance status from an automated audit report (never claims full compliance without explicit opt-in). */
|
|
51
|
+
export function inferComplianceStatus(
|
|
52
|
+
report: A11yAuditReport | undefined,
|
|
53
|
+
override?: ComplianceStatus | undefined,
|
|
54
|
+
): ComplianceStatus {
|
|
55
|
+
if (override !== undefined)
|
|
56
|
+
return override
|
|
57
|
+
if (report === undefined)
|
|
58
|
+
return 'none'
|
|
59
|
+
return report.totalViolations === 0 ? 'partial' : 'none'
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function escapeJsxText(value: string): string {
|
|
63
|
+
return value
|
|
64
|
+
.replaceAll('&', '&')
|
|
65
|
+
.replaceAll('<', '<')
|
|
66
|
+
.replaceAll('>', '>')
|
|
67
|
+
.replaceAll('{', '{')
|
|
68
|
+
.replaceAll('}', '}')
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function escapeAttr(value: string): string {
|
|
72
|
+
return value
|
|
73
|
+
.replaceAll('&', '&')
|
|
74
|
+
.replaceAll('"', '"')
|
|
75
|
+
.replaceAll('<', '<')
|
|
76
|
+
.replaceAll('>', '>')
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function formatFrenchDate(date: Date): { iso: string, human: string } {
|
|
80
|
+
const iso = date.toISOString().slice(0, 10)
|
|
81
|
+
const human = new Intl.DateTimeFormat('fr-FR', {
|
|
82
|
+
day: 'numeric',
|
|
83
|
+
month: 'long',
|
|
84
|
+
year: 'numeric',
|
|
85
|
+
timeZone: 'UTC',
|
|
86
|
+
}).format(date)
|
|
87
|
+
return { iso, human }
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function renderNonConformities(report: A11yAuditReport | undefined): string {
|
|
91
|
+
const routesWithIssues = report?.routes.filter(r => r.violations.length > 0) ?? []
|
|
92
|
+
if (routesWithIssues.length === 0) {
|
|
93
|
+
return [
|
|
94
|
+
' <p>',
|
|
95
|
+
' {/* TODO: compléter avec les non-conformités relevées lors de l\'audit manuel RGAA 4.1.2 */}',
|
|
96
|
+
' Aucune non-conformité n\'a été détectée par l\'audit automatisé axe-core.',
|
|
97
|
+
' Les résultats d\'un audit manuel RGAA 4.1.2 complet doivent être renseignés ci-dessous.',
|
|
98
|
+
' </p>',
|
|
99
|
+
].join('\n')
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const items: string[] = []
|
|
103
|
+
for (const route of routesWithIssues) {
|
|
104
|
+
for (const v of route.violations) {
|
|
105
|
+
const rgaaLabel = v.rgaa.length > 0
|
|
106
|
+
? `RGAA ${v.rgaa.map(c => c.id).join(', ')}`
|
|
107
|
+
: 'WCAG / axe-core'
|
|
108
|
+
const count = v.nodes.length
|
|
109
|
+
const elemWord = count === 1 ? 'élément' : 'éléments'
|
|
110
|
+
const line = `${route.route} — ${rgaaLabel} (${v.id}, impact ${v.impact}, ${count} ${elemWord}) : ${v.help}.`
|
|
111
|
+
items.push(` <li>${escapeJsxText(line)}</li>`)
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return [
|
|
115
|
+
' <p>Les non-conformités suivantes ont été détectées automatiquement par axe-core :</p>',
|
|
116
|
+
' <ul>',
|
|
117
|
+
...items,
|
|
118
|
+
' </ul>',
|
|
119
|
+
].join('\n')
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function renderAuditedRoutes(report: A11yAuditReport | undefined): string {
|
|
123
|
+
const routes = report?.routes ?? []
|
|
124
|
+
if (routes.length === 0) {
|
|
125
|
+
return [
|
|
126
|
+
' <ul>',
|
|
127
|
+
' <li><code>/</code> — Page d\'accueil (TODO : lister l\'échantillon complet audité)</li>',
|
|
128
|
+
' </ul>',
|
|
129
|
+
].join('\n')
|
|
130
|
+
}
|
|
131
|
+
const items = routes.map((r) => {
|
|
132
|
+
const summary = r.violations.length === 0
|
|
133
|
+
? '0 violation automatisée'
|
|
134
|
+
: `${r.violations.length} violation${r.violations.length === 1 ? '' : 's'} automatisée${r.violations.length === 1 ? '' : 's'}`
|
|
135
|
+
return ` <li><code>${escapeJsxText(r.route)}</code> (${escapeJsxText(summary)})</li>`
|
|
136
|
+
})
|
|
137
|
+
return [
|
|
138
|
+
' <ul>',
|
|
139
|
+
...items,
|
|
140
|
+
' </ul>',
|
|
141
|
+
].join('\n')
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function buildStatusParagraph(status: ComplianceStatus, siteUrl: string, report: A11yAuditReport | undefined): string {
|
|
145
|
+
const statusLabel = STATUS_LABELS[status]
|
|
146
|
+
const safeSite = escapeJsxText(siteUrl)
|
|
147
|
+
if (status === 'full') {
|
|
148
|
+
return [
|
|
149
|
+
` {/* TODO: ne conserver "totalement conforme" qu'après validation d'un audit manuel RGAA 4.1.2 complet (100 % des critères applicables conformes). */}`,
|
|
150
|
+
` <p>`,
|
|
151
|
+
` <strong>${safeSite}</strong> est <strong>${statusLabel}</strong> avec le référentiel général d'amélioration de l'accessibilité (RGAA), version 4.1.2.`,
|
|
152
|
+
` </p>`,
|
|
153
|
+
].join('\n')
|
|
154
|
+
}
|
|
155
|
+
if (status === 'partial') {
|
|
156
|
+
const detail = report !== undefined
|
|
157
|
+
? ` L'audit automatisé axe-core sur ${report.routes.length} page${report.routes.length === 1 ? '' : 's'} n'a relevé aucune violation, mais un audit manuel RGAA 4.1.2 reste nécessaire avant de déclarer une conformité totale.`
|
|
158
|
+
: ' Des non-conformités ou des vérifications manuelles RGAA 4.1.2 restent à compléter ci-dessous.'
|
|
159
|
+
return [
|
|
160
|
+
` {/* TODO: mettre à jour le niveau de conformité et le taux après réalisation de l'audit manuel RGAA 4.1.2. */}`,
|
|
161
|
+
` <p>`,
|
|
162
|
+
` <strong>${safeSite}</strong> est <strong>${statusLabel}</strong> avec le référentiel général d'amélioration de l'accessibilité (RGAA), version 4.1.2.${escapeJsxText(detail)}`,
|
|
163
|
+
` </p>`,
|
|
164
|
+
].join('\n')
|
|
165
|
+
}
|
|
166
|
+
const reason = report !== undefined && report.totalViolations > 0
|
|
167
|
+
? ` en raison des ${report.totalViolations} non-conformité${report.totalViolations === 1 ? '' : 's'} automatisée${report.totalViolations === 1 ? '' : 's'} recensée${report.totalViolations === 1 ? '' : 's'} ci-dessous`
|
|
168
|
+
: ' en l\'absence d\'audit de conformité RGAA 4.1.2 complet'
|
|
169
|
+
return [
|
|
170
|
+
` {/* TODO: corriger les non-conformités listées puis réaliser un audit manuel RGAA 4.1.2. */}`,
|
|
171
|
+
` <p>`,
|
|
172
|
+
` <strong>${safeSite}</strong> est <strong>${statusLabel}</strong> avec le référentiel général d'amélioration de l'accessibilité (RGAA), version 4.1.2${escapeJsxText(reason)}.`,
|
|
173
|
+
` </p>`,
|
|
174
|
+
].join('\n')
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Generates (and optionally writes) a draft French RGAA 4.1.2 accessibility declaration page in TSX. */
|
|
178
|
+
export function draftAccessibilityStatement(options: AccessibilityDeclarationOptions): AccessibilityDeclarationResult {
|
|
179
|
+
const root = resolve(options.root)
|
|
180
|
+
const dest = resolve(root, options.outPath ?? DEFAULT_DECLARATION_PATH)
|
|
181
|
+
const relativePath = relPosix(root, dest)
|
|
182
|
+
const status = inferComplianceStatus(options.report, options.status)
|
|
183
|
+
const org = options.organization?.trim() || '[Nom de l\'organisme]'
|
|
184
|
+
const siteUrl = options.siteUrl?.trim() || '[https://exemple.fr]'
|
|
185
|
+
const contactEmail = options.contactEmail?.trim() || 'accessibilite@exemple.fr'
|
|
186
|
+
const { iso, human } = formatFrenchDate(options.date ?? new Date())
|
|
187
|
+
const axeLabel = options.report?.axeVersion ? `axe-core ${options.report.axeVersion}` : 'axe-core'
|
|
188
|
+
const routeCount = options.report?.routes.length ?? 0
|
|
189
|
+
const violationCount = options.report?.totalViolations ?? 0
|
|
190
|
+
|
|
191
|
+
const content = `// Brouillon de déclaration d'accessibilité RGAA 4.1.2 (Décret n° 2019-768) généré par \`prunelle a11y --draft\`.
|
|
192
|
+
// TODO: Les vérifications automatisées axe-core ne couvrent qu'une partie des 106 critères du RGAA 4.1.2.
|
|
193
|
+
// Complétez chaque mention entre crochets ([...]) et renseignez les résultats de votre audit manuel avant publication.
|
|
194
|
+
|
|
195
|
+
import { Head } from 'prunelle'
|
|
196
|
+
|
|
197
|
+
export const prerender = true
|
|
198
|
+
|
|
199
|
+
export default function Accessibilite() {
|
|
200
|
+
return (
|
|
201
|
+
<>
|
|
202
|
+
<Head>
|
|
203
|
+
<title>Déclaration d'accessibilité</title>
|
|
204
|
+
</Head>
|
|
205
|
+
<main>
|
|
206
|
+
<h1>Déclaration d'accessibilité</h1>
|
|
207
|
+
<p>
|
|
208
|
+
<strong>${escapeJsxText(org)}</strong> s'engage à rendre ses sites internet, intranet, extranet et ses progiciels
|
|
209
|
+
accessibles (et ses applications mobiles et mobilier urbain numérique) conformément à l'article 47 de la loi n° 2005-102
|
|
210
|
+
du 11 février 2005.
|
|
211
|
+
</p>
|
|
212
|
+
<p>
|
|
213
|
+
Cette déclaration d'accessibilité s'applique à <strong>${escapeJsxText(siteUrl)}</strong>.
|
|
214
|
+
</p>
|
|
215
|
+
|
|
216
|
+
<section>
|
|
217
|
+
<h2>État de conformité</h2>
|
|
218
|
+
${buildStatusParagraph(status, siteUrl, options.report)}
|
|
219
|
+
</section>
|
|
220
|
+
|
|
221
|
+
<section>
|
|
222
|
+
<h2>Résultats des tests</h2>
|
|
223
|
+
<p>
|
|
224
|
+
L'audit automatisé réalisé via <code>prunelle a11y</code> (${escapeJsxText(axeLabel)}, règles WCAG 2.0 / 2.1 niveaux A et AA
|
|
225
|
+
mappées au RGAA 4.1) a porté sur <strong>${routeCount}</strong> page${routeCount === 1 ? '' : 's'} et a relevé{' '}
|
|
226
|
+
<strong>${violationCount}</strong> violation${violationCount === 1 ? '' : 's'} automatisée${violationCount === 1 ? '' : 's'}.
|
|
227
|
+
</p>
|
|
228
|
+
<p>
|
|
229
|
+
{/* TODO: remplacer par le taux de conformité issu de votre audit manuel RGAA 4.1.2 */}
|
|
230
|
+
L'audit de conformité manuel RGAA 4.1.2 révèle que <strong>[XX %]</strong> des critères du RGAA version 4.1.2 sont respectés.
|
|
231
|
+
</p>
|
|
232
|
+
</section>
|
|
233
|
+
|
|
234
|
+
<section>
|
|
235
|
+
<h2>Contenus non accessibles</h2>
|
|
236
|
+
|
|
237
|
+
<h3>Non-conformités</h3>
|
|
238
|
+
${renderNonConformities(options.report)}
|
|
239
|
+
|
|
240
|
+
<h3>Dérogations pour charge disproportionnée</h3>
|
|
241
|
+
<p>
|
|
242
|
+
{/* TODO: lister ici les éventuelles dérogations justifiées */}
|
|
243
|
+
Aucune.
|
|
244
|
+
</p>
|
|
245
|
+
|
|
246
|
+
<h3>Contenus non soumis à l'obligation d'accessibilité</h3>
|
|
247
|
+
<p>
|
|
248
|
+
{/* TODO: lister ici les contenus tiers ou archives hors périmètre */}
|
|
249
|
+
Aucun.
|
|
250
|
+
</p>
|
|
251
|
+
</section>
|
|
252
|
+
|
|
253
|
+
<section>
|
|
254
|
+
<h2>Établissement de cette déclaration d'accessibilité</h2>
|
|
255
|
+
<p>
|
|
256
|
+
Cette déclaration a été établie le <time dateTime="${escapeAttr(iso)}">${escapeJsxText(human)}</time>.
|
|
257
|
+
</p>
|
|
258
|
+
|
|
259
|
+
<h3>Technologies utilisées pour la réalisation du site</h3>
|
|
260
|
+
<ul>
|
|
261
|
+
<li>HTML5</li>
|
|
262
|
+
<li>CSS</li>
|
|
263
|
+
<li>JavaScript</li>
|
|
264
|
+
<li>Prunelle</li>
|
|
265
|
+
</ul>
|
|
266
|
+
|
|
267
|
+
<h3>Environnement de test</h3>
|
|
268
|
+
<p>
|
|
269
|
+
Les vérifications automatisées de restitution de contenus ont été réalisées dans l'environnement suivant :
|
|
270
|
+
</p>
|
|
271
|
+
<ul>
|
|
272
|
+
<li>Navigateur : Chromium (headless via Playwright)</li>
|
|
273
|
+
<li>Moteur d'analyse : ${escapeJsxText(axeLabel)}</li>
|
|
274
|
+
<li>{/* TODO: ajouter les combinaisons navigateur + lecteur d'écran testées manuellement (ex. Firefox + NVDA, Safari + VoiceOver) */}Lecteurs d'écran (audit manuel) : [À compléter]</li>
|
|
275
|
+
</ul>
|
|
276
|
+
|
|
277
|
+
<h3>Outils pour évaluer l'accessibilité</h3>
|
|
278
|
+
<ul>
|
|
279
|
+
<li><code>prunelle a11y</code> (${escapeJsxText(axeLabel)})</li>
|
|
280
|
+
<li><code>prunelle check</code> (vérifications statiques RGAA sur le JSX)</li>
|
|
281
|
+
</ul>
|
|
282
|
+
|
|
283
|
+
<h3>Pages du site ayant fait l'objet de la vérification de conformité</h3>
|
|
284
|
+
${renderAuditedRoutes(options.report)}
|
|
285
|
+
</section>
|
|
286
|
+
|
|
287
|
+
<section>
|
|
288
|
+
<h2>Retour d'information et contact</h2>
|
|
289
|
+
<p>
|
|
290
|
+
Si vous n'arrivez pas à accéder à un contenu ou à un service, vous pouvez contacter le responsable de{' '}
|
|
291
|
+
<strong>${escapeJsxText(siteUrl)}</strong> pour être orienté vers une alternative accessible ou obtenir le contenu sous une autre forme.
|
|
292
|
+
</p>
|
|
293
|
+
<ul>
|
|
294
|
+
<li>Envoyer un courriel : <a href="mailto:${escapeAttr(contactEmail)}">${escapeJsxText(contactEmail)}</a></li>
|
|
295
|
+
<li>Contacter : ${escapeJsxText(org)} — [Adresse postale / lien vers le formulaire de contact]</li>
|
|
296
|
+
</ul>
|
|
297
|
+
</section>
|
|
298
|
+
|
|
299
|
+
<section>
|
|
300
|
+
<h2>Voies de recours</h2>
|
|
301
|
+
<p>
|
|
302
|
+
Cette procédure est à utiliser dans le cas suivant : vous avez signalé au responsable du site internet un défaut
|
|
303
|
+
d'accessibilité qui vous empêche d'accéder à un contenu ou à un des services du portail et vous n'avez pas obtenu
|
|
304
|
+
de réponse satisfaisante.
|
|
305
|
+
</p>
|
|
306
|
+
<ul>
|
|
307
|
+
<li>
|
|
308
|
+
<a href="https://formulaire.defenseurdesdroits.fr/">Écrire un message au Défenseur des droits</a>
|
|
309
|
+
</li>
|
|
310
|
+
<li>
|
|
311
|
+
<a href="https://www.defenseurdesdroits.fr/saisir/delegues">Contacter le délégué du Défenseur des droits dans votre région</a>
|
|
312
|
+
</li>
|
|
313
|
+
<li>
|
|
314
|
+
Envoyer un courrier par la poste (gratuit, ne pas mettre de timbre) : Défenseur des droits, Libre réponse 71120, 75342 Paris CEDEX 07.
|
|
315
|
+
</li>
|
|
316
|
+
</ul>
|
|
317
|
+
</section>
|
|
318
|
+
</main>
|
|
319
|
+
</>
|
|
320
|
+
)
|
|
321
|
+
}
|
|
322
|
+
`
|
|
323
|
+
|
|
324
|
+
if (options.write !== false) {
|
|
325
|
+
mkdirSync(dirname(dest), { recursive: true })
|
|
326
|
+
writeFileSync(dest, content)
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
return {
|
|
330
|
+
path: dest,
|
|
331
|
+
relativePath,
|
|
332
|
+
status,
|
|
333
|
+
content,
|
|
334
|
+
}
|
|
335
|
+
}
|