prunelle 0.1.1 → 0.2.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 (48) hide show
  1. package/llms.txt +12 -12
  2. package/package.json +1 -1
  3. package/src/build/client-entries.ts +3 -2
  4. package/src/build/compile.ts +2 -1
  5. package/src/build/index.ts +68 -29
  6. package/src/build/manifest.ts +18 -1
  7. package/src/build/output.ts +2 -2
  8. package/src/build/precompress.ts +15 -2
  9. package/src/build/prerender.ts +2 -2
  10. package/src/build/routes.ts +171 -10
  11. package/src/build/static.ts +71 -17
  12. package/src/build/status-pages.ts +127 -0
  13. package/src/cli/check-forms.ts +654 -0
  14. package/src/cli/check-links.ts +619 -0
  15. package/src/cli/check.ts +37 -4
  16. package/src/cli/commands.ts +5 -3
  17. package/src/cli/inspect.ts +21 -2
  18. package/src/cli/upgrade-names.ts +73 -13
  19. package/src/cli/upgrade.ts +137 -16
  20. package/src/compiler/compliance-rgaa.ts +502 -0
  21. package/src/compiler/compliance.ts +119 -220
  22. package/src/compiler/ssr.ts +121 -24
  23. package/src/dom/action.ts +4 -1
  24. package/src/dom/island.ts +5 -5
  25. package/src/plugins/config.ts +1 -1
  26. package/src/plugins/types.ts +13 -0
  27. package/src/server/action-protect.ts +186 -0
  28. package/src/server/action.ts +33 -10
  29. package/src/server/errors.ts +291 -62
  30. package/src/server/form-schema.ts +343 -0
  31. package/src/server/health.ts +244 -0
  32. package/src/server/http.ts +84 -17
  33. package/src/server/index.ts +162 -91
  34. package/src/server/param-matchers.ts +112 -0
  35. package/src/server/plugin-host.ts +40 -14
  36. package/src/server/public.ts +3 -3
  37. package/src/server/route-table.ts +5 -2
  38. package/src/server/router.ts +125 -40
  39. package/src/server/routing.ts +95 -57
  40. package/src/server/security.ts +171 -22
  41. package/src/server/serve-handlers.ts +21 -7
  42. package/src/ssr/context.ts +49 -0
  43. package/src/ssr/index.ts +120 -1
  44. package/src/test/browser.ts +6 -0
  45. package/src/test/index.ts +17 -3
  46. package/templates/_shared/src/routes/legal.tsx +5 -0
  47. package/templates/blog/prunelle.config.ts +1 -1
  48. package/templates/blog/src/routes/index.tsx +4 -0
