prunelle 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/llms.txt +12 -12
  2. package/package.json +1 -1
  3. package/src/build/client-entries.ts +3 -2
  4. package/src/build/compile.ts +2 -1
  5. package/src/build/index.ts +68 -29
  6. package/src/build/manifest.ts +18 -1
  7. package/src/build/output.ts +2 -2
  8. package/src/build/precompress.ts +15 -2
  9. package/src/build/prerender.ts +2 -2
  10. package/src/build/routes.ts +171 -10
  11. package/src/build/static.ts +71 -17
  12. package/src/build/status-pages.ts +127 -0
  13. package/src/cli/check-forms.ts +654 -0
  14. package/src/cli/check-links.ts +619 -0
  15. package/src/cli/check.ts +37 -4
  16. package/src/cli/commands.ts +5 -3
  17. package/src/cli/inspect.ts +21 -2
  18. package/src/cli/upgrade-names.ts +73 -13
  19. package/src/cli/upgrade.ts +137 -16
  20. package/src/compiler/compliance-rgaa.ts +502 -0
  21. package/src/compiler/compliance.ts +119 -220
  22. package/src/compiler/ssr.ts +121 -24
  23. package/src/dom/action.ts +4 -1
  24. package/src/dom/island.ts +5 -5
  25. package/src/plugins/config.ts +1 -1
  26. package/src/plugins/types.ts +13 -0
  27. package/src/server/action-protect.ts +186 -0
  28. package/src/server/action.ts +33 -10
  29. package/src/server/errors.ts +291 -62
  30. package/src/server/form-schema.ts +343 -0
  31. package/src/server/health.ts +244 -0
  32. package/src/server/http.ts +84 -17
  33. package/src/server/index.ts +162 -91
  34. package/src/server/param-matchers.ts +112 -0
  35. package/src/server/plugin-host.ts +40 -14
  36. package/src/server/public.ts +3 -3
  37. package/src/server/route-table.ts +5 -2
  38. package/src/server/router.ts +125 -40
  39. package/src/server/routing.ts +95 -57
  40. package/src/server/security.ts +171 -22
  41. package/src/server/serve-handlers.ts +21 -7
  42. package/src/ssr/context.ts +49 -0
  43. package/src/ssr/index.ts +120 -1
  44. package/src/test/browser.ts +6 -0
  45. package/src/test/index.ts +17 -3
  46. package/templates/_shared/src/routes/legal.tsx +5 -0
  47. package/templates/blog/prunelle.config.ts +1 -1
  48. package/templates/blog/src/routes/index.tsx +4 -0
@@ -1,25 +1,35 @@
1
- // Errors a request runs into: the app's and plugins' `onError` hooks, and the `_error` and `_404` pages rendered outside any route.
1
+ // Errors and status pages: `onError` hooks, nested `_404`/`_error`/`_401`/`_403`/`_429`/`_503` lookup, and HTML `ctx.deny()` rendering.
2
2
 
3
- import type { BuildManifest } from '../build/index'
3
+ import type { BuildManifest, StatusPageKind, StatusPageManifestEntry } from '../build/index'
4
4
  import type { Html } from '../jsx-runtime'
5
5
  import type { PrunellePlugin, ServerErrorInfo } from '../plugins/index'
6
6
  import type { DocumentOptions } from '../ssr/index'
7
7
  import type { CookieStore } from './cookies'
8
8
  import type { DocumentHooks, HtmlHeaders } from './document'
9
- import type { RequestContext } from './http'
9
+ import type { DeniedInfo, RequestContext } from './http'
10
+ import type { ParamMatcherMap } from './param-matchers'
10
11
  import { createRenderContext, runWithRenderContext } from '../ssr/context'
11
12
  import { raw, renderDocument, ssrChild } from '../ssr/index'
12
13
  import { addedInlineStyleHashes, headTagStyleHashes, mergeStyleHashes, resolveRenderedIslands, revivePreload } from './document'
13
14
  import { wantsJson } from './http'
15
+ import { BUILTIN_PARAM_MATCHERS } from './param-matchers'
16
+ import { decodeRequestPath, pathPrefix } from './request-path'
17
+ import { Router } from './router'
14
18
  import { styleHashesOf } from './security'
15
19
 
16
- export type NotifyError = (error: unknown, request: Request, source: ServerErrorInfo['source']) => void
20
+ export type NotifyError = (error: unknown, request: Request, source: ServerErrorInfo['source'], requestId?: string) => void
17
21
 
