prunelle 0.1.1 → 0.6.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 (120) hide show
  1. package/llms.txt +130 -38
  2. package/package.json +8 -2
  3. package/src/a11y/declaration.ts +335 -0
  4. package/src/a11y/index.ts +446 -0
  5. package/src/a11y/rgaa-map.ts +184 -0
  6. package/src/attrs.ts +11 -3
  7. package/src/build/bundle.ts +80 -36
  8. package/src/build/client-entries.ts +3 -2
  9. package/src/build/client-plugin.ts +8 -4
  10. package/src/build/client-prune.ts +56 -6
  11. package/src/build/compile.ts +11 -9
  12. package/src/build/ecoindex.ts +229 -0
  13. package/src/build/index.ts +174 -108
  14. package/src/build/islands.ts +2 -2
  15. package/src/build/manifest.ts +66 -5
  16. package/src/build/output.ts +2 -2
  17. package/src/build/plugin-host.ts +92 -33
  18. package/src/build/precompress.ts +15 -2
  19. package/src/build/prerender.ts +128 -46
  20. package/src/build/report.ts +23 -2
  21. package/src/build/resolve.ts +8 -6
  22. package/src/build/routes.ts +175 -10
  23. package/src/build/static.ts +137 -39
  24. package/src/build/status-pages.ts +127 -0
  25. package/src/build/style-bundles.ts +526 -0
  26. package/src/cli/check-forms.ts +561 -0
  27. package/src/cli/check-links.ts +632 -0
  28. package/src/cli/check.ts +75 -20
  29. package/src/cli/commands.ts +85 -4
  30. package/src/cli/docs.ts +402 -0
  31. package/src/cli/inspect.ts +103 -14
  32. package/src/cli/mcp-tools.ts +490 -0
  33. package/src/cli/mcp.ts +205 -0
  34. package/src/cli/new.ts +2 -2
  35. package/src/cli/render.ts +421 -0
  36. package/src/cli/upgrade-names.ts +73 -13
  37. package/src/cli/upgrade.ts +137 -16
  38. package/src/compiler/analyze.ts +42 -9
  39. package/src/compiler/browser-globals.ts +140 -17
  40. package/src/compiler/cacheability.ts +636 -0
  41. package/src/compiler/compliance-rgaa.ts +508 -0
  42. package/src/compiler/compliance.ts +241 -289
  43. package/src/compiler/data-keys.ts +199 -192
  44. package/src/compiler/dev-source.ts +87 -0
  45. package/src/compiler/dom-attrs.ts +138 -65
  46. package/src/compiler/dom.ts +517 -442
  47. package/src/compiler/expr-context.ts +167 -57
  48. package/src/compiler/mistakes.ts +4 -1
  49. package/src/compiler/props.ts +87 -36
  50. package/src/compiler/scope.ts +400 -333
  51. package/src/compiler/server-only.ts +190 -151
  52. package/src/compiler/shared.ts +40 -12
  53. package/src/compiler/signal-reads.ts +6 -2
  54. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  55. package/src/compiler/ssr.ts +218 -87
  56. package/src/dev/error-log.ts +151 -0
  57. package/src/dev/index.ts +84 -34
  58. package/src/dev/open-editor.ts +204 -0
  59. package/src/dev/protocol.ts +1 -0
  60. package/src/dev/reload.ts +5 -3
  61. package/src/dev/supervisor.ts +42 -25
  62. package/src/dev/watchers.ts +47 -11
  63. package/src/dom/action.ts +43 -20
  64. package/src/dom/attrs.ts +15 -3
  65. package/src/dom/extras.ts +28 -12
  66. package/src/dom/index.ts +26 -8
  67. package/src/dom/island.ts +35 -28
  68. package/src/dom/loop.ts +10 -9
  69. package/src/plugins/config.ts +8 -7
  70. package/src/plugins/index.ts +2 -2
  71. package/src/plugins/load.ts +26 -7
  72. package/src/plugins/order.ts +38 -1
  73. package/src/plugins/public.ts +5 -2
  74. package/src/plugins/services.ts +81 -0
  75. package/src/plugins/types.ts +34 -0
  76. package/src/reactivity/graph.ts +10 -0
  77. package/src/reactivity/index.ts +24 -16
  78. package/src/reactivity/selector.ts +31 -4
  79. package/src/reactivity/store.ts +45 -13
  80. package/src/server/action-protect.ts +198 -0
  81. package/src/server/action-registry.ts +1 -1
  82. package/src/server/action.ts +82 -27
  83. package/src/server/assets.ts +34 -2
  84. package/src/server/compress.ts +91 -9
  85. package/src/server/document.ts +25 -10
  86. package/src/server/errors.ts +303 -65
  87. package/src/server/form-schema.ts +343 -0
  88. package/src/server/health.ts +244 -0
  89. package/src/server/http.ts +131 -32
  90. package/src/server/index.ts +231 -261
  91. package/src/server/loader.ts +5 -0
  92. package/src/server/param-matchers.ts +112 -0
  93. package/src/server/plugin-host.ts +123 -88
  94. package/src/server/public.ts +3 -3
  95. package/src/server/rate-limit.ts +58 -35
  96. package/src/server/request-body.ts +1 -1
  97. package/src/server/route-cache.ts +423 -0
  98. package/src/server/route-table.ts +339 -8
  99. package/src/server/router.ts +125 -40
  100. package/src/server/routing.ts +196 -63
  101. package/src/server/security.ts +208 -32
  102. package/src/server/serve-handlers.ts +21 -7
  103. package/src/server/start.ts +60 -16
  104. package/src/server/static-dir.ts +61 -8
  105. package/src/server/stream.ts +41 -22
  106. package/src/ssr/context.ts +85 -3
  107. package/src/ssr/index.ts +130 -3
  108. package/src/ssr/region.ts +31 -19
  109. package/src/test/browser.ts +28 -13
  110. package/src/test/index.ts +97 -12
  111. package/src/ts-plugin/diagnostics.ts +505 -0
  112. package/src/ts-plugin/fixes.ts +364 -0
  113. package/src/ts-plugin/index.ts +194 -0
  114. package/templates/_shared/AGENTS.md +2 -2
  115. package/templates/_shared/mcp.json +11 -0
  116. package/templates/_shared/src/routes/legal.tsx +5 -0
  117. package/templates/_shared/tsconfig.json +5 -0
  118. package/templates/blog/prunelle.config.ts +1 -1
  119. package/templates/blog/src/routes/index.tsx +4 -0
  120. package/ts-plugin.cjs +4277 -0
