prunelle 0.1.1 → 0.7.2

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