prunelle 0.7.3 → 0.7.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/llms.txt +11 -9
  2. package/package.json +1 -1
  3. package/src/a11y/index.ts +9 -2
  4. package/src/build/index.ts +29 -30
  5. package/src/build/prerender.ts +29 -13
  6. package/src/build/routes.ts +19 -1
  7. package/src/build/static.ts +24 -2
  8. package/src/cli/check-forms.ts +16 -6
  9. package/src/cli/check-links.ts +12 -9
  10. package/src/cli/check-security.ts +87 -12
  11. package/src/cli/check.ts +1 -1
  12. package/src/cli/commands.ts +3 -3
  13. package/src/cli/upgrade.ts +36 -3
  14. package/src/compiler/compliance.ts +2 -0
  15. package/src/compiler/dom.ts +41 -15
  16. package/src/compiler/ssr-helpers.ts +45 -21
  17. package/src/compiler/ssr.ts +32 -16
  18. package/src/context.ts +2 -0
  19. package/src/dev/error-log.ts +1 -1
  20. package/src/dev/index.ts +1 -1
  21. package/src/dev/supervisor.ts +2 -2
  22. package/src/dom/attrs.ts +1 -1
  23. package/src/dom/island.ts +30 -4
  24. package/src/jsx-runtime.ts +1 -1
  25. package/src/plugins/services.ts +1 -0
  26. package/src/reactivity/index.ts +14 -2
  27. package/src/server/action.ts +26 -18
  28. package/src/server/assets.ts +22 -4
  29. package/src/server/consent.ts +7 -2
  30. package/src/server/cookies.ts +8 -1
  31. package/src/server/errors.ts +57 -26
  32. package/src/server/http.ts +1 -1
  33. package/src/server/index.ts +7 -7
  34. package/src/server/page.ts +4 -0
  35. package/src/server/rate-limit.ts +36 -12
  36. package/src/server/route-cache.ts +9 -10
  37. package/src/server/route-table.ts +38 -13
  38. package/src/server/router.ts +4 -4
  39. package/src/server/sanitize-html.ts +21 -7
  40. package/src/server/security.ts +13 -3
  41. package/src/server/serve-handlers.ts +3 -3
  42. package/src/server/start.ts +2 -2
  43. package/src/server/static-dir.ts +3 -10
  44. package/src/server/stream.ts +4 -4
  45. package/src/ssr/consent-banner.ts +3 -1
  46. package/src/ssr/context.ts +85 -2
  47. package/src/ssr/index.ts +16 -4
  48. package/src/ssr/navigation.ts +1 -1
  49. package/src/style.ts +9 -7
  50. package/src/unrenderable.ts +15 -5