package/llms.txt CHANGED
@@ -4,30 +4,30 @@
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.
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, `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
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 &amp; 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. 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 and the runtime import (a streamed page its route's eager islands only). `<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).
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, wrapped in root layout), `_404.tsx` (server-only, wrapped in root layout, also emitted as `404.html` in `--static`); each 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: `[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).
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 `GET`, `POST`, `PUT`, `PATCH`, `DELETE` receiving `RequestContext` (`request`, `url`, `params`, `cookies`, `locals`, `ip`, `requestId`, `region`, `json()`, `text()`, `redirect()`, `deny()`). Optional `export const csrf = false` opts out of origin checks (e.g. webhooks/bearer APIs).
18
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`.
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; `action(schema, fn, { rateLimit: { max, windowMs, key? } })` refuses a client past `max` per window the same way with `Too many requests`, or a `429` `ActionResult` and `Retry-After` from script) 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). 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({ 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` or `/legal`), 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).
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` — renders a hidden honeypot and HMAC-signed `_pru_ts` timestamp into `<form action={fn}>` automatically and refuses bots/fast submits with `400` or past `rateLimit` with `429` + `Retry-After` / flash+303 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({ lang, port, routesDir, outDir, publicDir, assetPrefix, security, trustedOrigins, trustProxy, maxRequestBodySize, 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`), `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), `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">`, `<iframe src>`, and CSS `@import`/`url(...)` outside `<ConsentGate>` or `site`), `lcen/legal-notice` (page app missing `/mentions-legales` or `/legal`), 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
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 this file, installed at `node_modules/prunelle/llms.txt`; its `.gitignore` lists `node_modules/`, `dist/` and `.prunelle-cache/`), `prunelle check [dir] [--no-typecheck] [--json] [--strict]` (every compiler mistake of a file, each at its `file:line:col: error:`, warnings as `file:line:col: warning:`; `--json` prints `{ ok, checkedFiles, typecheck, errors, warnings }` with `file`/`line`/`col`/`severity`/`message`, `typecheck` being `{ ran: true, tool }` or `{ ran: false, reason }` (no tsconfig, `--no-typecheck`, no checker), which the summary line also names; `--strict` exits 1 on a warning; `prunelle build` refuses the same mistakes, without the typecheck; a plugin `check(ctx)` reports with `ctx.error()` or `ctx.warn()`), `prunelle inspect [dir] [--json]` (fast static report of routes, 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, islands, actions, plugins }`), `prunelle dev [dir] [--port 3000] [--host [addr]]` (loopback `127.0.0.1` default; a `prunelle.config.ts` that fails to load stops it naming `prunelle.config.ts:<line>:<col>: <error>`; the app runs in a child process behind the port: a save rebuilds in it, an edit to `prunelle.config.ts` or a local file it imports, or the child passing 2 GB after a rebuild, starts a fresh one (module and plugin memory reset, requests wait, the reload stream stays open); a crash answers with its exit and stderr until the next save; an edited `public/` file reloads with no rebuild), `prunelle build [dir] [--static] [--compile [out]] [--analyze] [--json] [--max-js <size>]` (`--analyze` lists each route's eager JS (the runtime a plugin's `clientEntry` puts on every page included), CSS, fonts and first load (what a first visit downloads besides the HTML, brotli) and its islands with why each is one; `firstLoadUrls`, `distLocator` and `measureFirstLoad` from `prunelle/config` give a plugin the same figure for a page (`measureFirstLoad(urls, locate, htmlBytes, cacheable)` also returns `cached`, the bytes of the URLs `cacheable` accepts, such as the hashed `/_pru/` files a browser keeps for the next page), and `await brotliSize(html)` the page's own bytes as prunelle serves it, from the build's brotli cache, as the docs footer does; `--analyze --json` outputs `BundleReport` JSON on stdout without summary lines; `--max-js 40kb` fails on a route whose gzipped eager JS is over it, naming its eager islands), `prunelle start [dir] [--port 3000] [--host [addr]]`, `prunelle upgrade [dir] [--no-install]` (moves a kay v2 app onto prunelle: `@kayjs/*` dependencies and imports, `kay.config.ts`, every `Kay*` name it imports, the `kay` names the browser receives, build and CI files, in each package a bun workspace lists; a package on kay v1 is left as it is; a kay `sqliteAuthStore()` database keeps its accounts), plus plugin commands (`prunelle ui-eject <grammar> [dest]`, `prunelle mcp-footprint`, `prunelle i18n-check`, `prunelle icons-find <words> [--set <prefix>] [--limit <n>]`). `prunelle --help`, `prunelle <command> --help` and `prunelle --completions fish|bash|zsh` come from `@kaynooo/cli-kit`; a typo'd command or option names the one meant. Exit codes: 0 done, 1 a finding or failure (`prunelle check` found an error, `prunelle upgrade` has steps left by hand, a build failed), 2 a usage error (unknown command or option, bad port or `--max-js`). Plugin commands are read from `prunelle.config.ts` only when the first word is no built-in, and take `--root <dir>` and `--help`; a config that fails to load leaves `prunelle --help` and the built-ins working, and a plugin command typed then names the error (exit 1).
27
- - **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)`, `app.fetch()`, `app.cookies`, `app.clearCookies()` 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 with `dev` (prunelle dev, `dev: true`): `console.error` unless an `onError` hook exists, and the 500 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` and `interaction` ones are the test's to trigger) (`b.open(path, { reducedMotion: true })` opens it for a visitor asking for less motion) with `page.click(sel)`, `page.hover(sel)`, `page.fill(sel, value)`, `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.
26
+ - **CLI**: `prunelle new <dir> [--template minimal|fullstack|blog|app] [--force]` (its `AGENTS.md` points agents at this file, installed at `node_modules/prunelle/llms.txt`; its `.gitignore` lists `node_modules/`, `dist/` and `.prunelle-cache/`, and `.prunelle-cache/` also writes its own `.gitignore`), `prunelle check [dir] [--no-typecheck] [--json] [--strict]` (every compiler mistake of a file, each at its `file:line:col: error:`, warnings as `file:line:col: warning:` — including RGAA/RGPD/LCEN compliance, broken internal links `[link/broken]` across JSX, `ctx.redirect()`, and Markdown content bodies (`// prunelle-ignore` silences one), form-vs-schema field/option/protection checks, and plugin `check(ctx)` hooks such as `@prunellejs/seo`; `--json` prints `{ ok, checkedFiles, typecheck, errors, warnings }` with `file`/`line`/`col`/`severity`/`message`, `typecheck` being `{ ran: true, tool }` or `{ ran: false, reason }` (no tsconfig, `--no-typecheck`, no checker), which the summary line also names; `--strict` exits 1 on a warning; `prunelle build` refuses the same mistakes and form-schema errors, without the typecheck; a plugin `check(ctx)` reports with `ctx.error()` or `ctx.warn()`), `prunelle inspect [dir] [--json]` (fast static report of routes with groups/optional params/matchers, 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, islands, actions, plugins }`), `prunelle dev [dir] [--port 3000] [--host [addr]]` (loopback `127.0.0.1` default; a `prunelle.config.ts` that fails to load stops it naming `prunelle.config.ts:<line>:<col>: <error>`; the app runs in a child process behind the port: a save rebuilds in it, an edit to `prunelle.config.ts` or a local file it imports, or the child passing 2 GB after a rebuild, starts a fresh one (module and plugin memory reset, requests wait, the reload stream stays open); a crash answers with its exit and stderr until the next save; an edited `public/` file reloads with no rebuild), `prunelle build [dir] [--static] [--compile [out]] [--analyze] [--json] [--max-js <size>]` (`--analyze` lists each route's eager JS (the runtime a plugin's `clientEntry` puts on every page included), CSS, fonts and first load (what a first visit downloads besides the HTML, brotli) and its islands with why each is one; `firstLoadUrls`, `distLocator` and `measureFirstLoad` from `prunelle/config` give a plugin the same figure for a page (`measureFirstLoad(urls, locate, htmlBytes, cacheable)` also returns `cached`, the bytes of the URLs `cacheable` accepts, such as the hashed `/_pru/` files a browser keeps for the next page), and `await brotliSize(html)` the page's own bytes as prunelle serves it, from the build's brotli cache, as the docs footer does; `--analyze --json` outputs `BundleReport` JSON on stdout without summary lines; `--max-js 40kb` fails on a route whose gzipped eager JS is over it, naming its eager islands), `prunelle start [dir] [--port 3000] [--host [addr]]`, `prunelle upgrade [dir] [--no-install]` (moves a kay v2 app onto prunelle: `@kayjs/*` dependencies, `npm:@kayjs/*` aliases and their imports, `kay.config.ts`, every `Kay*` name it imports, the `kay` names the browser receives, build and CI files, `.gitignore`, `AGENTS.md` and `CLAUDE.md`, leaving `public/` untouched, in each package of a bun workspace that depends on kay or prunelle; a package on kay v1 is left as it is; a kay `sqliteAuthStore()` database keeps its accounts), plus plugin commands (`prunelle ui-eject <grammar> [dest]`, `prunelle mcp-footprint`, `prunelle i18n-check`, `prunelle icons-find <words> [--set <prefix>] [--limit <n>]`). `prunelle --help`, `prunelle <command> --help` and `prunelle --completions fish|bash|zsh` come from `@kaynooo/cli-kit`; a typo'd command or option names the one meant. Exit codes: 0 done, 1 a finding or failure (`prunelle check` found an error, `prunelle upgrade` has steps left by hand, a build failed), 2 a usage error (unknown command or option, bad port or `--max-js`). Plugin commands are read from `prunelle.config.ts` only when the first word is no built-in, and take `--root <dir>` and `--help`; a config that fails to load leaves `prunelle --help` and the built-ins working, and a plugin command typed then names the error (exit 1).
27
+ - **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()` 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` and `interaction` ones are the test's to trigger) (`b.open(path, { reducedMotion: true })` opens it for a visitor asking for less motion) with `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
28
  - **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
29
  - 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)`, `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`, `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`.
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?, 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`, `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
31
  - `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
32
  - 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
33
  - First-party packages (13 total with `prunelle`; each ships its full reference at `node_modules/@prunellejs/<name>/llms.txt`):
@@ -37,7 +37,7 @@
37
37
  - `@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
38
  - `@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
39
  - `@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, and self-hosted fonts.
40
+ - `@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
41
  - `@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
42
  - `@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
43
  - `@prunellejs/mail` (`node_modules/@prunellejs/mail/llms.txt`): `createMailer()`, `resend()` HTTP or custom transport, and dev-only `/_pru/mail` (+ `.json`) outbox preview.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prunelle",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
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",
@@ -47,7 +47,6 @@ export function writeClientEntries(env: BundleEnv, entriesDir: string, options:
47
47
  const runtimeLines: string[] = []
48
48
  if (env.islands.targets.size > 0) {
49
49
  runtimeLines.push(`import { defineIslandElement } from 'prunelle/internal/island';`)
50
- runtimeLines.push(`export { hydrate${hasClientOnlyHydrate ? ', mount' : ''} } from 'prunelle/internal/dom';`)
51
50
  runtimeLines.push(`defineIslandElement();`)
52
51
  }
53
52
  for (const pe of pluginClientEntries)
@@ -64,12 +63,14 @@ export function writeClientEntries(env: BundleEnv, entriesDir: string, options:
64
63
 
65
64
  out.entryPoints.push(...options.standaloneCss)
66
65
 
66
+ // Each island hands the loader the DOM runtime its chunk imports anyway, so a page whose islands all wait downloads the loader alone.
67
+ const domExports = `export { hydrate${hasClientOnlyHydrate ? ', mount' : ''} } from 'prunelle/internal/dom';\n`
67
68
  for (const [key, target] of env.islands.targets) {
68
69
  const entryPath = join(entriesDir, `${target.id}.ts`)
69
70
  const exportStmt = target.exportName === 'default'
70
71
  ? `export { default } from ${JSON.stringify(target.file)};\n`
71
72
  : `export { ${target.exportName} as default } from ${JSON.stringify(target.file)};\n`
72
- writeEntry(entryPath, exportStmt)
73
+ writeEntry(entryPath, exportStmt + domExports)
73
74
  out.entryPoints.push(entryPath)
74
75
  out.islandEntryToKey.set(entryPath, key)
75
76
  }
@@ -72,6 +72,7 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
72
72
  }
73
73
 
74
74
  const siteProp = site !== undefined ? ` site: ${JSON.stringify(site)},` : ''
75
+ const healthPath = `${assetPrefix.replace(/\/$/, '')}/health`
75
76
  const code = [
76
77
  ...imports,
77
78
  `const manifest = ${JSON.stringify(manifest)};`,
@@ -83,7 +84,7 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
83
84
  `const port = Number(process.env.PORT || prunelleConfig.port || 3000);`,
84
85
  `const hostname = process.env.HOST || undefined;`,
85
86
  `const formatHost = (h: string) => h.includes(':') && !h.startsWith('[') ? \`[\${h}]\` : h;`,
86
- `if (Bun.argv.includes('--health')) { const rawHost = !hostname || hostname === '0.0.0.0' || hostname === '::' ? '127.0.0.1' : hostname; const r = await fetch(\`http://\${formatHost(rawHost)}:\${port}/\`).catch(() => null); process.exit(r && r.status < 500 ? 0 : 1); }`,
87
+ `if (Bun.argv.includes('--health')) { const rawHost = !hostname || hostname === '0.0.0.0' || hostname === '::' ? '127.0.0.1' : hostname; const r = await fetch(\`http://\${formatHost(rawHost)}:\${port}\${${JSON.stringify(healthPath)}}\`).catch(() => null); process.exit(r && r.ok ? 0 : 1); }`,
87
88
  `const app = await createApp({ assetPrefix: ${JSON.stringify(assetPrefix)},${siteProp} manifest, assets, publicAssets, publicEtags, prerenderedFiles, prerenderedEtags });`,
88
89
  `const server = app.serve(port, hostname);`,
89
90
  `handleSignals(app, server);`,
@@ -12,6 +12,7 @@ import type { BuildManifest } from './manifest'
12
12
  import type { PublicFiles } from './plugin-host'
13
13
  import { copyFileSync, existsSync, mkdirSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
14
14
  import { basename, dirname, join, relative, resolve } from 'node:path'
15
+ import { checkAppForms } from '../cli/check-forms'
15
16
  import { collectProjectComplianceWarnings, shouldEmitWarning } from '../compiler/compliance'
16
17
  import { formatCodeFrame, formatDiagnostic, formatLoc } from '../compiler/shared'
17
18
  import { createAppContext, loadConfig, resolvePlugins, runWithAppContext } from '../plugins/index'
@@ -31,12 +32,13 @@ import { prerender } from './prerender'
31
32
  import { analyzeBundleWeights, checkJsBudget, formatBundleReport, formatBundleReportJson, islandOrigins } from './report'
32
33
  import { SERVER_ENTRY_FILE, serverEntrySource } from './server-entry'
33
34
  import { PRUNELLE_SRC_ROOT, resolvePrunelleSpecifier } from './resolve'
34
- import { assertNoRouteConflicts, fileToRoutePath, hasRouteHandlerExport, missingPathsProblem, normalizeRoutePattern, routeExportProblem, routeFileProblem, SPECIAL_ROUTE_FILES } from './routes'
35
+ import { assertNoRouteConflicts, discoverRouteMatchers, fileToRoutePath, hasRouteHandlerExport, missingPathsProblem, normalizeRoutePattern, routeExportProblem, routeFileProblem, SPECIAL_ROUTE_FILES } from './routes'
35
36
  import { exportStatic } from './static'
37
+ import { findUnknownStatusPages } from './status-pages'
36
38
 
37
39
  export type { BuildCache } from './graph'
38
40
  export { createBuildCache } from './graph'
39
- export type { ActionManifestEntry, BuildManifest, RouteManifestEntry } from './manifest'
41
+ export type { ActionManifestEntry, BuildManifest, RouteManifestEntry, StatusPageKind, StatusPageManifestEntry } from './manifest'
40
42
  export { analyzeBundleWeights, checkJsBudget, formatBundleReport, formatBundleReportJson } from './report'
41
43
  export type { BundleReport, RouteBundleMetrics, RouteIsland } from './report'
42
44
  export { resolvePrunelleSpecifier } from './resolve'
@@ -281,6 +283,55 @@ function refreshCacheWatches(cache: BuildCache, graph: ModuleGraph, extraFiles:
281
283
  }
282
284
  }
283
285
 
286
+ function validateRoutesAndMatchers(root: string, routesDir: string, allRouteFiles: readonly string[], specialFiles: readonly string[], candidateFiles: readonly string[], graph: ModuleGraph): { pageFiles: string[], customMatchers: Map<string, string> } {
287
+ const unknownStatus = findUnknownStatusPages(root, allRouteFiles)
288
+ if (unknownStatus.length > 0)
289
+ throw new Error(`prunelle build: ${unknownStatus[0]!.message}`)
290
+ const routesRel = relPosix(root, routesDir)
291
+ for (const f of [...specialFiles, ...candidateFiles]) {
292
+ const analysis = graph.analyses.get(f)!
293
+ const problem = routeFileProblem(analysis, relPosix(root, f), routesRel) ?? routeExportProblem(analysis, relPosix(root, f))
294
+ if (problem !== undefined)
295
+ throw new Error(`prunelle build: ${problem}`)
296
+ }
297
+ // A file exporting only actions stays in routes/ for its folder's middleware.
298
+ const pageFiles = candidateFiles.filter(f => hasRouteHandlerExport(graph.analyses.get(f)!))
299
+ assertNoRouteConflicts(root, routesDir, pageFiles)
300
+ const { customFiles, problems } = discoverRouteMatchers({
301
+ root,
302
+ routesDir,
303
+ routeFiles: [...specialFiles, ...pageFiles],
304
+ loadAnalysis: file => graph.load(file),
305
+ })
306
+ if (problems.length > 0)
307
+ throw new Error(`prunelle build: ${problems[0]!.message}`)
308
+ return { pageFiles, customMatchers: customFiles }
309
+ }
310
+
311
+ function collectActionsByFile(graph: ModuleGraph, root: string, assetPrefix: string): ActionsByFile {
312
+ const actionsByFile: ActionsByFile = new Map()
313
+ for (const [file, analysis] of graph.analyses) {
314
+ if (analysis.exportedActions.length > 0) {
315
+ const rel = relPosix(root, file)
316
+ actionsByFile.set(file, analysis.exportedActions.map(exportName => ({
317
+ exportName,
318
+ url: `${assetPrefix}/action/${actionHash(rel, exportName)}`,
319
+ })))
320
+ }
321
+ }
322
+ return actionsByFile
323
+ }
324
+
325
+ async function validateAppForms(root: string, routesDir: string, routeFiles: readonly string[], graph: ModuleGraph, isDev: boolean): Promise<void> {
326
+ const formCheck = await checkAppForms({ root, routesDir, routeFiles, graph })
327
+ if (formCheck.errors.length > 0)
328
+ throw new Error(formCheck.errors.join('\n'))
329
+ if (!isDev) {
330
+ for (const warning of formCheck.warnings)
331
+ console.warn(warning)
332
+ }
333
+ }
334
+
284
335
  async function runBuild(run: BuildRun): Promise<BuildManifest> {
285
336
  const { options, root, plugins, routesDir, outDir, assetPrefix, isDev, publicFiles } = run
286
337
  const clientDir = join(outDir, 'client')
@@ -306,30 +357,12 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
306
357
  graph.load(f)
307
358
  emitBuildWarnings(run, graph, allRouteFiles)
308
359
 
309
- const routesRel = relPosix(root, routesDir)
310
- for (const f of [...specialFiles, ...candidateFiles]) {
311
- const analysis = graph.analyses.get(f)!
312
- const problem = routeFileProblem(analysis, relPosix(root, f), routesRel) ?? routeExportProblem(analysis, relPosix(root, f))
313
- if (problem !== undefined)
314
- throw new Error(`prunelle build: ${problem}`)
315
- }
316
- // A file exporting only actions stays in routes/ for its folder's middleware.
317
- const pageFiles = candidateFiles.filter(f => hasRouteHandlerExport(graph.analyses.get(f)!))
318
- assertNoRouteConflicts(root, routesDir, pageFiles)
319
-
320
- // Server actions, keyed by source file
321
- const actionsByFile: ActionsByFile = new Map()
322
- for (const [file, analysis] of graph.analyses) {
323
- if (analysis.exportedActions.length > 0) {
324
- const rel = relPosix(root, file)
325
- actionsByFile.set(file, analysis.exportedActions.map(exportName => ({
326
- exportName,
327
- url: `${assetPrefix}/action/${actionHash(rel, exportName)}`,
328
- })))
329
- }
330
- }
360
+ const { pageFiles, customMatchers } = validateRoutesAndMatchers(root, routesDir, allRouteFiles, specialFiles, candidateFiles, graph)
361
+ const customMatcherFiles = [...new Set(customMatchers.values())]
331
362
 
363
+ const actionsByFile = collectActionsByFile(graph, root, assetPrefix)
332
364
  const islands = planCheckedIslands(root, routesDir, graph, pageFiles, specialFiles, isStatic)
365
+ await validateAppForms(root, routesDir, allRouteFiles, graph, isDev)
333
366
 
334
367
  mkdirSync(clientDir, { recursive: true })
335
368
  mkdirSync(serverDir, { recursive: true })
@@ -342,14 +375,15 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
342
375
  const routeEntryFiles = new Set([...specialFiles, ...pageFiles])
343
376
  const standaloneActionFiles = [...actionsByFile.keys()].filter(f => !routeEntryFiles.has(f))
344
377
  // `_entry.js` imports all of these; each stays an entrypoint so its code lands in a content-named chunk that `prunelle dev` keeps loaded while it is unchanged.
345
- const serverEntries = [...specialFiles, ...pageFiles, ...standaloneActionFiles, ...(hasConfigFile ? [configSrc] : [])]
346
- const serverRoot = standaloneActionFiles.length > 0 || hasConfigFile ? root : routesDir
378
+ const bundledModules = [...specialFiles, ...pageFiles, ...standaloneActionFiles, ...customMatcherFiles]
379
+ const serverEntries = [...bundledModules, ...(hasConfigFile ? [configSrc] : [])]
380
+ const serverRoot = standaloneActionFiles.length > 0 || customMatcherFiles.length > 0 || hasConfigFile ? root : routesDir
347
381
  const toOutRel = (srcFile: string): string =>
348
382
  relPosix(outDir, join(serverDir, relative(serverRoot, srcFile).replace(/\.(tsx|ts)$/, '.js')))
349
383
  const serverEntry = {
350
384
  file: join(serverRoot, SERVER_ENTRY_FILE),
351
385
  source: serverEntrySource({
352
- modules: [...specialFiles, ...pageFiles, ...standaloneActionFiles].map(file => ({ file, key: toOutRel(file), source: relPosix(root, file) })),
386
+ modules: bundledModules.map(file => ({ file, key: toOutRel(file), source: relPosix(root, file) })),
353
387
  config: hasConfigFile ? { file: configSrc, source: relPosix(root, configSrc) } : undefined,
354
388
  assembler: join(PRUNELLE_SRC_ROOT, 'server/app-entry.ts'),
355
389
  }),
@@ -387,7 +421,7 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
387
421
  }
388
422
  const builtClientAssets = new Set(assets)
389
423
 
390
- const { routes, globalStyles } = buildRouteEntries({
424
+ const { routes, statusPages, globalStyles } = buildRouteEntries({
391
425
  graph,
392
426
  islands,
393
427
  islandChunks: client.islandChunks,
@@ -395,10 +429,14 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
395
429
  islandCssUrl: client.islandCssUrl,
396
430
  routesDir,
397
431
  pageFiles,
432
+ specialFiles,
398
433
  pluginCssFiles,
399
434
  isStatic,
400
435
  toOutRel,
401
436
  })
437
+ const paramMatchers = customMatchers.size > 0
438
+ ? Object.fromEntries([...customMatchers.entries()].map(([name, file]) => [name, toOutRel(file)]))
439
+ : undefined
402
440
 
403
441
  // public/ files are listed in the manifest and copied into outDir/public (`prunelle dev` serves public/ directly instead)
404
442
  const outPublicDir = join(outDir, 'public')
@@ -438,10 +476,11 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
438
476
  globalStyles,
439
477
  ...(host.headTags.length > 0 ? { headTags: host.headTags } : {}),
440
478
  routes,
441
-
442
479
  ...(hasRootLayout ? { rootLayoutFile: toOutRel(rootLayoutSrc) } : {}),
443
480
  errorFile: hasErrorFile ? toOutRel(errorSrc) : undefined,
444
481
  notFoundFile: hasNotFoundFile ? toOutRel(notFoundSrc) : undefined,
482
+ ...(statusPages.length > 0 ? { statusPages } : {}),
483
+ ...(paramMatchers !== undefined ? { paramMatchers } : {}),
445
484
  actions: buildActionEntries(actionsByFile, routesDir, toOutRel),
446
485
  islands: Object.fromEntries(client.islandChunks),
447
486
  assets,
@@ -2,10 +2,14 @@
2
2
 
3
3
  import type { ModuleGraph } from './graph'
4
4
  import type { IslandPlan } from './islands'
5
+ import type { StatusPageManifestEntry } from './status-pages'
5
6
  import { join } from 'node:path'
6
7
  import { isInside } from './is-inside'
7
8
  import { islandKey } from './islands'
8
9
  import { ancestorFiles, fileToRoutePath, MIDDLEWARE_NAMES } from './routes'
10
+ import { buildStatusPageEntries } from './status-pages'
11
+
12
+ export type { StatusPageKind, StatusPageManifestEntry } from './status-pages'
9
13
 
10
14
  const REGION_SOURCES = new Set(['prunelle', 'prunelle/internal/ssr'])
11
15
 
@@ -63,6 +67,10 @@ export interface BuildManifest {
63
67
  rootLayoutFile?: string | undefined
64
68
  errorFile?: string | undefined
65
69
  notFoundFile?: string | undefined
70
+ /** Discovered status/error pages (`_401`, `_403`, `_404`, `_429`, `_503`, `_error`), root and nested. */
71
+ statusPages?: StatusPageManifestEntry[] | undefined
72
+ /** Custom app param matchers (`src/params/<name>.ts`), mapping matcher name to compiled module key. */
73
+ paramMatchers?: Record<string, string> | undefined
66
74
  actions: ActionManifestEntry[]
67
75
  islands: Record<string, string>
68
76
  assets: string[]
@@ -185,6 +193,7 @@ function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islandChunks
185
193
 
186
194
  export interface RouteEntries {
187
195
  routes: RouteManifestEntry[]
196
+ statusPages: StatusPageManifestEntry[]
188
197
  /** Stylesheets of every page: the plugins' CSS, then the root layout's. */
189
198
  globalStyles: string[]
190
199
  /** The plugins' CSS alone. */
@@ -199,6 +208,7 @@ export function buildRouteEntries(options: {
199
208
  islandCssUrl: Map<string, string>
200
209
  routesDir: string
201
210
  pageFiles: string[]
211
+ specialFiles?: readonly string[] | undefined
202
212
  pluginCssFiles: string[]
203
213
  isStatic: boolean
204
214
  /** Maps a source file to its compiled module, relative to the out dir. */
@@ -249,7 +259,14 @@ export function buildRouteEntries(options: {
249
259
  prerender: analysis?.hasPrerender || options.isStatic,
250
260
  }
251
261
  })
252
- return { routes, globalStyles, globalPluginStyles }
262
+ const statusPages = buildStatusPageEntries({
263
+ routesDir,
264
+ specialFiles: options.specialFiles ?? [],
265
+ globalPluginStyles,
266
+ reachOf,
267
+ toOutRel,
268
+ })
269
+ return { routes, statusPages, globalStyles, globalPluginStyles }
253
270
  }
254
271
 
255
272
  export function buildActionEntries(actionsByFile: Map<string, { exportName: string, url: string }[]>, routesDir: string, toOutRel: (srcFile: string) => string): ActionManifestEntry[] {
@@ -16,9 +16,9 @@ export function assertOwnOutDir(root: string, outDir: string, assetPrefix: strin
16
16
  const names = new Set(readdirSync(outDir))
17
17
  if (names.size === 0 || names.has(OUTPUT_MARKER))
18
18
  return
19
- // A build made before the marker existed: a server build's manifest beside its server/ folder, or a static export's asset folder.
19
+ // A build made before the marker existed: a server build's manifest beside its server/ folder, or a static export's asset folder (including a kay v2 export's `_kay/`).
20
20
  const assetDir = assetPrefix.replace(LEADING_SLASH_RE, '').split('/')[0] ?? ''
21
- if ((names.has('manifest.json') && names.has('server')) || (assetDir !== '' && names.has(assetDir)))
21
+ if ((names.has('manifest.json') && names.has('server')) || (assetDir !== '' && names.has(assetDir)) || names.has('_kay'))
22
22
  return
23
23
  throw new Error(`prunelle build: refusing to replace "${relPosix(root, outDir)}": it holds files prunelle did not build. Delete it, or set \`outDir\` in prunelle.config.ts to a folder of its own.`)
24
24
  }
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'
4
4
  import { availableParallelism } from 'node:os'
5
- import { dirname, extname, join } from 'node:path'
5
+ import { basename, dirname, extname, join } from 'node:path'
6
6
  import { promisify } from 'node:util'
7
7
  import { brotliCompress, brotliCompressSync, constants as zlibConstants } from 'node:zlib'
8
8
  import { getAppContext } from '../plugins/context'
@@ -46,9 +46,22 @@ function readEntry(file: string): Buffer | undefined {
46
46
  }
47
47
  }
48
48
 
49
+ /** Writes a self-ignoring `.gitignore` inside `.prunelle-cache/` so git never lists cached files as untracked (#39). */
50
+ export function ensureCacheGitignore(cacheRoot: string): void {
51
+ const file = join(cacheRoot, '.gitignore')
52
+ if (existsSync(file))
53
+ return
54
+ mkdirSync(cacheRoot, { recursive: true })
55
+ writeFileSync(file, '*\n')
56
+ }
57
+
49
58
  // Renamed into place, so a build running beside this one never reads half an entry.
50
59
  function writeEntry(file: string, packed: Uint8Array): void {
51
- mkdirSync(dirname(file), { recursive: true })
60
+ const dir = dirname(file)
61
+ mkdirSync(dir, { recursive: true })
62
+ const parent = dirname(dir)
63
+ if (basename(parent) === '.prunelle-cache')
64
+ ensureCacheGitignore(parent)
52
65
  const tmp = `${file}.${process.pid}-${tmpCount++}.tmp`
53
66
  writeFileSync(tmp, packed)
54
67
  renameSync(tmp, file)
@@ -5,7 +5,7 @@ import type { RouteManifestEntry } from './manifest'
5
5
  import { mkdirSync, writeFileSync } from 'node:fs'
6
6
  import { dirname, extname, resolve } from 'node:path'
7
7
  import { prerenderOrigin } from '../server/prerendered'
8
- import { inlineStyleHashes } from '../server/security'
8
+ import { inlineStyleHashes, injectMetaCsp } from '../server/security'
9
9
  import { relPosix } from './files'
10
10
  import { runPluginHook } from './plugin-host'
11
11
  import { assertPathUrls } from './routes'
@@ -132,7 +132,7 @@ export async function prerender(options: PrerenderOptions) {
132
132
  mkdirSync(dirname(absOut), { recursive: true })
133
133
  if ((ct ?? '').toLowerCase().includes('text/html')) {
134
134
  const html = await res.text()
135
- writeFileSync(absOut, html)
135
+ writeFileSync(absOut, isStatic ? injectMetaCsp(html, res.headers.get('content-security-policy')) : html)
136
136
  const hashes = inlineStyleHashes(html)
137
137
  if (hashes.length > 0)
138
138
  styleHashes[u] = hashes