prunelle 0.1.1 → 0.1.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 +7 -7
- package/package.json +1 -1
- package/src/build/client-entries.ts +3 -2
- package/src/build/output.ts +2 -2
- package/src/build/precompress.ts +15 -2
- package/src/build/prerender.ts +2 -2
- package/src/build/static.ts +3 -2
- package/src/cli/commands.ts +5 -3
- package/src/cli/upgrade-names.ts +73 -13
- package/src/cli/upgrade.ts +137 -16
- package/src/dom/island.ts +5 -5
- package/src/plugins/types.ts +5 -0
- package/src/server/errors.ts +2 -2
- package/src/server/index.ts +8 -2
- package/src/server/plugin-host.ts +34 -13
- package/src/server/public.ts +2 -2
- package/src/server/router.ts +14 -6
- package/src/server/security.ts +171 -22
- package/src/test/browser.ts +6 -0
- package/src/test/index.ts +9 -3
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 & 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
|
|
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
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`).
|
|
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), 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
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
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
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`).
|
|
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; 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`). `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
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).
|
|
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
|
|
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
|
|
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:`; `--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, `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)`, `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), `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`.
|
|
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`):
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "prunelle",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.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",
|
|
@@ -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
|
}
|
package/src/build/output.ts
CHANGED
|
@@ -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
|
}
|
package/src/build/precompress.ts
CHANGED
|
@@ -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
|
-
|
|
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)
|
package/src/build/prerender.ts
CHANGED
|
@@ -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
|
package/src/build/static.ts
CHANGED
|
@@ -8,6 +8,7 @@ import { copyFileSync, mkdirSync, writeFileSync } from 'node:fs'
|
|
|
8
8
|
import { dirname, join, relative } from 'node:path'
|
|
9
9
|
import { resolvePlugins } from '../plugins/index'
|
|
10
10
|
import { createDocumentHooks, createHtmlHeaders } from '../server/document'
|
|
11
|
+
import { injectMetaCsp } from '../server/security'
|
|
11
12
|
import { createNavigation } from '../ssr/navigation'
|
|
12
13
|
import { createFallbackPages } from '../server/errors'
|
|
13
14
|
import { walkAllFiles } from './files'
|
|
@@ -77,12 +78,12 @@ async function renderStaticNotFound(options: StaticExportOptions): Promise<strin
|
|
|
77
78
|
const res = await buildNotFoundResponse(url, new Request(url))
|
|
78
79
|
if (renderError !== undefined || res.status >= 500)
|
|
79
80
|
throw pageFailure(`prunelle build: the _404 page of the static export answered HTTP ${res.status}`, renderError)
|
|
80
|
-
return await res.text()
|
|
81
|
+
return injectMetaCsp(await res.text(), res.headers.get('content-security-policy'))
|
|
81
82
|
}
|
|
82
83
|
const res = await options.app!.handle(new Request(`${origin}/__pru_404__`))
|
|
83
84
|
if (res.status >= 500)
|
|
84
85
|
throw pageFailure(`prunelle build: the _404 page of the static export answered HTTP ${res.status}`, undefined)
|
|
85
|
-
return await res.text()
|
|
86
|
+
return injectMetaCsp(await res.text(), res.headers.get('content-security-policy'))
|
|
86
87
|
}
|
|
87
88
|
|
|
88
89
|
export async function exportStatic(options: StaticExportOptions): Promise<void> {
|
package/src/cli/commands.ts
CHANGED
|
@@ -123,13 +123,15 @@ function upgradeCommand(cwd: string): Commands[string] {
|
|
|
123
123
|
const res = upgradeProject(root)
|
|
124
124
|
for (const file of res.changed)
|
|
125
125
|
console.log(` ${file}`)
|
|
126
|
-
console.log(`prunelle upgrade rewrote ${res.changed.length}
|
|
127
|
-
|
|
126
|
+
console.log(`prunelle upgrade rewrote ${res.changed.length} file${res.changed.length === 1 ? '' : 's'}`)
|
|
127
|
+
// The dependencies moved: the first run for this app, which renames its cookies; a later run only fixes what an older prunelle left.
|
|
128
|
+
const moved = res.changed.some(file => file === 'package.json' || file.endsWith('/package.json'))
|
|
129
|
+
if (moved && values['no-install'] !== true) {
|
|
128
130
|
const install = Bun.spawnSync(['bun', 'install'], { cwd: root, stdout: 'inherit', stderr: 'inherit' })
|
|
129
131
|
if (install.exitCode !== 0)
|
|
130
132
|
return 1
|
|
131
133
|
}
|
|
132
|
-
if (
|
|
134
|
+
if (moved)
|
|
133
135
|
console.log('Signed-in users sign in again and visitors answer the cookie banner again: prunelle names its cookies pru_session and pru_consent.')
|
|
134
136
|
for (const line of res.manual)
|
|
135
137
|
console.error(line)
|
package/src/cli/upgrade-names.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { walk } from '../compiler/ast'
|
|
|
6
6
|
import { SourceEditor } from '../compiler/patch'
|
|
7
7
|
|
|
8
8
|
const KAY_SOURCE_RE = /^@kayjs\//
|
|
9
|
+
const REF_TYPES_RE = /^(\s*\/\/\/\s*<reference\s+types=)(["'])([^"']+)\2(\s*\/>)/gm
|
|
9
10
|
|
|
10
11
|
type Import = Extract<AstNode, { type: 'ImportDeclaration' }>
|
|
11
12
|
type Specifier = Extract<AstNode, { type: 'ImportSpecifier' }>
|
|
@@ -25,17 +26,61 @@ export function prunelleName(name: string): string | undefined {
|
|
|
25
26
|
}
|
|
26
27
|
|
|
27
28
|
const nameOf = (node: { type: string, name?: string, value?: unknown }): string => node.type === 'Identifier' ? node.name! : String(node.value)
|
|
28
|
-
const fromKay = (source: { value: unknown } | null | undefined): boolean => typeof source?.value === 'string' && KAY_SOURCE_RE.test(source.value)
|
|
29
29
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
30
|
+
function resolveAlias(spec: string, aliases?: ReadonlyMap<string, string>): string | undefined {
|
|
31
|
+
if (aliases === undefined || aliases.size === 0)
|
|
32
|
+
return undefined
|
|
33
|
+
for (const [alias, target] of aliases) {
|
|
34
|
+
if (spec === alias)
|
|
35
|
+
return target
|
|
36
|
+
if (spec.startsWith(`${alias}/`))
|
|
37
|
+
return `${target}${spec.slice(alias.length)}`
|
|
38
|
+
}
|
|
39
|
+
return undefined
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function hasKaySourceHint(code: string, aliases?: ReadonlyMap<string, string>): boolean {
|
|
43
|
+
if (code.includes('@kayjs/'))
|
|
44
|
+
return true
|
|
45
|
+
if (aliases === undefined || aliases.size === 0)
|
|
46
|
+
return false
|
|
47
|
+
for (const alias of aliases.keys()) {
|
|
48
|
+
if (code.includes(alias))
|
|
49
|
+
return true
|
|
50
|
+
}
|
|
51
|
+
return false
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function rewriteTripleSlash(code: string, aliases?: ReadonlyMap<string, string>): string {
|
|
55
|
+
if (aliases === undefined || aliases.size === 0 || !code.includes('<reference'))
|
|
56
|
+
return code
|
|
57
|
+
return code.replace(REF_TYPES_RE, (full, pre: string, quote: string, spec: string, post: string) => {
|
|
58
|
+
const target = resolveAlias(spec, aliases)
|
|
59
|
+
return target === undefined ? full : `${pre}${quote}${target}${quote}${post}`
|
|
60
|
+
})
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Rewrites the names `code` imports from `@kayjs/*` (and any npm aliases in `aliases`), plus alias module specifiers, run before `@kayjs/*` specifiers are renamed. */
|
|
64
|
+
export function renameKayNames(file: string, code: string, aliases?: ReadonlyMap<string, string>): string {
|
|
65
|
+
if (!hasKaySourceHint(code, aliases))
|
|
33
66
|
return code
|
|
34
67
|
const program = parseTsx(file, code)
|
|
35
68
|
const editor = new SourceEditor(code)
|
|
36
69
|
const bindings = new Map<string, Binding>()
|
|
37
70
|
const namespaces = new Set<string>()
|
|
38
71
|
const skipped = new Set<number>()
|
|
72
|
+
const patchedSources = new Set<number>()
|
|
73
|
+
const fromKay = (source: { value?: unknown } | null | undefined): boolean =>
|
|
74
|
+
typeof source?.value === 'string' && (KAY_SOURCE_RE.test(source.value) || resolveAlias(source.value, aliases) !== undefined)
|
|
75
|
+
const rewriteSource = (source: { start: number, end: number, value?: unknown } | null | undefined): void => {
|
|
76
|
+
if (source === null || source === undefined || typeof source.value !== 'string' || patchedSources.has(source.start))
|
|
77
|
+
return
|
|
78
|
+
const target = resolveAlias(source.value, aliases)
|
|
79
|
+
if (target === undefined)
|
|
80
|
+
return
|
|
81
|
+
patchedSources.add(source.start)
|
|
82
|
+
editor.replace(source.start + 1, source.end - 1, target)
|
|
83
|
+
}
|
|
39
84
|
const rename = (node: AstNode): void => {
|
|
40
85
|
const renamed = node.type === 'Identifier' || node.type === 'JSXIdentifier' ? prunelleName(node.name) : undefined
|
|
41
86
|
if (renamed !== undefined)
|
|
@@ -45,8 +90,11 @@ export function renameKayNames(file: string, code: string): string {
|
|
|
45
90
|
for (const stmt of program.body) {
|
|
46
91
|
if (stmt.type === 'ImportDeclaration' && fromKay(stmt.source))
|
|
47
92
|
collectImport(stmt, bindings, namespaces)
|
|
48
|
-
if (stmt.type === 'TSModuleDeclaration' && stmt.id.type === 'Literal'
|
|
49
|
-
|
|
93
|
+
if (stmt.type === 'TSModuleDeclaration' && stmt.id.type === 'Literal') {
|
|
94
|
+
rewriteSource(stmt.id)
|
|
95
|
+
if (fromKay(stmt.id))
|
|
96
|
+
renameAugmented(stmt.body, rename)
|
|
97
|
+
}
|
|
50
98
|
}
|
|
51
99
|
|
|
52
100
|
const names = new Set<string>()
|
|
@@ -56,13 +104,22 @@ export function renameKayNames(file: string, code: string): string {
|
|
|
56
104
|
binding.pinned = true
|
|
57
105
|
}
|
|
58
106
|
walk(program.body, (node) => {
|
|
59
|
-
if (node.type === 'ImportDeclaration')
|
|
107
|
+
if (node.type === 'ImportDeclaration') {
|
|
108
|
+
rewriteSource(node.source)
|
|
60
109
|
return false
|
|
110
|
+
}
|
|
61
111
|
if (node.type === 'ExportNamedDeclaration' && node.source !== null) {
|
|
112
|
+
rewriteSource(node.source)
|
|
62
113
|
if (fromKay(node.source))
|
|
63
114
|
reexport(node.specifiers, editor)
|
|
64
115
|
return false
|
|
65
116
|
}
|
|
117
|
+
if (node.type === 'ExportAllDeclaration') {
|
|
118
|
+
rewriteSource(node.source)
|
|
119
|
+
return false
|
|
120
|
+
}
|
|
121
|
+
if (node.type === 'ImportExpression' && node.source.type === 'Literal')
|
|
122
|
+
rewriteSource(node.source)
|
|
66
123
|
// Every keyed node (property, method, class field, type member) names its key, which is no reference.
|
|
67
124
|
const keyed = node as AstNode & { key?: AstNode & { type: string, name?: string }, computed?: boolean, shorthand?: boolean }
|
|
68
125
|
if (keyed.key !== undefined && keyed.computed === false) {
|
|
@@ -79,11 +136,14 @@ export function renameKayNames(file: string, code: string): string {
|
|
|
79
136
|
rename(right)
|
|
80
137
|
skipped.add(right.start)
|
|
81
138
|
}
|
|
82
|
-
if (node.type === 'TSImportType'
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
head =
|
|
86
|
-
|
|
139
|
+
if (node.type === 'TSImportType') {
|
|
140
|
+
rewriteSource(node.source)
|
|
141
|
+
if (fromKay(node.source) && node.qualifier !== null) {
|
|
142
|
+
let head: AstNode = node.qualifier
|
|
143
|
+
while (head.type === 'TSQualifiedName')
|
|
144
|
+
head = head.left
|
|
145
|
+
rename(head)
|
|
146
|
+
}
|
|
87
147
|
}
|
|
88
148
|
if (node.type === 'ExportSpecifier')
|
|
89
149
|
pin(nameOf(node.local))
|
|
@@ -109,7 +169,7 @@ export function renameKayNames(file: string, code: string): string {
|
|
|
109
169
|
for (const ref of binding.refs)
|
|
110
170
|
editor.replace(ref.start, ref.end, binding.renamed)
|
|
111
171
|
}
|
|
112
|
-
return editor.toString()
|
|
172
|
+
return rewriteTripleSlash(editor.toString(), aliases)
|
|
113
173
|
}
|
|
114
174
|
|
|
115
175
|
function collectImport(stmt: Import, bindings: Map<string, Binding>, namespaces: Set<string>): void {
|
package/src/cli/upgrade.ts
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
// `prunelle upgrade`: moves an app written for kay v2 (`@kayjs/kay`) onto prunelle: its dependencies, config file, imports, the names it imports and the names the browser receives.
|
|
2
2
|
|
|
3
|
+
import type { Dirent } from 'node:fs'
|
|
3
4
|
import { existsSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
|
4
|
-
import { dirname, join } from 'node:path'
|
|
5
|
+
import { dirname, join, resolve } from 'node:path'
|
|
5
6
|
import pkg from '../../package.json' with { type: 'json' }
|
|
6
7
|
import { isNotSourceDir, relPosix } from '../build/files'
|
|
7
8
|
import { resolvePrunelleSpecifier } from '../build/resolve'
|
|
8
9
|
import { parseTsx } from '../compiler/analyze'
|
|
10
|
+
import { walk } from '../compiler/ast'
|
|
9
11
|
import { renameKayNames } from './upgrade-names'
|
|
10
12
|
|
|
11
13
|
export interface UpgradeResult {
|
|
@@ -17,11 +19,13 @@ export interface UpgradeResult {
|
|
|
17
19
|
|
|
18
20
|
// The specifiers and file names every kind of file may name.
|
|
19
21
|
const PATH_RULES: [RegExp, string][] = [
|
|
22
|
+
// A kay v2 version written beside a package, as notes do, names no prunelle release: the current one replaces it.
|
|
23
|
+
[/(@kayjs\/[\w-]+)@[\^~]?2\.\d+\.\d+[\w.-]*/g, `$1@^${pkg.version}`],
|
|
20
24
|
[/@kayjs\/kay(?![\w-])/g, 'prunelle'],
|
|
21
25
|
[/@kayjs\//g, '@prunellejs/'],
|
|
22
26
|
[/\.kay-(cache|dev)\b/g, '.prunelle-$1'],
|
|
23
27
|
[/\bkay\.config\b/g, 'prunelle.config'],
|
|
24
|
-
[/\bkay v2\b/
|
|
28
|
+
[/\bkay v2\b/gi, 'prunelle'],
|
|
25
29
|
]
|
|
26
30
|
// The names kay sent the browser, as app code and styles may spell them.
|
|
27
31
|
const WIRE_RULES: [RegExp, string][] = [
|
|
@@ -37,19 +41,31 @@ const CLI_RULE: [RegExp, string] = [/(?<![\w.@/-])kay(?![\w.:/-])/g, 'prunelle']
|
|
|
37
41
|
|
|
38
42
|
const SOURCE_FILE_RE = /\.(?:tsx?|mts)$/
|
|
39
43
|
const STYLE_OR_SCRIPT_RE = /\.(?:css|js|mjs)$/
|
|
44
|
+
const TSCONFIG_FILE_RE = /^tsconfig(?:\.[\w-]+)?\.json$/
|
|
40
45
|
const CONFIG_FILE_RE = /^(?:tsconfig(?:\.[\w-]+)?\.json|bunfig\.toml|\.gitignore|\.dockerignore)$/
|
|
41
46
|
const BUILD_FILE_RE = /^(?:Dockerfile(?:\.[\w-]+)?|[\w-]+\.Dockerfile|[Jj]ustfile|Makefile|(?:docker-)?compose(?:\.[\w-]+)?\.ya?ml)$/
|
|
47
|
+
// The agent instructions `prunelle new` writes, which name the llms.txt to read and the CLI to run (#42).
|
|
48
|
+
const AGENT_FILE_RE = /^(?:AGENTS|CLAUDE)\.md$/
|
|
42
49
|
const CI_DIRS = ['.forgejo/workflows', '.github/workflows', '.gitea/workflows']
|
|
43
50
|
const CACHE_DIRS = ['.kay-cache', '.kay-dev']
|
|
44
51
|
const PRUNELLE_SOURCE_RE = /^prunelle(\/.*)?$/
|
|
52
|
+
const NPM_KAY_ALIAS_RE = /^npm:(@kayjs\/[\w-]+)(?:@.*)?$/
|
|
53
|
+
const ESCAPE_RE = /[.*+?^${}()|[\]\\]/g
|
|
54
|
+
const GITIGNORE_CACHE_RE = /(?:^|\/)\.prunelle-cache(?:\/|$|\s)/m
|
|
45
55
|
|
|
46
56
|
const apply = (text: string, rules: readonly [RegExp, string][]): string => rules.reduce((out, [re, to]) => out.replace(re, to), text)
|
|
47
57
|
|
|
48
58
|
/** Rewrites the app at `root` in place, and each package its bun workspace lists; installing the renamed dependencies is the caller's job. */
|
|
49
59
|
export function upgradeProject(root: string): UpgradeResult {
|
|
60
|
+
return upgradeDir(root)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function upgradeDir(root: string, inheritedAliases?: ReadonlyMap<string, string>): UpgradeResult {
|
|
50
64
|
const v1 = kayV1Dependency(root)
|
|
51
65
|
if (v1 !== undefined)
|
|
52
66
|
return { changed: [], manual: [`package.json:1: ${v1} is kay v1: prunelle upgrade moves kay v2 apps, so this one is left as it is.`] }
|
|
67
|
+
const aliases = kayAliases(root, inheritedAliases)
|
|
68
|
+
const isApp = hasKayOrPrunelle(root)
|
|
53
69
|
const changed: string[] = []
|
|
54
70
|
const manual: string[] = []
|
|
55
71
|
const write = (file: string, before: string, after: string): void => {
|
|
@@ -63,9 +79,13 @@ export function upgradeProject(root: string): UpgradeResult {
|
|
|
63
79
|
const text = readFileSync(join(root, file), 'utf8')
|
|
64
80
|
if (file === 'package.json')
|
|
65
81
|
write(file, text, upgradePackageJson(text))
|
|
82
|
+
else if (TSCONFIG_FILE_RE.test(file))
|
|
83
|
+
write(file, text, upgradeTsconfig(text, aliases))
|
|
84
|
+
else if (file === '.gitignore')
|
|
85
|
+
write(file, text, upgradeGitignore(text, isApp))
|
|
66
86
|
else if (CONFIG_FILE_RE.test(file))
|
|
67
87
|
write(file, text, apply(text, PATH_RULES))
|
|
68
|
-
else if (BUILD_FILE_RE.test(file))
|
|
88
|
+
else if (BUILD_FILE_RE.test(file) || AGENT_FILE_RE.test(file))
|
|
69
89
|
write(file, text, apply(apply(text, PATH_RULES), [CLI_RULE]))
|
|
70
90
|
}
|
|
71
91
|
for (const dir of CI_DIRS) {
|
|
@@ -77,9 +97,10 @@ export function upgradeProject(root: string): UpgradeResult {
|
|
|
77
97
|
write(file, text, apply(apply(text, PATH_RULES), [CLI_RULE]))
|
|
78
98
|
}
|
|
79
99
|
}
|
|
80
|
-
|
|
100
|
+
const publicDir = configuredPublicDir(root)
|
|
101
|
+
for (const file of sourceFiles(root, publicDir)) {
|
|
81
102
|
const text = readFileSync(join(root, file), 'utf8')
|
|
82
|
-
const renamed = SOURCE_FILE_RE.test(file) ? renameKayNames(file, text) : text
|
|
103
|
+
const renamed = SOURCE_FILE_RE.test(file) ? renameKayNames(file, text, aliases) : text
|
|
83
104
|
const next = apply(apply(renamed, PATH_RULES), WIRE_RULES)
|
|
84
105
|
write(file, text, next)
|
|
85
106
|
if (SOURCE_FILE_RE.test(file) && next !== text)
|
|
@@ -91,8 +112,9 @@ export function upgradeProject(root: string): UpgradeResult {
|
|
|
91
112
|
changed.push(`${dir}/`)
|
|
92
113
|
}
|
|
93
114
|
}
|
|
94
|
-
|
|
95
|
-
|
|
115
|
+
// A member on neither kay nor prunelle, a plain Bun app or a tool, has nothing to move; one already on prunelle may keep names an earlier upgrade missed.
|
|
116
|
+
for (const member of workspaceMembers(root).filter(m => hasKayOrPrunelle(join(root, m)))) {
|
|
117
|
+
const res = upgradeDir(join(root, member), aliases)
|
|
96
118
|
changed.push(...res.changed.map(file => `${member}/${file}`))
|
|
97
119
|
manual.push(...res.manual.map(line => `${member}/${line}`))
|
|
98
120
|
}
|
|
@@ -102,6 +124,83 @@ export function upgradeProject(root: string): UpgradeResult {
|
|
|
102
124
|
const DEP_FIELDS = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']
|
|
103
125
|
const V1_RANGE_RE = /^[~^>=\s]*1\./
|
|
104
126
|
|
|
127
|
+
const KAY_OR_PRUNELLE_RE = /^(?:npm:)?(?:@kayjs\/|prunelle(?:@|$)|@prunellejs\/)/
|
|
128
|
+
|
|
129
|
+
function hasKayOrPrunelle(root: string): boolean {
|
|
130
|
+
if (!existsSync(join(root, 'package.json')))
|
|
131
|
+
return false
|
|
132
|
+
const json = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as Record<string, Record<string, string> | undefined>
|
|
133
|
+
return DEP_FIELDS.some(field => Object.entries(json[field] ?? {}).some(([name, range]) => KAY_OR_PRUNELLE_RE.test(name) || KAY_OR_PRUNELLE_RE.test(range)))
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function kayTargetPackage(name: string, version: string): string | undefined {
|
|
137
|
+
if (name.startsWith('@kayjs/'))
|
|
138
|
+
return apply(name, PATH_RULES)
|
|
139
|
+
const match = NPM_KAY_ALIAS_RE.exec(version)
|
|
140
|
+
return match === null ? undefined : apply(match[1]!, PATH_RULES)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function kayAliases(root: string, inherited?: ReadonlyMap<string, string>): Map<string, string> {
|
|
144
|
+
const aliases = new Map<string, string>(inherited)
|
|
145
|
+
if (!existsSync(join(root, 'package.json')))
|
|
146
|
+
return aliases
|
|
147
|
+
const json = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as Record<string, Record<string, string> | undefined>
|
|
148
|
+
for (const field of DEP_FIELDS) {
|
|
149
|
+
for (const [name, version] of Object.entries(json[field] ?? {})) {
|
|
150
|
+
if (name.startsWith('@kayjs/'))
|
|
151
|
+
continue
|
|
152
|
+
const match = NPM_KAY_ALIAS_RE.exec(version)
|
|
153
|
+
if (match !== null)
|
|
154
|
+
aliases.set(name, apply(match[1]!, PATH_RULES))
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return aliases
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function upgradeTsconfig(text: string, aliases: ReadonlyMap<string, string>): string {
|
|
161
|
+
let out = apply(text, PATH_RULES)
|
|
162
|
+
for (const [alias, target] of aliases) {
|
|
163
|
+
const escaped = alias.replace(ESCAPE_RE, '\\$&')
|
|
164
|
+
if (target === 'prunelle')
|
|
165
|
+
out = out.replace(new RegExp(`("jsxImportSource"\\s*:\\s*")${escaped}(")`, 'g'), `$1${target}$2`)
|
|
166
|
+
out = out.replace(/"types"\s*:\s*\[[^\]]*\]/g, block =>
|
|
167
|
+
block.replace(new RegExp(`"${escaped}((?:/[^"]*)?)"`, 'g'), `"${target}$1"`))
|
|
168
|
+
}
|
|
169
|
+
return out
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function upgradeGitignore(text: string, addCache: boolean): string {
|
|
173
|
+
const next = apply(text, PATH_RULES)
|
|
174
|
+
if (!addCache || GITIGNORE_CACHE_RE.test(next))
|
|
175
|
+
return next
|
|
176
|
+
const eol = next.includes('\r\n') ? '\r\n' : '\n'
|
|
177
|
+
const sep = next === '' || next.endsWith('\n') ? '' : eol
|
|
178
|
+
return `${next}${sep}.prunelle-cache/${eol}`
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Reads `publicDir` statically from prunelle.config.ts (or kay.config.ts) so built scripts in `public/` are left alone (#43).
|
|
182
|
+
function configuredPublicDir(root: string): string {
|
|
183
|
+
const file = existsSync(join(root, 'prunelle.config.ts'))
|
|
184
|
+
? 'prunelle.config.ts'
|
|
185
|
+
: existsSync(join(root, 'kay.config.ts')) ? 'kay.config.ts' : undefined
|
|
186
|
+
if (file === undefined)
|
|
187
|
+
return resolve(root, 'public')
|
|
188
|
+
const program = parseTsx(file, readFileSync(join(root, file), 'utf8'))
|
|
189
|
+
let value: string | undefined
|
|
190
|
+
walk(program.body, (node) => {
|
|
191
|
+
if (value !== undefined)
|
|
192
|
+
return false
|
|
193
|
+
if (node.type === 'Property' && !node.computed && node.key.type === 'Identifier' && node.key.name === 'publicDir') {
|
|
194
|
+
if (node.value.type === 'Literal' && typeof node.value.value === 'string')
|
|
195
|
+
value = node.value.value
|
|
196
|
+
else if (node.value.type === 'TemplateLiteral' && node.value.expressions.length === 0)
|
|
197
|
+
value = node.value.quasis[0]?.value.cooked ?? node.value.quasis[0]?.value.raw
|
|
198
|
+
}
|
|
199
|
+
return true
|
|
200
|
+
})
|
|
201
|
+
return resolve(root, value ?? 'public')
|
|
202
|
+
}
|
|
203
|
+
|
|
105
204
|
// kay's core at a 1.x range, as `@kayjs/kay` or an `npm:@kayjs/kay@` alias: an app of `.kay` files prunelle cannot take.
|
|
106
205
|
function kayV1Dependency(root: string): string | undefined {
|
|
107
206
|
if (!existsSync(join(root, 'package.json')))
|
|
@@ -149,18 +248,33 @@ function rootFiles(root: string): string[] {
|
|
|
149
248
|
return readdirSync(root, { withFileTypes: true }).filter(e => e.isFile()).map(e => e.name).sort()
|
|
150
249
|
}
|
|
151
250
|
|
|
152
|
-
//
|
|
153
|
-
function
|
|
251
|
+
// The entries of `dir`, none for a folder the user cannot read: a container's data, never source they edit.
|
|
252
|
+
function readableEntries(dir: string): Dirent[] {
|
|
253
|
+
try {
|
|
254
|
+
return readdirSync(dir, { withFileTypes: true })
|
|
255
|
+
}
|
|
256
|
+
catch (err) {
|
|
257
|
+
if ((err as NodeJS.ErrnoException).code === 'EACCES' || (err as NodeJS.ErrnoException).code === 'EPERM')
|
|
258
|
+
return []
|
|
259
|
+
throw err
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// A folder holding its own package.json is another package, upgraded on its own; `publicDir` holds built static files left untouched (#43).
|
|
264
|
+
function sourceFiles(root: string, publicDir: string, dir = root, out: string[] = []): string[] {
|
|
154
265
|
if (dir !== root && existsSync(join(dir, 'package.json')))
|
|
155
266
|
return out
|
|
156
|
-
for (const entry of
|
|
267
|
+
for (const entry of readableEntries(dir)) {
|
|
157
268
|
if (isNotSourceDir(entry.name))
|
|
158
269
|
continue
|
|
159
270
|
const path = join(dir, entry.name)
|
|
160
|
-
if (entry.isDirectory())
|
|
161
|
-
|
|
162
|
-
|
|
271
|
+
if (entry.isDirectory()) {
|
|
272
|
+
if (resolve(path) !== publicDir)
|
|
273
|
+
sourceFiles(root, publicDir, path, out)
|
|
274
|
+
}
|
|
275
|
+
else if (SOURCE_FILE_RE.test(entry.name) || STYLE_OR_SCRIPT_RE.test(entry.name)) {
|
|
163
276
|
out.push(relPosix(root, path))
|
|
277
|
+
}
|
|
164
278
|
}
|
|
165
279
|
return out.sort()
|
|
166
280
|
}
|
|
@@ -173,10 +287,17 @@ function upgradePackageJson(text: string): string {
|
|
|
173
287
|
const range = `^${pkg.version}`
|
|
174
288
|
for (const field of DEP_FIELDS) {
|
|
175
289
|
const deps = json[field] as Record<string, string> | undefined
|
|
176
|
-
if (deps === undefined || !Object.
|
|
290
|
+
if (deps === undefined || !Object.entries(deps).some(([name, version]) => kayTargetPackage(name, version) !== undefined))
|
|
177
291
|
continue
|
|
178
|
-
const
|
|
179
|
-
|
|
292
|
+
const next = new Map<string, string>()
|
|
293
|
+
for (const [name, version] of Object.entries(deps)) {
|
|
294
|
+
const target = kayTargetPackage(name, version)
|
|
295
|
+
if (target !== undefined)
|
|
296
|
+
next.set(target, range)
|
|
297
|
+
else if (!next.has(name))
|
|
298
|
+
next.set(name, version)
|
|
299
|
+
}
|
|
300
|
+
json[field] = Object.fromEntries([...next.entries()].sort(([a], [b]) => a.localeCompare(b)))
|
|
180
301
|
}
|
|
181
302
|
const scripts = json.scripts as Record<string, string> | undefined
|
|
182
303
|
if (scripts !== undefined)
|
package/src/dom/island.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
// Native <pru-island> Custom Element: the build defines which strategies an app uses, so the loader drops the code of the others.
|
|
2
2
|
|
|
3
|
-
import { hydrate, mount } from './index'
|
|
4
|
-
|
|
3
|
+
import type { hydrate, mount } from './index'
|
|
5
4
|
|
|
6
5
|
declare const PRUNELLE_VISIBLE: boolean | undefined
|
|
7
6
|
declare const PRUNELLE_IDLE: boolean | undefined
|
|
@@ -14,7 +13,8 @@ declare const PRUNELLE_REVIVE: string | undefined
|
|
|
14
13
|
// Only props holding a Date, Map, Set or another tagged value load the revivers: plain JSON parses with no extra file.
|
|
15
14
|
const reviver = (): Promise<typeof import('./revive')> => typeof PRUNELLE_REVIVE === 'undefined' ? import('./revive') : import(PRUNELLE_REVIVE)
|
|
16
15
|
|
|
17
|
-
|
|
16
|
+
// An island chunk also re-exports the DOM runtime it imports (`writeClientEntries`), `mount` only in an app with a client-only island.
|
|
17
|
+
type IslandModule = { default: (props: Record<string, unknown>) => Node | DocumentFragment | null, hydrate: typeof hydrate, mount?: typeof mount }
|
|
18
18
|
|
|
19
19
|
/** Finds this island's own `<script type="application/json" data-pru-props>` direct child. */
|
|
20
20
|
function findOwnPropsScript(root: Element): Element | null {
|
|
@@ -262,8 +262,8 @@ export function defineIslandElement(): void {
|
|
|
262
262
|
const idPrefix = this.getAttribute('i') ?? `c${clientIslandIdSeq++}-`
|
|
263
263
|
const render = () => loaded.default(props)
|
|
264
264
|
dispose = (typeof PRUNELLE_CLIENT_ONLY === 'undefined' || PRUNELLE_CLIENT_ONLY) && clientOnly
|
|
265
|
-
? mount(this, render, idPrefix)
|
|
266
|
-
: hydrate(this, render, idPrefix)
|
|
265
|
+
? loaded.mount!(this, render, idPrefix)
|
|
266
|
+
: loaded.hydrate(this, render, idPrefix)
|
|
267
267
|
if (!this.isConnected || token !== this._t) {
|
|
268
268
|
dispose()
|
|
269
269
|
return
|
package/src/plugins/types.ts
CHANGED
|
@@ -89,6 +89,11 @@ export interface PluginRouteOptions {
|
|
|
89
89
|
trustProxy?: TrustProxy | undefined
|
|
90
90
|
/** How often one client may call the route: past `max` per `windowMs`, it answers 429 with `Retry-After` before the handler runs. */
|
|
91
91
|
rateLimit?: RateLimit<RequestContext> | undefined
|
|
92
|
+
/**
|
|
93
|
+
* Let the route's catch-all take a segment with an encoded `/`, `\` or NUL (`%2F`, `%5C`, `%00`), which every route refuses by default.
|
|
94
|
+
* Such a segment reaches the param still encoded, never as a separator: for a route that reads it as text (a QR code of a URL), never one that joins it into a file path.
|
|
95
|
+
*/
|
|
96
|
+
encodedSlashes?: boolean | undefined
|
|
92
97
|
}
|
|
93
98
|
|
|
94
99
|
export interface MiddlewareOptions {
|
package/src/server/errors.ts
CHANGED
|
@@ -28,7 +28,7 @@ export function devErrorResponse(error: unknown, request: Request): Response {
|
|
|
28
28
|
}
|
|
29
29
|
|
|
30
30
|
export interface ErrorNotifierOptions {
|
|
31
|
-
/** With no `onError` hook to hear an unhandled error, `console.error` does. */
|
|
31
|
+
/** With no `onError` hook to hear an unhandled error, `console.error` does (unless a `sink` captures it outside dev, as `testApp` and prerender do). */
|
|
32
32
|
dev?: boolean | undefined
|
|
33
33
|
/** Hears every unhandled error, hooks or not: how `testApp().errors` fills. */
|
|
34
34
|
sink?: ((info: ServerErrorInfo) => void) | undefined
|
|
@@ -44,7 +44,7 @@ export function createErrorNotifier(onError: ((info: ServerErrorInfo) => void) |
|
|
|
44
44
|
}
|
|
45
45
|
return (error, request, source) => {
|
|
46
46
|
options.sink?.({ error, request, source })
|
|
47
|
-
if (options.dev === true
|
|
47
|
+
if (errorHooks.length === 0 && (options.dev === true || options.sink === undefined))
|
|
48
48
|
console.error(`prunelle: unhandled error in ${source} ${request.method} ${new URL(request.url).pathname}`, error)
|
|
49
49
|
for (const { owner, hook } of errorHooks) {
|
|
50
50
|
try {
|
package/src/server/index.ts
CHANGED
|
@@ -13,6 +13,7 @@ import type { NotifyError } from './errors'
|
|
|
13
13
|
import type { EmbeddedServerConfig, PrunelleApp, PrunelleServer, Middleware, RequestContext } from './http'
|
|
14
14
|
import type { RateLimiter, RateLimitStore } from './rate-limit'
|
|
15
15
|
import type { LoadedMiddlewareModule } from './page'
|
|
16
|
+
import type { ServerPluginHost } from './plugin-host'
|
|
16
17
|
import type { RequestPath } from './request-path'
|
|
17
18
|
import type { CompiledRoute } from './route-table'
|
|
18
19
|
import type { FastHandler } from './routing'
|
|
@@ -31,7 +32,7 @@ import { addedInlineStyleHashes, createDocumentHooks, createHtmlHeaders, mergeSt
|
|
|
31
32
|
import { createErrorNotifier, createFallbackPages, devErrorResponse } from './errors'
|
|
32
33
|
import { applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, finalizeResponse, isNotFound, makeRequestContext, runChain, wantsJson } from './http'
|
|
33
34
|
import { allowedMethodsHeader, pickPageIslandProps, stripHeadBody } from './page'
|
|
34
|
-
import { allowedPluginMethodsHeader, createServerPluginHost } from './plugin-host'
|
|
35
|
+
import { allowedPluginMethodsHeader, createServerPluginHost, takesEncoded } from './plugin-host'
|
|
35
36
|
|
|
36
37
|
import { hasRegionHeader, invalidRegionResponse, requestedRegion, respondRegion, withRegionVary } from './region'
|
|
37
38
|
import { decodeRequestPath, literalPath } from './request-path'
|
|
@@ -82,6 +83,11 @@ function lookupPrerendered<T>(map: ReadonlyMap<string, T>, staticPath: string |
|
|
|
82
83
|
return map.get(staticPath) ?? map.get(normPath)
|
|
83
84
|
}
|
|
84
85
|
|
|
86
|
+
function matchPluginRoute(pluginRouter: ServerPluginHost['router'], requestPath: RequestPath, effective: RequestPath) {
|
|
87
|
+
const rawMatch = effective !== requestPath ? takesEncoded(pluginRouter.match(requestPath), requestPath) : undefined
|
|
88
|
+
return rawMatch ?? takesEncoded(pluginRouter.match(effective), effective)
|
|
89
|
+
}
|
|
90
|
+
|
|
85
91
|
async function renderRouteBody(route: CompiledRoute, data: unknown, pageProps: Record<string, unknown>, ctx: RequestContext): Promise<string> {
|
|
86
92
|
const { entry, mod, layouts } = route
|
|
87
93
|
let inner: string
|
|
@@ -503,7 +509,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
503
509
|
|
|
504
510
|
// Custom plugin routes run behind path-matched plugin middlewares so ctx.locals is available without cross-scope leaks.
|
|
505
511
|
const method = request.method.toUpperCase()
|
|
506
|
-
const pluginMatch = pluginRouter
|
|
512
|
+
const pluginMatch = matchPluginRoute(pluginRouter, requestPath, effective)
|
|
507
513
|
const directPluginDef = pluginMatch?.data.get(method) ?? pluginMatch?.data.get('ALL')
|
|
508
514
|
const headFallbackPluginDef = directPluginDef === undefined && method === 'HEAD' ? pluginMatch?.data.get('GET') : undefined
|
|
509
515
|
const routeDef = directPluginDef ?? headFallbackPluginDef
|
|
@@ -10,6 +10,8 @@ import { runWithAppContext } from '../plugins/context'
|
|
|
10
10
|
import { enforceRequirements } from '../plugins/requires'
|
|
11
11
|
import { normalizeConsentConfig, registerConsentRoute } from './consent'
|
|
12
12
|
import { assertRateLimit, createRateLimitStore, hitFor, tooManyRequests } from './rate-limit'
|
|
13
|
+
import type { RequestPath } from './request-path'
|
|
14
|
+
import type { RouteMatch } from './router'
|
|
13
15
|
import { Router } from './router'
|
|
14
16
|
|
|
15
17
|
export interface PluginRouteDef {
|
|
@@ -18,6 +20,8 @@ export interface PluginRouteDef {
|
|
|
18
20
|
csrf: boolean
|
|
19
21
|
trustedOrigins: Set<string> | undefined
|
|
20
22
|
trustProxy: TrustProxy
|
|
23
|
+
/** The catch-all takes an encoded separator for this method (`PluginRouteOptions.encodedSlashes`). */
|
|
24
|
+
encodedSlashes: boolean
|
|
21
25
|
}
|
|
22
26
|
|
|
23
27
|
interface ScopedMiddleware {
|
|
@@ -59,6 +63,14 @@ function middlewareAppliesToPath(scope: ScopedMiddleware['scope'], path: string,
|
|
|
59
63
|
return normPath === normScope || normPath.startsWith(`${normScope}/`)
|
|
60
64
|
}
|
|
61
65
|
|
|
66
|
+
/** The methods of `match` that may answer `path`: for a path with an encoded separator, only those that set `encodedSlashes`; none left is no match. */
|
|
67
|
+
export function takesEncoded(match: RouteMatch<Map<string, PluginRouteDef>> | undefined, path: RequestPath): RouteMatch<Map<string, PluginRouteDef>> | undefined {
|
|
68
|
+
if (match === undefined || path.encoded === undefined || path.encoded.size === 0)
|
|
69
|
+
return match
|
|
70
|
+
const data = new Map([...match.data].filter(([, def]) => def.encodedSlashes))
|
|
71
|
+
return data.size === 0 ? undefined : { data, params: match.params }
|
|
72
|
+
}
|
|
73
|
+
|
|
62
74
|
export function allowedPluginMethodsHeader(methods: ReadonlyMap<string, PluginRouteDef>): string {
|
|
63
75
|
const allowed = new Set<string>()
|
|
64
76
|
for (const m of methods.keys()) {
|
|
@@ -71,6 +83,19 @@ export function allowedPluginMethodsHeader(methods: ReadonlyMap<string, PluginRo
|
|
|
71
83
|
return [...allowed].join(', ')
|
|
72
84
|
}
|
|
73
85
|
|
|
86
|
+
function assertRouteFree(pluginName: string, upperMethod: string, normPath: string, byMethod: ReadonlyMap<string, PluginRouteDef>): void {
|
|
87
|
+
const directConflict = byMethod.get(upperMethod)
|
|
88
|
+
if (directConflict !== undefined)
|
|
89
|
+
throw new Error(`prunelle: plugin "${pluginName}" registered ${upperMethod} ${normPath}, which collides with "${directConflict.plugin}". Mount one of the plugins on a different path.`)
|
|
90
|
+
if (upperMethod === 'ALL' && byMethod.size > 0) {
|
|
91
|
+
const [existingMethod, existingDef] = byMethod.entries().next().value!
|
|
92
|
+
throw new Error(`prunelle: plugin "${pluginName}" registered ALL ${normPath}, which collides with ${existingMethod} ${normPath} from "${existingDef.plugin}". Mount one of the plugins on a different path.`)
|
|
93
|
+
}
|
|
94
|
+
const allConflict = byMethod.get('ALL')
|
|
95
|
+
if (allConflict !== undefined)
|
|
96
|
+
throw new Error(`prunelle: plugin "${pluginName}" registered ${upperMethod} ${normPath}, which collides with ALL ${normPath} from "${allConflict.plugin}". Mount one of the plugins on a different path.`)
|
|
97
|
+
}
|
|
98
|
+
|
|
74
99
|
export async function createServerPluginHost(options: ServerPluginHostOptions) {
|
|
75
100
|
const { plugins, config, manifest, appCtx, trustedOrigins, trustProxy } = options
|
|
76
101
|
// The counters of every limited route and action of this server, dropped with it.
|
|
@@ -89,25 +114,20 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
|
|
|
89
114
|
): void => {
|
|
90
115
|
const upperMethod = method.toUpperCase()
|
|
91
116
|
const normPath = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
|
|
117
|
+
const encodedSlashes = routeOptions?.encodedSlashes === true
|
|
118
|
+
if (encodedSlashes && !normPath.split('/').some(seg => seg.startsWith('*')))
|
|
119
|
+
throw new Error(`prunelle: plugin "${pluginName}" set encodedSlashes on ${upperMethod} ${normPath}, which has no catch-all: only a \`*name\` segment takes an encoded /, so end the path with one, or drop the option.`)
|
|
92
120
|
let byMethod = routeEntries.get(normPath)
|
|
93
121
|
if (byMethod === undefined) {
|
|
94
122
|
byMethod = new Map()
|
|
95
123
|
routeEntries.set(normPath, byMethod)
|
|
96
|
-
router.add(normPath, byMethod)
|
|
124
|
+
router.add(normPath, byMethod, { encodedSlashes })
|
|
97
125
|
}
|
|
98
126
|
else {
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
if (upperMethod === 'ALL' && byMethod.size > 0) {
|
|
104
|
-
const [existingMethod, existingDef] = byMethod.entries().next().value!
|
|
105
|
-
throw new Error(`prunelle: plugin "${pluginName}" registered ALL ${normPath}, which collides with ${existingMethod} ${normPath} from "${existingDef.plugin}". Mount one of the plugins on a different path.`)
|
|
106
|
-
}
|
|
107
|
-
const allConflict = byMethod.get('ALL')
|
|
108
|
-
if (allConflict !== undefined) {
|
|
109
|
-
throw new Error(`prunelle: plugin "${pluginName}" registered ${upperMethod} ${normPath}, which collides with ALL ${normPath} from "${allConflict.plugin}". Mount one of the plugins on a different path.`)
|
|
110
|
-
}
|
|
127
|
+
assertRouteFree(pluginName, upperMethod, normPath, byMethod)
|
|
128
|
+
// The path matches encoded separators once any method takes them; takesEncoded still refuses them to the others.
|
|
129
|
+
if (encodedSlashes)
|
|
130
|
+
router.add(normPath, byMethod, { encodedSlashes })
|
|
111
131
|
}
|
|
112
132
|
let routeTrustedOrigins = trustedOrigins
|
|
113
133
|
if (routeOptions?.trustedOrigins !== undefined && routeOptions.trustedOrigins.length > 0) {
|
|
@@ -129,6 +149,7 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
|
|
|
129
149
|
csrf: routeOptions?.csrf ?? true,
|
|
130
150
|
trustedOrigins: routeTrustedOrigins,
|
|
131
151
|
trustProxy: routeOptions?.trustProxy ?? trustProxy,
|
|
152
|
+
encodedSlashes,
|
|
132
153
|
})
|
|
133
154
|
}
|
|
134
155
|
|
package/src/server/public.ts
CHANGED
|
@@ -12,8 +12,8 @@ export { createServer } from './loader'
|
|
|
12
12
|
export { createRateLimitStore } from './rate-limit'
|
|
13
13
|
export type { RateLimit, RateLimiter, RateLimitStore, RateLimitStoreOptions } from './rate-limit'
|
|
14
14
|
export { readStringFields } from './request-body'
|
|
15
|
-
export { getClientIp, isHttpsRequest, isTrustedOrigin, safeEqual, safeRedirect, verifyOrigin } from './security'
|
|
16
|
-
export type { SecurityHeadersOptions, TrustProxy } from './security'
|
|
15
|
+
export { DEFAULT_CSP, extendCsp, getClientIp, isHttpsRequest, isTrustedOrigin, safeEqual, safeRedirect, verifyOrigin } from './security'
|
|
16
|
+
export type { CspDirectives, SecurityHeadersOptions, TrustProxy } from './security'
|
|
17
17
|
export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
|
|
18
18
|
export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult, ValidationSuccess } from './standard-schema'
|
|
19
19
|
export { esc, escAttr, escJson, raw } from '../ssr/index'
|
package/src/server/router.ts
CHANGED
|
@@ -20,9 +20,15 @@ interface RoutePattern<T> {
|
|
|
20
20
|
segments: CompiledSegment[]
|
|
21
21
|
isStatic: boolean
|
|
22
22
|
hasCatchAll: boolean
|
|
23
|
+
/** The catch-all takes a segment holding an encoded separator, left encoded. */
|
|
24
|
+
encodedSlashes: boolean
|
|
23
25
|
data: T
|
|
24
26
|
}
|
|
25
27
|
|
|
28
|
+
export interface RouteOptions {
|
|
29
|
+
encodedSlashes?: boolean | undefined
|
|
30
|
+
}
|
|
31
|
+
|
|
26
32
|
export interface RouteMatch<T> {
|
|
27
33
|
data: T
|
|
28
34
|
params: Record<string, string>
|
|
@@ -57,7 +63,7 @@ function compareRoutes<T>(a: RoutePattern<T>, b: RoutePattern<T>): number {
|
|
|
57
63
|
return 0
|
|
58
64
|
}
|
|
59
65
|
|
|
60
|
-
function compileRoutePattern<T>(path: string, data: T): RoutePattern<T> {
|
|
66
|
+
function compileRoutePattern<T>(path: string, data: T, options?: RouteOptions): RoutePattern<T> {
|
|
61
67
|
const norm = normalizePath(path)
|
|
62
68
|
const clean = norm === '/' ? '' : norm.replace(/^\/|\/$/g, '')
|
|
63
69
|
const rawSegments = clean === '' ? [] : clean.split('/')
|
|
@@ -81,7 +87,7 @@ function compileRoutePattern<T>(path: string, data: T): RoutePattern<T> {
|
|
|
81
87
|
}
|
|
82
88
|
}
|
|
83
89
|
|
|
84
|
-
return { path: norm, segments, isStatic, hasCatchAll, data }
|
|
90
|
+
return { path: norm, segments, isStatic, hasCatchAll, encodedSlashes: options?.encodedSlashes === true, data }
|
|
85
91
|
}
|
|
86
92
|
|
|
87
93
|
export class Router<T> {
|
|
@@ -89,8 +95,9 @@ export class Router<T> {
|
|
|
89
95
|
readonly #dynamicRoutes: RoutePattern<T>[] = []
|
|
90
96
|
#sorted = true
|
|
91
97
|
|
|
92
|
-
|
|
93
|
-
|
|
98
|
+
/** Adds the route at `path`, or replaces the one already there. */
|
|
99
|
+
add(path: string, data: T, options?: RouteOptions): void {
|
|
100
|
+
const compiled = compileRoutePattern(path, data, options)
|
|
94
101
|
if (compiled.isStatic) {
|
|
95
102
|
this.#staticRoutes.set(compiled.path, data)
|
|
96
103
|
}
|
|
@@ -127,7 +134,8 @@ export class Router<T> {
|
|
|
127
134
|
|
|
128
135
|
const parts = path.segments
|
|
129
136
|
// A param never receives a separator, a NUL or a dot segment, encoded or not: joined into a path, it would walk out of the folder it names.
|
|
130
|
-
const
|
|
137
|
+
const dotSegment = (k: number): boolean => parts[k] === '.' || parts[k] === '..'
|
|
138
|
+
const refused = (k: number): boolean => path.encoded?.has(k) === true || dotSegment(k)
|
|
131
139
|
|
|
132
140
|
for (let i = 0; i < dynLen; i++) {
|
|
133
141
|
const route = this.#dynamicRoutes[i]!
|
|
@@ -143,7 +151,7 @@ export class Router<T> {
|
|
|
143
151
|
const seg = segs[j]!
|
|
144
152
|
if (seg.kind === SegmentKind.CatchAll) {
|
|
145
153
|
for (let k = j; k < parts.length; k++) {
|
|
146
|
-
if (refused(k))
|
|
154
|
+
if (route.encodedSlashes ? dotSegment(k) : refused(k))
|
|
147
155
|
matched = false
|
|
148
156
|
}
|
|
149
157
|
break
|
package/src/server/security.ts
CHANGED
|
@@ -71,28 +71,47 @@ export function inlineStyleHashes(html: string): string[] {
|
|
|
71
71
|
return hashes
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
): string {
|
|
79
|
-
const styleHashes = opts.styleHashes ?? []
|
|
80
|
-
const scriptHashes = opts.scriptHashes ?? []
|
|
81
|
-
if (styleHashes.length === 0 && scriptHashes.length === 0)
|
|
82
|
-
return csp
|
|
74
|
+
interface ParsedCsp {
|
|
75
|
+
order: string[]
|
|
76
|
+
directives: Map<string, string[]>
|
|
77
|
+
}
|
|
83
78
|
|
|
84
|
-
|
|
79
|
+
function parseCsp(csp: string): ParsedCsp {
|
|
85
80
|
const directives = new Map<string, string[]>()
|
|
86
81
|
const order: string[] = []
|
|
87
|
-
for (const part of
|
|
88
|
-
const
|
|
82
|
+
for (const part of csp.split(';')) {
|
|
83
|
+
const trimmed = part.trim()
|
|
84
|
+
if (!trimmed)
|
|
85
|
+
continue
|
|
86
|
+
const tokens = trimmed.split(/\s+/)
|
|
89
87
|
const name = tokens[0]!.toLowerCase()
|
|
90
88
|
if (!directives.has(name)) {
|
|
91
89
|
order.push(name)
|
|
92
90
|
directives.set(name, tokens.slice(1))
|
|
93
91
|
}
|
|
94
92
|
}
|
|
93
|
+
return { order, directives }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function serializeCsp(parsed: ParsedCsp): string {
|
|
97
|
+
return parsed.order.map((name) => {
|
|
98
|
+
const tokens = parsed.directives.get(name)!
|
|
99
|
+
return tokens.length > 0 ? `${name} ${tokens.join(' ')}` : name
|
|
100
|
+
}).join('; ')
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Augments a Content-Security-Policy header with exact SHA-256 hashes (no `'unsafe-inline'` required). */
|
|
104
|
+
export function withCspHashes(
|
|
105
|
+
csp: string,
|
|
106
|
+
opts: { styleHashes?: readonly string[], scriptHashes?: readonly string[] },
|
|
107
|
+
): string {
|
|
108
|
+
const styleHashes = opts.styleHashes ?? []
|
|
109
|
+
const scriptHashes = opts.scriptHashes ?? []
|
|
110
|
+
if (styleHashes.length === 0 && scriptHashes.length === 0)
|
|
111
|
+
return csp
|
|
95
112
|
|
|
113
|
+
const parsed = parseCsp(csp)
|
|
114
|
+
const { order, directives } = parsed
|
|
96
115
|
const defaultSrc = directives.get('default-src') ?? ["'self'"]
|
|
97
116
|
const addHashes = (dirName: string, hashes: readonly string[]) => {
|
|
98
117
|
if (hashes.length === 0)
|
|
@@ -121,22 +140,151 @@ export function withCspHashes(
|
|
|
121
140
|
if (directives.has('script-src-elem'))
|
|
122
141
|
addHashes('script-src-elem', scriptHashes)
|
|
123
142
|
|
|
124
|
-
return
|
|
125
|
-
const tokens = directives.get(name)!
|
|
126
|
-
return tokens.length > 0 ? `${name} ${tokens.join(' ')}` : name
|
|
127
|
-
}).join('; ')
|
|
143
|
+
return serializeCsp(parsed)
|
|
128
144
|
}
|
|
129
145
|
|
|
130
146
|
export const DEFAULT_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'"
|
|
131
147
|
export const DEFAULT_HSTS = 'max-age=31536000; includeSubDomains'
|
|
132
148
|
export const DEFAULT_PERMISSIONS_POLICY = 'camera=(), microphone=(), geolocation=()'
|
|
133
149
|
|
|
150
|
+
export type CspDirectiveValue = string | readonly string[]
|
|
151
|
+
|
|
152
|
+
export interface KnownCspDirectives {
|
|
153
|
+
'default-src'?: CspDirectiveValue | undefined
|
|
154
|
+
'script-src'?: CspDirectiveValue | undefined
|
|
155
|
+
'script-src-elem'?: CspDirectiveValue | undefined
|
|
156
|
+
'script-src-attr'?: CspDirectiveValue | undefined
|
|
157
|
+
'style-src'?: CspDirectiveValue | undefined
|
|
158
|
+
'style-src-elem'?: CspDirectiveValue | undefined
|
|
159
|
+
'style-src-attr'?: CspDirectiveValue | undefined
|
|
160
|
+
'img-src'?: CspDirectiveValue | undefined
|
|
161
|
+
'font-src'?: CspDirectiveValue | undefined
|
|
162
|
+
'connect-src'?: CspDirectiveValue | undefined
|
|
163
|
+
'media-src'?: CspDirectiveValue | undefined
|
|
164
|
+
'object-src'?: CspDirectiveValue | undefined
|
|
165
|
+
'frame-src'?: CspDirectiveValue | undefined
|
|
166
|
+
'child-src'?: CspDirectiveValue | undefined
|
|
167
|
+
'worker-src'?: CspDirectiveValue | undefined
|
|
168
|
+
'manifest-src'?: CspDirectiveValue | undefined
|
|
169
|
+
'base-uri'?: CspDirectiveValue | undefined
|
|
170
|
+
'form-action'?: CspDirectiveValue | undefined
|
|
171
|
+
'frame-ancestors'?: CspDirectiveValue | undefined
|
|
172
|
+
'sandbox'?: CspDirectiveValue | undefined
|
|
173
|
+
'report-to'?: CspDirectiveValue | undefined
|
|
174
|
+
'report-uri'?: CspDirectiveValue | undefined
|
|
175
|
+
'upgrade-insecure-requests'?: CspDirectiveValue | undefined
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export type CspDirectives = Readonly<KnownCspDirectives & Record<string, CspDirectiveValue | undefined>>
|
|
179
|
+
|
|
180
|
+
const isFetchDirective = (name: string): boolean =>
|
|
181
|
+
name.endsWith('-src') || name.endsWith('-src-elem') || name.endsWith('-src-attr')
|
|
182
|
+
|
|
183
|
+
function splitCspTokens(value: CspDirectiveValue): string[] {
|
|
184
|
+
const parts = typeof value === 'string' ? [value] : value
|
|
185
|
+
const tokens: string[] = []
|
|
186
|
+
for (const part of parts) {
|
|
187
|
+
for (const token of part.split(/\s+/)) {
|
|
188
|
+
if (token.length > 0 && !tokens.includes(token))
|
|
189
|
+
tokens.push(token)
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return tokens
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function mergeCspDirective(parsed: ParsedCsp, name: string, tokens: readonly string[]): void {
|
|
196
|
+
const { order, directives } = parsed
|
|
197
|
+
const existing = directives.get(name)
|
|
198
|
+
if (existing === undefined) {
|
|
199
|
+
order.push(name)
|
|
200
|
+
if (tokens.length === 0) {
|
|
201
|
+
directives.set(name, [])
|
|
202
|
+
}
|
|
203
|
+
else if (tokens.includes("'none'")) {
|
|
204
|
+
directives.set(name, ["'none'"])
|
|
205
|
+
}
|
|
206
|
+
else if (isFetchDirective(name)) {
|
|
207
|
+
const seeded = (directives.get('default-src') ?? ["'self'"]).filter(t => t !== "'none'")
|
|
208
|
+
for (const token of tokens) {
|
|
209
|
+
if (!seeded.includes(token))
|
|
210
|
+
seeded.push(token)
|
|
211
|
+
}
|
|
212
|
+
directives.set(name, seeded)
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
directives.set(name, [...tokens])
|
|
216
|
+
}
|
|
217
|
+
return
|
|
218
|
+
}
|
|
219
|
+
if (tokens.length === 0)
|
|
220
|
+
return
|
|
221
|
+
if (tokens.includes("'none'")) {
|
|
222
|
+
directives.set(name, ["'none'"])
|
|
223
|
+
return
|
|
224
|
+
}
|
|
225
|
+
const noneIdx = existing.indexOf("'none'")
|
|
226
|
+
if (noneIdx !== -1)
|
|
227
|
+
existing.splice(noneIdx, 1)
|
|
228
|
+
for (const token of tokens) {
|
|
229
|
+
if (!existing.includes(token))
|
|
230
|
+
existing.push(token)
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Extends a Content-Security-Policy (default: `DEFAULT_CSP`) by merging additional sources into one or more directives. */
|
|
235
|
+
export function extendCsp(extra: CspDirectives, base = DEFAULT_CSP): string {
|
|
236
|
+
const parsed = parseCsp(base)
|
|
237
|
+
for (const [rawName, rawValue] of Object.entries(extra)) {
|
|
238
|
+
if (rawValue === undefined)
|
|
239
|
+
continue
|
|
240
|
+
const name = rawName.trim().toLowerCase()
|
|
241
|
+
if (name.length === 0)
|
|
242
|
+
continue
|
|
243
|
+
mergeCspDirective(parsed, name, splitCspTokens(rawValue))
|
|
244
|
+
}
|
|
245
|
+
return serializeCsp(parsed)
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Directives browsers ignore (and log an error for) when delivered via <meta http-equiv="Content-Security-Policy"> (W3C CSP3 §4.2.1).
|
|
249
|
+
const META_CSP_IGNORED = new Set(['frame-ancestors', 'report-uri', 'sandbox'])
|
|
250
|
+
const EXISTING_META_CSP_RE = /<meta\b[^>]*\bhttp-equiv\s*=\s*(?:"content-security-policy"|'content-security-policy'|content-security-policy\b)/i
|
|
251
|
+
const META_CHARSET_RE = /<meta\b[^>]*\bcharset\s*=\s*[^>]*>/i
|
|
252
|
+
const HEAD_OPEN_RE = /<head\b[^>]*>/i
|
|
253
|
+
const ESC_DOUBLE_ATTR_RE = /[&"<>]/g
|
|
254
|
+
const DOUBLE_ATTR_MAP: Record<string, string> = { '&': '&', '"': '"', '<': '<', '>': '>' }
|
|
255
|
+
|
|
256
|
+
/** Strips directives browsers reject in a `<meta http-equiv="Content-Security-Policy">` element. */
|
|
257
|
+
export function toMetaCsp(csp: string): string {
|
|
258
|
+
const parsed = parseCsp(csp)
|
|
259
|
+
parsed.order = parsed.order.filter(name => !META_CSP_IGNORED.has(name))
|
|
260
|
+
return serializeCsp(parsed)
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Injects `<meta http-equiv="Content-Security-Policy">` at the top of `<head>` for static HTML exports. */
|
|
264
|
+
export function injectMetaCsp(html: string, csp: string | null | undefined): string {
|
|
265
|
+
if (!csp || EXISTING_META_CSP_RE.test(html))
|
|
266
|
+
return html
|
|
267
|
+
const metaCsp = toMetaCsp(csp)
|
|
268
|
+
if (metaCsp.length === 0)
|
|
269
|
+
return html
|
|
270
|
+
const headMatch = HEAD_OPEN_RE.exec(html)
|
|
271
|
+
if (headMatch === null)
|
|
272
|
+
return html
|
|
273
|
+
const headEnd = headMatch.index + headMatch[0].length
|
|
274
|
+
const headCloseIdx = html.toLowerCase().indexOf('</head>', headEnd)
|
|
275
|
+
const headSlice = headCloseIdx === -1 ? html.slice(headEnd) : html.slice(headEnd, headCloseIdx)
|
|
276
|
+
const charsetMatch = META_CHARSET_RE.exec(headSlice)
|
|
277
|
+
const insertAt = charsetMatch !== null ? headEnd + charsetMatch.index + charsetMatch[0].length : headEnd
|
|
278
|
+
const escaped = metaCsp.replace(ESC_DOUBLE_ATTR_RE, ch => DOUBLE_ATTR_MAP[ch]!)
|
|
279
|
+
return `${html.slice(0, insertAt)}<meta http-equiv="Content-Security-Policy" content="${escaped}">${html.slice(insertAt)}`
|
|
280
|
+
}
|
|
281
|
+
|
|
134
282
|
export interface SecurityHeadersOptions {
|
|
135
283
|
frameOptions?: 'DENY' | 'SAMEORIGIN' | false | undefined
|
|
136
284
|
referrerPolicy?: string | false | undefined
|
|
137
285
|
contentTypeOptions?: boolean | undefined
|
|
138
286
|
permissionsPolicy?: string | false | undefined
|
|
139
|
-
csp?: string | false | undefined
|
|
287
|
+
csp?: string | CspDirectives | false | undefined
|
|
140
288
|
hsts?: string | boolean | undefined
|
|
141
289
|
}
|
|
142
290
|
|
|
@@ -289,10 +437,10 @@ export function verifyOrigin(
|
|
|
289
437
|
}
|
|
290
438
|
|
|
291
439
|
export function resolveCspPolicy(options: SecurityHeadersOptions | false | undefined): string | undefined {
|
|
292
|
-
if (options === false)
|
|
293
|
-
return undefined
|
|
294
|
-
if (options?.csp === false)
|
|
440
|
+
if (options === false || options?.csp === false)
|
|
295
441
|
return undefined
|
|
442
|
+
if (typeof options?.csp === 'object')
|
|
443
|
+
return extendCsp(options.csp)
|
|
296
444
|
return options?.csp ?? DEFAULT_CSP
|
|
297
445
|
}
|
|
298
446
|
|
|
@@ -317,7 +465,8 @@ export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | fal
|
|
|
317
465
|
entries.push(['referrer-policy', opts.referrerPolicy ?? 'strict-origin-when-cross-origin'])
|
|
318
466
|
if (opts.permissionsPolicy !== false)
|
|
319
467
|
entries.push(['permissions-policy', opts.permissionsPolicy ?? DEFAULT_PERMISSIONS_POLICY])
|
|
320
|
-
|
|
321
|
-
|
|
468
|
+
const csp = resolveCspPolicy(opts)
|
|
469
|
+
if (csp !== undefined)
|
|
470
|
+
entries.push(['content-security-policy', csp])
|
|
322
471
|
return entries
|
|
323
472
|
}
|
package/src/test/browser.ts
CHANGED
|
@@ -23,6 +23,8 @@ export interface BrowserPage {
|
|
|
23
23
|
/** Moves the pointer over the first element matching `selector`, as a visitor hovering a link does. */
|
|
24
24
|
hover(selector: string): Promise<void>
|
|
25
25
|
fill(selector: string, value: string): Promise<void>
|
|
26
|
+
/** Presses a key (`'Escape'`, `'ArrowRight'`, `'Tab'`) through the browser's keyboard input pipeline. */
|
|
27
|
+
press(key: string): Promise<void>
|
|
26
28
|
/** The text content of the first element matching `selector`. */
|
|
27
29
|
text(selector: string): Promise<string>
|
|
28
30
|
close(): Promise<void>
|
|
@@ -53,6 +55,7 @@ interface Page {
|
|
|
53
55
|
click(selector: string, options: { timeout: number }): Promise<void>
|
|
54
56
|
hover(selector: string, options: { timeout: number }): Promise<void>
|
|
55
57
|
fill(selector: string, value: string, options: { timeout: number }): Promise<void>
|
|
58
|
+
keyboard: { press(key: string): Promise<void> }
|
|
56
59
|
locator(selector: string): { first: () => { innerText: (options: { timeout: number }) => Promise<string> } }
|
|
57
60
|
}
|
|
58
61
|
interface BrowserContext {
|
|
@@ -126,6 +129,9 @@ function wrapPage(page: Page, context: BrowserContext, timeout: number, url: str
|
|
|
126
129
|
async fill(selector, value) {
|
|
127
130
|
await page.fill(selector, value, { timeout })
|
|
128
131
|
},
|
|
132
|
+
async press(key) {
|
|
133
|
+
await page.keyboard.press(key)
|
|
134
|
+
},
|
|
129
135
|
async text(selector) {
|
|
130
136
|
return await page.locator(selector).first().innerText({ timeout })
|
|
131
137
|
},
|
package/src/test/index.ts
CHANGED
|
@@ -2,11 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
import type { BuildManifest, BuildOptions } from '../build/index'
|
|
4
4
|
import type { PrunelleApp, ServerAction, ServerRuntimeConfig } from '../server/index'
|
|
5
|
-
import { readdirSync, rmSync } from 'node:fs'
|
|
5
|
+
import { existsSync, readdirSync, rmSync } from 'node:fs'
|
|
6
6
|
import { dirname, join, resolve } from 'node:path'
|
|
7
7
|
import { build } from '../build/index'
|
|
8
8
|
import { relPosix } from '../build/files'
|
|
9
9
|
import { processSuffix, removeDeadProcessDirs } from '../build/output'
|
|
10
|
+
import { ensureCacheGitignore } from '../build/precompress'
|
|
10
11
|
import { resolveServerConfig } from '../server/index'
|
|
11
12
|
import { startBuiltApp } from '../server/loader'
|
|
12
13
|
|
|
@@ -41,12 +42,17 @@ const ownOutDirs: string[] = []
|
|
|
41
42
|
function ownOutDir(root: string): string {
|
|
42
43
|
const cacheDir = join(root, '.prunelle-cache')
|
|
43
44
|
removeDeadProcessDirs(cacheDir, TEST_DIR_PREFIX)
|
|
45
|
+
ensureCacheGitignore(cacheDir)
|
|
44
46
|
if (ownOutDirs.length === 0) {
|
|
45
47
|
process.once('exit', () => {
|
|
46
48
|
for (const dir of ownOutDirs) {
|
|
47
49
|
rmSync(dir, { recursive: true, force: true })
|
|
48
|
-
|
|
49
|
-
|
|
50
|
+
const parent = dirname(dir)
|
|
51
|
+
if (!existsSync(parent))
|
|
52
|
+
continue
|
|
53
|
+
const remaining = readdirSync(parent)
|
|
54
|
+
if (remaining.length === 0 || (remaining.length === 1 && remaining[0] === '.gitignore'))
|
|
55
|
+
rmSync(parent, { recursive: true, force: true })
|
|
50
56
|
}
|
|
51
57
|
})
|
|
52
58
|
}
|