18
22
  /** The text of an error a dev response shows: its stack, which starts with its message. */
19
23
  export const errorDetail = (error: unknown): string => error instanceof Error ? error.stack ?? error.message : String(error)
20
24
 
21
25
  const errorMessage = (error: unknown): string => error instanceof Error ? error.message : String(error)
22
26
 
27
+ const HTML_ESCAPE_RE = /[&<>"']/g
28
+ const HTML_ESCAPES: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }
29
+ const escapeHtml = (value: string): string => value.replace(HTML_ESCAPE_RE, ch => HTML_ESCAPES[ch]!)
30
+
31
+ const STATUS_KINDS = new Set<string>(['401', '403', '404', '429', '503'])
32
+
23
33
  /** What a dev server answers with an unhandled error: its message and stack, as JSON when the request wants it. */
24
34
  export function devErrorResponse(error: unknown, request: Request): Response {
25
35
  if (wantsJson(request))
@@ -28,7 +38,7 @@ export function devErrorResponse(error: unknown, request: Request): Response {
28
38
  }
29
39
 
30
40
  export interface ErrorNotifierOptions {
31
- /** With no `onError` hook to hear an unhandled error, `console.error` does. */
41
+ /** With no `onError` hook to hear an unhandled error, `console.error` does (unless a `sink` captures it outside dev, as `testApp` and prerender do). */
32
42
  dev?: boolean | undefined
33
43
  /** Hears every unhandled error, hooks or not: how `testApp().errors` fills. */
34
44
  sink?: ((info: ServerErrorInfo) => void) | undefined
@@ -42,13 +52,16 @@ export function createErrorNotifier(onError: ((info: ServerErrorInfo) => void) |
42
52
  if (p.onError !== undefined)
43
53
  errorHooks.push({ owner: p.name, hook: p.onError })
44
54
  }
45
- return (error, request, source) => {
46
- options.sink?.({ error, request, source })
47
- if (options.dev === true && errorHooks.length === 0)
48
- console.error(`prunelle: unhandled error in ${source} ${request.method} ${new URL(request.url).pathname}`, error)
55
+ return (error, request, source, requestId) => {
56
+ const info: ServerErrorInfo = requestId !== undefined ? { error, request, source, requestId } : { error, request, source }
57
+ options.sink?.(info)
58
+ if (errorHooks.length === 0 && (options.dev === true || options.sink === undefined)) {
59
+ const idSuffix = requestId !== undefined ? ` [${requestId}]` : ''
60
+ console.error(`prunelle: unhandled error in ${source} ${request.method} ${new URL(request.url).pathname}${idSuffix}`, error)
61
+ }
49
62
  for (const { owner, hook } of errorHooks) {
50
63
  try {
51
- hook({ error, request, source })
64
+ hook(info)
52
65
  }
53
66
  catch (hookError) {
54
67
  console.error(`prunelle: the onError hook of ${owner} threw; the other hooks still run.`, hookError)
@@ -61,17 +74,167 @@ interface LayoutModule {
61
74
  default: (props: { children: Html, url?: URL, params?: Record<string, string>, locals?: object }) => Html | string | Promise<Html | string>
62
75
  }
63
76
 
64
- interface ErrorModule {
65
- default: (props: { error: unknown }) => Html | string | Promise<Html | string>
77
+ interface StatusPageModule {
78
+ default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
66
79
  }
67
80
 
68
- interface NotFoundModule {
69
- default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
81
+ interface CompiledStatusPage {
82
+ entry: StatusPageManifestEntry
83
+ render: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
84
+ layouts: LayoutModule[]
85
+ doc: DocumentOptions
86
+ }
87
+
88
+ interface StatusPageLookup {
89
+ find: (kind: StatusPageKind, url?: URL, routeFile?: string) => { page: CompiledStatusPage, params?: Record<string, string> } | undefined
90
+ }
91
+
92
+ function dirnamePrefix(file: string): string {
93
+ const slash = file.lastIndexOf('/')
94
+ return slash === -1 ? '' : file.slice(0, slash + 1)
95
+ }
96
+
97
+ function parentDirPrefix(dir: string): string | undefined {
98
+ if (dir === '')
99
+ return undefined
100
+ const trimmed = dir.endsWith('/') ? dir.slice(0, -1) : dir
101
+ const slash = trimmed.lastIndexOf('/')
102
+ return slash === -1 ? '' : trimmed.slice(0, slash + 1)
103
+ }
104
+
105
+ function legacyStatusEntries(manifest: BuildManifest, routesPrefix: string): StatusPageManifestEntry[] {
106
+ const layouts = manifest.rootLayoutFile !== undefined ? [manifest.rootLayoutFile] : []
107
+ const styles = manifest.globalStyles ?? manifest.styles
108
+ const entries: StatusPageManifestEntry[] = []
109
+ if (manifest.errorFile !== undefined)
110
+ entries.push({ kind: 'error', dirPattern: '/', dirPrefix: routesPrefix, file: manifest.errorFile, layouts, styles, islandChunks: [] })
111
+ if (manifest.notFoundFile !== undefined)
112
+ entries.push({ kind: '404', dirPattern: '/', dirPrefix: routesPrefix, file: manifest.notFoundFile, layouts, styles, islandChunks: [] })
113
+ return entries
114
+ }
115
+
116
+ function buildStatusPageLookup(
117
+ manifest: BuildManifest,
118
+ modules: Record<string, unknown>,
119
+ baseDoc: DocumentOptions,
120
+ routesPrefix: string,
121
+ paramMatchers: ParamMatcherMap,
122
+ ): StatusPageLookup {
123
+ const rawEntries = manifest.statusPages ?? legacyStatusEntries(manifest, routesPrefix)
124
+ const byDirPrefix = new Map<StatusPageKind, Map<string, CompiledStatusPage>>()
125
+ const byUrlRouter = new Map<StatusPageKind, Router<CompiledStatusPage>>()
126
+ const groupCandidates = new Map<StatusPageKind, Map<string, CompiledStatusPage[]>>()
127
+
128
+ for (const entry of rawEntries) {
129
+ const mod = modules[entry.file] as StatusPageModule | undefined
130
+ if (typeof mod?.default !== 'function')
131
+ continue
132
+ const layouts = entry.layouts
133
+ .map(key => modules[key] as LayoutModule | undefined)
134
+ .filter((l): l is LayoutModule => typeof l?.default === 'function')
135
+ const compiled: CompiledStatusPage = {
136
+ entry,
137
+ render: mod.default,
138
+ layouts,
139
+ doc: { ...baseDoc, styles: entry.styles },
140
+ }
141
+ let dirMap = byDirPrefix.get(entry.kind)
142
+ if (dirMap === undefined) {
143
+ dirMap = new Map()
144
+ byDirPrefix.set(entry.kind, dirMap)
145
+ }
146
+ dirMap.set(entry.dirPrefix, compiled)
147
+
148
+ if (entry.inGroup === true) {
149
+ let byPattern = groupCandidates.get(entry.kind)
150
+ if (byPattern === undefined) {
151
+ byPattern = new Map()
152
+ groupCandidates.set(entry.kind, byPattern)
153
+ }
154
+ const list = byPattern.get(entry.dirPattern) ?? []
155
+ list.push(compiled)
156
+ byPattern.set(entry.dirPattern, list)
157
+ }
158
+ else {
159
+ let router = byUrlRouter.get(entry.kind)
160
+ if (router === undefined) {
161
+ router = new Router<CompiledStatusPage>(paramMatchers)
162
+ byUrlRouter.set(entry.kind, router)
163
+ }
164
+ router.add(entry.dirPattern, compiled)
165
+ }
166
+ }
167
+
168
+ const groupUrlRouter = new Map<StatusPageKind, Router<CompiledStatusPage>>()
169
+ for (const [kind, byPattern] of groupCandidates) {
170
+ const router = new Router<CompiledStatusPage>(paramMatchers)
171
+ let added = false
172
+ for (const [pattern, list] of byPattern) {
173
+ if (list.length === 1) {
174
+ router.add(pattern, list[0]!)
175
+ added = true
176
+ }
177
+ }
178
+ if (added)
179
+ groupUrlRouter.set(kind, router)
180
+ }
181
+
182
+ return {
183
+ find(kind, url, routeFile) {
184
+ if (routeFile !== undefined) {
185
+ const dirMap = byDirPrefix.get(kind)
186
+ if (dirMap !== undefined) {
187
+ let dir: string | undefined = dirnamePrefix(routeFile)
188
+ while (dir !== undefined) {
189
+ const hit = dirMap.get(dir)
190
+ if (hit !== undefined)
191
+ return { page: hit }
192
+ if (dir === routesPrefix || !dir.startsWith(routesPrefix))
193
+ break
194
+ dir = parentDirPrefix(dir)
195
+ }
196
+ const rootHit = dirMap.get(routesPrefix)
197
+ if (rootHit !== undefined)
198
+ return { page: rootHit }
199
+ }
200
+ return undefined
201
+ }
202
+
203
+ const decoded = decodeRequestPath(url?.pathname ?? '/')
204
+ if (decoded === undefined)
205
+ return undefined
206
+ const urlRouter = byUrlRouter.get(kind)
207
+ if (urlRouter !== undefined) {
208
+ for (let i = decoded.segments.length; i >= 0; i--) {
209
+ const matched = urlRouter.match(pathPrefix(decoded, i))
210
+ if (matched !== undefined)
211
+ return { page: matched.data, params: matched.params }
212
+ }
213
+ }
214
+ const fallbackGroup = groupUrlRouter.get(kind)
215
+ if (fallbackGroup !== undefined) {
216
+ for (let i = decoded.segments.length; i >= 0; i--) {
217
+ const matched = fallbackGroup.match(pathPrefix(decoded, i))
218
+ if (matched !== undefined)
219
+ return { page: matched.data, params: matched.params }
220
+ }
221
+ }
222
+ return undefined
223
+ },
224
+ }
225
+ }
226
+
227
+ function minimalStatusHtml(status: number, message: string, lang: string): string {
228
+ const safeLang = escapeHtml(lang)
229
+ const safeMsg = escapeHtml(message)
230
+ return `<!DOCTYPE html><html lang="${safeLang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${status}</title></head><body><main><h1>${status}</h1><p>${safeMsg}</p></main></body></html>`
70
231
  }
71
232
 
72
233
  export interface FallbackPagesOptions {
73
234
  manifest: BuildManifest
74
235
  modules: Record<string, unknown>
236
+ routesPrefix?: string | undefined
237
+ paramMatchers?: ParamMatcherMap | undefined
75
238
  lang: string
76
239
  alwaysLoadRuntime: boolean
77
240
  navigation?: string | undefined
@@ -79,18 +242,17 @@ export interface FallbackPagesOptions {
79
242
  document: DocumentHooks
80
243
  htmlHeaders: HtmlHeaders
81
244
  notifyError: NotifyError
82
- finish: (res: Response, request: Request, cookieStore?: CookieStore) => Response
245
+ finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response
83
246
  }
84
247
 
85
248
  export function createFallbackPages(options: FallbackPagesOptions) {
86
249
  const { manifest, modules, document, htmlHeaders, notifyError, finish } = options
87
- const errorMod = manifest.errorFile ? modules[manifest.errorFile] as ErrorModule : undefined
88
- const notFoundMod = manifest.notFoundFile ? modules[manifest.notFoundFile] as NotFoundModule : undefined
89
-
90
- // Error and 404 pages sit outside any route, so they render with the global styles and the explicit root layout only.
91
- const rootLayoutFile = manifest.rootLayoutFile
92
- const rootLayoutMod = rootLayoutFile !== undefined ? modules[rootLayoutFile] as LayoutModule | undefined : undefined
93
- const fallbackDoc: DocumentOptions = {
250
+ const routesPrefix = options.routesPrefix ?? (
251
+ manifest.rootLayoutFile ?? manifest.errorFile ?? manifest.notFoundFile
252
+ ? dirnamePrefix((manifest.rootLayoutFile ?? manifest.errorFile ?? manifest.notFoundFile)!)
253
+ : 'server/'
254
+ )
255
+ const baseDoc: DocumentOptions = {
94
256
  body: '',
95
257
  headTags: manifest.headTags,
96
258
  styles: manifest.globalStyles ?? manifest.styles,
@@ -100,54 +262,121 @@ export function createFallbackPages(options: FallbackPagesOptions) {
100
262
  navigation: options.navigation,
101
263
  lang: options.lang,
102
264
  }
103
- const fallbackHeadStyleHashes = headTagStyleHashes(fallbackDoc.headTags)
265
+ const fallbackHeadStyleHashes = headTagStyleHashes(baseDoc.headTags)
266
+ const lookup = buildStatusPageLookup(manifest, modules, baseDoc, routesPrefix, options.paramMatchers ?? BUILTIN_PARAM_MATCHERS)
104
267
 
105
- async function renderFallbackPage(status: number, renderInner: (() => unknown) | undefined, text: string, url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> {
106
- if (renderInner !== undefined) {
107
- try {
108
- const effUrl = url ?? new URL(`http://localhost/${status}`)
109
- const rctx = createRenderContext(undefined, undefined, ctx?.consent, req !== undefined ? error => notifyError(error, req, 'route') : undefined)
110
- const body = await runWithRenderContext(rctx, async () => {
111
- let inner = ssrChild(await renderInner() as Html)
112
- if (rootLayoutMod !== undefined)
113
- inner = ssrChild(await rootLayoutMod.default({ children: raw(inner), url: effUrl, params: {}, locals: ctx?.locals ?? {} }) as Html)
268
+ async function renderCompiledStatusPage(
269
+ page: CompiledStatusPage,
270
+ status: number,
271
+ props: Record<string, unknown>,
272
+ effUrl: URL,
273
+ params: Record<string, string>,
274
+ req?: Request,
275
+ ctx?: RequestContext,
276
+ ): Promise<Response | undefined> {
277
+ try {
278
+ const locals = ctx?.locals ?? {}
279
+ const rctx = createRenderContext(undefined, undefined, ctx?.consent, req !== undefined ? error => notifyError(error, req, 'route', ctx?.requestId) : undefined)
280
+ const body = await runWithRenderContext(rctx, async () => {
281
+ const inner = ssrChild(await page.render(props) as Html)
282
+ let wrapped = inner
283
+ try {
284
+ for (let i = page.layouts.length - 1; i >= 0; i--)
285
+ wrapped = ssrChild(await page.layouts[i]!.default({ children: raw(wrapped), url: effUrl, params, locals }) as Html)
286
+ }
287
+ catch (layoutErr) {
288
+ if (req !== undefined)
289
+ notifyError(layoutErr, req, 'route', ctx?.requestId)
114
290
  return inner
115
- })
116
- const { hasIslands, eagerChunks } = resolveRenderedIslands(rctx, body)
117
- const docHead = await document.resolveDocumentHead(rctx, manifest.headTags, effUrl, req, ctx)
118
- const docHtml = renderDocument({
119
- ...fallbackDoc,
120
- body,
121
- head: docHead.head,
122
- lang: docHead.lang,
123
- htmlAttrs: docHead.htmlAttrs,
124
- preloadChunks: [...eagerChunks, ...revivePreload(rctx, manifest.reviveScript)],
125
- hasIslands,
126
- })
127
- const html = await document.applyHtmlTransforms(docHtml, effUrl, req, ctx)
128
- const styleHashes = mergeStyleHashes(fallbackHeadStyleHashes, docHead.styleHashes, styleHashesOf(rctx.inlineStyles), addedInlineStyleHashes(docHtml, html))
129
- return new Response(html, { status, headers: htmlHeaders(hasIslands, false, true, styleHashes) })
130
- }
131
- catch (err) {
132
- if (req !== undefined)
133
- notifyError(err, req, 'route')
134
- }
291
+ }
292
+ return wrapped
293
+ })
294
+ const { hasIslands, eagerChunks } = resolveRenderedIslands(rctx, body)
295
+ const docHead = await document.resolveDocumentHead(rctx, manifest.headTags, effUrl, req, ctx)
296
+ const docHtml = renderDocument({
297
+ ...page.doc,
298
+ body,
299
+ head: docHead.head,
300
+ lang: docHead.lang,
301
+ htmlAttrs: docHead.htmlAttrs,
302
+ preloadChunks: [...eagerChunks, ...revivePreload(rctx, manifest.reviveScript)],
303
+ hasIslands,
304
+ })
305
+ const html = await document.applyHtmlTransforms(docHtml, effUrl, req, ctx)
306
+ const styleHashes = mergeStyleHashes(fallbackHeadStyleHashes, docHead.styleHashes, styleHashesOf(rctx.inlineStyles), addedInlineStyleHashes(docHtml, html))
307
+ return new Response(html, { status, headers: htmlHeaders(hasIslands, false, true, styleHashes) })
308
+ }
309
+ catch (err) {
310
+ if (req !== undefined)
311
+ notifyError(err, req, 'route', ctx?.requestId)
312
+ return undefined
313
+ }
314
+ }
315
+
316
+ async function buildErrorResponse(error: unknown, url?: URL, req?: Request, ctx?: RequestContext, routeFile?: string): Promise<Response> {
317
+ const effUrl = url ?? new URL('http://localhost/500')
318
+ const found = lookup.find('error', effUrl, routeFile)
319
+ if (found !== undefined) {
320
+ const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
321
+ const rendered = await renderCompiledStatusPage(
322
+ found.page,
323
+ 500,
324
+ { error, status: 500, message: errorMessage(error), url: effUrl, params, locals: ctx?.locals ?? {} },
325
+ effUrl,
326
+ params,
327
+ req,
328
+ ctx,
329
+ )
330
+ if (rendered !== undefined)
331
+ return rendered
135
332
  }
136
- return new Response(text, { status, headers: { 'content-type': 'text/plain; charset=utf-8' } })
333
+ return new Response(options.dev ? errorDetail(error) : 'Internal Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
137
334
  }
138
335
 
139
- const buildErrorResponse = (error: unknown, url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> =>
140
- renderFallbackPage(500, errorMod && (() => errorMod.default({ error })), options.dev ? errorDetail(error) : 'Internal Server Error', url, req, ctx)
336
+ async function buildNotFoundResponse(url?: URL, req?: Request, ctx?: RequestContext, routeFile?: string): Promise<Response> {
337
+ const effUrl = url ?? new URL('http://localhost/404')
338
+ const found = lookup.find('404', effUrl, routeFile)
339
+ if (found !== undefined) {
340
+ const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
341
+ const rendered = await renderCompiledStatusPage(
342
+ found.page,
343
+ 404,
344
+ { status: 404, message: 'Not Found', url: effUrl, params, locals: ctx?.locals ?? {} },
345
+ effUrl,
346
+ params,
347
+ req,
348
+ ctx,
349
+ )
350
+ if (rendered !== undefined)
351
+ return rendered
352
+ }
353
+ return new Response('Not Found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' } })
354
+ }
141
355
 
142
- const notFoundPage = notFoundMod?.default
143
- const buildNotFoundResponse = (url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> =>
144
- renderFallbackPage(404, notFoundPage && (() => notFoundPage({})), 'Not Found', url, req, ctx)
356
+ async function renderDenied(denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string): Promise<Response> {
357
+ const statusKey = String(denied.status)
358
+ const statusHit = STATUS_KINDS.has(statusKey) ? lookup.find(statusKey as StatusPageKind, url, routeFile) : undefined
359
+ const found = statusHit ?? lookup.find('error', url, routeFile)
360
+ if (found !== undefined) {
361
+ const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
362
+ const props = statusHit !== undefined
363
+ ? { status: denied.status, message: denied.message, url, params, locals: ctx?.locals ?? {} }
364
+ : { error: new Error(denied.message), status: denied.status, message: denied.message, url, params, locals: ctx?.locals ?? {} }
365
+ const rendered = await renderCompiledStatusPage(found.page, denied.status, props, url, params, req, ctx)
366
+ if (rendered !== undefined)
367
+ return rendered
368
+ }
369
+ return new Response(minimalStatusHtml(denied.status, denied.message, options.lang), {
370
+ status: denied.status,
371
+ headers: htmlHeaders(false, false, true, fallbackHeadStyleHashes),
372
+ })
373
+ }
145
374
 
146
- async function renderError(error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext): Promise<Response> {
375
+ async function renderError(error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext, routeFile?: string): Promise<Response> {
147
376
  if (wantsJson(request))
148
- return finish(options.dev ? devErrorResponse(error, request) : Response.json({ ok: false, status: 500, error: 'Internal Server Error' }, { status: 500 }), request, cookieStore)
149
- return finish(await buildErrorResponse(error, url, request, ctx), request, cookieStore)
377
+ return finish(options.dev ? devErrorResponse(error, request) : Response.json({ ok: false, status: 500, error: 'Internal Server Error' }, { status: 500 }), request, cookieStore, ctx?.requestId)
378
+ return finish(await buildErrorResponse(error, url, request, ctx, routeFile), request, cookieStore, ctx?.requestId)
150
379
  }
151
380
 
152
- return { buildNotFoundResponse, renderError }
381
+ return { buildNotFoundResponse, renderError, renderDenied }
153
382
  }