@@ -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/attrs.ts CHANGED
@@ -64,7 +64,7 @@ export function setAttr(el: Element, name: string, value: unknown): void {
64
64
 
65
65
  export function setProp(el: Element, name: string, value: unknown): void {
66
66
  const next = name === 'value'
67
- ? (value == null ? '' : String(value))
67
+ ? (value == null || typeof value === 'boolean' ? '' : String(value))
68
68
  : Boolean(value)
69
69
  const rec = el as unknown as Record<string, unknown>
70
70
  if (rec[name] !== next)
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: 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
- after?.()
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) {
@@ -425,7 +425,7 @@ type VoidElementTagName =
425
425
  | 'link' | 'meta' | 'param' | 'source' | 'track' | 'wbr'
426
426
 
427
427
  type HtmlIntrinsicElements = {
428
- [K in keyof HTMLElementTagNameMap]:
428
+ [K in Exclude<keyof HTMLElementTagNameMap, 'slot'>]:
429
429
  (K extends keyof HtmlElementOverrides
430
430
  ? Omit<HTMLAttributes<HTMLElementTagNameMap[K]>, keyof HtmlElementOverrides[K] | (K extends VoidElementTagName ? 'children' : never)> & HtmlElementOverrides[K]
431
431
  : Omit<HTMLAttributes<HTMLElementTagNameMap[K]>, K extends VoidElementTagName ? 'children' : never>)
@@ -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 {
@@ -301,9 +301,17 @@ class EffectNode implements SubNode, Owner {
301
301
  if (this.f & F.DISPOSED)
302
302
  return
303
303
  this.f &= ~(F.DIRTY | F.CHECK)
304
- releaseOwned(this)
305
- if (this.f & F.DISPOSED)
304
+ let errors: unknown[] | undefined
305
+ try {
306
+ releaseOwned(this)
307
+ }
308
+ catch (err) {
309
+ errors = [err]
310
+ }
311
+ if (this.f & F.DISPOSED) {
312
+ throwErrors(errors)
306
313
  return
314
+ }
307
315
  const prevSub = currentSub
308
316
  const prevOwner = currentOwner
309
317
  this.f |= F.RUNNING
@@ -320,12 +328,16 @@ class EffectNode implements SubNode, Owner {
320
328
  ;(this.cl ??= []).unshift(ret)
321
329
  }
322
330
  }
331
+ catch (err) {
332
+ ;(errors ??= []).push(err)
333
+ }
323
334
  finally {
324
335
  unlinkRemaining(this)
325
336
  this.f &= ~F.RUNNING
326
337
  currentSub = prevSub
327
338
  currentOwner = prevOwner
328
339
  }
340
+ throwErrors(errors)
329
341
  }
330
342
  }
331
343
 
@@ -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
- function appendFormValue(target: Record<string, unknown>, key: string, value: FormDataEntryValue, forceArray: boolean): void {
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
- let blocked = false
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
- else if (isPlainRecord(cur[seg])) {
199
- cur = cur[seg]
200
- }
201
- else {
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
- if (!blocked)
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
- return Response.json({ ok: false, status: 400, error: 'Invalid request body' }, { status: 400 })
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
 
@@ -34,16 +34,34 @@ export interface PrerenderedSources {
34
34
  isFast: (urlPath: string, route: RouteManifestEntry) => boolean
35
35
  }
36
36
 
37
- const EXTRA_PRERENDER_MIME: Record<string, string> = {
37
+ /** Shared MIME table for `public/`, hashed assets, prerendered files and `prunelle start --static`. */
38
+ export const STATIC_MIME: Readonly<Record<string, string>> = {
39
+ ...MIME,
38
40
  '.htm': 'text/html; charset=utf-8',
39
41
  '.rss': 'application/rss+xml; charset=utf-8',
40
42
  '.atom': 'application/atom+xml; charset=utf-8',
41
43
  '.ics': 'text/calendar; charset=utf-8',
42
44
  '.csv': 'text/csv; charset=utf-8',
45
+ '.vtt': 'text/vtt; charset=utf-8',
46
+ '.geojson': 'application/geo+json; charset=utf-8',
47
+ '.mp3': 'audio/mpeg',
48
+ '.ogg': 'audio/ogg',
49
+ '.oga': 'audio/ogg',
50
+ '.ogv': 'video/ogg',
51
+ '.m4a': 'audio/mp4',
52
+ '.wav': 'audio/wav',
53
+ '.flac': 'audio/flac',
54
+ '.opus': 'audio/opus',
55
+ '.zip': 'application/zip',
56
+ }
57
+
58
+ /** MIME type for a file extension, falling back to `application/octet-stream`. */
59
+ export function staticMime(ext: string): string {
60
+ return STATIC_MIME[ext.toLowerCase()] ?? 'application/octet-stream'
43
61
  }
44
62
 
45
63
  function prerenderedMime(ext: string, filePath: string | undefined): string {
46
- const mapped = MIME[ext] ?? EXTRA_PRERENDER_MIME[ext]
64
+ const mapped = STATIC_MIME[ext.toLowerCase()]
47
65
  if (mapped !== undefined)
48
66
  return mapped
49
67
  if (filePath !== undefined) {
@@ -74,7 +92,7 @@ export function createAssets(options: AssetsOptions) {
74
92
 
75
93
  const registerPublic = (rel: string, body: EmbeddedBody, etag?: string, sidecars: ReturnType<typeof sidecarsOf> = { br: undefined, gz: undefined }): void => {
76
94
  const cleanRel = rel.replace(/^\/+/, '')
77
- const type = MIME[extname(cleanRel).toLowerCase()] ?? 'application/octet-stream'
95
+ const type = staticMime(extname(cleanRel))
78
96
  publicMap.set(`/${cleanRel}`, servedFile({
79
97
  key: `p:/${cleanRel}`,
80
98
  source: embedded(body),
@@ -105,7 +123,7 @@ export function createAssets(options: AssetsOptions) {
105
123
  for (const [rel, body] of Object.entries(assets)) {
106
124
  if ((rel.endsWith('.br') || rel.endsWith('.gz')) && rel.slice(0, -3) in assets)
107
125
  continue
108
- const type = MIME[extname(rel).toLowerCase()] ?? 'application/octet-stream'
126
+ const type = staticMime(extname(rel))
109
127
  const sidecar = (ext: 'br' | 'gz'): FileSource | undefined => {
110
128
  const source = assets[`${rel}.${ext}`] ?? (typeof body === 'string' && existsSync(`${body}.${ext}`) ? `${body}.${ext}` : undefined)
111
129
  return source === undefined ? undefined : embedded(source)
@@ -75,6 +75,8 @@ export function normalizeConsentConfig(config: ConsentConfig | undefined): Norma
75
75
  continue
76
76
  if (name.includes(',') || name.includes(':'))
77
77
  throw new Error(`prunelle: consent category "${name}" cannot contain "," or ":"`)
78
+ if (name === 'action' || name === 'redirect' || name === 'categories')
79
+ throw new Error(`prunelle: consent category "${name}" is reserved by the consent form; choose another category name.`)
78
80
  categorySet.add(name)
79
81
  categories.push(name)
80
82
  labels[name] = given[item]?.trim() || name
@@ -116,7 +118,10 @@ export function parseConsentCookie(raw: string | undefined, declared: ReadonlySe
116
118
  return version === '' ? { decided: true, decidedAt: undefined, granted: grantedOf(raw.slice(LEGACY_COOKIE_PREFIX.length), declared) } : none
117
119
  if (!raw.startsWith(COOKIE_PREFIX))
118
120
  return none
119
- const [seconds, storedVersion, list] = raw.slice(COOKIE_PREFIX.length).split(':')
121
+ const parts = raw.slice(COOKIE_PREFIX.length).split(':')
122
+ if (parts.length !== 3)
123
+ return none
124
+ const [seconds, storedVersion, list] = parts
120
125
  const at = Number(seconds)
121
126
  if (list === undefined || storedVersion !== version || !Number.isSafeInteger(at) || at <= 0)
122
127
  return none
@@ -243,7 +248,7 @@ async function parseConsentSubmission(
243
248
 
244
249
  const listed = new Set(form.getAll('categories').filter((v): v is string => typeof v === 'string'))
245
250
  for (const cat of config.categories) {
246
- if (listed.has(cat) || isTruthyFormValue(form.get(cat)))
251
+ if (listed.has(cat) || (cat !== 'action' && cat !== 'redirect' && cat !== 'categories' && isTruthyFormValue(form.get(cat))))
247
252
  granted.add(cat)
248
253
  }
249
254
  return { ok: true, granted, redirect }
@@ -73,7 +73,14 @@ function serializeCookie(name: string, value: string, options: CookieOptions = {
73
73
  if (sameSite === 'none' && !secure)
74
74
  throw new Error(`prunelle: Cookie "${name}" with sameSite: "none" requires secure: true`)
75
75
 
76
- let out = `${name}=${encodeURIComponent(value)}`
76
+ let encoded: string
77
+ try {
78
+ encoded = encodeURIComponent(value)
79
+ }
80
+ catch {
81
+ throw new TypeError(`prunelle: invalid cookie value for "${name}": contains an unpaired UTF-16 surrogate; sanitize with value.toWellFormed() before setting the cookie.`)
82
+ }
83
+ let out = `${name}=${encoded}`
77
84
  out += `; Path=${path}`
78
85
  if (options.domain !== undefined)
79
86
  out += `; Domain=${options.domain}`
@@ -20,10 +20,14 @@ import { styleHashesOf } from './security'
20
20
 
21
21
  export type NotifyError = (error: unknown, request: Request, source: ServerErrorInfo['source'], requestId?: string) => void
22
22
 
23
+ const describeNonError = (error: unknown): string => error instanceof Response
24
+ ? `prunelle: a Response (HTTP ${error.status}) was thrown instead of returned; return it from load() or the route handler instead.`
25
+ : String(error)
26
+
23
27
  /** The text of an error a dev response shows: its stack, which starts with its message. */
24
- export const errorDetail = (error: unknown): string => error instanceof Error ? error.stack ?? error.message : String(error)
28
+ export const errorDetail = (error: unknown): string => error instanceof Error ? error.stack ?? error.message : describeNonError(error)
25
29
 
26
- const errorMessage = (error: unknown): string => error instanceof Error ? error.message : String(error)
30
+ const errorMessage = (error: unknown): string => error instanceof Error ? error.message : describeNonError(error)
27
31
 
28
32
  const HTML_ESCAPE_RE = /[&<>"']/g
29
33
  const HTML_ESCAPES: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }
@@ -57,11 +61,14 @@ export function createErrorNotifier(onError: ((info: ServerErrorInfo) => void) |
57
61
  errorHooks.push({ owner: p.name, hook: p.onError })
58
62
  }
59
63
  return (error, request, source, requestId) => {
60
- const info: ServerErrorInfo = requestId !== undefined ? { error, request, source, requestId } : { error, request, source }
64
+ const normalized = error instanceof Response
65
+ ? (void error.body?.cancel().catch(() => undefined), new Error(describeNonError(error)))
66
+ : error
67
+ const info: ServerErrorInfo = requestId !== undefined ? { error: normalized, request, source, requestId } : { error: normalized, request, source }
61
68
  options.sink?.(info)
62
69
  if (errorHooks.length === 0 && (options.dev === true || options.sink === undefined)) {
63
70
  const idSuffix = requestId !== undefined ? ` [${requestId}]` : ''
64
- console.error(`prunelle: unhandled error in ${source} ${request.method} ${new URL(request.url).pathname}${idSuffix}`, error)
71
+ console.error(`prunelle: unhandled error in ${source} ${request.method} ${new URL(request.url).pathname}${idSuffix}`, normalized)
65
72
  }
66
73
  for (const { owner, hook } of errorHooks) {
67
74
  try {
@@ -89,8 +96,13 @@ interface CompiledStatusPage {
89
96
  doc: DocumentOptions
90
97
  }
91
98
 
99
+ interface StatusPageHit {
100
+ page: CompiledStatusPage
101
+ params?: Record<string, string>
102
+ }
103
+
92
104
  interface StatusPageLookup {
93
- find: (kind: StatusPageKind, url?: URL, routeFile?: string) => { page: CompiledStatusPage, params?: Record<string, string> } | undefined
105
+ findAll: (kind: StatusPageKind, url?: URL, routeFile?: string) => StatusPageHit[]
94
106
  }
95
107
 
96
108
  function dirnamePrefix(file: string): string {
@@ -184,7 +196,16 @@ function buildStatusPageLookup(
184
196
  }
185
197
 
186
198
  return {
187
- find(kind, url, routeFile) {
199
+ findAll(kind, url, routeFile) {
200
+ const out: StatusPageHit[] = []
201
+ const seen = new Set<CompiledStatusPage>()
202
+ const push = (page: CompiledStatusPage, params?: Record<string, string>) => {
203
+ if (seen.has(page))
204
+ return
205
+ seen.add(page)
206
+ out.push(params !== undefined ? { page, params } : { page })
207
+ }
208
+
188
209
  if (routeFile !== undefined) {
189
210
  const dirMap = byDirPrefix.get(kind)
190
211
  if (dirMap !== undefined) {
@@ -192,27 +213,27 @@ function buildStatusPageLookup(
192
213
  while (dir !== undefined) {
193
214
  const hit = dirMap.get(dir)
194
215
  if (hit !== undefined)
195
- return { page: hit }
216
+ push(hit)
196
217
  if (dir === routesPrefix || !dir.startsWith(routesPrefix))
197
218
  break
198
219
  dir = parentDirPrefix(dir)
199
220
  }
200
221
  const rootHit = dirMap.get(routesPrefix)
201
222
  if (rootHit !== undefined)
202
- return { page: rootHit }
223
+ push(rootHit)
203
224
  }
204
- return undefined
225
+ return out
205
226
  }
206
227
 
207
228
  const decoded = decodeRequestPath(url?.pathname ?? '/')
208
229
  if (decoded === undefined)
209
- return undefined
230
+ return out
210
231
  const urlRouter = byUrlRouter.get(kind)
211
232
  if (urlRouter !== undefined) {
212
233
  for (let i = decoded.segments.length; i >= 0; i--) {
213
234
  const matched = urlRouter.match(pathPrefix(decoded, i))
214
235
  if (matched !== undefined)
215
- return { page: matched.data, params: matched.params }
236
+ push(matched.data, matched.params)
216
237
  }
217
238
  }
218
239
  const fallbackGroup = groupUrlRouter.get(kind)
@@ -220,10 +241,10 @@ function buildStatusPageLookup(
220
241
  for (let i = decoded.segments.length; i >= 0; i--) {
221
242
  const matched = fallbackGroup.match(pathPrefix(decoded, i))
222
243
  if (matched !== undefined)
223
- return { page: matched.data, params: matched.params }
244
+ push(matched.data, matched.params)
224
245
  }
225
246
  }
226
- return undefined
247
+ return out
227
248
  },
228
249
  }
229
250
  }
@@ -321,11 +342,11 @@ export function createFallbackPages(options: FallbackPagesOptions) {
321
342
 
322
343
  async function buildErrorResponse(error: unknown, url?: URL, req?: Request, ctx?: RequestContext, routeFile?: string): Promise<Response> {
323
344
  const effUrl = url ?? new URL('http://localhost/500')
324
- const found = lookup.find('error', effUrl, routeFile)
325
- if (found !== undefined) {
345
+ const candidates = lookup.findAll('error', effUrl, routeFile)
346
+ // Outside dev the page gets a bare error: a thrown message can name a host, a table or a credential, and it lands in HTML anyone can load.
347
+ const shown = options.dev ? error : Object.assign(new Error('Internal Server Error'), { stack: 'Error: Internal Server Error' })
348
+ for (const found of candidates) {
326
349
  const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
327
- // Outside dev the page gets a bare error: a thrown message can name a host, a table or a credential, and it lands in HTML anyone can load.
328
- const shown = options.dev ? error : Object.assign(new Error('Internal Server Error'), { stack: 'Error: Internal Server Error' })
329
350
  const rendered = await renderCompiledStatusPage(
330
351
  found.page,
331
352
  500,
@@ -338,13 +359,19 @@ export function createFallbackPages(options: FallbackPagesOptions) {
338
359
  if (rendered !== undefined)
339
360
  return rendered
340
361
  }
341
- return new Response(req?.method === 'HEAD' ? null : (options.dev ? errorDetail(error) : 'Internal Server Error'), { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
362
+ const text = options.dev ? errorDetail(error) : 'Internal Server Error'
363
+ if (candidates.length > 0) {
364
+ return new Response(req?.method === 'HEAD' ? null : minimalStatusHtml(500, text, options.lang), {
365
+ status: 500,
366
+ headers: htmlHeaders(false, false, true, fallbackHeadStyleHashes),
367
+ })
368
+ }
369
+ return new Response(req?.method === 'HEAD' ? null : text, { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
342
370
  }
343
371
 
344
372
  async function buildNotFoundResponse(url?: URL, req?: Request, ctx?: RequestContext, routeFile?: string): Promise<Response> {
345
373
  const effUrl = url ?? new URL('http://localhost/404')
346
- const found = lookup.find('404', effUrl, routeFile)
347
- if (found !== undefined) {
374
+ for (const found of lookup.findAll('404', effUrl, routeFile)) {
348
375
  const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
349
376
  const rendered = await renderCompiledStatusPage(
350
377
  found.page,
@@ -363,13 +390,17 @@ export function createFallbackPages(options: FallbackPagesOptions) {
363
390
 
364
391
  async function renderDenied(denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string): Promise<Response> {
365
392
  const statusKey = String(denied.status)
366
- const statusHit = STATUS_KINDS.has(statusKey) ? lookup.find(statusKey as StatusPageKind, url, routeFile) : undefined
367
- const found = statusHit ?? lookup.find('error', url, routeFile)
368
- if (found !== undefined) {
393
+ const statusHits = STATUS_KINDS.has(statusKey) ? lookup.findAll(statusKey as StatusPageKind, url, routeFile) : []
394
+ for (const found of statusHits) {
395
+ const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
396
+ const props = { status: denied.status, message: denied.message, url, params, locals: ctx?.locals ?? {} }
397
+ const rendered = await renderCompiledStatusPage(found.page, denied.status, props, url, params, req, ctx)
398
+ if (rendered !== undefined)
399
+ return rendered
400
+ }
401
+ for (const found of lookup.findAll('error', url, routeFile)) {
369
402
  const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
370
- const props = statusHit !== undefined
371
- ? { status: denied.status, message: denied.message, url, params, locals: ctx?.locals ?? {} }
372
- : { error: new Error(denied.message), status: denied.status, message: denied.message, url, params, locals: ctx?.locals ?? {} }
403
+ const props = { error: new Error(denied.message), status: denied.status, message: denied.message, url, params, locals: ctx?.locals ?? {} }
373
404
  const rendered = await renderCompiledStatusPage(found.page, denied.status, props, url, params, req, ctx)
374
405
  if (rendered !== undefined)
375
406
  return rendered
@@ -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, disableTimeout?: () => void) => Promise<Response>
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
@@ -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, disableTimeout?: () => void, bodyLimited = false): Promise<Response> {
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, disableTimeout)
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, disableTimeout, staticPath, timing, routeMiddlewares), timing, runChain))
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, disableTimeout) : 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, disableTimeout?: () => void): Promise<Response> {
599
- return runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp, disableTimeout))
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, disableTimeout: () => void): Promise<Response> => runWithAppContext(serverAppCtx, () => handleInternal(req, remoteIp, disableTimeout, true))
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
 
@@ -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>