prunelle 0.0.0-stage → 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 (181) hide show
  1. package/llms.txt +148 -0
  2. package/package.json +53 -4
  3. package/src/ambient.d.ts +6 -0
  4. package/src/attrs.ts +35 -0
  5. package/src/build/bundle.ts +613 -0
  6. package/src/build/carry.ts +57 -0
  7. package/src/build/client-entries.ts +107 -0
  8. package/src/build/client-plugin.ts +169 -0
  9. package/src/build/client-prune.ts +118 -0
  10. package/src/build/compile.ts +128 -0
  11. package/src/build/files.ts +156 -0
  12. package/src/build/first-load.ts +164 -0
  13. package/src/build/graph.ts +247 -0
  14. package/src/build/index.ts +614 -0
  15. package/src/build/is-inside.ts +12 -0
  16. package/src/build/islands.ts +641 -0
  17. package/src/build/manifest.ts +281 -0
  18. package/src/build/output.ts +84 -0
  19. package/src/build/plugin-host.ts +220 -0
  20. package/src/build/precompress.ts +139 -0
  21. package/src/build/prerender.ts +150 -0
  22. package/src/build/render-rules.ts +205 -0
  23. package/src/build/report.ts +247 -0
  24. package/src/build/resolve.ts +50 -0
  25. package/src/build/routes.ts +338 -0
  26. package/src/build/server-entry.ts +38 -0
  27. package/src/build/static.ts +163 -0
  28. package/src/build/status-pages.ts +127 -0
  29. package/src/cli/check-forms.ts +654 -0
  30. package/src/cli/check-links.ts +619 -0
  31. package/src/cli/check.ts +367 -0
  32. package/src/cli/commands.ts +265 -0
  33. package/src/cli/index.ts +70 -0
  34. package/src/cli/inspect.ts +335 -0
  35. package/src/cli/new.ts +41 -0
  36. package/src/cli/upgrade-names.ts +209 -0
  37. package/src/cli/upgrade.ts +354 -0
  38. package/src/compiler/analyze.ts +618 -0
  39. package/src/compiler/ast.ts +82 -0
  40. package/src/compiler/browser-globals.ts +127 -0
  41. package/src/compiler/compliance-rgaa.ts +502 -0
  42. package/src/compiler/compliance.ts +497 -0
  43. package/src/compiler/data-keys.ts +295 -0
  44. package/src/compiler/dom-attrs.ts +379 -0
  45. package/src/compiler/dom.ts +566 -0
  46. package/src/compiler/emit.ts +131 -0
  47. package/src/compiler/expr-context.ts +408 -0
  48. package/src/compiler/index.ts +8 -0
  49. package/src/compiler/interactivity.ts +366 -0
  50. package/src/compiler/mistakes.ts +499 -0
  51. package/src/compiler/node-env.ts +50 -0
  52. package/src/compiler/patch.ts +97 -0
  53. package/src/compiler/props.ts +460 -0
  54. package/src/compiler/scope.ts +568 -0
  55. package/src/compiler/server-only.ts +326 -0
  56. package/src/compiler/shared.ts +369 -0
  57. package/src/compiler/signal-reads.ts +242 -0
  58. package/src/compiler/slots.ts +227 -0
  59. package/src/compiler/ssr-helpers.ts +555 -0
  60. package/src/compiler/ssr-island.ts +90 -0
  61. package/src/compiler/ssr-prunelle-tags.ts +56 -0
  62. package/src/compiler/ssr.ts +491 -0
  63. package/src/context.ts +165 -0
  64. package/src/dev/child.ts +30 -0
  65. package/src/dev/index.ts +208 -0
  66. package/src/dev/modules.ts +68 -0
  67. package/src/dev/protocol.ts +21 -0
  68. package/src/dev/queue.ts +79 -0
  69. package/src/dev/reload.ts +157 -0
  70. package/src/dev/supervisor.ts +187 -0
  71. package/src/dev/watchers.ts +215 -0
  72. package/src/dom/action.ts +164 -0
  73. package/src/dom/attrs.ts +72 -0
  74. package/src/dom/claim.ts +120 -0
  75. package/src/dom/extras.ts +562 -0
  76. package/src/dom/index.ts +289 -0
  77. package/src/dom/island.ts +284 -0
  78. package/src/dom/loop.ts +450 -0
  79. package/src/dom/revive.ts +36 -0
  80. package/src/index.ts +22 -0
  81. package/src/jsx-runtime.ts +566 -0
  82. package/src/plugins/config.ts +86 -0
  83. package/src/plugins/context.ts +66 -0
  84. package/src/plugins/index.ts +14 -0
  85. package/src/plugins/load.ts +70 -0
  86. package/src/plugins/order.ts +111 -0
  87. package/src/plugins/public.ts +12 -0
  88. package/src/plugins/requires.ts +47 -0
  89. package/src/plugins/services.ts +35 -0
  90. package/src/plugins/types.ts +242 -0
  91. package/src/reactivity/graph.ts +249 -0
  92. package/src/reactivity/index.ts +533 -0
  93. package/src/reactivity/selector.ts +51 -0
  94. package/src/reactivity/store.ts +208 -0
  95. package/src/server/action-protect.ts +186 -0
  96. package/src/server/action-registry.ts +78 -0
  97. package/src/server/action.ts +498 -0
  98. package/src/server/app-entry.ts +23 -0
  99. package/src/server/assets.ts +136 -0
  100. package/src/server/compress.ts +560 -0
  101. package/src/server/consent.ts +253 -0
  102. package/src/server/cookies.ts +139 -0
  103. package/src/server/document.ts +271 -0
  104. package/src/server/env.ts +33 -0
  105. package/src/server/errors.ts +382 -0
  106. package/src/server/form-schema.ts +343 -0
  107. package/src/server/health.ts +244 -0
  108. package/src/server/http.ts +508 -0
  109. package/src/server/index.ts +687 -0
  110. package/src/server/lifecycle.ts +75 -0
  111. package/src/server/loader.ts +118 -0
  112. package/src/server/page.ts +107 -0
  113. package/src/server/param-matchers.ts +112 -0
  114. package/src/server/plugin-host.ts +256 -0
  115. package/src/server/prerendered.ts +71 -0
  116. package/src/server/public.ts +19 -0
  117. package/src/server/rate-limit.ts +133 -0
  118. package/src/server/region.ts +96 -0
  119. package/src/server/request-body.ts +27 -0
  120. package/src/server/request-path.ts +73 -0
  121. package/src/server/request-scope.ts +22 -0
  122. package/src/server/route-table.ts +82 -0
  123. package/src/server/router.ts +261 -0
  124. package/src/server/routing.ts +377 -0
  125. package/src/server/security.ts +472 -0
  126. package/src/server/serve-handlers.ts +83 -0
  127. package/src/server/served-file.ts +128 -0
  128. package/src/server/standard-schema.ts +87 -0
  129. package/src/server/start.ts +99 -0
  130. package/src/server/static-dir.ts +167 -0
  131. package/src/server/stream.ts +192 -0
  132. package/src/ssr/context.ts +350 -0
  133. package/src/ssr/index.ts +596 -0
  134. package/src/ssr/navigation.ts +96 -0
  135. package/src/ssr/region.ts +171 -0
  136. package/src/style.ts +33 -0
  137. package/src/test/browser.ts +192 -0
  138. package/src/test/index.ts +191 -0
  139. package/src/unrenderable.ts +35 -0
  140. package/templates/_shared/AGENTS.md +10 -0
  141. package/templates/_shared/CLAUDE.md +1 -0
  142. package/templates/_shared/gitignore +3 -0
  143. package/templates/_shared/public/robots.txt +2 -0
  144. package/templates/_shared/src/routes/legal.tsx +13 -0
  145. package/templates/_shared/tsconfig.json +20 -0
  146. package/templates/app/.env.example +4 -0
  147. package/templates/app/package.json +21 -0
  148. package/templates/app/prunelle.config.ts +11 -0
  149. package/templates/app/src/auth.ts +14 -0
  150. package/templates/app/src/routes/_layout.tsx +32 -0
  151. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  152. package/templates/app/src/routes/dashboard/index.tsx +13 -0
  153. package/templates/app/src/routes/index.tsx +15 -0
  154. package/templates/app/src/routes/login.tsx +34 -0
  155. package/templates/app/src/styles/app.css +7 -0
  156. package/templates/app/tests/app.test.ts +32 -0
  157. package/templates/blog/content/posts/welcome.md +9 -0
  158. package/templates/blog/package.json +22 -0
  159. package/templates/blog/prunelle.config.ts +23 -0
  160. package/templates/blog/src/posts.ts +26 -0
  161. package/templates/blog/src/routes/_layout.tsx +20 -0
  162. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  163. package/templates/blog/src/routes/index.tsx +33 -0
  164. package/templates/blog/src/styles/app.css +10 -0
  165. package/templates/fullstack/package.json +19 -0
  166. package/templates/fullstack/prunelle.config.ts +6 -0
  167. package/templates/fullstack/src/actions/greet.ts +19 -0
  168. package/templates/fullstack/src/components/Counter.tsx +10 -0
  169. package/templates/fullstack/src/components/GreetForm.tsx +27 -0
  170. package/templates/fullstack/src/routes/_layout.tsx +14 -0
  171. package/templates/fullstack/src/routes/api/health.ts +5 -0
  172. package/templates/fullstack/src/routes/index.tsx +13 -0
  173. package/templates/fullstack/src/styles/app.css +29 -0
  174. package/templates/fullstack/tests/app.test.ts +37 -0
  175. package/templates/minimal/package.json +19 -0
  176. package/templates/minimal/prunelle.config.ts +6 -0
  177. package/templates/minimal/src/components/Counter.tsx +10 -0
  178. package/templates/minimal/src/routes/_layout.tsx +14 -0
  179. package/templates/minimal/src/routes/index.tsx +11 -0
  180. package/templates/minimal/src/styles/app.css +22 -0
  181. package/README.md +0 -3
