@kayjs/kay 2.0.0-beta.0 → 2.0.0-beta.3

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 (69) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +617 -0
  4. package/src/build/compile.ts +27 -51
  5. package/src/build/files.ts +174 -0
  6. package/src/build/graph.ts +223 -0
  7. package/src/build/index.ts +272 -1466
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +229 -0
  10. package/src/build/plugin-host.ts +186 -0
  11. package/src/build/prerender.ts +102 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +51 -0
  14. package/src/build/routes.ts +163 -0
  15. package/src/build/server-entry.ts +38 -0
  16. package/src/build/static.ts +73 -0
  17. package/src/cli/check.ts +300 -129
  18. package/src/cli/index.ts +297 -94
  19. package/src/cli/new.ts +58 -38
  20. package/src/compiler/analyze.ts +723 -93
  21. package/src/compiler/dom.ts +848 -762
  22. package/src/compiler/mistakes.ts +354 -0
  23. package/src/compiler/patch.ts +1 -1
  24. package/src/compiler/server-only.ts +172 -23
  25. package/src/compiler/shared.ts +485 -0
  26. package/src/compiler/ssr.ts +331 -342
  27. package/src/context.ts +120 -0
  28. package/src/dev/index.ts +339 -76
  29. package/src/dom/action.ts +114 -14
  30. package/src/dom/extras.ts +121 -83
  31. package/src/dom/index.ts +122 -80
  32. package/src/dom/island.ts +71 -36
  33. package/src/dom/loop.ts +28 -20
  34. package/src/index.ts +5 -1
  35. package/src/jsx-runtime.ts +432 -93
  36. package/src/plugins/config.ts +49 -0
  37. package/src/plugins/context.ts +61 -0
  38. package/src/plugins/index.ts +10 -123
  39. package/src/plugins/load.ts +38 -0
  40. package/src/plugins/order.ts +107 -0
  41. package/src/plugins/services.ts +23 -0
  42. package/src/plugins/types.ts +197 -0
  43. package/src/reactivity/index.ts +237 -213
  44. package/src/reactivity/selector.ts +11 -9
  45. package/src/reactivity/store.ts +36 -11
  46. package/src/server/action-registry.ts +72 -0
  47. package/src/server/action.ts +157 -79
  48. package/src/server/app-entry.ts +23 -0
  49. package/src/server/assets.ts +182 -0
  50. package/src/server/compress.ts +197 -104
  51. package/src/server/cookies.ts +46 -16
  52. package/src/server/document.ts +192 -0
  53. package/src/server/env.ts +18 -13
  54. package/src/server/errors.ts +123 -0
  55. package/src/server/http.ts +203 -77
  56. package/src/server/index.ts +420 -973
  57. package/src/server/loader.ts +113 -0
  58. package/src/server/page.ts +107 -0
  59. package/src/server/plugin-host.ts +167 -0
  60. package/src/server/router.ts +69 -26
  61. package/src/server/security.ts +90 -59
  62. package/src/server/standard-schema.ts +42 -11
  63. package/src/server/static-dir.ts +163 -0
  64. package/src/server/stream.ts +94 -0
  65. package/src/ssr/context.ts +95 -10
  66. package/src/ssr/index.ts +167 -66
  67. package/src/style.ts +33 -0
  68. package/src/test/index.ts +24 -18
  69. package/src/unrenderable.ts +35 -0
@@ -1,4 +1,4 @@
1
- // Typed cookie jar for RequestContext (parses Cookie header, serializes Set-Cookie headers).
1
+ // Typed cookie jar for RequestContext (lazy Cookie header parsing, validated & deduplicated Set-Cookie serialization).
2
2
 