@@ -11,6 +11,18 @@ import { extractRenderedIslands, makeRequestContext } from './http'
11
11
  import { inlineStyleHashes, PRUNELLE_ISLAND_STYLE_HASH, PRUNELLE_STREAM_SCRIPT_HASH, PRUNELLE_SUSPENSE_STYLE_HASH, resolveCspPolicy, withCspHashes } from './security'
12
12
 
13
13
  const TITLE_INNER_RE = /^<title\b[^>]*>([\s\S]*?)<\/title>$/i
14
+ const UNESCAPED_TITLE_CHAR_RE = /[<>]|&(?!(?:#\d+|#x[\da-f]+|[a-z][a-z0-9]+);)/gi
15
+
16
+ // Escapes raw `<`, `>` and unescaped `&` in plugin-supplied `head.title` values without double-escaping existing HTML entities (such as `&amp;` from compiled `<Head><title>` or `@prunellejs/seo`).
17
+ function escapeTitleHtml(title: string): string {
18
+ return title.replace(UNESCAPED_TITLE_CHAR_RE, (ch) => {
19
+ if (ch === '<')
20
+ return '&lt;'
21
+ if (ch === '>')
22
+ return '&gt;'
23
+ return '&amp;'
24
+ })
25
+ }
14
26
 
15
27
  /** `styleHashes` are the page's own `<style>` blocks (`inlineStyleHashes`), added to its CSP. */
16
28
  export type HtmlHeaders = (hasIslands: boolean, hasSuspense: boolean, isDynamic: boolean, styleHashes?: readonly string[]) => Record<string, string>
@@ -181,7 +193,7 @@ export function createDocumentHooks(options: DocumentHooksOptions) {
181
193
  if (!hasHeadHooks) {
182
194
  return {
183
195
  head: (rctx.title ?? '') + collectedParts,
184
- lang,
196
+ lang: rctx.htmlAttrs.lang ?? lang,
185
197
  htmlAttrs: rctx.htmlAttrs,
186
198
  styleHashes: [],
187
199
  }
@@ -194,16 +206,21 @@ export function createDocumentHooks(options: DocumentHooksOptions) {
194
206
  let currentTitle = initialTitleInner
195
207
  let titleDirty = false
196
208
  let currentLang = htmlAttrs.lang ?? lang
197
- let headBuf = (initialTitleTag ?? '') + collectedParts
209
+ let headRest = collectedParts
198
210
  if (baseHeadTags !== undefined) {
199
211
  for (let i = 0; i < baseHeadTags.length; i++)
200
- headBuf += baseHeadTags[i]
212
+ headRest += baseHeadTags[i]
201
213
  }
202
214
  const added: string[] = []
215
+ const renderTitleTag = (): string => (
216
+ titleDirty
217
+ ? (currentTitle !== undefined ? `<title>${escapeTitleHtml(currentTitle)}</title>` : '')
218
+ : (initialTitleTag ?? '')
219
+ )
203
220
 
204
221
  const docHead: DocumentHeadContext = {
205
222
  get lang() {
206
- return currentLang
223
+ return htmlAttrs.lang ?? currentLang
207
224
  },
208
225
  set lang(v: string) {
209
226
  currentLang = v
@@ -218,12 +235,12 @@ export function createDocumentHooks(options: DocumentHooksOptions) {
218
235
  titleDirty = true
219
236
  },
220
237
  get headHtml() {
221
- return headBuf
238
+ return renderTitleTag() + headRest
222
239
  },
223
240
  add(html: string) {
224
241
  if (html !== '') {
225
242
  added.push(html)
226
- headBuf += html
243
+ headRest += html
227
244
  }
228
245
  },
229
246
  }
@@ -237,13 +254,11 @@ export function createDocumentHooks(options: DocumentHooksOptions) {
237
254
  }
238
255
  }
239
256
 
240
- const titleHtml = titleDirty
241
- ? (currentTitle !== undefined ? `<title>${currentTitle}</title>` : '')
242
- : (initialTitleTag ?? '')
257
+ const titleHtml = renderTitleTag()
243
258
  const addedHtml = added.length > 0 ? added.join('') : ''
244
259
  return {
245
260
  head: titleHtml + collectedParts + addedHtml,
246
- lang: currentLang,
261
+ lang: htmlAttrs.lang ?? currentLang,
247
262
  htmlAttrs,
248
263
  styleHashes: addedHtml !== '' ? inlineStyleHashes(addedHtml) : [],
249
264
  }
@@ -1,34 +1,47 @@
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
- if (wantsJson(request))
35
+ if (wantsJson(request)) {
36
+ if (request.method === 'HEAD')
37
+ return new Response(null, { status: 500, headers: { 'content-type': 'application/json; charset=utf-8' } })
26
38
  return Response.json({ ok: false, status: 500, error: errorMessage(error), stack: errorDetail(error) }, { status: 500 })
27
- return new Response(errorDetail(error), { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
39
+ }
40
+ return new Response(request.method === 'HEAD' ? null : errorDetail(error), { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
28
41
  }
29
42
 
30
43
  export interface ErrorNotifierOptions {
31
- /** With no `onError` hook to hear an unhandled error, `console.error` does. */
44
+ /** 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
45
  dev?: boolean | undefined
33
46
  /** Hears every unhandled error, hooks or not: how `testApp().errors` fills. */
34
47
  sink?: ((info: ServerErrorInfo) => void) | undefined
@@ -42,13 +55,16 @@ export function createErrorNotifier(onError: ((info: ServerErrorInfo) => void) |
42
55
  if (p.onError !== undefined)
43
56
  errorHooks.push({ owner: p.name, hook: p.onError })
44
57
  }
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)
58
+ return (error, request, source, requestId) => {
59
+ const info: ServerErrorInfo = requestId !== undefined ? { error, request, source, requestId } : { error, request, source }
60
+ options.sink?.(info)
61
+ if (errorHooks.length === 0 && (options.dev === true || options.sink === undefined)) {
62
+ const idSuffix = requestId !== undefined ? ` [${requestId}]` : ''
63
+ console.error(`prunelle: unhandled error in ${source} ${request.method} ${new URL(request.url).pathname}${idSuffix}`, error)
64
+ }
49
65
  for (const { owner, hook } of errorHooks) {
50
66
  try {
51
- hook({ error, request, source })
67
+ hook(info)
52
68
  }
53
69
  catch (hookError) {
54
70
  console.error(`prunelle: the onError hook of ${owner} threw; the other hooks still run.`, hookError)
@@ -61,17 +77,167 @@ interface LayoutModule {
61
77
  default: (props: { children: Html, url?: URL, params?: Record<string, string>, locals?: object }) => Html | string | Promise<Html | string>
62
78
  }
63
79
 
64
- interface ErrorModule {
65
- default: (props: { error: unknown }) => Html | string | Promise<Html | string>
80
+ interface StatusPageModule {
81
+ default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
66
82
  }
67
83
 
68
- interface NotFoundModule {
69
- default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
84
+ interface CompiledStatusPage {
85
+ entry: StatusPageManifestEntry
86
+ render: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
87
+ layouts: LayoutModule[]
88
+ doc: DocumentOptions
89
+ }
90
+
91
+ interface StatusPageLookup {
92
+ find: (kind: StatusPageKind, url?: URL, routeFile?: string) => { page: CompiledStatusPage, params?: Record<string, string> } | undefined
93
+ }
94
+
95
+ function dirnamePrefix(file: string): string {
96
+ const slash = file.lastIndexOf('/')
97
+ return slash === -1 ? '' : file.slice(0, slash + 1)
98
+ }
99
+
100
+ function parentDirPrefix(dir: string): string | undefined {
101
+ if (dir === '')
102
+ return undefined
103
+ const trimmed = dir.endsWith('/') ? dir.slice(0, -1) : dir
104
+ const slash = trimmed.lastIndexOf('/')
105
+ return slash === -1 ? '' : trimmed.slice(0, slash + 1)
106
+ }
107
+
108
+ function legacyStatusEntries(manifest: BuildManifest, routesPrefix: string): StatusPageManifestEntry[] {
109
+ const layouts = manifest.rootLayoutFile !== undefined ? [manifest.rootLayoutFile] : []
110
+ const styles = manifest.globalStyles ?? manifest.styles
111
+ const entries: StatusPageManifestEntry[] = []
112
+ if (manifest.errorFile !== undefined)
113
+ entries.push({ kind: 'error', dirPattern: '/', dirPrefix: routesPrefix, file: manifest.errorFile, layouts, styles, islandChunks: [] })
114
+ if (manifest.notFoundFile !== undefined)
115
+ entries.push({ kind: '404', dirPattern: '/', dirPrefix: routesPrefix, file: manifest.notFoundFile, layouts, styles, islandChunks: [] })
116
+ return entries
117
+ }
118
+
119
+ function buildStatusPageLookup(
120
+ manifest: BuildManifest,
121
+ modules: Record<string, unknown>,
122
+ baseDoc: DocumentOptions,
123
+ routesPrefix: string,
124
+ paramMatchers: ParamMatcherMap,
125
+ ): StatusPageLookup {
126
+ const rawEntries = manifest.statusPages ?? legacyStatusEntries(manifest, routesPrefix)
127
+ const byDirPrefix = new Map<StatusPageKind, Map<string, CompiledStatusPage>>()
128
+ const byUrlRouter = new Map<StatusPageKind, Router<CompiledStatusPage>>()
129
+ const groupCandidates = new Map<StatusPageKind, Map<string, CompiledStatusPage[]>>()
130
+
131
+ for (const entry of rawEntries) {
132
+ const mod = modules[entry.file] as StatusPageModule | undefined
133
+ if (typeof mod?.default !== 'function')
134
+ continue
135
+ const layouts = entry.layouts
136
+ .map(key => modules[key] as LayoutModule | undefined)
137
+ .filter((l): l is LayoutModule => typeof l?.default === 'function')
138
+ const compiled: CompiledStatusPage = {
139
+ entry,
140
+ render: mod.default,
141
+ layouts,
142
+ doc: { ...baseDoc, styles: entry.styles },
143
+ }
144
+ let dirMap = byDirPrefix.get(entry.kind)
145
+ if (dirMap === undefined) {
146
+ dirMap = new Map()
147
+ byDirPrefix.set(entry.kind, dirMap)
148
+ }
149
+ dirMap.set(entry.dirPrefix, compiled)
150
+
151
+ if (entry.inGroup === true) {
152
+ let byPattern = groupCandidates.get(entry.kind)
153
+ if (byPattern === undefined) {
154
+ byPattern = new Map()
155
+ groupCandidates.set(entry.kind, byPattern)
156
+ }
157
+ const list = byPattern.get(entry.dirPattern) ?? []
158
+ list.push(compiled)
159
+ byPattern.set(entry.dirPattern, list)
160
+ }
161
+ else {
162
+ let router = byUrlRouter.get(entry.kind)
163
+ if (router === undefined) {
164
+ router = new Router<CompiledStatusPage>(paramMatchers)
165
+ byUrlRouter.set(entry.kind, router)
166
+ }
167
+ router.add(entry.dirPattern, compiled)
168
+ }
169
+ }
170
+
171
+ const groupUrlRouter = new Map<StatusPageKind, Router<CompiledStatusPage>>()
172
+ for (const [kind, byPattern] of groupCandidates) {
173
+ const router = new Router<CompiledStatusPage>(paramMatchers)
174
+ let added = false
175
+ for (const [pattern, list] of byPattern) {
176
+ if (list.length === 1) {
177
+ router.add(pattern, list[0]!)
178
+ added = true
179
+ }
180
+ }
181
+ if (added)
182
+ groupUrlRouter.set(kind, router)
183
+ }
184
+
185
+ return {
186
+ find(kind, url, routeFile) {
187
+ if (routeFile !== undefined) {
188
+ const dirMap = byDirPrefix.get(kind)
189
+ if (dirMap !== undefined) {
190
+ let dir: string | undefined = dirnamePrefix(routeFile)
191
+ while (dir !== undefined) {
192
+ const hit = dirMap.get(dir)
193
+ if (hit !== undefined)
194
+ return { page: hit }
195
+ if (dir === routesPrefix || !dir.startsWith(routesPrefix))
196
+ break
197
+ dir = parentDirPrefix(dir)
198
+ }
199
+ const rootHit = dirMap.get(routesPrefix)
200
+ if (rootHit !== undefined)
201
+ return { page: rootHit }
202
+ }
203
+ return undefined
204
+ }
205
+
206
+ const decoded = decodeRequestPath(url?.pathname ?? '/')
207
+ if (decoded === undefined)
208
+ return undefined
209
+ const urlRouter = byUrlRouter.get(kind)
210
+ if (urlRouter !== undefined) {
211
+ for (let i = decoded.segments.length; i >= 0; i--) {
212
+ const matched = urlRouter.match(pathPrefix(decoded, i))
213
+ if (matched !== undefined)
214
+ return { page: matched.data, params: matched.params }
215
+ }
216
+ }
217
+ const fallbackGroup = groupUrlRouter.get(kind)
218
+ if (fallbackGroup !== undefined) {
219
+ for (let i = decoded.segments.length; i >= 0; i--) {
220
+ const matched = fallbackGroup.match(pathPrefix(decoded, i))
221
+ if (matched !== undefined)
222
+ return { page: matched.data, params: matched.params }
223
+ }
224
+ }
225
+ return undefined
226
+ },
227
+ }
228
+ }
229
+
230
+ function minimalStatusHtml(status: number, message: string, lang: string): string {
231
+ const safeLang = escapeHtml(lang)
232
+ const safeMsg = escapeHtml(message)
233
+ 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
234
  }
71
235
 
72
236
  export interface FallbackPagesOptions {
73
237
  manifest: BuildManifest
74
238
  modules: Record<string, unknown>
239
+ routesPrefix?: string | undefined
240
+ paramMatchers?: ParamMatcherMap | undefined
75
241
  lang: string
76
242
  alwaysLoadRuntime: boolean
77
243
  navigation?: string | undefined
@@ -79,18 +245,17 @@ export interface FallbackPagesOptions {
79
245
  document: DocumentHooks
80
246
  htmlHeaders: HtmlHeaders
81
247
  notifyError: NotifyError
82
- finish: (res: Response, request: Request, cookieStore?: CookieStore) => Response
248
+ finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response
83
249
  }
84
250
 
85
251
  export function createFallbackPages(options: FallbackPagesOptions) {
86
252
  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 = {
253
+ const routesPrefix = options.routesPrefix ?? (
254
+ manifest.rootLayoutFile ?? manifest.errorFile ?? manifest.notFoundFile
255
+ ? dirnamePrefix((manifest.rootLayoutFile ?? manifest.errorFile ?? manifest.notFoundFile)!)
256
+ : 'server/'
257
+ )
258
+ const baseDoc: DocumentOptions = {
94
259
  body: '',
95
260
  headTags: manifest.headTags,
96
261
  styles: manifest.globalStyles ?? manifest.styles,
@@ -100,54 +265,127 @@ export function createFallbackPages(options: FallbackPagesOptions) {
100
265
  navigation: options.navigation,
101
266
  lang: options.lang,
102
267
  }
103
- const fallbackHeadStyleHashes = headTagStyleHashes(fallbackDoc.headTags)
268
+ const fallbackHeadStyleHashes = headTagStyleHashes(baseDoc.headTags)
269
+ const lookup = buildStatusPageLookup(manifest, modules, baseDoc, routesPrefix, options.paramMatchers ?? BUILTIN_PARAM_MATCHERS)
104
270
 
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)
271
+ async function renderCompiledStatusPage(
272
+ page: CompiledStatusPage,
273
+ status: number,
274
+ props: Record<string, unknown>,
275
+ effUrl: URL,
276
+ params: Record<string, string>,
277
+ req?: Request,
278
+ ctx?: RequestContext,
279
+ ): Promise<Response | undefined> {
280
+ try {
281
+ const locals = ctx?.locals ?? {}
282
+ const rctx = createRenderContext(undefined, undefined, ctx?.consent, req !== undefined ? error => notifyError(error, req, 'route', ctx?.requestId) : undefined)
283
+ const body = await runWithRenderContext(rctx, async () => {
284
+ const inner = ssrChild(await page.render(props) as Html)
285
+ let wrapped = inner
286
+ try {
287
+ for (let i = page.layouts.length - 1; i >= 0; i--)
288
+ wrapped = ssrChild(await page.layouts[i]!.default({ children: raw(wrapped), url: effUrl, params, locals }) as Html)
289
+ }
290
+ catch (layoutErr) {
291
+ if (req !== undefined)
292
+ notifyError(layoutErr, req, 'route', ctx?.requestId)
114
293
  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
- }
294
+ }
295
+ return wrapped
296
+ })
297
+ const { hasIslands, eagerChunks } = resolveRenderedIslands(rctx, body)
298
+ const docHead = await document.resolveDocumentHead(rctx, manifest.headTags, effUrl, req, ctx)
299
+ const docHtml = renderDocument({
300
+ ...page.doc,
301
+ body,
302
+ head: docHead.head,
303
+ lang: docHead.lang,
304
+ htmlAttrs: docHead.htmlAttrs,
305
+ preloadChunks: [...eagerChunks, ...revivePreload(rctx, manifest.reviveScript)],
306
+ hasIslands,
307
+ })
308
+ const html = await document.applyHtmlTransforms(docHtml, effUrl, req, ctx)
309
+ const styleHashes = mergeStyleHashes(fallbackHeadStyleHashes, docHead.styleHashes, styleHashesOf(rctx.inlineStyles), addedInlineStyleHashes(docHtml, html))
310
+ return new Response(req?.method === 'HEAD' ? null : html, { status, headers: htmlHeaders(hasIslands, false, true, styleHashes) })
311
+ }
312
+ catch (err) {
313
+ if (req !== undefined)
314
+ notifyError(err, req, 'route', ctx?.requestId)
315
+ return undefined
316
+ }
317
+ }
318
+
319
+ async function buildErrorResponse(error: unknown, url?: URL, req?: Request, ctx?: RequestContext, routeFile?: string): Promise<Response> {
320
+ const effUrl = url ?? new URL('http://localhost/500')
321
+ const found = lookup.find('error', effUrl, routeFile)
322
+ if (found !== undefined) {
323
+ const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
324
+ const rendered = await renderCompiledStatusPage(
325
+ found.page,
326
+ 500,
327
+ { error, status: 500, message: errorMessage(error), url: effUrl, params, locals: ctx?.locals ?? {} },
328
+ effUrl,
329
+ params,
330
+ req,
331
+ ctx,
332
+ )
333
+ if (rendered !== undefined)
334
+ return rendered
135
335
  }
136
- return new Response(text, { status, headers: { 'content-type': 'text/plain; charset=utf-8' } })
336
+ return new Response(req?.method === 'HEAD' ? null : (options.dev ? errorDetail(error) : 'Internal Server Error'), { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
137
337
  }
138
338
 
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)
339
+ async function buildNotFoundResponse(url?: URL, req?: Request, ctx?: RequestContext, routeFile?: string): Promise<Response> {
340
+ const effUrl = url ?? new URL('http://localhost/404')
341
+ const found = lookup.find('404', effUrl, routeFile)
342
+ if (found !== undefined) {
343
+ const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
344
+ const rendered = await renderCompiledStatusPage(
345
+ found.page,
346
+ 404,
347
+ { status: 404, message: 'Not Found', url: effUrl, params, locals: ctx?.locals ?? {} },
348
+ effUrl,
349
+ params,
350
+ req,
351
+ ctx,
352
+ )
353
+ if (rendered !== undefined)
354
+ return rendered
355
+ }
356
+ return new Response(req?.method === 'HEAD' ? null : 'Not Found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' } })
357
+ }
141
358
 
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)
359
+ async function renderDenied(denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string): Promise<Response> {
360
+ const statusKey = String(denied.status)
361
+ const statusHit = STATUS_KINDS.has(statusKey) ? lookup.find(statusKey as StatusPageKind, url, routeFile) : undefined
362
+ const found = statusHit ?? lookup.find('error', url, routeFile)
363
+ if (found !== undefined) {
364
+ const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
365
+ const props = statusHit !== undefined
366
+ ? { status: denied.status, message: denied.message, url, params, locals: ctx?.locals ?? {} }
367
+ : { error: new Error(denied.message), status: denied.status, message: denied.message, url, params, locals: ctx?.locals ?? {} }
368
+ const rendered = await renderCompiledStatusPage(found.page, denied.status, props, url, params, req, ctx)
369
+ if (rendered !== undefined)
370
+ return rendered
371
+ }
372
+ return new Response(req.method === 'HEAD' ? null : minimalStatusHtml(denied.status, denied.message, options.lang), {
373
+ status: denied.status,
374
+ headers: htmlHeaders(false, false, true, fallbackHeadStyleHashes),
375
+ })
376
+ }
145
377
 
146
- async function renderError(error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext): Promise<Response> {
147
- 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)
378
+ async function renderError(error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext, routeFile?: string): Promise<Response> {
379
+ if (wantsJson(request)) {
380
+ const res = options.dev
381
+ ? devErrorResponse(error, request)
382
+ : (request.method === 'HEAD'
383
+ ? new Response(null, { status: 500, headers: { 'content-type': 'application/json; charset=utf-8' } })
384
+ : Response.json({ ok: false, status: 500, error: 'Internal Server Error' }, { status: 500 }))
385
+ return finish(res, request, cookieStore, ctx?.requestId)
386
+ }
387
+ return finish(await buildErrorResponse(error, url, request, ctx, routeFile), request, cookieStore, ctx?.requestId)
150
388
  }
151
389
 
152
- return { buildNotFoundResponse, renderError }
390
+ return { buildNotFoundResponse, renderError, renderDenied }
153
391
  }