@@ -0,0 +1,382 @@
1
+ // Errors and status pages: `onError` hooks, nested `_404`/`_error`/`_401`/`_403`/`_429`/`_503` lookup, and HTML `ctx.deny()` rendering.
2
+
3
+ import type { BuildManifest, StatusPageKind, StatusPageManifestEntry } from '../build/index'
4
+ import type { Html } from '../jsx-runtime'
5
+ import type { PrunellePlugin, ServerErrorInfo } from '../plugins/index'
6
+ import type { DocumentOptions } from '../ssr/index'
7
+ import type { CookieStore } from './cookies'
8
+ import type { DocumentHooks, HtmlHeaders } from './document'
9
+ import type { DeniedInfo, RequestContext } from './http'
10
+ import type { ParamMatcherMap } from './param-matchers'
11
+ import { createRenderContext, runWithRenderContext } from '../ssr/context'
12
+ import { raw, renderDocument, ssrChild } from '../ssr/index'
13
+ import { addedInlineStyleHashes, headTagStyleHashes, mergeStyleHashes, resolveRenderedIslands, revivePreload } from './document'
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'
18
+ import { styleHashesOf } from './security'
19
+
20
+ export type NotifyError = (error: unknown, request: Request, source: ServerErrorInfo['source'], requestId?: string) => void
21
+
22
+ /** The text of an error a dev response shows: its stack, which starts with its message. */
23
+ export const errorDetail = (error: unknown): string => error instanceof Error ? error.stack ?? error.message : String(error)
24
+
25
+ const errorMessage = (error: unknown): string => error instanceof Error ? error.message : String(error)
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
+
33
+ /** What a dev server answers with an unhandled error: its message and stack, as JSON when the request wants it. */
34
+ export function devErrorResponse(error: unknown, request: Request): Response {
35
+ if (wantsJson(request))
36
+ return Response.json({ ok: false, status: 500, error: errorMessage(error), stack: errorDetail(error) }, { status: 500 })
37
+ return new Response(errorDetail(error), { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
38
+ }
39
+
40
+ export interface ErrorNotifierOptions {
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). */
42
+ dev?: boolean | undefined
43
+ /** Hears every unhandled error, hooks or not: how `testApp().errors` fills. */
44
+ sink?: ((info: ServerErrorInfo) => void) | undefined
45
+ }
46
+
47
+ export function createErrorNotifier(onError: ((info: ServerErrorInfo) => void) | undefined, plugins: readonly PrunellePlugin[], options: ErrorNotifierOptions = {}): NotifyError {
48
+ const errorHooks: { owner: string, hook: (info: ServerErrorInfo) => void }[] = []
49
+ if (onError !== undefined)
50
+ errorHooks.push({ owner: 'prunelle.config.ts', hook: onError })
51
+ for (const p of plugins) {
52
+ if (p.onError !== undefined)
53
+ errorHooks.push({ owner: p.name, hook: p.onError })
54
+ }
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
+ }
62
+ for (const { owner, hook } of errorHooks) {
63
+ try {
64
+ hook(info)
65
+ }
66
+ catch (hookError) {
67
+ console.error(`prunelle: the onError hook of ${owner} threw; the other hooks still run.`, hookError)
68
+ }
69
+ }
70
+ }
71
+ }
72
+
73
+ interface LayoutModule {
74
+ default: (props: { children: Html, url?: URL, params?: Record<string, string>, locals?: object }) => Html | string | Promise<Html | string>
75
+ }
76
+
77
+ interface StatusPageModule {
78
+ default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
79
+ }
80
+
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>`
231
+ }
232
+
233
+ export interface FallbackPagesOptions {
234
+ manifest: BuildManifest
235
+ modules: Record<string, unknown>
236
+ routesPrefix?: string | undefined
237
+ paramMatchers?: ParamMatcherMap | undefined
238
+ lang: string
239
+ alwaysLoadRuntime: boolean
240
+ navigation?: string | undefined
241
+ dev: boolean
242
+ document: DocumentHooks
243
+ htmlHeaders: HtmlHeaders
244
+ notifyError: NotifyError
245
+ finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response
246
+ }
247
+
248
+ export function createFallbackPages(options: FallbackPagesOptions) {
249
+ const { manifest, modules, document, htmlHeaders, notifyError, finish } = options
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 = {
256
+ body: '',
257
+ headTags: manifest.headTags,
258
+ styles: manifest.globalStyles ?? manifest.styles,
259
+ runtimeScript: manifest.runtimeScript,
260
+ chunkImports: manifest.chunkImports,
261
+ alwaysLoadRuntime: options.alwaysLoadRuntime,
262
+ navigation: options.navigation,
263
+ lang: options.lang,
264
+ }
265
+ const fallbackHeadStyleHashes = headTagStyleHashes(baseDoc.headTags)
266
+ const lookup = buildStatusPageLookup(manifest, modules, baseDoc, routesPrefix, options.paramMatchers ?? BUILTIN_PARAM_MATCHERS)
267
+
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)
290
+ return inner
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
332
+ }
333
+ return new Response(options.dev ? errorDetail(error) : 'Internal Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
334
+ }
335
+
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
+ }
355
+
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
+ }
374
+
375
+ async function renderError(error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext, routeFile?: string): Promise<Response> {
376
+ if (wantsJson(request))
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)
379
+ }
380
+
381
+ return { buildNotFoundResponse, renderError, renderDenied }
382
+ }