3
3
  export interface CookieOptions {
4
4
  path?: string | undefined
@@ -17,7 +17,10 @@ export interface Cookies {
17
17
  all(): Record<string, string>
18
18
  }
19
19
 
20
- export function parseCookieHeader(header: string | null): Map<string, string> {
20
+ const VALID_COOKIE_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/
21
+ const UNSAFE_ATTR_VAL = /[;\r\n\u0000-\u001F\u007F]/
22
+
23
+ function parseCookieHeader(header: string | null): Map<string, string> {
21
24
  const map = new Map<string, string>()
22
25
  if (!header)
23
26
  return map
@@ -28,6 +31,9 @@ export function parseCookieHeader(header: string | null): Map<string, string> {
28
31
  if (eq <= 0)
29
32
  continue
30
33
  const name = part.slice(0, eq).trim()
34
+ // RFC 6265 §5.4: more specific path cookies come first, so first wins.
35
+ if (name === '' || map.has(name))
36
+ continue
31
37
  const raw = part.slice(eq + 1).trim()
32
38
  try {
33
39
  map.set(name, decodeURIComponent(raw))
@@ -40,17 +46,28 @@ export function parseCookieHeader(header: string | null): Map<string, string> {
40
46
  }
41
47
 
42
48
  function serializeCookie(name: string, value: string, options: CookieOptions = {}, defaultSecure = false): string {
49
+ if (!VALID_COOKIE_NAME.test(name))
50
+ throw new TypeError(`kay: invalid cookie name "${name}"`)
51
+ const path = options.path ?? '/'
52
+ if (UNSAFE_ATTR_VAL.test(path))
53
+ throw new TypeError(`kay: invalid cookie path "${path}"`)
54
+ if (options.domain !== undefined && UNSAFE_ATTR_VAL.test(options.domain))
55
+ throw new TypeError(`kay: invalid cookie domain "${options.domain}"`)
56
+
43
57
  const secure = options.secure ?? defaultSecure
44
58
  const sameSite = options.sameSite ?? 'lax'
45
59
  if (sameSite === 'none' && !secure)
46
60
  throw new Error(`kay: Cookie "${name}" with sameSite: "none" requires secure: true`)
47
61
 
48
62
  let out = `${name}=${encodeURIComponent(value)}`
49
- out += `; Path=${options.path ?? '/'}`
63
+ out += `; Path=${path}`
50
64
  if (options.domain !== undefined)
51
65
  out += `; Domain=${options.domain}`
52
- if (options.maxAge !== undefined)
66
+ if (options.maxAge !== undefined) {
67
+ if (!Number.isFinite(options.maxAge))
68
+ throw new TypeError(`kay: invalid cookie maxAge "${options.maxAge}"`)
53
69
  out += `; Max-Age=${Math.floor(options.maxAge)}`
70
+ }
54
71
  if (options.expires !== undefined)
55
72
  out += `; Expires=${options.expires.toUTCString()}`
56
73
  if (options.httpOnly ?? true)
@@ -61,41 +78,54 @@ function serializeCookie(name: string, value: string, options: CookieOptions = {
61
78
  return out
62
79
  }
63
80
 
81
+ function cookieKey(name: string, options?: Pick<CookieOptions, 'path' | 'domain'>): string {
82
+ return `${name}\0${options?.path ?? '/'}\0${options?.domain ?? ''}`
83
+ }
84
+
64
85
  export class CookieStore implements Cookies {
65
- readonly #values: Map<string, string>
66
- readonly #headers: string[] = []
86
+ #rawHeader: string | null
87
+ #values: Map<string, string> | undefined
88
+ readonly #headers = new Map<string, string>()
67
89
  readonly #isHttps: boolean
68
90
 
69
91
  constructor(cookieHeader: string | null, isHttps = false) {
70
- this.#values = parseCookieHeader(cookieHeader)
92
+ this.#rawHeader = cookieHeader
71
93
  this.#isHttps = isHttps
72
94
  }
73
95
 
96
+ #ensureValues(): Map<string, string> {
97
+ if (this.#values === undefined) {
98
+ this.#values = parseCookieHeader(this.#rawHeader)
99
+ this.#rawHeader = null
100
+ }
101
+ return this.#values
102
+ }
103
+
74
104
  get(name: string): string | undefined {
75
- return this.#values.get(name)
105
+ return this.#ensureValues().get(name)
76
106
  }
77
107
 
78
108
  set(name: string, value: string, options?: CookieOptions): void {
79
109
  const serialized = serializeCookie(name, value, options, this.#isHttps)
80
- this.#values.set(name, value)
81
- this.#headers.push(serialized)
110
+ this.#ensureValues().set(name, value)
111
+ this.#headers.set(cookieKey(name, options), serialized)
82
112
  }
83
113
 
84
114
  delete(name: string, options?: Pick<CookieOptions, 'path' | 'domain' | 'secure'>): void {
85
- this.#values.delete(name)
86
- this.#headers.push(serializeCookie(name, '', { ...options, maxAge: 0, expires: new Date(0) }, this.#isHttps))
115
+ this.#ensureValues().delete(name)
116
+ this.#headers.set(cookieKey(name, options), serializeCookie(name, '', { ...options, maxAge: 0, expires: new Date(0) }, this.#isHttps))
87
117
  }
88
118
 
89
119
  all(): Record<string, string> {
90
- return Object.fromEntries(this.#values)
120
+ return Object.fromEntries(this.#ensureValues())
91
121
  }
92
122
 
93
123
  get hasChanges(): boolean {
94
- return this.#headers.length > 0
124
+ return this.#headers.size > 0
95
125
  }
96
126
 
97
127
  applyTo(headers: Headers): void {
98
- for (let i = 0; i < this.#headers.length; i++)
99
- headers.append('set-cookie', this.#headers[i]!)
128
+ for (const serialized of this.#headers.values())
129
+ headers.append('set-cookie', serialized)
100
130
  }
101
131
  }
@@ -0,0 +1,192 @@
1
+ // What every rendered document shares: its HTML headers, the plugins' `head` hooks and `transformHtml` passes, and the islands it rendered.
2
+
3
+ import type { DocumentHeadContext, KayPlugin, ServerErrorInfo } from '../plugins/index'
4
+ import type { RenderContext } from '../ssr/context'
5
+ import type { RequestContext } from './http'
6
+ import type { SecurityHeadersOptions, TrustProxy } from './security'
7
+ import { extractRenderedIslands, makeRequestContext } from './http'
8
+ import { KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, resolveCspPolicy, withCspHashes } from './security'
9
+
10
+ const TITLE_INNER_RE = /^<title\b[^>]*>([\s\S]*?)<\/title>$/i
11
+
12
+ /** `styleHashes` are the page's own `<style>` blocks (`inlineStyleHashes`), added to its CSP. */
13
+ export type HtmlHeaders = (hasIslands: boolean, hasSuspense: boolean, isDynamic: boolean, styleHashes?: readonly string[]) => Record<string, string>
14
+
15
+ const STYLED_HEADER_CACHE_SIZE = 256
16
+
17
+ // HTML headers, one set per (dynamic, islands, suspense) combination: the CSP only gains the hashes a page needs.
18
+ export function createHtmlHeaders(security: SecurityHeadersOptions | false | undefined, securityRecord: Record<string, string>): HtmlHeaders {
19
+ const baseCsp = resolveCspPolicy(security)
20
+ const htmlHeaderSets: Record<string, string>[] = []
21
+ const kayStyleHashes: string[][] = []
22
+ for (let i = 0; i < 8; i++) {
23
+ const isDynamic = (i & 4) !== 0
24
+ const hasIslands = (i & 2) !== 0
25
+ const hasSuspense = (i & 1) !== 0
26
+ const headers: Record<string, string> = { 'content-type': 'text/html; charset=utf-8', ...securityRecord }
27
+ if (isDynamic)
28
+ headers['cache-control'] = 'private'
29
+ const styleHashes = [...(hasIslands ? [KAY_ISLAND_STYLE_HASH] : []), ...(hasSuspense ? [KAY_SUSPENSE_STYLE_HASH] : [])]
30
+ kayStyleHashes.push(styleHashes)
31
+ if (baseCsp !== undefined && (hasIslands || hasSuspense)) {
32
+ headers['content-security-policy'] = withCspHashes(baseCsp, {
33
+ styleHashes,
34
+ scriptHashes: hasSuspense ? [KAY_STREAM_SCRIPT_HASH] : [],
35
+ })
36
+ }
37
+ htmlHeaderSets.push(headers)
38
+ }
39
+
40
+ // Pages sharing a layout share its blocks, so their header sets are kept by set and hashes; past the cap a new combination is built each time.
41
+ const styledSets = new Map<string, Record<string, string>>()
42
+ return (hasIslands, hasSuspense, isDynamic, styleHashes) => {
43
+ const index = (isDynamic ? 4 : 0) | (hasIslands ? 2 : 0) | (hasSuspense ? 1 : 0)
44
+ const base = htmlHeaderSets[index]!
45
+ if (baseCsp === undefined || styleHashes === undefined || styleHashes.length === 0)
46
+ return base
47
+ const key = `${index} ${styleHashes.join(' ')}`
48
+ let headers = styledSets.get(key)
49
+ if (headers === undefined) {
50
+ headers = {
51
+ ...base,
52
+ 'content-security-policy': withCspHashes(baseCsp, {
53
+ styleHashes: [...kayStyleHashes[index]!, ...styleHashes],
54
+ scriptHashes: hasSuspense ? [KAY_STREAM_SCRIPT_HASH] : [],
55
+ }),
56
+ }
57
+ if (styledSets.size < STYLED_HEADER_CACHE_SIZE)
58
+ styledSets.set(key, headers)
59
+ }
60
+ return headers
61
+ }
62
+ }
63
+
64
+ export function resolveRenderedIslands(rctx: RenderContext, body: string): { hasIslands: boolean, eagerChunks: string[] } {
65
+ if (rctx.hasIslands) {
66
+ const eagerChunks: string[] = []
67
+ for (const [chunk, eager] of rctx.renderedIslands) {
68
+ if (eager)
69
+ eagerChunks.push(chunk)
70
+ }
71
+ return { hasIslands: true, eagerChunks }
72
+ }
73
+ // Fallback only if raw HTML injected a <kay-island> without going through ssrIsland/ssrIslandStatic.
74
+ if (body.includes('<kay-island'))
75
+ return extractRenderedIslands(body)
76
+ return { hasIslands: false, eagerChunks: [] }
77
+ }
78
+
79
+ export interface DocumentHooksOptions {
80
+ plugins: readonly KayPlugin[]
81
+ lang: string
82
+ trustProxy: TrustProxy
83
+ notifyError: (error: unknown, request: Request, source: ServerErrorInfo['source']) => void
84
+ }
85
+
86
+ export function createDocumentHooks(options: DocumentHooksOptions) {
87
+ const { lang, trustProxy, notifyError } = options
88
+ const headHooks = options.plugins
89
+ .map(p => p.head)
90
+ .filter((fn): fn is NonNullable<KayPlugin['head']> => typeof fn === 'function')
91
+ const htmlTransformers = options.plugins
92
+ .map(p => p.transformHtml)
93
+ .filter((fn): fn is NonNullable<KayPlugin['transformHtml']> => typeof fn === 'function')
94
+ const hasHeadHooks = headHooks.length > 0
95
+ const hasHtmlTransformers = htmlTransformers.length > 0
96
+
97
+ async function resolveDocumentHead(
98
+ rctx: RenderContext,
99
+ baseHeadTags: readonly string[] | undefined,
100
+ url: URL,
101
+ req?: Request,
102
+ ctx?: RequestContext,
103
+ ): Promise<{ head: string, lang: string, htmlAttrs: Record<string, string> }> {
104
+ const collectedParts = rctx.headParts.join('')
105
+ if (!hasHeadHooks) {
106
+ return {
107
+ head: (rctx.title ?? '') + collectedParts,
108
+ lang,
109
+ htmlAttrs: rctx.htmlAttrs,
110
+ }
111
+ }
112
+
113
+ const headCtx = ctx ?? makeRequestContext(req ?? new Request(url.toString()), {}, { trustProxy, url }).ctx
114
+ const htmlAttrs: Record<string, string> = { ...rctx.htmlAttrs }
115
+ const initialTitleTag = rctx.title
116
+ const initialTitleInner = initialTitleTag !== undefined ? TITLE_INNER_RE.exec(initialTitleTag)?.[1] : undefined
117
+ let currentTitle = initialTitleInner
118
+ let titleDirty = false
119
+ let currentLang = htmlAttrs.lang ?? lang
120
+ let headBuf = (initialTitleTag ?? '') + collectedParts
121
+ if (baseHeadTags !== undefined) {
122
+ for (let i = 0; i < baseHeadTags.length; i++)
123
+ headBuf += baseHeadTags[i]
124
+ }
125
+ const added: string[] = []
126
+
127
+ const docHead: DocumentHeadContext = {
128
+ get lang() {
129
+ return currentLang
130
+ },
131
+ set lang(v: string) {
132
+ currentLang = v
133
+ htmlAttrs.lang = v
134
+ },
135
+ htmlAttrs,
136
+ get title() {
137
+ return currentTitle
138
+ },
139
+ set title(v: string | undefined) {
140
+ currentTitle = v
141
+ titleDirty = true
142
+ },
143
+ get headHtml() {
144
+ return headBuf
145
+ },
146
+ add(html: string) {
147
+ if (html !== '') {
148
+ added.push(html)
149
+ headBuf += html
150
+ }
151
+ },
152
+ }
153
+
154
+ for (const hook of headHooks) {
155
+ try {
156
+ await hook(docHead, headCtx)
157
+ }
158
+ catch (err) {
159
+ notifyError(err, req ?? headCtx.request, 'plugin')
160
+ }
161
+ }
162
+
163
+ const titleHtml = titleDirty
164
+ ? (currentTitle !== undefined ? `<title>${currentTitle}</title>` : '')
165
+ : (initialTitleTag ?? '')
166
+ return {
167
+ head: titleHtml + collectedParts + (added.length > 0 ? added.join('') : ''),
168
+ lang: currentLang,
169
+ htmlAttrs,
170
+ }
171
+ }
172
+
173
+ async function applyHtmlTransforms(html: string, url: URL, req?: Request, ctx?: RequestContext): Promise<string> {
174
+ if (!hasHtmlTransformers)
175
+ return html
176
+ const transformCtx = ctx ?? makeRequestContext(req ?? new Request(url.toString()), {}, { trustProxy, url }).ctx
177
+ let out = html
178
+ for (const transform of htmlTransformers) {
179
+ try {
180
+ out = await transform(out, transformCtx)
181
+ }
182
+ catch (err) {
183
+ notifyError(err, req ?? transformCtx.request, 'plugin')
184
+ }
185
+ }
186
+ return out
187
+ }
188
+
189
+ return { hasHeadHooks, hasHtmlTransformers, htmlTransformers, resolveDocumentHead, applyHtmlTransforms }
190
+ }
191
+
192
+ export type DocumentHooks = ReturnType<typeof createDocumentHooks>
package/src/server/env.ts CHANGED
@@ -1,27 +1,32 @@
1
1
  // Typed environment variable loader using any Standard Schema validator.
2
2
 
3
3
  import type { InferOutput, StandardSchemaV1 } from './standard-schema'
4
+ import { formatIssuePath, validateSchemaSync } from './standard-schema'
5
+
6
+ const NODE_ENV_KEY = 'NODE_ENV'
7
+
8
+ /** Reads NODE_ENV at runtime: the dynamic key keeps Bun.build from constant-folding it in compiled binaries. */
9
+ export function nodeEnv(): string | undefined {
10
+ return process.env[NODE_ENV_KEY]
11
+ }
4
12
 
5
13
  export function defineEnv<S extends StandardSchemaV1>(
6
14
  schema: S,
7
15
  source: Record<string, string | undefined> = process.env,
8
16
  ): Readonly<InferOutput<S>> {
9
- const result = schema['~standard'].validate(source)
10
- if (result instanceof Promise)
11
- throw new Error('kay: defineEnv() requires a synchronous Standard Schema validator')
12
-
13
- if (result.issues && result.issues.length > 0) {
17
+ const result = validateSchemaSync(
18
+ schema,
19
+ source,
20
+ 'kay: defineEnv() requires a synchronous Standard Schema validator',
21
+ )
22
+ if (!result.ok) {
14
23
  const details = result.issues
15
- .map((issue) => {
16
- const key = issue.path && issue.path.length > 0
17
- ? issue.path.map(seg => (typeof seg === 'object' && seg !== null && 'key' in seg ? String(seg.key) : String(seg))).join('.')
18
- : '(root)'
19
- return ` - ${key}: ${issue.message}`
20
- })
24
+ .map(issue => ` - ${formatIssuePath(issue) || '(root)'}: ${issue.message}`)
21
25
  .join('\n')
22
26
  throw new Error(`kay: invalid environment variables:\n${details}`)
23
27
  }
24
28
 
25
- const value = (result as { value: InferOutput<S> }).value
26
- return typeof value === 'object' && value !== null ? Object.freeze({ ...value }) : value
29
+ return typeof result.value === 'object' && result.value !== null
30
+ ? Object.freeze({ ...result.value })
31
+ : result.value
27
32
  }
@@ -0,0 +1,123 @@
1
+ // Errors a request runs into: the app's and plugins' `onError` hooks, and the `_error` and `_404` pages rendered outside any route.
2
+
3
+ import type { BuildManifest } from '../build/index'
4
+ import type { Html } from '../jsx-runtime'
5
+ import type { KayPlugin, 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 { RequestContext } from './http'
10
+ import { createRenderContext, runWithRenderContext } from '../ssr/context'
11
+ import { raw, renderDocument, ssrChild } from '../ssr/index'
12
+ import { resolveRenderedIslands } from './document'
13
+ import { wantsJson } from './http'
14
+ import { inlineStyleHashes } from './security'
15
+
16
+ export type NotifyError = (error: unknown, request: Request, source: ServerErrorInfo['source']) => void
17
+
18
+ export function createErrorNotifier(onError: ((info: ServerErrorInfo) => void) | undefined, plugins: readonly KayPlugin[]): NotifyError {
19
+ const errorHooks: ((info: ServerErrorInfo) => void)[] = []
20
+ if (onError !== undefined)
21
+ errorHooks.push(onError)
22
+ for (const p of plugins) {
23
+ if (p.onError !== undefined)
24
+ errorHooks.push(p.onError)
25
+ }
26
+ return (error, request, source) => {
27
+ for (const hook of errorHooks) {
28
+ try {
29
+ hook({ error, request, source })
30
+ }
31
+ catch {}
32
+ }
33
+ }
34
+ }
35
+
36
+ interface LayoutModule {
37
+ default: (props: { children: Html, url?: URL, params?: Record<string, string>, locals?: object }) => Html | string | Promise<Html | string>
38
+ }
39
+
40
+ interface ErrorModule {
41
+ default: (props: { error: unknown }) => Html | string | Promise<Html | string>
42
+ }
43
+
44
+ interface NotFoundModule {
45
+ default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
46
+ }
47
+
48
+ export interface FallbackPagesOptions {
49
+ manifest: BuildManifest
50
+ modules: Record<string, unknown>
51
+ lang: string
52
+ alwaysLoadRuntime: boolean
53
+ document: DocumentHooks
54
+ htmlHeaders: HtmlHeaders
55
+ notifyError: NotifyError
56
+ finish: (res: Response, request: Request, cookieStore?: CookieStore) => Response
57
+ }
58
+
59
+ export function createFallbackPages(options: FallbackPagesOptions) {
60
+ const { manifest, modules, document, htmlHeaders, notifyError, finish } = options
61
+ const errorMod = manifest.errorFile ? modules[manifest.errorFile] as ErrorModule : undefined
62
+ const notFoundMod = manifest.notFoundFile ? modules[manifest.notFoundFile] as NotFoundModule : undefined
63
+
64
+ // Error and 404 pages sit outside any route, so they render with the global styles and the explicit root layout only.
65
+ const rootLayoutFile = manifest.rootLayoutFile
66
+ const rootLayoutMod = rootLayoutFile !== undefined ? modules[rootLayoutFile] as LayoutModule | undefined : undefined
67
+ const fallbackDoc: DocumentOptions = {
68
+ body: '',
69
+ headTags: manifest.headTags,
70
+ styles: manifest.globalStyles ?? manifest.styles,
71
+ runtimeScript: manifest.runtimeScript,
72
+ alwaysLoadRuntime: options.alwaysLoadRuntime,
73
+ lang: options.lang,
74
+ }
75
+
76
+ async function renderFallbackPage(status: number, renderInner: (() => unknown) | undefined, text: string, url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> {
77
+ if (renderInner !== undefined) {
78
+ try {
79
+ const effUrl = url ?? new URL(`http://localhost/${status}`)
80
+ const rctx = createRenderContext()
81
+ const body = await runWithRenderContext(rctx, async () => {
82
+ let inner = ssrChild(await renderInner() as Html)
83
+ if (rootLayoutMod !== undefined)
84
+ inner = ssrChild(await rootLayoutMod.default({ children: raw(inner), url: effUrl, params: {}, locals: ctx?.locals ?? {} }) as Html)
85
+ return inner
86
+ })
87
+ const { hasIslands, eagerChunks } = resolveRenderedIslands(rctx, body)
88
+ const docHead = await document.resolveDocumentHead(rctx, manifest.headTags, effUrl, req, ctx)
89
+ const docHtml = renderDocument({
90
+ ...fallbackDoc,
91
+ body,
92
+ head: docHead.head,
93
+ lang: docHead.lang,
94
+ htmlAttrs: docHead.htmlAttrs,
95
+ preloadChunks: eagerChunks,
96
+ hasIslands,
97
+ })
98
+ const html = await document.applyHtmlTransforms(docHtml, effUrl, req, ctx)
99
+ return new Response(html, { status, headers: htmlHeaders(hasIslands, false, true, inlineStyleHashes(html)) })
100
+ }
101
+ catch (err) {
102
+ if (req !== undefined)
103
+ notifyError(err, req, 'route')
104
+ }
105
+ }
106
+ return new Response(text, { status, headers: { 'content-type': 'text/plain; charset=utf-8' } })
107
+ }
108
+
109
+ const buildErrorResponse = (error: unknown, url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> =>
110
+ renderFallbackPage(500, errorMod && (() => errorMod.default({ error })), 'Internal Server Error', url, req, ctx)
111
+
112
+ const notFoundPage = notFoundMod?.default
113
+ const buildNotFoundResponse = (url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> =>
114
+ renderFallbackPage(404, notFoundPage && (() => notFoundPage({})), 'Not Found', url, req, ctx)
115
+
116
+ async function renderError(error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext): Promise<Response> {
117
+ if (wantsJson(request))
118
+ return finish(Response.json({ ok: false, status: 500, error: 'Internal Server Error' }, { status: 500 }), request, cookieStore)
119
+ return finish(await buildErrorResponse(error, url, request, ctx), request, cookieStore)
120
+ }
121
+
122
+ return { buildNotFoundResponse, renderError }
123
+ }