prunelle 0.1.1 → 0.1.2
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 +3 -3
- package/package.json +1 -1
- package/src/cli/commands.ts +5 -3
- package/src/cli/upgrade.ts +30 -5
- package/src/plugins/types.ts +5 -0
- package/src/server/index.ts +2 -2
- package/src/server/plugin-host.ts +34 -13
- package/src/server/router.ts +14 -6
package/llms.txt
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
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.
|
|
@@ -23,11 +23,11 @@
|
|
|
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
|
|
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, `AGENTS.md` and `CLAUDE.md`, 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
27
|
- **Testing (`prunelle/test`)**: `const app = await testApp({ root, prebuilt?, outDir? })` (builds into its own `.prunelle-cache/test-*` folder, removed at exit, never into `dist/`; `prebuilt: true` reuses the latest testApp build of that root in the process, else `dist/`) — in-process `app.get()`, `app.post()`, `app.import(path)` (the app's bundled copy of a route, action file or `prunelle.config.ts`), `app.submit(action | url, fields)`, `app.fetch()`, `app.cookies`, `app.clearCookies()` with persistent cookie jar and zero port binding; `app.errors` lists unhandled route/action/plugin errors (`route GET /p: message`), and `testApp({ dev: true })` shows them in the 500 like `prunelle dev` does. Unhandled errors with `dev` (prunelle dev, `dev: true`): `console.error` unless an `onError` hook exists, and the 500 carries message and stack, each frame at its `src/` file and line (under `prunelle start` too, through the source maps `prunelle build` writes; a `--compile` binary names its own code) (JSON `{ ok: false, status: 500, error, stack }` when the request wants JSON, else text; `_error.tsx` still renders); production stays `Internal Server Error`. `prunelle dev` build errors also answer JSON/text per `Accept`. Islands: `const b = await testBrowser({ root, timeout?, browserPath? })` (needs `playwright-core` as a dev dependency and Chrome/Chromium; production build served on `b.origin`, a free 127.0.0.1 port) then `const page = await b.open(path)` (resolves once the page has loaded and its `load`/`client` islands have hydrated; `visible`, `idle` and `interaction` ones are the test's to trigger) (`b.open(path, { reducedMotion: true })` opens it for a visitor asking for less motion) with `page.click(sel)`, `page.hover(sel)`, `page.fill(sel, value)`, `page.text(sel)`, `page.waitFor(sel | fn)`, `page.evaluate(fn)`, `page.errors` (page errors, console errors, 4xx/5xx responses), `page.close()`, and `await b.close()` at the end.
|
|
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.2",
|
|
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/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.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
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
5
|
import { dirname, join } from 'node:path'
|
|
5
6
|
import pkg from '../../package.json' with { type: 'json' }
|
|
@@ -17,11 +18,13 @@ export interface UpgradeResult {
|
|
|
17
18
|
|
|
18
19
|
// The specifiers and file names every kind of file may name.
|
|
19
20
|
const PATH_RULES: [RegExp, string][] = [
|
|
21
|
+
// A kay v2 version written beside a package, as notes do, names no prunelle release: the current one replaces it.
|
|
22
|
+
[/(@kayjs\/[\w-]+)@[\^~]?2\.\d+\.\d+[\w.-]*/g, `$1@^${pkg.version}`],
|
|
20
23
|
[/@kayjs\/kay(?![\w-])/g, 'prunelle'],
|
|
21
24
|
[/@kayjs\//g, '@prunellejs/'],
|
|
22
25
|
[/\.kay-(cache|dev)\b/g, '.prunelle-$1'],
|
|
23
26
|
[/\bkay\.config\b/g, 'prunelle.config'],
|
|
24
|
-
[/\bkay v2\b/
|
|
27
|
+
[/\bkay v2\b/gi, 'prunelle'],
|
|
25
28
|
]
|
|
26
29
|
// The names kay sent the browser, as app code and styles may spell them.
|
|
27
30
|
const WIRE_RULES: [RegExp, string][] = [
|
|
@@ -39,6 +42,8 @@ const SOURCE_FILE_RE = /\.(?:tsx?|mts)$/
|
|
|
39
42
|
const STYLE_OR_SCRIPT_RE = /\.(?:css|js|mjs)$/
|
|
40
43
|
const CONFIG_FILE_RE = /^(?:tsconfig(?:\.[\w-]+)?\.json|bunfig\.toml|\.gitignore|\.dockerignore)$/
|
|
41
44
|
const BUILD_FILE_RE = /^(?:Dockerfile(?:\.[\w-]+)?|[\w-]+\.Dockerfile|[Jj]ustfile|Makefile|(?:docker-)?compose(?:\.[\w-]+)?\.ya?ml)$/
|
|
45
|
+
// The agent instructions `prunelle new` writes, which name the llms.txt to read and the CLI to run (#42).
|
|
46
|
+
const AGENT_FILE_RE = /^(?:AGENTS|CLAUDE)\.md$/
|
|
42
47
|
const CI_DIRS = ['.forgejo/workflows', '.github/workflows', '.gitea/workflows']
|
|
43
48
|
const CACHE_DIRS = ['.kay-cache', '.kay-dev']
|
|
44
49
|
const PRUNELLE_SOURCE_RE = /^prunelle(\/.*)?$/
|
|
@@ -65,7 +70,7 @@ export function upgradeProject(root: string): UpgradeResult {
|
|
|
65
70
|
write(file, text, upgradePackageJson(text))
|
|
66
71
|
else if (CONFIG_FILE_RE.test(file))
|
|
67
72
|
write(file, text, apply(text, PATH_RULES))
|
|
68
|
-
else if (BUILD_FILE_RE.test(file))
|
|
73
|
+
else if (BUILD_FILE_RE.test(file) || AGENT_FILE_RE.test(file))
|
|
69
74
|
write(file, text, apply(apply(text, PATH_RULES), [CLI_RULE]))
|
|
70
75
|
}
|
|
71
76
|
for (const dir of CI_DIRS) {
|
|
@@ -91,7 +96,8 @@ export function upgradeProject(root: string): UpgradeResult {
|
|
|
91
96
|
changed.push(`${dir}/`)
|
|
92
97
|
}
|
|
93
98
|
}
|
|
94
|
-
|
|
99
|
+
// 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.
|
|
100
|
+
for (const member of workspaceMembers(root).filter(m => onKayOrPrunelle(join(root, m)))) {
|
|
95
101
|
const res = upgradeProject(join(root, member))
|
|
96
102
|
changed.push(...res.changed.map(file => `${member}/${file}`))
|
|
97
103
|
manual.push(...res.manual.map(line => `${member}/${line}`))
|
|
@@ -102,6 +108,13 @@ export function upgradeProject(root: string): UpgradeResult {
|
|
|
102
108
|
const DEP_FIELDS = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']
|
|
103
109
|
const V1_RANGE_RE = /^[~^>=\s]*1\./
|
|
104
110
|
|
|
111
|
+
const KAY_OR_PRUNELLE_RE = /^(?:npm:)?(?:@kayjs\/|prunelle(?:@|$)|@prunellejs\/)/
|
|
112
|
+
|
|
113
|
+
function onKayOrPrunelle(root: string): boolean {
|
|
114
|
+
const json = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as Record<string, Record<string, string> | undefined>
|
|
115
|
+
return DEP_FIELDS.some(field => Object.entries(json[field] ?? {}).some(([name, range]) => KAY_OR_PRUNELLE_RE.test(name) || KAY_OR_PRUNELLE_RE.test(range)))
|
|
116
|
+
}
|
|
117
|
+
|
|
105
118
|
// 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
119
|
function kayV1Dependency(root: string): string | undefined {
|
|
107
120
|
if (!existsSync(join(root, 'package.json')))
|
|
@@ -149,17 +162,29 @@ function rootFiles(root: string): string[] {
|
|
|
149
162
|
return readdirSync(root, { withFileTypes: true }).filter(e => e.isFile()).map(e => e.name).sort()
|
|
150
163
|
}
|
|
151
164
|
|
|
165
|
+
// The entries of `dir`, none for a folder the user cannot read: a container's data, never source they edit.
|
|
166
|
+
function readableEntries(dir: string): Dirent[] {
|
|
167
|
+
try {
|
|
168
|
+
return readdirSync(dir, { withFileTypes: true })
|
|
169
|
+
}
|
|
170
|
+
catch (err) {
|
|
171
|
+
if ((err as NodeJS.ErrnoException).code === 'EACCES' || (err as NodeJS.ErrnoException).code === 'EPERM')
|
|
172
|
+
return []
|
|
173
|
+
throw err
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
152
177
|
// A folder holding its own package.json is another package, upgraded on its own.
|
|
153
178
|
function sourceFiles(root: string, dir = root, out: string[] = []): string[] {
|
|
154
179
|
if (dir !== root && existsSync(join(dir, 'package.json')))
|
|
155
180
|
return out
|
|
156
|
-
for (const entry of
|
|
181
|
+
for (const entry of readableEntries(dir)) {
|
|
157
182
|
if (isNotSourceDir(entry.name))
|
|
158
183
|
continue
|
|
159
184
|
const path = join(dir, entry.name)
|
|
160
185
|
if (entry.isDirectory())
|
|
161
186
|
sourceFiles(root, path, out)
|
|
162
|
-
else if (
|
|
187
|
+
else if (SOURCE_FILE_RE.test(entry.name) || STYLE_OR_SCRIPT_RE.test(entry.name))
|
|
163
188
|
out.push(relPosix(root, path))
|
|
164
189
|
}
|
|
165
190
|
return out.sort()
|
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/index.ts
CHANGED
|
@@ -31,7 +31,7 @@ import { addedInlineStyleHashes, createDocumentHooks, createHtmlHeaders, mergeSt
|
|
|
31
31
|
import { createErrorNotifier, createFallbackPages, devErrorResponse } from './errors'
|
|
32
32
|
import { applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, finalizeResponse, isNotFound, makeRequestContext, runChain, wantsJson } from './http'
|
|
33
33
|
import { allowedMethodsHeader, pickPageIslandProps, stripHeadBody } from './page'
|
|
34
|
-
import { allowedPluginMethodsHeader, createServerPluginHost } from './plugin-host'
|
|
34
|
+
import { allowedPluginMethodsHeader, createServerPluginHost, takesEncoded } from './plugin-host'
|
|
35
35
|
|
|
36
36
|
import { hasRegionHeader, invalidRegionResponse, requestedRegion, respondRegion, withRegionVary } from './region'
|
|
37
37
|
import { decodeRequestPath, literalPath } from './request-path'
|
|
@@ -503,7 +503,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
503
503
|
|
|
504
504
|
// Custom plugin routes run behind path-matched plugin middlewares so ctx.locals is available without cross-scope leaks.
|
|
505
505
|
const method = request.method.toUpperCase()
|
|
506
|
-
const pluginMatch = pluginRouter.match(effective)
|
|
506
|
+
const pluginMatch = takesEncoded(pluginRouter.match(effective), effective)
|
|
507
507
|
const directPluginDef = pluginMatch?.data.get(method) ?? pluginMatch?.data.get('ALL')
|
|
508
508
|
const headFallbackPluginDef = directPluginDef === undefined && method === 'HEAD' ? pluginMatch?.data.get('GET') : undefined
|
|
509
509
|
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/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
|