prunelle 0.7.4 → 0.7.5
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 +8 -6
- package/package.json +1 -1
- package/src/build/routes.ts +19 -1
- package/src/cli/check-security.ts +12 -4
- package/src/cli/check.ts +1 -1
- package/src/compiler/compliance.ts +2 -0
- package/src/dev/index.ts +1 -1
- package/src/dev/supervisor.ts +2 -2
- package/src/dom/island.ts +30 -4
- package/src/plugins/services.ts +1 -0
- package/src/server/action.ts +26 -18
- package/src/server/http.ts +1 -1
- package/src/server/index.ts +7 -7
- package/src/server/page.ts +4 -0
- package/src/server/route-table.ts +24 -11
- package/src/server/serve-handlers.ts +3 -3
- package/src/server/start.ts +2 -2
- package/src/server/stream.ts +4 -4
- package/src/ssr/navigation.ts +1 -1
package/llms.txt
CHANGED
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
- A same-file helper that needs the browser makes each component calling it an island; a primitive called at a file's top level makes every component of the file one.
|
|
28
28
|
- `<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.
|
|
29
29
|
- Hydration steps over a node an extension injected, redraws a part whose tag differs from the server's and removes the server nodes no list row claimed (mid-list or past the last row), in production too (dev also warns), and dispatches a bubbling `pru:hydration-mismatch` event (`detail: { removed, added }`) on the list's parent, which reaches the island.
|
|
30
|
-
- **Hydration**: `$hydrate="load" | "visible" | "idle" | "interaction" | "media(...)" | "client"` per call site, or the component file's default `export const hydrate = 'visible'`; unknown modes and `$hydrate` on a non-island fail compile. `idle` islands hydrate within 2 s; an `interaction` island whose chunk fails to load logs the error and retries on the next interaction, replaying it; a chunk URL off this origin is refused with a console error. A delegated handler that throws is reported with `reportError` and the other handlers still run; `onTouchStart` is delegated from the document, which browsers make passive so scrolling never waits on it: a handler that must `preventDefault` adds its own listener in `onMount` with `{ passive: false }`.
|
|
30
|
+
- **Hydration**: `$hydrate="load" | "visible" | "idle" | "interaction" | "media(...)" | "client"` per call site, or the component file's default `export const hydrate = 'visible'`; unknown modes and `$hydrate` on a non-island fail compile. `idle` islands hydrate within 2 s; an `interaction` island also hydrates on a shortcut an element inside it names with `aria-keyshortcuts` (`"Control+K Meta+K"`), pressed anywhere on the page and kept from the browser, and replays it to `document` after the component's `onMount` callbacks; one whose chunk fails to load logs the error and retries on the next interaction, replaying it; a chunk URL off this origin is refused with a console error. A delegated handler that throws is reported with `reportError` and the other handlers still run; `onTouchStart` is delegated from the document, which browsers make passive so scrolling never waits on it: a handler that must `preventDefault` adds its own listener in `onMount` with `{ passive: false }`.
|
|
31
31
|
- The loader carries only the strategies the app's islands can use. A page modulepreloads its eager islands with every chunk they import (a streamed page, its route's eager islands only); 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.
|
|
32
32
|
- **Island boundary**: props crossing it must be serializable: JSON primitives plus `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.
|
|
33
33
|
- A page island receives only the `load()` keys it reads. When the compiler cannot tell which (`data` passed whole to a helper or a child), the whole result is sent and build and check warn: `export const clientData = ['key']` or `(data) => subset` picks what is sent.
|
|
@@ -42,16 +42,18 @@
|
|
|
42
42
|
- 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 `_`.
|
|
43
43
|
- Params, groups & optionals: `(name)/` groups routes under its `_layout.tsx` and `_middleware.ts` without adding a URL segment; `[[lang]]/about.tsx` matches `/about` and `/fr/about` (`params.lang` typed `string | undefined`); `[slug].tsx` → `params.slug`; `[...path].tsx` → `params.path` (segments joined by `/`).
|
|
44
44
|
- Matchers: `[id=integer].tsx` and `[...path=slug].tsx` match only accepted values and fall through on mismatch (built-ins: `integer` → `` `${number}` ``, `uuid` → `` `${string}-${string}-${string}-${string}-${string}` ``, `slug` → `string`; custom matchers live in `src/params/<name>.ts` exporting `match` or `default`). Unknown matchers or conflicting route patterns fail build and check naming both files; precedence is `static > matched param > param > optional > catch-all`.
|
|
45
|
-
- 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
|
|
46
|
-
- API routes: `.ts` files exporting standard `HTTP_METHOD_EXPORTS` (`GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS`) receiving `RequestContext` (`request`, `url`, `params`, `cookies`, `locals`, `ip`, `requestId`, `region`, `json()`, `text()`, `redirect(location, status?, { external? })`, `deny()`). `redirect()` stays on this site: a target on another origin throws unless `{ external: true }`, so never pass one read from the request. CSRF checks run on every method outside the safe allowlist (`GET`, `HEAD`, `OPTIONS`), trusting only the forwarded origin when `trustProxy` resolves one (or `trustedOrigins`). `export const csrf = false` opts out of origin checks (webhooks, bearer APIs).
|
|
45
|
+
- 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` serving a `--static` export decode by the same rule (`/a%2fb.txt` never serves `a/b.txt`).
|
|
46
|
+
- API routes: `.ts` files exporting standard `HTTP_METHOD_EXPORTS` (`GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS`) receiving `RequestContext` (`request`, `url`, `params`, `cookies`, `locals`, `ip`, `requestId`, `region`, `json()`, `text()`, `redirect(location, status?, { external? })`, `deny()`). `redirect()` stays on this site: a target on another origin throws unless `{ external: true }`, so never pass one read from the request. CSRF checks run on every method outside the safe allowlist (`GET`, `HEAD`, `OPTIONS`), trusting only the forwarded origin when `trustProxy` resolves one (or `trustedOrigins`). `export const csrf = false` opts out of origin checks (webhooks, bearer APIs); `prunelle check` warns on it (`security/csrf-off`) until `// prunelle-ignore security/csrf-off` above the export says the route verifies its own signature or token.
|
|
47
47
|
- 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`, and so does a listed URL that answered other than `200` at build, which the build warns about). Skipped in `prunelle dev`. Static pages that read nothing from the request or clock are reported `cacheable` by `prunelle inspect` and prerender automatically with `autoPrerender: true` or `prunelle build --auto-prerender`.
|
|
48
|
+
- Page language: `export const lang = 'fr'` gives that route `<html lang="fr">` when it is written in another language than `lang` in `prunelle.config.ts` (a French accessibility statement on an English site). It wins over plugin head hooks such as `@prunellejs/i18n`'s; `@prunellejs/ui` labels keep the config's language. A value that is not a language tag literal (`'french'`, `''`, a variable) fails `prunelle check` and `prunelle build`.
|
|
49
|
+
- Slow responses: the server closes a request silent for 30 s (streamed pages and SSE lift it themselves); `export const idleTimeout = '5m'` (seconds or a duration string, `0` for no limit) sets it for that route's requests alone, from when its handler or page starts. A value that is not such a literal fails `prunelle check` and `prunelle build`.
|
|
48
50
|
- Route caching: `export const cache = '1h'` (or `{ maxAge: '1h', staleWhileRevalidate?: '1d' }`) serves a bounded in-memory LRU render (`routeCache: { maxEntries?, maxBytes? } | false`), re-renders in the background once stale, and sends `cache-control: public, s-maxage=..., stale-while-revalidate=...` (`private, no-cache` under an app `_middleware.ts`, which may gate it; the server cache still serves it behind the middleware), with a weak `ETag` that a matching `If-None-Match` turns into a `304`. Its key leaves out `utm_*`, `gclid`, `gbraid`, `wbraid`, `dclid`, `fbclid`, `msclkid`, `mc_cid` and `mc_eid`, so a campaign link reuses the entry (a page showing them reads them uncached). A cached route (or its layout `load()` or imported local modules) reading `ctx.cookies`, `ctx.locals`, `ctx.consent`, `ctx.ip`, `Cookie`/`Authorization` or dynamic/bulk headers, `getActionError()`, `<ConsentGate>`, or passing `ctx`/`props`/`request` to a helper that does (or cannot be followed) fails `prunelle check` and `prunelle build` naming the read; at runtime the route cache also refuses to store any render that reads private request data.
|
|
49
51
|
- **Streaming & Head**: `<Head><title>...</title></Head>` (innermost `<title>` wins). A page with no `<link rel="icon">` and no `public/favicon.ico` gets `<link rel="icon" href="data:,">`, so no `/favicon.ico` 404.
|
|
50
52
|
- `<Suspense fallback={<p>Loading</p>} error={<p>Failed</p>}><AsyncComp /></Suspense>` streams resolved HTML inline with 0 KB external JS. It takes exactly one child; an async component anywhere but as the only child of `<Suspense>` fails build and check, even inside an async page. Boundaries nest, time out after `streamTimeout` (default `30000` ms), and their errors also fire `onError`.
|
|
51
53
|
- `<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.
|
|
52
54
|
- **Regions** (`<Region>` from `prunelle`, swapped by `regions()` from `@prunellejs/spa`): `<Region name="pane" as="section" ...attrs>children</Region>` is server-only like `Head` and renders `<section data-pru-region="pane">`. `<a href data-pru-target="pane">` and `<form data-pru-target="pane">` swap that region in place with the server's answer; without JS the link or form loads the whole page. Load more, live search, nested regions, `refreshRegion()` and the mistakes it reports: `node_modules/@prunellejs/spa/llms.txt`.
|
|
53
55
|
- **Actions (`prunelle/server` & `useAction` from `prunelle`)**: `export const fn = action(standardSchema, async (input, ctx) => ..., options?)` or `action(async (ctx) => ...)`, a top-level named export so Prunelle can assign it a URL. `ctx` provides `redirect()` and `deny(status, message, fieldErrors?)`.
|
|
54
|
-
- Zero-JS form: `<form action={fn} method="post">`. Array fields are coerced from checkboxes/multi-selects (`name="tags"` or `name="tags[]"` always parses as an array `tags`, and dotted names like `name="address.city"` parse into nested objects `{ address: { city } }`). SSR adds `required`, `minlength`/`maxlength`, `min`/`max`/`step`, `pattern` and `type="email"|"url"|"number"` to `<input>`/`<select>`/`<textarea>` from the action's Standard Schema JSON Schema unless the app wrote that attribute (0 B client JS, no implicit `<option>` tags). A validation failure sets an `HttpOnly` flash cookie, read with `getActionError(ctx.locals)` (the flash is signed with `PRUNELLE_FORM_SECRET` or `AUTH_SECRET`; its `values` are the fields the action schema declares, minus secrets such as password, token, card or `format: "password"`, or exactly `flashFields`; a schema with no JSON Schema output declares none, so list `flashFields`), and redirects `303` to the trusted Referer.
|
|
56
|
+
- Zero-JS form: `<form action={fn} method="post">`. Array fields are coerced from checkboxes/multi-selects (`name="tags"` or `name="tags[]"` always parses as an array `tags`, and dotted names like `name="address.city"` parse into nested objects `{ address: { city } }`; a name that both holds a value and nests others, `a` beside `a.b`, answers `400` with that field in `fieldErrors`). SSR adds `required`, `minlength`/`maxlength`, `min`/`max`/`step`, `pattern` and `type="email"|"url"|"number"` to `<input>`/`<select>`/`<textarea>` from the action's Standard Schema JSON Schema unless the app wrote that attribute (0 B client JS, no implicit `<option>` tags). A validation failure sets an `HttpOnly` flash cookie, read with `getActionError(ctx.locals)` (the flash is signed with `PRUNELLE_FORM_SECRET` or `AUTH_SECRET`; its `values` are the fields the action schema declares, minus secrets such as password, token, card or `format: "password"`, or exactly `flashFields`; a schema with no JSON Schema output declares none, so list `flashFields`), and redirects `303` to the trusted Referer.
|
|
55
57
|
- `protect: { rateLimit?: { max, windowMs, key? }, honeypot?: boolean | string, minTime?: number }` (or top-level `rateLimit`) enforces `rateLimit` (`429` + `Retry-After` / flash+303) before body parsing, then honeypot/`minTime`, then schema validation. It renders a hidden honeypot and an action-URL-bound HMAC-signed `_pru_ts` timestamp into `<form action={fn}>` automatically and refuses bots, fast submits and timestamps older than two hours with `400` and the one message `Submission rejected` before the handler runs. Set `PRUNELLE_FORM_SECRET` or `AUTH_SECRET` in production when using `minTime`, else Prunelle logs a warning when the action is defined (the key is derived from it with HKDF). A `minTime` form an island renders only in the browser has no timestamp and is refused (`prunelle dev` says so): render it on the first render, hidden until needed. The timestamp is signed per request, so a `minTime` form on a page exporting `prerender = true` or `cache` fails `prunelle check` and `prunelle build` (`action/min-time-frozen`), a `--static` export of one fails the build, and `autoPrerender` leaves such a page to render at request time.
|
|
56
58
|
- `prunelle check` and `prunelle build` report unknown form fields with the closest name (a schema taking extra keys through `additionalProperties` or `patternProperties` accepts those), missing required fields, invalid `<select>` enum options, unsupported schema libraries (once per vendor) and unguarded public form actions without `protect`.
|
|
57
59
|
- Island RPC: `const res = await fn(data)` always resolves to `{ ok: true, data }` or `{ ok: false, status, error, fieldErrors?, issues? }`; it accepts `FormData` for files, and redirects navigate the page (to another site only for `ctx.redirect(url, status, { external: true })`; any other cross-site target fails with `Redirect to another site refused`).
|
|
@@ -77,11 +79,11 @@
|
|
|
77
79
|
- RGESN: `rgesn/autoplay` (`<video>`/`<audio>` with `autoplay`), `rgesn/img-size` (`<img>` without both `width` and `height`, unless spread), `rgesn/img-sizes` (a `srcset` of `w` descriptors without `sizes`), `rgesn/large-public-file` (a file in `public/` over 1 MB), `rgesn/declaration` (`/ecoconception` still holding a `[à compléter` placeholder), `rgesn/island-by-value` (an imported island read as a value, `const D = Counter`, `{ C: Counter }` or `c={Counter}`, which hydrates what holds it whole: render `<Counter />` itself).
|
|
78
80
|
- `lcen/legal-notice`: a page app missing `/mentions-legales`, `/legal`, or a localized variant (`/fr/mentions-legales`, `/[lang]/mentions-legales`), or a legal notice still holding a `[to fill in` placeholder.
|
|
79
81
|
- `rgpd/privacy-notice`: a `.tsx` file in `src/` with an `<input>` collecting an email or a phone number (`type="email|tel"` or `name="email|phone|tel"`) while the app has no `/privacy`, `/confidentialite`, `/politique-de-confidentialite` or localized variant, or a privacy notice still holding a `[to fill in` placeholder. The `app` template ships `/privacy` and links it under its sign-up form.
|
|
80
|
-
- Silence per rule with `compliance: { ignore: [...], legalNotice?: string | false, privacyNotice?: string | false, publicBody?: boolean }`, or `// prunelle-ignore <rule>` / `/* prunelle-ignore <rule> */` / `// prunelle-ignore-file <rule>`. The form check's warnings (`action/unguarded-public-form`, `form/invalid-option`, `form/schema-unsupported`, `form/unchecked` for an action module that fails to import) are silenced the same way, the comment going on the line above the `<form>` or `<option>`; its errors cannot be.
|
|
82
|
+
- Silence per rule with `compliance: { ignore: [...], legalNotice?: string | false, privacyNotice?: string | false, publicBody?: boolean }`, or `// prunelle-ignore <rule>` / `/* prunelle-ignore <rule> */` / `// prunelle-ignore-file <rule>`. The form check's warnings (`action/unguarded-public-form`, `form/invalid-option`, `form/schema-unsupported`, `form/unchecked` for an action module that fails to import) are silenced the same way, the comment going on the line above the `<form>` or `<option>`; its errors cannot be. So is `security/csrf-off`, the comment going above `export const csrf = false`.
|
|
81
83
|
- One-declaration consent: `consent: { categories: ['analytics', 'media'] | { analytics: 'Audience measurement' }, cookieName?: 'pru_consent', maxAge?: 15552000, endpoint?: '/_pru/consent', version?: '2026-11' }` wires a CSRF-protected `POST /_pru/consent` endpoint (a zero-JS `<form method="post" action="/_pru/consent">` with `action="accept-all"|"reject-all"` or category checkboxes, `name="categories" value="analytics"` or `name="analytics"`, gets a `303`, JSON a `200`), exposes `ctx.consent` (`decided`, `decidedAt`, `categories`, `labels`, `endpoint`, `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). The cookie stores the time of the choice and `version`: changing `version` asks every visitor again. `prunelle check` warns (`rgpd/consent-retention`) when `maxAge` is past 180 days, and `prunelle dev` warns once per cookie set with no `category`, which counts as essential.
|
|
82
84
|
- `<ConsentBanner policyHref?="/cookies" policyLabel? title? accept? refuse? choose? save? legend?>{text?}</ConsentBanner>` renders, until the visitor decides, a form with Refuse all and Accept all side by side and the categories (by label) behind a `<details>`; `<ConsentPreferences />` renders the choice in force, to change or withdraw it (put it on the cookie policy page). Both are server-only, private on a cached route, and throw `prunelle: <ConsentBanner> has no consent category to ask about` without `consent.categories`. Markup: `data-ui="consent"` with `data-part` `title`, `body`, `form`, `actions`, `details`, `choices`, `choice`, `preferences`; buttons carry `data-ui="button"`.
|
|
83
85
|
- **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 press (`eagerness: conservative`); it 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`.
|
|
84
|
-
- `defineConfig({ navigation: { viewTransitions?: boolean (true), prefetch?: 'conservative' | 'moderate' | 'eager' | false ('conservative'), prerender?: 'conservative' | 'moderate' | 'eager' | boolean (false; true is 'moderate'; it runs `load()` of pages nobody opens) } })`; a bad value throws `prunelle: navigation.<key> is ...`.
|
|
86
|
+
- `defineConfig({ navigation: { viewTransitions?: boolean (true; `false` also keeps `@prunellejs/spa` region and page swaps out of view transitions), prefetch?: 'conservative' | 'moderate' | 'eager' | false ('conservative'), prerender?: 'conservative' | 'moderate' | 'eager' | boolean (false; true is 'moderate'; it runs `load()` of pages nobody opens) } })`; a bad value throws `prunelle: navigation.<key> is ...`.
|
|
85
87
|
- `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; a no-op when `sessionStorage` is blocked), through one inline hashed script at the end of `<body>` on pages using 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.
|
|
86
88
|
- **Static files & CSS**: Files in `public/` are served at `/` (dotfiles and dot folders stay out of the build except `.well-known/`; `prunelle check` warns `security/public-dotfile`; a plugin `emitAsset`/`emitPublic` path that leaves the output folder throws, naming the plugin) with ETag/`304` (`Cache-Control: no-cache` in `prunelle dev`; embedded in `--static` and `--compile`); prerendered pages (sent with `Cache-Control: no-cache`, so a revisit revalidates) and hashed assets answer an ETag, a `304` and a `HEAD` length too. Import `.css` or `*.module.css` directly from any component or layout.
|
|
87
89
|
- `prunelle build` consolidates local stylesheets into at most one site-wide hashed immutable sheet plus one per-route sheet when needed, preserving `@layer` and plugin-before-app cascade order.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "prunelle",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.5",
|
|
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",
|
package/src/build/routes.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
// Route files: their URL patterns, groups, param matchers, conflicts, and the `_layout`/`_middleware` chain that wraps them.
|
|
2
2
|
|
|
3
|
+
import type { Expression } from 'oxc-parser'
|
|
3
4
|
import type { ModuleAnalysis } from '../compiler/index'
|
|
4
5
|
import { existsSync } from 'node:fs'
|
|
5
6
|
import { basename, dirname, join, relative } from 'node:path'
|
|
6
7
|
import { parseCacheExport } from '../compiler/cacheability'
|
|
8
|
+
import { parseCacheDuration } from '../server/route-cache'
|
|
7
9
|
import { BUILTIN_PARAM_MATCHER_NAMES, extractPatternMatchers, isBuiltinMatcher, parsePatternSegment } from '../server/param-matchers'
|
|
8
10
|
import { relPosix } from './files'
|
|
9
11
|
|
|
@@ -144,6 +146,18 @@ function findExportOffset(analysis: ModuleAnalysis, exportName: string): number
|
|
|
144
146
|
return 0
|
|
145
147
|
}
|
|
146
148
|
|
|
149
|
+
// `idleTimeout = -1` as written: a negative number is a unary minus on a literal.
|
|
150
|
+
function idleTimeoutText(init: Expression | null | undefined): string | undefined {
|
|
151
|
+
if (init?.type === 'Literal')
|
|
152
|
+
return `idleTimeout = ${init.raw ?? String(init.value)}`
|
|
153
|
+
if (init?.type === 'UnaryExpression' && init.operator === '-' && init.argument.type === 'Literal')
|
|
154
|
+
return `idleTimeout = -${init.argument.raw ?? String(init.argument.value)}`
|
|
155
|
+
return undefined
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** A BCP 47 language tag as `<html lang>` takes it: `fr`, `en-GB`, `zh-Hant-TW`. */
|
|
159
|
+
const LANG_TAG_RE = /^[a-z]{2,3}(?:-[a-z\d]{2,8})*$/i
|
|
160
|
+
|
|
147
161
|
/** Returns the first route export problem together with its byte offset in the module source. */
|
|
148
162
|
export function routeExportProblemLocation(analysis: ModuleAnalysis, file: string): { message: string, offset: number } | undefined {
|
|
149
163
|
for (const name of analysis.exportedNames) {
|
|
@@ -159,6 +173,10 @@ export function routeExportProblemLocation(analysis: ModuleAnalysis, file: strin
|
|
|
159
173
|
const init = d.init
|
|
160
174
|
if (name === 'paths' && init !== null && init.type !== 'ArrowFunctionExpression' && init.type !== 'FunctionExpression')
|
|
161
175
|
return { message: `export const paths in ${file}: export function paths() returning the URLs, such as () => ['/posts/a'].`, offset: d.start }
|
|
176
|
+
if (name === 'lang' && !(init?.type === 'Literal' && typeof init.value === 'string' && LANG_TAG_RE.test(init.value)))
|
|
177
|
+
return { message: `${init?.type === 'Literal' ? `lang = ${init.raw ?? String(init.value)}` : 'lang set at runtime'} in ${file}: write the language the page is written in, such as lang = 'fr' or lang = 'en-GB'.`, offset: d.start }
|
|
178
|
+
if (name === 'idleTimeout' && !(init?.type === 'Literal' && parseCacheDuration(init.value, true) !== undefined))
|
|
179
|
+
return { message: `${idleTimeoutText(init) ?? 'idleTimeout set at runtime'} in ${file}: write the seconds a request may stay silent, such as idleTimeout = 120 or idleTimeout = '5m', or 0 for no limit.`, offset: d.start }
|
|
162
180
|
if (name === 'prerender' && !(init?.type === 'Literal' && typeof init.value === 'boolean'))
|
|
163
181
|
return { message: `${init?.type === 'Literal' ? `prerender = ${init.raw ?? String(init.value)}` : 'prerender set at runtime'} in ${file}: write prerender = true or prerender = false.`, offset: d.start }
|
|
164
182
|
}
|
|
@@ -169,7 +187,7 @@ export function routeExportProblemLocation(analysis: ModuleAnalysis, file: strin
|
|
|
169
187
|
return undefined
|
|
170
188
|
}
|
|
171
189
|
|
|
172
|
-
/** The first route export prunelle never reads (Next, Remix and Astro names), `paths` that is not a function,
|
|
190
|
+
/** The first route export prunelle never reads (Next, Remix and Astro names), `paths` that is not a function, `prerender` that is not literally `true` or `false`, or `lang` that is not a language tag literal, worded for `prunelle build` and `prunelle check` to prefix. */
|
|
173
191
|
export function routeExportProblem(analysis: ModuleAnalysis, file: string): string | undefined {
|
|
174
192
|
return routeExportProblemLocation(analysis, file)?.message
|
|
175
193
|
}
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
// `prunelle check` warnings about what weakens an app's defences: dotfiles under public/, and the security opt-outs in its config.
|
|
2
2
|
|
|
3
3
|
import type { Node } from 'oxc-parser'
|
|
4
|
+
import type { ComplianceConfig } from '../compiler/compliance'
|
|
4
5
|
import type { SecurityHeadersOptions } from '../server/security'
|
|
5
6
|
import { relative } from 'node:path'
|
|
6
7
|
import { parseSync } from 'oxc-parser'
|
|
7
8
|
import { isHiddenPublicPath, walkAllFiles } from '../build/files'
|
|
8
9
|
import { walk } from '../compiler/ast'
|
|
10
|
+
import { isIgnoredAt, isRuleIgnored, parsePrunelleIgnores } from '../compiler/compliance'
|
|
9
11
|
import { formatDiagnostic, unwrapTsExpr } from '../compiler/shared'
|
|
10
12
|
import { resolveCspPolicy } from '../server/security'
|
|
11
13
|
|
|
@@ -120,12 +122,18 @@ export function securityConfigWarnings(security: SecurityHeadersOptions | false
|
|
|
120
122
|
|
|
121
123
|
const CSRF_OFF_RE = /export\s+const\s+csrf\s*=\s*false\b/g
|
|
122
124
|
|
|
123
|
-
/** One warning per route file that exports `csrf = false`: it accepts a cross-site POST, so it must check a signature or a token itself. */
|
|
124
|
-
export function csrfOffWarnings(files: readonly string[], read: (file: string) => string, locate: (file: string, offset: number) => string): string[] {
|
|
125
|
+
/** One warning per route file that exports `csrf = false`: it accepts a cross-site POST, so it must check a signature or a token itself. A route that does says so with `// prunelle-ignore security/csrf-off` above the export. */
|
|
126
|
+
export function csrfOffWarnings(files: readonly string[], read: (file: string) => string, locate: (file: string, offset: number) => string, compliance?: ComplianceConfig | undefined): string[] {
|
|
127
|
+
if (isRuleIgnored('security/csrf-off', compliance))
|
|
128
|
+
return []
|
|
125
129
|
const warnings: string[] = []
|
|
126
130
|
for (const file of files) {
|
|
127
|
-
|
|
128
|
-
|
|
131
|
+
const code = read(file)
|
|
132
|
+
const ignores = parsePrunelleIgnores(code)
|
|
133
|
+
for (const match of code.matchAll(CSRF_OFF_RE)) {
|
|
134
|
+
if (!isIgnoredAt(ignores, 'security/csrf-off', match.index))
|
|
135
|
+
warnings.push(formatDiagnostic(locate(file, match.index), '[security/csrf-off] this route skips the cross-site request check, so any site can post to it: keep it only for a webhook or bearer-token API that verifies a signature or token itself, and say so with `// prunelle-ignore security/csrf-off` above the export; drop `export const csrf = false` for anything a browser form posts to.', 'warning'))
|
|
136
|
+
}
|
|
129
137
|
}
|
|
130
138
|
return warnings
|
|
131
139
|
}
|
package/src/cli/check.ts
CHANGED
|
@@ -394,7 +394,7 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
394
394
|
|
|
395
395
|
warnings.push(...publicDotfileWarnings(publicDir, root))
|
|
396
396
|
warnings.push(...securityConfigWarnings(loadedConfig.security))
|
|
397
|
-
warnings.push(...csrfOffWarnings(routeFiles, file => sourceOf(file, sources), (file, offset) => locOf(root, file, sources, offset)))
|
|
397
|
+
warnings.push(...csrfOffWarnings(routeFiles, file => sourceOf(file, sources), (file, offset) => locOf(root, file, sources, offset), compliance))
|
|
398
398
|
warnings.push(...externalRedirectWarnings(files, file => sourceOf(file, sources), (file, offset) => locOf(root, file, sources, offset)))
|
|
399
399
|
|
|
400
400
|
// 3e. Broken internal link checks (#3)
|
|
@@ -41,6 +41,7 @@ export type ComplianceRule =
|
|
|
41
41
|
| 'lcen/legal-notice'
|
|
42
42
|
| 'rgaa/document-lang'
|
|
43
43
|
| 'rgaa/accessibility-statement'
|
|
44
|
+
| 'security/csrf-off'
|
|
44
45
|
| FormWarningRule
|
|
45
46
|
|
|
46
47
|
/** The warnings of the form-vs-action check (`cli/check-forms.ts`), silenced like the compliance rules. */
|
|
@@ -69,6 +70,7 @@ const COMPLIANCE_RULES = new Set<ComplianceRule>([
|
|
|
69
70
|
'lcen/legal-notice',
|
|
70
71
|
'rgaa/document-lang',
|
|
71
72
|
'rgaa/accessibility-statement',
|
|
73
|
+
'security/csrf-off',
|
|
72
74
|
'action/unguarded-public-form',
|
|
73
75
|
'form/invalid-option',
|
|
74
76
|
'form/schema-unsupported',
|
package/src/dev/index.ts
CHANGED
|
@@ -98,7 +98,7 @@ async function handleAppFetch(
|
|
|
98
98
|
if (state.lastError !== undefined)
|
|
99
99
|
return buildErrorResponse(request, state.lastError, state.reloadAssets.script)
|
|
100
100
|
|
|
101
|
-
const res = await state.app!.handle(request, remoteIp)
|
|
101
|
+
const res = await state.app!.handle(request, remoteIp, seconds => srv.timeout(request, seconds))
|
|
102
102
|
const ct = res.headers.get('content-type') ?? ''
|
|
103
103
|
const isStreamedHtml = ct.includes('text/html') && request.method !== 'HEAD' && res.body !== null && !res.headers.has('content-length')
|
|
104
104
|
if (ct.includes('text/event-stream') || isStreamedHtml)
|
package/src/dev/supervisor.ts
CHANGED
|
@@ -162,6 +162,8 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
|
|
|
162
162
|
const child = await ready
|
|
163
163
|
if (child === undefined)
|
|
164
164
|
return buildErrorResponse(request, crashed ?? 'prunelle dev: the app process is not running.', reloadAssets.script)
|
|
165
|
+
// The app process keeps its own idle timeout, which a stream or a route's `export const idleTimeout` sets, so this hop waits on it alone.
|
|
166
|
+
srv.timeout(request, 0)
|
|
165
167
|
const headers = new Headers(request.headers)
|
|
166
168
|
headers.set(DEV_CLIENT_IP_HEADER, srv.requestIP(request)?.address ?? '')
|
|
167
169
|
try {
|
|
@@ -173,8 +175,6 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
|
|
|
173
175
|
redirect: 'manual',
|
|
174
176
|
signal: request.signal,
|
|
175
177
|
})
|
|
176
|
-
if (!res.headers.has('content-length'))
|
|
177
|
-
srv.timeout(request, 0)
|
|
178
178
|
return res
|
|
179
179
|
}
|
|
180
180
|
catch (err) {
|
package/src/dom/island.ts
CHANGED
|
@@ -71,7 +71,7 @@ function collectVisibleTargets(root: Element, out: Element[]): void {
|
|
|
71
71
|
function replayEvent(root: Element, ev: Event, target: EventTarget | null): void {
|
|
72
72
|
if (target === null || typeof target.dispatchEvent !== 'function')
|
|
73
73
|
return
|
|
74
|
-
if (typeof (target as Node).nodeType === 'number' && !root.contains(target as Node))
|
|
74
|
+
if (typeof (target as Node).nodeType === 'number' && target !== document && !root.contains(target as Node))
|
|
75
75
|
return
|
|
76
76
|
const init: EventInit = { bubbles: ev.bubbles, cancelable: ev.cancelable, composed: ev.composed }
|
|
77
77
|
let clone: Event
|
|
@@ -90,16 +90,31 @@ function replayEvent(root: Element, ev: Event, target: EventTarget | null): void
|
|
|
90
90
|
target.dispatchEvent(clone)
|
|
91
91
|
}
|
|
92
92
|
|
|
93
|
+
const MODIFIERS = ['Alt', 'Control', 'Meta', 'Shift']
|
|
94
|
+
|
|
95
|
+
// True when the key is one an element inside names with `aria-keyshortcuts="Control+K Meta+K"`, with exactly its modifiers held.
|
|
96
|
+
function isKeyShortcut(root: Element, e: KeyboardEvent): boolean {
|
|
97
|
+
for (const el of root.querySelectorAll('[aria-keyshortcuts]')) {
|
|
98
|
+
for (const combo of el.getAttribute('aria-keyshortcuts')!.split(' ')) {
|
|
99
|
+
const parts = combo.split('+')
|
|
100
|
+
if (parts.pop()!.toLowerCase() === e.key?.toLowerCase() && MODIFIERS.every(m => e.getModifierState(m) === parts.includes(m)))
|
|
101
|
+
return true
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return false
|
|
105
|
+
}
|
|
106
|
+
|
|
93
107
|
// A failed load keeps the listeners and drops the queued events: the next interaction loads the chunk again and is replayed once it is in.
|
|
108
|
+
// A shortcut the island declares is heard on the whole page, kept from the browser, and replayed on the document, where the component listens for it.
|
|
94
109
|
function watchInteraction(root: Element, onTrigger: (after: () => void) => Promise<boolean>): () => void {
|
|
95
110
|
const evs = ['pointerdown', 'click', 'focusin', 'keydown']
|
|
96
111
|
const queued: { ev: Event, target: EventTarget | null }[] = []
|
|
97
112
|
let loading = false
|
|
98
|
-
const go = (ev: Event) => {
|
|
113
|
+
const go = (ev: Event, target = ev.target) => {
|
|
99
114
|
// Prevent native toggle/submit/navigation before hydration so replaying the click triggers it once with handlers attached.
|
|
100
115
|
if (ev.type === 'click')
|
|
101
116
|
ev.preventDefault()
|
|
102
|
-
queued.push({ ev, target
|
|
117
|
+
queued.push({ ev, target })
|
|
103
118
|
if (!loading) {
|
|
104
119
|
loading = true
|
|
105
120
|
void onTrigger(() => {
|
|
@@ -113,9 +128,18 @@ function watchInteraction(root: Element, onTrigger: (after: () => void) => Promi
|
|
|
113
128
|
})
|
|
114
129
|
}
|
|
115
130
|
}
|
|
131
|
+
const onShortcut = (ev: Event) => {
|
|
132
|
+
if (!isKeyShortcut(root, ev as KeyboardEvent))
|
|
133
|
+
return
|
|
134
|
+
ev.preventDefault()
|
|
135
|
+
if (!root.contains(ev.target as Node))
|
|
136
|
+
go(ev, document)
|
|
137
|
+
}
|
|
116
138
|
for (const e of evs) root.addEventListener(e, go, true)
|
|
139
|
+
addEventListener('keydown', onShortcut, true)
|
|
117
140
|
return () => {
|
|
118
141
|
for (const e of evs) root.removeEventListener(e, go, true)
|
|
142
|
+
removeEventListener('keydown', onShortcut, true)
|
|
119
143
|
}
|
|
120
144
|
}
|
|
121
145
|
|
|
@@ -300,7 +324,9 @@ export function defineIslandElement(): void {
|
|
|
300
324
|
return true
|
|
301
325
|
}
|
|
302
326
|
this._d = dispose
|
|
303
|
-
|
|
327
|
+
// Queued behind the component's `onMount` callbacks, so a listener it binds there hears the replayed event.
|
|
328
|
+
if (after)
|
|
329
|
+
queueMicrotask(after)
|
|
304
330
|
return true
|
|
305
331
|
}
|
|
306
332
|
catch (err) {
|
package/src/plugins/services.ts
CHANGED
|
@@ -85,6 +85,7 @@ export const CMS_INLINE_ENABLED_SERVICE = serviceKey<boolean>('prunelle.cms.inli
|
|
|
85
85
|
export interface JobsQueueOptions {
|
|
86
86
|
attempts?: number | undefined
|
|
87
87
|
backoff?: 'exponential' | 'fixed' | number | undefined
|
|
88
|
+
timeout?: number | undefined
|
|
88
89
|
}
|
|
89
90
|
|
|
90
91
|
export interface JobsEnqueueOptions {
|
package/src/server/action.ts
CHANGED
|
@@ -157,54 +157,58 @@ function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
|
|
157
157
|
return typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Blob)
|
|
158
158
|
}
|
|
159
159
|
|
|
160
|
-
|
|
160
|
+
/** A form field whose name both holds a value and nests dotted fields (`a` and `a.b`): the body has no shape that keeps both. */
|
|
161
|
+
class FormFieldConflict extends Error {
|
|
162
|
+
constructor(readonly field: string) {
|
|
163
|
+
super(`form field "${field}" conflicts with another field`)
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function appendFormValue(target: Record<string, unknown>, key: string, value: FormDataEntryValue, forceArray: boolean, rawKey: string): void {
|
|
161
168
|
if (!Object.hasOwn(target, key)) {
|
|
162
169
|
setField(target, key, forceArray ? [value] : value)
|
|
163
170
|
return
|
|
164
171
|
}
|
|
165
172
|
const prev = target[key]
|
|
173
|
+
if (isPlainRecord(prev))
|
|
174
|
+
throw new FormFieldConflict(rawKey)
|
|
166
175
|
if (Array.isArray(prev))
|
|
167
176
|
prev.push(value)
|
|
168
177
|
else
|
|
169
178
|
setField(target, key, [prev, value])
|
|
170
179
|
}
|
|
171
180
|
|
|
172
|
-
/** Parses `FormData` into a plain record, mapping trailing `[]` names to arrays and dotted names (`a.b`, `a.b.c`) to nested objects safely. */
|
|
181
|
+
/** Parses `FormData` into a plain record, mapping trailing `[]` names to arrays and dotted names (`a.b`, `a.b.c`) to nested objects safely; throws `FormFieldConflict` when a name both holds a value and nests others. */
|
|
173
182
|
export function parseFormData(formData: FormData): Record<string, unknown> {
|
|
174
183
|
const out: Record<string, unknown> = {}
|
|
175
184
|
for (const [rawKey, val] of formData.entries()) {
|
|
176
185
|
const forceArray = rawKey.length > 2 && rawKey.endsWith('[]')
|
|
177
186
|
const key = forceArray ? rawKey.slice(0, -2) : rawKey
|
|
178
187
|
if (!key.includes('.')) {
|
|
179
|
-
appendFormValue(out, key, val, forceArray)
|
|
188
|
+
appendFormValue(out, key, val, forceArray, rawKey)
|
|
180
189
|
continue
|
|
181
190
|
}
|
|
182
191
|
const parts = key.split('.')
|
|
183
192
|
if (parts.some(p => UNSAFE_NESTED_KEYS.has(p)))
|
|
184
193
|
continue
|
|
185
194
|
if (parts.length > MAX_NESTED_DEPTH || parts.some(p => p.length === 0)) {
|
|
186
|
-
appendFormValue(out, key, val, forceArray)
|
|
195
|
+
appendFormValue(out, key, val, forceArray, rawKey)
|
|
187
196
|
continue
|
|
188
197
|
}
|
|
189
198
|
let cur = out
|
|
190
|
-
|
|
191
|
-
for (let i = 0; i < parts.length - 1; i++) {
|
|
192
|
-
const seg = parts[i]!
|
|
199
|
+
for (const seg of parts.slice(0, -1)) {
|
|
193
200
|
if (!Object.hasOwn(cur, seg)) {
|
|
194
201
|
const next: Record<string, unknown> = {}
|
|
195
202
|
setField(cur, seg, next)
|
|
196
203
|
cur = next
|
|
204
|
+
continue
|
|
197
205
|
}
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
blocked = true
|
|
203
|
-
break
|
|
204
|
-
}
|
|
206
|
+
const held = cur[seg]
|
|
207
|
+
if (!isPlainRecord(held))
|
|
208
|
+
throw new FormFieldConflict(rawKey)
|
|
209
|
+
cur = held
|
|
205
210
|
}
|
|
206
|
-
|
|
207
|
-
appendFormValue(cur, parts[parts.length - 1]!, val, forceArray)
|
|
211
|
+
appendFormValue(cur, parts[parts.length - 1]!, val, forceArray, rawKey)
|
|
208
212
|
}
|
|
209
213
|
return out
|
|
210
214
|
}
|
|
@@ -448,8 +452,12 @@ export async function executeAction(
|
|
|
448
452
|
try {
|
|
449
453
|
rawBody = await parseActionBody(request)
|
|
450
454
|
}
|
|
451
|
-
catch {
|
|
452
|
-
|
|
455
|
+
catch (error) {
|
|
456
|
+
if (!(error instanceof FormFieldConflict))
|
|
457
|
+
return Response.json({ ok: false, status: 400, error: 'Invalid request body' }, { status: 400 })
|
|
458
|
+
const fieldErrors = { [error.field]: 'This field conflicts with another field of the form' }
|
|
459
|
+
return flashAndRedirect('Invalid request body', fieldErrors, undefined)
|
|
460
|
+
?? Response.json({ ok: false, status: 400, error: 'Invalid request body', fieldErrors }, { status: 400 })
|
|
453
461
|
}
|
|
454
462
|
}
|
|
455
463
|
|
package/src/server/http.ts
CHANGED
|
@@ -167,7 +167,7 @@ export type Middleware = (ctx: RequestContext, next: () => Promise<Response>) =>
|
|
|
167
167
|
export type PrunelleServer = ReturnType<typeof Bun.serve>
|
|
168
168
|
|
|
169
169
|
export interface PrunelleApp {
|
|
170
|
-
handle: (request: Request, remoteIp?: string,
|
|
170
|
+
handle: (request: Request, remoteIp?: string, setIdleTimeout?: (seconds: number) => void) => Promise<Response>
|
|
171
171
|
serve: (port?: number, hostname?: string) => PrunelleServer
|
|
172
172
|
/** @internal Swaps this app's handlers into a server another app started, with no dropped connection: `prunelle start` reloads a new build with it. */
|
|
173
173
|
reloadInto?: (server: PrunelleServer) => void
|
package/src/server/index.ts
CHANGED
|
@@ -440,7 +440,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
440
440
|
}
|
|
441
441
|
|
|
442
442
|
// `bodyLimited` is set under `serve()`, where Bun.serve already enforces maxRequestBodySize on every body, chunked ones included.
|
|
443
|
-
async function handleInternal(request: Request, remoteIp?: string,
|
|
443
|
+
async function handleInternal(request: Request, remoteIp?: string, setIdleTimeout?: (seconds: number) => void, bodyLimited = false): Promise<Response> {
|
|
444
444
|
const requestId = resolveRequestId(request)
|
|
445
445
|
try {
|
|
446
446
|
const url = new URL(request.url)
|
|
@@ -522,7 +522,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
522
522
|
if (headFallbackPluginDef !== undefined)
|
|
523
523
|
res = stripHeadBody(res)
|
|
524
524
|
else if (isEventStream(res))
|
|
525
|
-
res = streams.track(res,
|
|
525
|
+
res = streams.track(res, setIdleTimeout)
|
|
526
526
|
return finish(await maybeCompressResponse(await withPluginHtmlCsp(res, htmlHeaders), ctx.request, compressCache), ctx.request, cookieStore, requestId, formatServerTiming(timing))
|
|
527
527
|
}
|
|
528
528
|
catch (error) {
|
|
@@ -577,9 +577,9 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
577
577
|
: route.middlewares
|
|
578
578
|
|
|
579
579
|
try {
|
|
580
|
-
const rawRes = await actions.run(ctx, () => runTimedChain(ctx, routeMiddlewares, () => renderCompiledRoute(route, ctx, cookieStore,
|
|
580
|
+
const rawRes = await actions.run(ctx, () => runTimedChain(ctx, routeMiddlewares, () => renderCompiledRoute(route, ctx, cookieStore, setIdleTimeout, staticPath, timing, routeMiddlewares), timing, runChain))
|
|
581
581
|
const handledRes = await maybeRenderDenied(rawRes, ctx.request, ctx.url, ctx, renderDenied, route.entry.file, isApiHandler(route.mod, method))
|
|
582
|
-
const res = isEventStream(handledRes) ? streams.track(handledRes,
|
|
582
|
+
const res = isEventStream(handledRes) ? streams.track(handledRes, setIdleTimeout) : handledRes
|
|
583
583
|
// Compress uncompressed API/middleware responses after the middleware chain unwinds.
|
|
584
584
|
const finalRes = res.headers.has('content-encoding') ? res : await maybeCompressResponse(res, ctx.request, compressCache)
|
|
585
585
|
return finish(finalRes, ctx.request, cookieStore, requestId, formatServerTiming(timing))
|
|
@@ -595,11 +595,11 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
595
595
|
}
|
|
596
596
|
}
|
|
597
597
|
|
|
598
|
-
function handle(request: Request, remoteIp?: string,
|
|
599
|
-
return runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp,
|
|
598
|
+
function handle(request: Request, remoteIp?: string, setIdleTimeout?: (seconds: number) => void): Promise<Response> {
|
|
599
|
+
return runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp, setIdleTimeout))
|
|
600
600
|
}
|
|
601
601
|
|
|
602
|
-
const runRequest = (req: Request, remoteIp: string | undefined,
|
|
602
|
+
const runRequest = (req: Request, remoteIp: string | undefined, setIdleTimeout: (seconds: number) => void): Promise<Response> => runWithAppContext(serverAppCtx, () => handleInternal(req, remoteIp, setIdleTimeout, true))
|
|
603
603
|
const runFast = (handler: FastHandler, req: Request, remoteIp: string | undefined): Response | Promise<Response> => runWithAppContext(serverAppCtx, () => handler(req, remoteIp))
|
|
604
604
|
const handlers = (server: () => PrunelleServer | undefined) => serveHandlers(server, { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone })
|
|
605
605
|
|
package/src/server/page.ts
CHANGED
|
@@ -12,6 +12,10 @@ export interface LoadedPageModule {
|
|
|
12
12
|
load?: (ctx: RequestContext) => unknown | Promise<unknown>
|
|
13
13
|
clientData?: readonly string[] | ((data: unknown) => unknown) | undefined
|
|
14
14
|
csrf?: boolean | undefined
|
|
15
|
+
/** The language the page is written in, for its `<html lang>`, when it differs from `lang` in prunelle.config.ts. */
|
|
16
|
+
lang?: string | undefined
|
|
17
|
+
/** How long this route's request may stay silent before the connection closes, in seconds or a duration string (`'5m'`), `0` for no limit; the server's is 30 s. */
|
|
18
|
+
idleTimeout?: number | string | undefined
|
|
15
19
|
GET?: (ctx: RequestContext) => Response | Promise<Response>
|
|
16
20
|
POST?: (ctx: RequestContext) => Response | Promise<Response>
|
|
17
21
|
PUT?: (ctx: RequestContext) => Response | Promise<Response>
|
|
@@ -31,7 +31,7 @@ import { isNotFound, makeRequestContext, runChain } from './http'
|
|
|
31
31
|
import { allowedMethodsHeader, hasPublicFavicon, mergedHeadTags, pickPageIslandProps, stripHeadBody } from './page'
|
|
32
32
|
import { BUILTIN_PARAM_MATCHERS } from './param-matchers'
|
|
33
33
|
import { hasRegionHeader, invalidRegionResponse, requestedRegion, respondRegion, withRegionVary } from './region'
|
|
34
|
-
import { GATED_ROUTE_CACHE_CONTROL, isCacheableRequest, routeCacheKey, serveCachedHit, trackPrivateReads, withCacheControl } from './route-cache'
|
|
34
|
+
import { GATED_ROUTE_CACHE_CONTROL, isCacheableRequest, parseCacheDuration, routeCacheKey, serveCachedHit, trackPrivateReads, withCacheControl } from './route-cache'
|
|
35
35
|
import { Router } from './router'
|
|
36
36
|
import { createFastStaticPageHandler, methodNotAllowed } from './routing'
|
|
37
37
|
import { styleHashesOf } from './security'
|
|
@@ -60,13 +60,20 @@ export interface CompiledRoute {
|
|
|
60
60
|
/** Options every document of this route shares; a request adds its body, head and islands. */
|
|
61
61
|
doc: DocumentOptions
|
|
62
62
|
headStyleHashes: string[]
|
|
63
|
+
/** The route's `export const idleTimeout` in whole seconds, as `server.timeout()` takes it. */
|
|
64
|
+
idleTimeout: number | undefined
|
|
63
65
|
}
|
|
64
66
|
|
|
65
|
-
function
|
|
67
|
+
function routeIdleTimeout(value: unknown): number | undefined {
|
|
68
|
+
const ms = value === undefined ? undefined : parseCacheDuration(value, true)
|
|
69
|
+
return ms === undefined ? undefined : Math.ceil(ms / 1000)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function routeDocument(manifest: BuildManifest, entry: RouteManifestEntry, mod: LoadedPageModule, lang: string, alwaysLoadRuntime: boolean, navigation: DocumentOptions['navigation'], hasFavicon: boolean): DocumentOptions {
|
|
66
73
|
return {
|
|
67
74
|
body: '',
|
|
68
75
|
headTags: mergedHeadTags(manifest, entry),
|
|
69
|
-
lang,
|
|
76
|
+
lang: typeof mod.lang === 'string' ? mod.lang : lang,
|
|
70
77
|
runtimeScript: manifest.runtimeScript,
|
|
71
78
|
chunkImports: manifest.chunkImports,
|
|
72
79
|
alwaysLoadRuntime,
|
|
@@ -104,18 +111,19 @@ export function compileRouteTable(options: RouteTableOptions): { router: Router<
|
|
|
104
111
|
const dirMiddlewares = entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default)
|
|
105
112
|
const hasLoad = Boolean(entry.hasLoad && typeof mod.load === 'function')
|
|
106
113
|
const dynamic = entry.path.includes(':') || entry.path.includes('*')
|
|
107
|
-
const doc = routeDocument(manifest, entry, lang, alwaysLoadRuntime, navigation, hasFavicon)
|
|
114
|
+
const doc = routeDocument(manifest, entry, mod, lang, alwaysLoadRuntime, navigation, hasFavicon)
|
|
115
|
+
const idleTimeout = routeIdleTimeout(mod.idleTimeout)
|
|
108
116
|
|
|
109
117
|
// Zero-overhead path for a static route with no middleware, no <Head>/<Suspense>, no route cache, and no intercepting plugin hook
|
|
110
118
|
const canFastPath = middlewaresFor(entry.path, hasLoad ? 'dynamic' : 'static').length === 0
|
|
111
119
|
&& !pluginIntercepts(entry.path) && !dynamic
|
|
112
120
|
&& dirMiddlewares.length === 0 && !entry.usesRenderContext && entry.cache === undefined
|
|
113
|
-
&& typeof mod.default === 'function' && mod.GET === undefined
|
|
121
|
+
&& typeof mod.default === 'function' && mod.GET === undefined && idleTimeout === undefined
|
|
114
122
|
if (canFastPath)
|
|
115
123
|
fastStaticPages.set(entry.path, createFastStaticPageHandler({ ...fast, entry, mod, layouts, doc, reviveScript: manifest.reviveScript, hasIslands: entry.islandChunks.length > 0, hasLoad }))
|
|
116
124
|
|
|
117
125
|
const routeEntry = entry.cache !== undefined && dirMiddlewares.length > 0 ? { ...entry, cache: { ...entry.cache, cacheControl: GATED_ROUTE_CACHE_CONTROL } } : entry
|
|
118
|
-
router.add(entry.path, { entry: routeEntry, mod, layouts, dirMiddlewares, middlewares: [...middlewaresFor(entry.path), ...dirMiddlewares], dynamic, doc, headStyleHashes: headTagStyleHashes(doc.headTags) })
|
|
126
|
+
router.add(entry.path, { entry: routeEntry, mod, layouts, dirMiddlewares, middlewares: [...middlewaresFor(entry.path), ...dirMiddlewares], dynamic, doc, headStyleHashes: headTagStyleHashes(doc.headTags), idleTimeout })
|
|
119
127
|
}
|
|
120
128
|
return { router, fastStaticPages }
|
|
121
129
|
}
|
|
@@ -182,7 +190,7 @@ async function renderPageDocument(
|
|
|
182
190
|
pageProps: Record<string, unknown>,
|
|
183
191
|
ctx: RequestContext,
|
|
184
192
|
hasFlash: boolean,
|
|
185
|
-
|
|
193
|
+
setIdleTimeout?: (seconds: number) => void,
|
|
186
194
|
timing?: DevTiming,
|
|
187
195
|
privateTracker?: PrivateReadTracker,
|
|
188
196
|
): Promise<RenderedPageOutput> {
|
|
@@ -192,7 +200,10 @@ async function renderPageDocument(
|
|
|
192
200
|
const body = await runWithRenderContext(rctx, () => renderRouteBody(route, data, pageProps, privateTracker?.ctx ?? ctx))
|
|
193
201
|
if (hasFlash)
|
|
194
202
|
ctx.cookies.delete(ACTION_ERROR_COOKIE)
|
|
195
|
-
const
|
|
203
|
+
// A route's `export const lang` names the language it is written in, so a plugin head hook such as i18n's cannot replace it.
|
|
204
|
+
const pageLang = typeof route.mod.lang === 'string' ? route.mod.lang : undefined
|
|
205
|
+
const resolvedHead = await deps.resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx)
|
|
206
|
+
const docHead = pageLang === undefined ? resolvedHead : { ...resolvedHead, lang: pageLang, htmlAttrs: { ...resolvedHead.htmlAttrs, lang: pageLang } }
|
|
196
207
|
rctx.headFlushed = true
|
|
197
208
|
const renderedIslands = resolveRenderedIslands(rctx, body)
|
|
198
209
|
const isStreamed = rctx.pending.length > 0
|
|
@@ -212,7 +223,7 @@ async function renderPageDocument(
|
|
|
212
223
|
headers.vary = mergeVaryValue(headers.vary, 'Accept-Encoding')
|
|
213
224
|
return { kind: 'stream', response: markCompressionHandled(new Response(null, { status: 200, headers })) }
|
|
214
225
|
}
|
|
215
|
-
|
|
226
|
+
setIdleTimeout?.(0)
|
|
216
227
|
const docShell = renderDocument({ ...doc, body: body + STREAM_TAIL_MARK, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands, hasSuspense: true })
|
|
217
228
|
const shell = deps.hasHtmlTransformers ? await deps.applyHtmlTransforms(docShell, ctx.url, ctx.request, ctx) : docShell
|
|
218
229
|
const streamStyleHashes = mergeStyleHashes(trustedStyleHashes, addedInlineStyleHashes(docShell, shell))
|
|
@@ -350,12 +361,14 @@ export function createCompiledRouteRenderer(deps: CompiledRouteRendererDeps) {
|
|
|
350
361
|
route: CompiledRoute,
|
|
351
362
|
ctx: RequestContext,
|
|
352
363
|
cookieStore: CookieStore,
|
|
353
|
-
|
|
364
|
+
setIdleTimeout?: (seconds: number) => void,
|
|
354
365
|
staticPath?: string,
|
|
355
366
|
timing?: DevTiming,
|
|
356
367
|
middlewares: readonly Middleware[] = route.middlewares,
|
|
357
368
|
): Promise<Response> {
|
|
358
369
|
const { entry, mod, doc } = route
|
|
370
|
+
if (route.idleTimeout !== undefined)
|
|
371
|
+
setIdleTimeout?.(route.idleTimeout)
|
|
359
372
|
const isRegion = hasRegionHeader(ctx.request)
|
|
360
373
|
|
|
361
374
|
const early = await resolvePrerenderedOrApi(deps, route, ctx, isRegion, staticPath)
|
|
@@ -412,7 +425,7 @@ export function createCompiledRouteRenderer(deps: CompiledRouteRendererDeps) {
|
|
|
412
425
|
)
|
|
413
426
|
}
|
|
414
427
|
|
|
415
|
-
const rendered = await renderPageDocument(deps, route, loaded.data, pageProps, ctx, hasFlash,
|
|
428
|
+
const rendered = await renderPageDocument(deps, route, loaded.data, pageProps, ctx, hasFlash, setIdleTimeout, timing, privateTracker)
|
|
416
429
|
if (rendered.kind === 'stream')
|
|
417
430
|
return rendered.response
|
|
418
431
|
if (privateTracker?.didReadPrivate())
|
|
@@ -20,8 +20,8 @@ export interface ServeHandlerSources {
|
|
|
20
20
|
healthPath?: string | undefined
|
|
21
21
|
healthHandler?: ((request: Request, requestId?: string) => Response | Promise<Response>) | undefined
|
|
22
22
|
resolveRequestId?: RequestIdResolver | undefined
|
|
23
|
-
/** Answers through the app's whole pipeline,
|
|
24
|
-
runRequest: (req: Request, remoteIp: string | undefined,
|
|
23
|
+
/** Answers through the app's whole pipeline, `setIdleTimeout` setting the request's idle timeout in seconds: 0 for a long-lived stream, or a route's `export const idleTimeout`. */
|
|
24
|
+
runRequest: (req: Request, remoteIp: string | undefined, setIdleTimeout: (seconds: number) => void) => Promise<Response>
|
|
25
25
|
runFast: (handler: FastHandler, req: Request, remoteIp: string | undefined) => Response | Promise<Response>
|
|
26
26
|
notifyError: NotifyError
|
|
27
27
|
serverError: () => Response
|
|
@@ -38,7 +38,7 @@ export const isPlainRead = (request: Request): boolean => isRead(request) && !ha
|
|
|
38
38
|
export function serveHandlers(server: () => PrunelleServer | undefined, sources: ServeHandlerSources) {
|
|
39
39
|
const { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone } = sources
|
|
40
40
|
const ipOf = (req: Request) => server()?.requestIP(req)?.address
|
|
41
|
-
const fetchReq = (req: Request) => runRequest(req, ipOf(req),
|
|
41
|
+
const fetchReq = (req: Request) => runRequest(req, ipOf(req), seconds => server()?.timeout(req, seconds))
|
|
42
42
|
// A file that fails to open answers here, where the request is known: gone since the build is a 404, anything else is reported with it.
|
|
43
43
|
const serveFile = async (req: Request, file: ServedFile): Promise<Response> => {
|
|
44
44
|
const reqId = resolveRequestId?.(req)
|
package/src/server/start.ts
CHANGED
|
@@ -30,7 +30,7 @@ export async function startServer(options: StartOptions): Promise<{ app: Prunell
|
|
|
30
30
|
let current = first.app
|
|
31
31
|
const server = current.serve(options.port, options.hostname)
|
|
32
32
|
const app: PrunelleApp = {
|
|
33
|
-
handle: async (request, remoteIp,
|
|
33
|
+
handle: async (request, remoteIp, setIdleTimeout) => current.handle(request, remoteIp, setIdleTimeout),
|
|
34
34
|
serve: () => server,
|
|
35
35
|
closeStreams: async () => current.closeStreams?.(),
|
|
36
36
|
dispose: async () => {
|
|
@@ -73,7 +73,7 @@ function watchSwaps(outDir: string, isStatic: boolean, current: () => PrunelleAp
|
|
|
73
73
|
catch {
|
|
74
74
|
return new Response('Service Unavailable', { status: 503, headers: { ...current().securityHeaders, 'content-type': 'text/plain; charset=utf-8' } })
|
|
75
75
|
}
|
|
76
|
-
return target.handle(request, server.requestIP(request)?.address,
|
|
76
|
+
return target.handle(request, server.requestIP(request)?.address, seconds => server.timeout(request, seconds))
|
|
77
77
|
},
|
|
78
78
|
})
|
|
79
79
|
}
|
package/src/server/stream.ts
CHANGED
|
@@ -150,8 +150,8 @@ function safeClose(controller: ReadableStreamDefaultController<Uint8Array>): boo
|
|
|
150
150
|
}
|
|
151
151
|
}
|
|
152
152
|
|
|
153
|
-
function trackEventStream(res: Response, active: Set<() => void>,
|
|
154
|
-
|
|
153
|
+
function trackEventStream(res: Response, active: Set<() => void>, setIdleTimeout?: (seconds: number) => void): Response {
|
|
154
|
+
setIdleTimeout?.(0)
|
|
155
155
|
if (res.body === null)
|
|
156
156
|
return res
|
|
157
157
|
const reader = res.body.getReader()
|
|
@@ -206,7 +206,7 @@ function trackEventStream(res: Response, active: Set<() => void>, disableTimeout
|
|
|
206
206
|
}
|
|
207
207
|
|
|
208
208
|
export interface StreamTracker {
|
|
209
|
-
track: (res: Response,
|
|
209
|
+
track: (res: Response, setIdleTimeout?: (seconds: number) => void) => Response
|
|
210
210
|
/** Registers a streamed page's way to end early; the returned function drops it once the page is done. */
|
|
211
211
|
trackPage: (end: () => void) => () => void
|
|
212
212
|
closeAll: () => Promise<void>
|
|
@@ -217,7 +217,7 @@ export function createStreamTracker(): StreamTracker {
|
|
|
217
217
|
const active = new Set<() => void>()
|
|
218
218
|
const pages = new Set<() => void>()
|
|
219
219
|
return {
|
|
220
|
-
track: (res,
|
|
220
|
+
track: (res, setIdleTimeout) => trackEventStream(res, active, setIdleTimeout),
|
|
221
221
|
trackPage: (end) => {
|
|
222
222
|
pages.add(end)
|
|
223
223
|
return () => { pages.delete(end) }
|
package/src/ssr/navigation.ts
CHANGED
|
@@ -8,7 +8,7 @@ export const NO_PREFETCH_ATTR = 'data-pru-no-prefetch'
|
|
|
8
8
|
export type Eagerness = 'conservative' | 'moderate' | 'eager'
|
|
9
9
|
|
|
10
10
|
export interface NavigationConfig {
|
|
11
|
-
/** Fades one page into the next with a cross-document view transition (`@view-transition { navigation: auto }`), off under `prefers-reduced-motion`. On by default, `false` leaves the browser's plain repaint. */
|
|
11
|
+
/** Fades one page into the next with a cross-document view transition (`@view-transition { navigation: auto }`), off under `prefers-reduced-motion`. On by default, `false` leaves the browser's plain repaint, for `@prunellejs/spa` swaps too. */
|
|
12
12
|
viewTransitions?: boolean | undefined
|
|
13
13
|
/** When the browser fetches the page a same-origin link points at, through Speculation Rules: `'conservative'` (the default) on press, `'moderate'` on hover (and, on phones, as a link scrolls into view), `'eager'` as soon as it can, `false` never. A link, or an ancestor of it, with `data-pru-no-prefetch` is never fetched; neither is a `download` or `rel="nofollow"` link, a prunelle route (actions among them) or another origin's page. */
|
|
14
14
|
prefetch?: Eagerness | false | undefined
|