@kayjs/kay 2.0.0-beta.1 → 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 (48) hide show
  1. package/package.json +1 -1
  2. package/src/build/bundle.ts +209 -34
  3. package/src/build/compile.ts +22 -46
  4. package/src/build/files.ts +38 -0
  5. package/src/build/graph.ts +67 -2
  6. package/src/build/index.ts +75 -13
  7. package/src/build/manifest.ts +5 -0
  8. package/src/build/plugin-host.ts +2 -0
  9. package/src/build/prerender.ts +16 -7
  10. package/src/build/resolve.ts +11 -18
  11. package/src/build/routes.ts +33 -5
  12. package/src/build/server-entry.ts +38 -0
  13. package/src/cli/check.ts +102 -45
  14. package/src/cli/new.ts +6 -7
  15. package/src/compiler/analyze.ts +65 -10
  16. package/src/compiler/dom.ts +143 -122
  17. package/src/compiler/server-only.ts +14 -8
  18. package/src/compiler/shared.ts +57 -14
  19. package/src/compiler/ssr.ts +14 -12
  20. package/src/dev/index.ts +96 -29
  21. package/src/dom/action.ts +91 -1
  22. package/src/dom/index.ts +8 -3
  23. package/src/index.ts +3 -0
  24. package/src/jsx-runtime.ts +421 -93
  25. package/src/plugins/config.ts +49 -0
  26. package/src/plugins/context.ts +4 -0
  27. package/src/plugins/index.ts +7 -216
  28. package/src/plugins/load.ts +38 -0
  29. package/src/plugins/order.ts +107 -0
  30. package/src/plugins/services.ts +23 -0
  31. package/src/plugins/types.ts +197 -0
  32. package/src/server/action-registry.ts +72 -0
  33. package/src/server/action.ts +15 -8
  34. package/src/server/app-entry.ts +23 -0
  35. package/src/server/assets.ts +182 -0
  36. package/src/server/compress.ts +87 -14
  37. package/src/server/document.ts +192 -0
  38. package/src/server/errors.ts +123 -0
  39. package/src/server/http.ts +103 -30
  40. package/src/server/index.ts +131 -701
  41. package/src/server/loader.ts +62 -69
  42. package/src/server/page.ts +107 -0
  43. package/src/server/plugin-host.ts +167 -0
  44. package/src/server/router.ts +49 -20
  45. package/src/server/security.ts +44 -3
  46. package/src/server/static-dir.ts +22 -3
  47. package/src/server/stream.ts +94 -0
  48. package/src/test/index.ts +24 -19
@@ -5,104 +5,55 @@
5
5
  // - <Head> collection + cancel-safe streaming <Suspense> (0-overhead fast path when unused)
6
6
  // - Hybrid prerendered HTML serving + embedded single-executable mode
7
7
 
8
- import type { BuildManifest, RouteManifestEntry } from '../build/index'
8
+ import type { RouteManifestEntry } from '../build/index'
9
9
  import type { Html, HydrateStrategy } from '../jsx-runtime'
10
- import type { KayPlugin, MiddlewareOptions, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI } from '../plugins/index'
11
- import type { PendingChunk, SettledChunk } from '../ssr/context'
12
10
  import type { DocumentOptions } from '../ssr/index'
13
- import type { ActionErrorFlash, ActionResult, ServerAction } from './action'
11
+ import type { ActionErrorFlash } from './action'
14
12
  import type { CookieStore } from './cookies'
15
- import type { EmbeddedBody, EmbeddedServerConfig, KayApp, Middleware, RequestContext } from './http'
16
- import type { TrustProxy } from './security'
17
- import { existsSync, statSync } from 'node:fs'
18
- import { extname, join } from 'node:path'
19
- import { createAppContext, getAppContext, runWithAppContext } from '../plugins/index'
20
- import { createRenderContext, renderCollectedHead, runWithRenderContext, streamChunkScript } from '../ssr/context'
13
+ import type { EmbeddedServerConfig, KayApp, Middleware, RequestContext } from './http'
14
+ import type { LoadedLayoutModule, LoadedMiddlewareModule, LoadedPageModule } from './page'
15
+ import { join } from 'node:path'
16
+ import { createAppContext, getAppContext, resolvePlugins, runWithAppContext } from '../plugins/index'
17
+ import { createRenderContext, runWithRenderContext } from '../ssr/context'
21
18
  import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
22
- import { ACTION_ERROR_COOKIE, executeAction, invokeActionCore, isServerAction } from './action'
23
- import { CompressionCache, compressedHtmlResponse, isCompressibleType, maybeCompressResponse, pickEncoding, pickPrecompressedEncoding, toWeakEtag } from './compress'
24
- import { applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, etagMatches, extractRenderedIslands, finalizeResponse, makeRequestContext, MIME, wantsJson } from './http'
19
+ import { ACTION_ERROR_COOKIE, executeAction, isServerAction } from './action'
20
+ import { createActionRegistry } from './action-registry'
21
+ import { createAssets } from './assets'
22
+ import { CompressionCache, compressedHtmlResponse, maybeCompressResponse } from './compress'
23
+ import { createDocumentHooks, createHtmlHeaders, resolveRenderedIslands } from './document'
24
+ import { createErrorNotifier, createFallbackPages } from './errors'
25
+ import { applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, finalizeResponse, isNotFound, makeRequestContext, runChain, wantsJson } from './http'
26
+ import { allowedMethodsHeader, isPlainObject, mergedHeadTags, pickPageIslandProps, stripHeadBody } from './page'
27
+ import { allowedPluginMethodsHeader, createServerPluginHost } from './plugin-host'
25
28
  import { Router } from './router'
26
- import { buildSecurityHeaderEntries, KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, resolveCspPolicy, resolveHstsValue, verifyOrigin, withCspHashes } from './security'
29
+ import { buildSecurityHeaderEntries, inlineStyleHashes, resolveHstsValue, verifyOrigin } from './security'
30
+ import { STREAM_TAIL_MARK, streamDocument } from './stream'
27
31
 
28
- export { createAppContext, defineConfig, definePlugin, getAppContext, loadConfig, pickRuntimeConfig, runWithAppContext } from '../plugins/index'
29
- export type { AppRuntimeContext, BuildPluginContext, BuildPluginTarget, CheckPluginContext, CreateAppContextOptions, FinalizeBuildContext, KayConfig, KayPlugin, MiddlewareOptions, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI } from '../plugins/index'
32
+ /**
33
+ * Request-scoped locals bag shared across middlewares, plugins, actions, layouts, and pages.
34
+ * Augment via `declare module '@kayjs/kay/server' { interface KayLocals { ... } }`.
35
+ */
36
+ export interface KayLocals {}
37
+
38
+ export { CONTENT_IMAGE_RESOLVER_SERVICE, createAppContext, defineConfig, definePlugin, getAppContext, I18N_CONFIG_SERVICE, loadConfig, pickRuntimeConfig, resolvePlugins, resolveServerConfig, runWithAppContext } from '../plugins/index'
39
+ export type { ActiveI18nConfig, AppRuntimeContext, BuildPluginContext, BuildPluginTarget, CheckPluginContext, ContentImageResolver, ContentImageResult, CreateAppContextOptions, DocumentHeadContext, FinalizeBuildContext, KayConfig, KayPlugin, MiddlewareOptions, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from '../plugins/index'
30
40
  export { action, getActionError } from './action'
31
41
  export type { ActionContext, ActionErrorFlash, ActionOptions, ActionResult, ServerAction } from './action'
32
42
  export { CompressionCache, isCompressibleType, pickEncoding, pickPrecompressedEncoding, toWeakEtag } from './compress'
33
43
  export type { CompressionEncoding, PrecompressedEncoding } from './compress'
34
44
  export type { CookieOptions, Cookies } from './cookies'
35
45
  export { defineEnv, nodeEnv } from './env'
36
- export { DEFAULT_MAX_REQUEST_BODY_SIZE } from './http'
37
- export type { EmbeddedServerConfig, KayApp, Middleware, RequestContext, ServerOptions } from './http'
46
+ export { DEFAULT_MAX_REQUEST_BODY_SIZE, notFound } from './http'
47
+ export type { EmbeddedServerConfig, ExtractRouteParams, KayApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, RequestContext, RouteContext, ServerOptions } from './http'
38
48
  export { createServer } from './loader'
39
49
  export { DEFAULT_CSP, DEFAULT_HSTS, DEFAULT_PERMISSIONS_POLICY, getClientIp, isHttpsRequest, isTrustedOrigin, KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, verifyOrigin, withCspHashes } from './security'
40
50
  export type { SecurityHeadersOptions, TrustProxy } from './security'
41
51
  export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
42
52
  export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult, ValidationSuccess } from './standard-schema'
43
53
 
44
- interface LoadedPageModule {
45
- default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
46
- load?: (ctx: RequestContext) => unknown | Promise<unknown>
47
- clientData?: readonly string[] | ((data: unknown) => unknown) | undefined
48
- csrf?: boolean | undefined
49
- GET?: (ctx: RequestContext) => Response | Promise<Response>
50
- POST?: (ctx: RequestContext) => Response | Promise<Response>
51
- PUT?: (ctx: RequestContext) => Response | Promise<Response>
52
- PATCH?: (ctx: RequestContext) => Response | Promise<Response>
53
- DELETE?: (ctx: RequestContext) => Response | Promise<Response>
54
- HEAD?: (ctx: RequestContext) => Response | Promise<Response>
55
- OPTIONS?: (ctx: RequestContext) => Response | Promise<Response>
56
- [key: string]: unknown
57
- }
58
-
59
- interface LoadedLayoutModule {
60
- default: (props: { children: Html, url?: URL, params?: Record<string, string>, locals?: Record<string, unknown> }) => Html | string | Promise<Html | string>
61
- }
62
-
63
- interface LoadedMiddlewareModule {
64
- default: Middleware
65
- }
66
-
67
- interface LoadedErrorModule {
68
- default: (props: { error: unknown }) => Html | string | Promise<Html | string>
69
- }
70
-
71
- const HTTP_METHOD_EXPORTS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'] as const
72
-
73
- const textEncoder = new TextEncoder()
74
- // Where a streamed page's document splits: everything before it flushes first, resolved boundaries go in between.
75
- const STREAM_TAIL_MARK = '<!--kay:stream-tail-->'
76
54
  // Matches Bun.serve's 30 s idle timeout, which a streamed page turns off.
77
55
  const DEFAULT_STREAM_TIMEOUT = 30_000
78
56
 
79
- // A build file ready to serve: headers and compression key are fixed at startup, so a request only picks a variant.
80
- interface ServedFile {
81
- key: string
82
- headers: Record<string, string>
83
- /** Headers of the on-the-fly compressed variant; undefined when the file is never compressed here. */
84
- compressedHeaders: Record<string, string> | undefined
85
- body: BodyInit
86
- read: () => Uint8Array<ArrayBuffer> | Promise<Uint8Array<ArrayBuffer>>
87
- }
88
-
89
- interface Sidecar {
90
- body: BodyInit
91
- headers: Record<string, string>
92
- }
93
-
94
- interface AssetEntry {
95
- file: ServedFile
96
- br: Sidecar | undefined
97
- gz: Sidecar | undefined
98
- }
99
-
100
- interface PublicEntry {
101
- file: ServedFile
102
- etag: string
103
- notModifiedHeaders: Record<string, string>
104
- }
105
-
106
57
  type FastHandler = (req: Request, remoteIp?: string, url?: URL) => Response | Promise<Response>
107
58
 
108
59
  interface CompiledRoute {
@@ -116,172 +67,18 @@ interface CompiledRoute {
116
67
  doc: DocumentOptions
117
68
  }
118
69
 
119
- interface PluginRouteDef {
120
- handler: (ctx: RequestContext) => Response | Promise<Response>
121
- csrf: boolean
122
- trustedOrigins: Set<string> | undefined
123
- trustProxy: TrustProxy
124
- }
125
-
126
- interface ScopedMiddleware {
127
- mw: Middleware
128
- scope: 'all' | 'dynamic' | string
129
- }
130
-
131
70
  const isRead = (request: Request): boolean => request.method === 'GET' || request.method === 'HEAD'
132
71
  const isEventStream = (res: Response): boolean => (res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream')
133
72
  const hasActionErrorCookie = (request: Request): boolean => (request.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
134
73
  // A read the pre-rendered and fast static paths may answer: nothing to flash back to the page.
135
74
  const isPlainRead = (request: Request): boolean => isRead(request) && !hasActionErrorCookie(request)
136
75
 
137
- /** Runs `middlewares` in order around `last`; each calls `next` at most once. */
138
- async function runChain(ctx: RequestContext, middlewares: readonly Middleware[], last: () => Response | Promise<Response>): Promise<Response> {
139
- if (middlewares.length === 0)
140
- return last()
141
- let index = -1
142
- const dispatch = async (i: number): Promise<Response> => {
143
- if (i <= index)
144
- throw new Error('kay: middleware called next() multiple times')
145
- index = i
146
- return i < middlewares.length ? middlewares[i]!(ctx, () => dispatch(i + 1)) : last()
147
- }
148
- return dispatch(0)
149
- }
150
-
151
- async function settleWithin(chunk: PendingChunk, deadlineMs: number, signal: AbortSignal): Promise<SettledChunk | undefined> {
152
- if (signal.aborted)
153
- return undefined
154
- const remaining = Math.max(0, deadlineMs - Date.now())
155
- let timer: ReturnType<typeof setTimeout> | undefined
156
- const abortedOrTimedOut = new Promise<SettledChunk | undefined>((resolve) => {
157
- const onAbort = () => resolve(undefined)
158
- signal.addEventListener('abort', onAbort, { once: true })
159
- timer = setTimeout(() => {
160
- signal.removeEventListener('abort', onAbort)
161
- const error = new Error(`<Suspense> boundary ${chunk.id} did not resolve within ${remaining} ms`)
162
- resolve({ html: chunk.renderError(error), error })
163
- }, remaining)
164
- })
165
- try {
166
- return await Promise.race([chunk.settled, abortedOrTimedOut])
167
- }
168
- finally {
169
- clearTimeout(timer)
170
- }
171
- }
172
-
173
- function mergedHeadTags(manifest: BuildManifest, entry: RouteManifestEntry): string[] | undefined {
174
- return entry.headTags !== undefined && entry.headTags.length > 0
175
- ? [...(manifest.headTags ?? []), ...entry.headTags]
176
- : manifest.headTags
177
- }
178
-
179
- function allowedMethodsHeader(mod: LoadedPageModule): string {
180
- const allowed = new Set<string>()
181
- if (typeof mod.default === 'function') {
182
- allowed.add('GET')
183
- allowed.add('HEAD')
184
- }
185
- for (const m of HTTP_METHOD_EXPORTS) {
186
- if (typeof mod[m] === 'function')
187
- allowed.add(m)
188
- }
189
- if (allowed.has('GET'))
190
- allowed.add('HEAD')
191
- return [...allowed].join(', ')
192
- }
193
-
194
- function allowedPluginMethodsHeader(methods: ReadonlyMap<string, PluginRouteDef>): string {
195
- const allowed = new Set<string>()
196
- for (const m of methods.keys()) {
197
- if (m === 'ALL')
198
- continue
199
- allowed.add(m)
200
- }
201
- if (allowed.has('GET'))
202
- allowed.add('HEAD')
203
- return [...allowed].join(', ')
204
- }
205
-
206
- function stripHeadBody(res: Response): Response {
207
- if (res.body !== null)
208
- void res.body.cancel().catch(() => {})
209
- return new Response(null, { status: res.status, statusText: res.statusText, headers: res.headers })
210
- }
211
-
212
- function isPlainObject(v: unknown): v is Record<string, unknown> {
213
- return typeof v === 'object' && v !== null && !Array.isArray(v)
214
- }
215
-
216
- function pickObjectKeys(obj: Record<string, unknown>, keys: readonly string[]): Record<string, unknown> | undefined {
217
- if (keys.length === 0)
218
- return undefined
219
- const picked: Record<string, unknown> = {}
220
- let count = 0
221
- for (const k of keys) {
222
- if (Object.hasOwn(obj, k)) {
223
- Object.defineProperty(picked, k, { value: obj[k], enumerable: true, writable: true, configurable: true })
224
- count++
225
- }
226
- }
227
- return count > 0 ? picked : undefined
228
- }
229
-
230
- function pickPageIslandProps(data: unknown, entry: RouteManifestEntry, mod: LoadedPageModule): Record<string, unknown> {
231
- if (data === undefined)
232
- return {}
233
- if (typeof mod.clientData === 'function') {
234
- const subset = mod.clientData(data)
235
- return subset === undefined ? {} : { data: subset }
236
- }
237
- if (Array.isArray(mod.clientData)) {
238
- if (!isPlainObject(data))
239
- return {}
240
- const subset = pickObjectKeys(data, mod.clientData)
241
- return subset === undefined ? {} : { data: subset }
242
- }
243
- if (entry.islandDataKeys !== undefined) {
244
- if (entry.islandDataKeys.length === 0)
245
- return {}
246
- if (isPlainObject(data)) {
247
- const subset = pickObjectKeys(data, entry.islandDataKeys)
248
- return subset === undefined ? {} : { data: subset }
249
- }
250
- }
251
- return { data }
252
- }
253
-
254
- function pickRootLayoutFile(manifest: BuildManifest): string | undefined {
255
- // Prefer a layout attached to a root route (`/`) or shared at the shallowest directory depth.
256
- const rootRoute = manifest.routes.find(r => r.path === '/' && r.layouts.length > 0)
257
- if (rootRoute !== undefined)
258
- return rootRoute.layouts[0]
259
- let best: string | undefined
260
- let bestDepth = Number.POSITIVE_INFINITY
261
- for (const r of manifest.routes) {
262
- const first = r.layouts[0]
263
- if (first === undefined)
264
- continue
265
- const depth = first.split('/').length
266
- if (depth < bestDepth) {
267
- bestDepth = depth
268
- best = first
269
- }
270
- }
271
- return best
272
- }
273
-
274
- function middlewareAppliesToPath(scope: ScopedMiddleware['scope'], path: string, isStaticFast: boolean): boolean {
275
- if (scope === 'all')
276
- return true
277
- if (scope === 'dynamic')
278
- return !isStaticFast
279
- return path === scope || path.startsWith(scope.endsWith('/') ? scope : `${scope}/`)
280
- }
281
76
 
282
77
  export async function createServerFromEmbedded(config: EmbeddedServerConfig): Promise<KayApp> {
283
- const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered, prerenderedFiles = {}, lang = 'en', security, plugins = [] } = config
78
+ const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered = {}, prerenderedFiles = {}, lang = 'en', security } = config
79
+ const plugins = resolvePlugins(config.plugins)
284
80
  const assetPrefix = (config.assetPrefix ?? '/_kay').replace(/\/$/, '')
81
+ const site = config.site?.replace(/\/$/, '') || undefined
285
82
  const trustedOriginsList = config.trustedOrigins ?? []
286
83
  const trustedOrigins = trustedOriginsList.length > 0 ? new Set(trustedOriginsList) : undefined
287
84
  const trustProxy = config.trustProxy ?? false
@@ -294,9 +91,9 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
294
91
  const parentAppCtx = getAppContext()
295
92
 
296
93
  const alwaysLoadRuntime = plugins.some(p => Boolean(p.clientEntry))
297
- const htmlTransformers = plugins
298
- .map(p => p.transformHtml)
299
- .filter((fn): fn is NonNullable<KayPlugin['transformHtml']> => typeof fn === 'function')
94
+ const notifyError = createErrorNotifier(config.onError, plugins)
95
+ const document = createDocumentHooks({ plugins, lang, trustProxy, notifyError })
96
+ const { hasHeadHooks, hasHtmlTransformers, htmlTransformers, resolveDocumentHead } = document
300
97
 
301
98
  const securityEntries = buildSecurityHeaderEntries(security)
302
99
  const securityRecord: Record<string, string> = Object.fromEntries(securityEntries)
@@ -309,395 +106,67 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
309
106
  status: 500,
310
107
  headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord },
311
108
  })
312
-
313
- // HTML headers, one set per (dynamic, islands, suspense) combination: the CSP only gains the hashes a page needs.
314
- const baseCsp = resolveCspPolicy(security)
315
- const htmlHeaderSets: Record<string, string>[] = []
316
- for (let i = 0; i < 8; i++) {
317
- const isDynamic = (i & 4) !== 0
318
- const hasIslands = (i & 2) !== 0
319
- const hasSuspense = (i & 1) !== 0
320
- const headers: Record<string, string> = { 'content-type': 'text/html; charset=utf-8', ...securityRecord }
321
- if (isDynamic)
322
- headers['cache-control'] = 'private'
323
- if (baseCsp !== undefined && (hasIslands || hasSuspense)) {
324
- headers['content-security-policy'] = withCspHashes(baseCsp, {
325
- styleHashes: [...(hasIslands ? [KAY_ISLAND_STYLE_HASH] : []), ...(hasSuspense ? [KAY_SUSPENSE_STYLE_HASH] : [])],
326
- scriptHashes: hasSuspense ? [KAY_STREAM_SCRIPT_HASH] : [],
327
- })
328
- }
329
- htmlHeaderSets.push(headers)
330
- }
331
- const htmlHeaders = (hasIslands: boolean, hasSuspense: boolean, isDynamic: boolean): Record<string, string> =>
332
- htmlHeaderSets[(isDynamic ? 4 : 0) | (hasIslands ? 2 : 0) | (hasSuspense ? 1 : 0)]!
109
+ const htmlHeaders = createHtmlHeaders(security, securityRecord)
333
110
 
334
111
  const compressEnabled = config.compress ?? !isDev
335
112
  const compressCache = compressEnabled ? new CompressionCache() : undefined
336
- const varyEncoding: Record<string, string> = compressCache !== undefined ? { vary: 'Accept-Encoding' } : {}
337
-
338
- const toBody = (body: EmbeddedBody): BodyInit => typeof body === 'string' ? Bun.file(body) : body
339
- const readBody = async (body: EmbeddedBody): Promise<Uint8Array<ArrayBuffer>> => typeof body === 'string' ? new Uint8Array(await Bun.file(body).arrayBuffer()) : body
340
- const builtFile = (key: string, source: EmbeddedBody, headers: Record<string, string>, compressedHeaders: Record<string, string> | undefined): ServedFile =>
341
- ({ key, headers, compressedHeaders, body: toBody(source), read: () => readBody(source) })
342
-
343
- const publicMap = new Map<string, PublicEntry>()
344
- const publicCacheControl = isDev ? 'no-cache' : 'public, max-age=3600'
345
-
346
- const registerPublicEntry = (rel: string, body: EmbeddedBody, explicitEtag?: string): void => {
347
- const cleanRel = rel.replace(/^\/+/, '')
348
- const etag = explicitEtag ?? `W/"${Bun.hash(typeof body === 'string' ? cleanRel : body).toString(36)}"`
349
- const type = MIME[extname(cleanRel).toLowerCase()] ?? 'application/octet-stream'
350
- const hasVary = compressCache !== undefined && isCompressibleType(type)
351
- const validators = { etag, 'cache-control': publicCacheControl, ...(hasVary ? { vary: 'Accept-Encoding' } : {}), ...nosniffHeader }
352
- const headers = { 'content-type': type, ...validators }
353
- publicMap.set(`/${cleanRel}`, {
354
- etag,
355
- notModifiedHeaders: validators,
356
- file: builtFile(`p:/${cleanRel}:${etag}`, body, headers, hasVary ? { ...headers, etag: toWeakEtag(etag) } : undefined),
357
- })
358
- }
359
113
 
114
+ const files = createAssets({ assets, assetPrefix, isDev, compressEnabled, compressCache, nosniffHeader, withHsts })
115
+ const { assetMap, publicMap, serveFile, serveAsset, servePublic } = files
360
116
  for (const [rel, body] of Object.entries(publicAssets))
361
- registerPublicEntry(rel, body, publicEtags[rel])
117
+ files.registerPublic(rel, body, publicEtags[rel])
362
118
 
363
119
  const serverAppCtx = createAppContext({
364
120
  root: serverRoot,
365
121
  outDir: serverOutDir,
366
122
  publicDir: serverPublicDir,
367
123
  assetPrefix,
124
+ site,
368
125
  dev: isDev,
369
126
  onRegisterPublicFile: (rel) => {
370
127
  parentAppCtx?.registerPublicFile(rel)
371
- const cleanRel = rel.replace(/^\/+/, '')
372
- const abs = join(serverPublicDir, cleanRel)
373
- if (existsSync(abs)) {
374
- const st = statSync(abs)
375
- registerPublicEntry(cleanRel, abs, `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`)
376
- }
128
+ files.registerPublicFromDisk(serverPublicDir, rel)
377
129
  },
378
130
  })
379
131
 
380
- // Plugin server hooks (plugin setup may be sync or async)
381
- const scopedMiddlewares: ScopedMiddleware[] = []
382
- const shutdownHooks: (() => void | Promise<void>)[] = []
383
- const pluginRewrites: ((pathname: string, ctx: RequestContext) => string | undefined)[] = []
384
- const pluginRouter = new Router<Map<string, PluginRouteDef>>()
385
- const pluginRouteEntries = new Map<string, Map<string, PluginRouteDef>>()
386
-
387
- const actionHandlers = new Map<string, { act: ServerAction<unknown, unknown>, middlewares: Middleware[] }>()
388
- const actionByRef = new WeakMap<ServerAction<unknown, unknown>, Middleware[]>()
389
-
390
- const registerPluginRoute = (
391
- method: string,
392
- path: string,
393
- handler: (ctx: RequestContext) => Response | Promise<Response>,
394
- options?: PluginRouteOptions,
395
- ): void => {
396
- const normPath = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
397
- let byMethod = pluginRouteEntries.get(normPath)
398
- if (byMethod === undefined) {
399
- byMethod = new Map()
400
- pluginRouteEntries.set(normPath, byMethod)
401
- pluginRouter.add(normPath, byMethod)
402
- }
403
- let routeTrustedOrigins = trustedOrigins
404
- if (options?.trustedOrigins !== undefined && options.trustedOrigins.length > 0) {
405
- routeTrustedOrigins = new Set([...(trustedOrigins ?? []), ...options.trustedOrigins])
406
- }
407
- byMethod.set(method.toUpperCase(), {
408
- handler,
409
- csrf: options?.csrf ?? true,
410
- trustedOrigins: routeTrustedOrigins,
411
- trustProxy: options?.trustProxy ?? trustProxy,
412
- })
413
- }
414
-
415
- async function invokeRegisteredAction<I, O>(act: ServerAction<I, O>, input: I, ctx: RequestContext): Promise<ActionResult<O>> {
416
- const dirMiddlewares = actionByRef.get(act as unknown as ServerAction<unknown, unknown>) ?? []
417
- if (dirMiddlewares.length === 0)
418
- return invokeActionCore(act, input, ctx)
419
-
420
- let actionResult: ActionResult<O> | undefined
421
- const res = await runChain(ctx, dirMiddlewares, async () => {
422
- actionResult = await invokeActionCore(act, input, ctx)
423
- return new Response(null, { status: actionResult.ok ? 200 : actionResult.status })
424
- })
425
- if (actionResult !== undefined)
426
- return actionResult
427
- // A directory `_middleware.ts` short-circuited the request (e.g. 401/403 auth guard).
428
- const ct = res.headers.get('content-type') ?? ''
429
- if (ct.includes('application/json')) {
430
- try {
431
- const body = await res.clone().json() as Record<string, unknown>
432
- return {
433
- ok: false,
434
- status: res.status,
435
- error: typeof body.error === 'string' ? body.error : res.statusText || 'Forbidden',
436
- }
437
- }
438
- catch {}
439
- }
440
- return {
441
- ok: false,
442
- status: res.status,
443
- error: (await res.clone().text().catch(() => '')) || res.statusText || 'Forbidden',
444
- }
445
- }
446
-
447
- const {
448
- manifest: _m,
449
- modules: _mods,
450
- assets: _a,
451
- publicAssets: _pa,
452
- publicEtags: _pe,
453
- prerendered: _pr,
454
- prerenderedFiles: _pf,
455
- ...forwardedConfig
456
- } = config as EmbeddedServerConfig & Record<string, unknown>
457
- const readonlyRuntimeConfig: Readonly<Record<string, unknown>> = Object.freeze({ ...forwardedConfig })
458
-
459
- for (const plugin of plugins) {
460
- if (plugin.dispose !== undefined)
461
- shutdownHooks.push(() => plugin.dispose!())
462
- if (plugin.server !== undefined) {
463
- const pluginApi: ServerPluginAPI = {
464
- root: serverRoot,
465
- outDir: serverOutDir,
466
- assetPrefix,
467
- dev: isDev,
468
- trustProxy,
469
- trustedOrigins: trustedOriginsList,
470
- config: readonlyRuntimeConfig,
471
- use(mw: Middleware, options?: MiddlewareOptions) {
472
- scopedMiddlewares.push({ mw, scope: options?.scope ?? 'all' })
473
- },
474
- route: registerPluginRoute,
475
- rewrite(fn) {
476
- pluginRewrites.push(fn)
477
- },
478
- provide: serverAppCtx.provide,
479
- inject: serverAppCtx.inject,
480
- getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined {
481
- return manifest.pluginData?.[pluginName ?? plugin.name] as T | undefined
482
- },
483
- onShutdown(fn) {
484
- shutdownHooks.push(fn)
485
- },
486
- invokeAction: invokeRegisteredAction,
487
- }
488
- await runWithAppContext(serverAppCtx, () => plugin.server!(pluginApi))
489
- }
490
- }
491
-
492
- const middlewaresFor = (path: string, isStaticFast = false): Middleware[] =>
493
- scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, path, isStaticFast)).map(m => m.mw)
494
- const allPluginMiddlewares = scopedMiddlewares.map(m => m.mw)
495
- const hasPluginRewrites = pluginRewrites.length > 0
496
- const hasHtmlTransformers = htmlTransformers.length > 0
497
-
498
- const errorHooks: ((info: ServerErrorInfo) => void)[] = []
499
- if (config.onError !== undefined)
500
- errorHooks.push(config.onError)
501
- for (const p of plugins) {
502
- if (p.onError !== undefined)
503
- errorHooks.push(p.onError)
504
- }
505
- const notifyError = (error: unknown, request: Request, source: ServerErrorInfo['source']) => {
506
- for (const hook of errorHooks) {
507
- try {
508
- hook({ error, request, source })
509
- }
510
- catch {}
511
- }
512
- }
513
-
514
- // Hashed build assets: immutable cache, precompressed .br/.gz sidecars, optional lazy compression.
515
- // Skip `.br`/`.gz` sidecars as standalone HTTP routes when their base asset exists.
516
- const assetMap = new Map<string, AssetEntry>()
517
- for (const [rel, body] of Object.entries(assets)) {
518
- if ((rel.endsWith('.br') || rel.endsWith('.gz')) && rel.slice(0, -3) in assets)
519
- continue
520
- const type = MIME[extname(rel).toLowerCase()] ?? 'application/octet-stream'
521
- const compressible = compressCache !== undefined && isCompressibleType(type)
522
- const headers: Record<string, string> = {
523
- 'content-type': type,
524
- 'cache-control': 'public, max-age=31536000, immutable',
525
- ...nosniffHeader,
526
- }
527
- const sidecar = (ext: 'br' | 'gz', encoding: string): Sidecar | undefined => {
528
- const source = assets[`${rel}.${ext}`] ?? (typeof body === 'string' && existsSync(`${body}.${ext}`) ? `${body}.${ext}` : undefined)
529
- return source === undefined ? undefined : { body: toBody(source), headers: { ...headers, 'content-encoding': encoding, 'vary': 'Accept-Encoding' } }
530
- }
531
- const br = sidecar('br', 'br')
532
- const gz = sidecar('gz', 'gzip')
533
- const varyHeaders = compressible || br !== undefined || gz !== undefined ? { ...headers, vary: 'Accept-Encoding' } : headers
534
- assetMap.set(`${assetPrefix}/${rel}`, {
535
- file: builtFile(`a:${assetPrefix}/${rel}`, body, varyHeaders, compressible ? varyHeaders : undefined),
536
- br,
537
- gz,
538
- })
539
- }
540
-
541
- async function serveFile(request: Request, file: ServedFile): Promise<Response> {
542
- if (request.method === 'HEAD')
543
- return withHsts(new Response(null, { status: 200, headers: file.headers }), request)
544
- if (file.compressedHeaders !== undefined && compressCache !== undefined) {
545
- const enc = pickEncoding(request.headers.get('accept-encoding'))
546
- if (enc !== undefined) {
547
- const compressed = await compressCache.file(file.key, enc, file.read)
548
- if (compressed !== undefined)
549
- return withHsts(new Response(compressed, { status: 200, headers: { ...file.compressedHeaders, 'content-encoding': enc } }), request)
550
- }
551
- }
552
- return withHsts(new Response(file.body, { status: 200, headers: file.headers }), request)
553
- }
554
-
555
- async function serveAsset(request: Request, asset: AssetEntry): Promise<Response> {
556
- if (compressEnabled && request.method !== 'HEAD' && (asset.br !== undefined || asset.gz !== undefined)) {
557
- const preEnc = pickPrecompressedEncoding(request.headers.get('accept-encoding'), { br: asset.br !== undefined, gz: asset.gz !== undefined })
558
- if (preEnc !== undefined) {
559
- const sidecar = preEnc === 'br' ? asset.br! : asset.gz!
560
- return withHsts(new Response(sidecar.body, { status: 200, headers: sidecar.headers }), request)
561
- }
562
- }
563
- return serveFile(request, asset.file)
564
- }
565
-
566
- async function servePublic(request: Request, pub: PublicEntry): Promise<Response> {
567
- if (etagMatches(request.headers.get('if-none-match'), pub.etag))
568
- return withHsts(new Response(null, { status: 304, headers: pub.notModifiedHeaders }), request)
569
- return serveFile(request, pub.file)
570
- }
132
+ const actions = createActionRegistry()
133
+ const pluginHost = await createServerPluginHost({
134
+ plugins,
135
+ config,
136
+ manifest,
137
+ appCtx: serverAppCtx,
138
+ root: serverRoot,
139
+ outDir: serverOutDir,
140
+ assetPrefix,
141
+ site,
142
+ dev: isDev,
143
+ trustProxy,
144
+ trustedOriginsList,
145
+ trustedOrigins,
146
+ invokeAction: actions.invoke,
147
+ })
148
+ const { router: pluginRouter, middlewaresFor } = pluginHost
149
+ const hasPluginRewrites = pluginHost.rewrites.length > 0
571
150
 
572
151
  // Server actions and their live URLs
573
152
  for (const entry of manifest.actions) {
574
153
  const mod = modules[entry.file] as Record<string, unknown> | undefined
575
154
  const act = mod?.[entry.exportName]
576
- if (isServerAction(act)) {
577
- ;(act as { url: string }).url = entry.url
578
- const dirMiddlewares = entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default)
579
- actionByRef.set(act, dirMiddlewares)
580
- actionHandlers.set(entry.url, { act, middlewares: [...middlewaresFor(entry.url), ...dirMiddlewares] })
581
- }
155
+ if (isServerAction(act))
156
+ actions.register(act, entry.url, entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default), middlewaresFor(entry.url))
582
157
  }
583
158
 
584
- const errorMod = manifest.errorFile ? modules[manifest.errorFile] as LoadedErrorModule : undefined
585
- const notFoundMod = manifest.notFoundFile ? modules[manifest.notFoundFile] as LoadedPageModule : undefined
586
-
587
- // Prerendered pages (zero-copy file paths preferred; raw HTML strings supported). `fastPrerenderedMap` holds those nothing may intercept.
588
- const prerenderedMap = new Map<string, ServedFile>()
589
- const fastPrerenderedMap = new Map<string, ServedFile>()
590
- for (const route of manifest.routes) {
591
- if (route.prerendered === undefined)
592
- continue
593
- const headers: Record<string, string> = { ...htmlHeaders(route.islandChunks.length > 0, false, false), ...varyEncoding }
594
- const compressedHeaders = compressCache !== undefined ? headers : undefined
595
- for (const [urlPath, relHtml] of Object.entries(route.prerendered)) {
596
- const filePath = prerenderedFiles[relHtml]
597
- const html = prerendered[relHtml]
598
- const key = `pre:${urlPath}`
599
- const entry: ServedFile | undefined = filePath !== undefined
600
- ? builtFile(key, filePath, headers, compressedHeaders)
601
- : html !== undefined
602
- ? { key, headers, compressedHeaders, body: html, read: () => textEncoder.encode(html) }
603
- : undefined
604
- if (entry === undefined)
605
- continue
606
- prerenderedMap.set(urlPath, entry)
607
- if (route.middlewares.length === 0 && middlewaresFor(urlPath, true).length === 0 && !hasPluginRewrites && pluginRouter.match(urlPath) === undefined)
608
- fastPrerenderedMap.set(urlPath, entry)
609
- }
610
- }
159
+ const { all: prerenderedMap, fast: fastPrerenderedMap } = files.collectPrerendered(manifest.routes, {
160
+ prerendered,
161
+ prerenderedFiles,
162
+ htmlHeaders: (route, urlPath) => htmlHeaders(route.islandChunks.length > 0, false, false, route.prerenderedStyleHashes?.[urlPath]),
163
+ isFast: (urlPath, route) => route.middlewares.length === 0 && middlewaresFor(urlPath, true).length === 0 && !hasPluginRewrites && pluginRouter.match(urlPath) === undefined,
164
+ })
611
165
 
612
166
  const router = new Router<CompiledRoute>()
613
167
  const fastStaticPages = new Map<string, FastHandler>()
614
168
 
615
- // Error and 404 pages sit outside any route, so they render with the global styles and the true root layout.
616
- const rootLayoutFile = pickRootLayoutFile(manifest)
617
- const rootLayoutMod = rootLayoutFile !== undefined ? modules[rootLayoutFile] as LoadedLayoutModule | undefined : undefined
618
- const fallbackDoc: DocumentOptions = {
619
- body: '',
620
- headTags: manifest.headTags,
621
- styles: manifest.globalStyles ?? manifest.styles,
622
- runtimeScript: manifest.runtimeScript,
623
- alwaysLoadRuntime,
624
- lang,
625
- }
626
-
627
- async function applyHtmlTransforms(html: string, url: URL, req?: Request, ctx?: RequestContext): Promise<string> {
628
- if (!hasHtmlTransformers)
629
- return html
630
- const transformCtx = ctx ?? makeRequestContext(req ?? new Request(url.toString()), {}, { trustProxy }).ctx
631
- let out = html
632
- for (const transform of htmlTransformers) {
633
- try {
634
- out = await transform(out, transformCtx)
635
- }
636
- catch (err) {
637
- notifyError(err, req ?? transformCtx.request, 'plugin')
638
- }
639
- }
640
- return out
641
- }
642
-
643
- function resolveRenderedIslands(rctx: ReturnType<typeof createRenderContext>, body: string): { hasIslands: boolean, eagerChunks: string[] } {
644
- if (rctx.hasIslands) {
645
- const eagerChunks: string[] = []
646
- for (const [chunk, eager] of rctx.renderedIslands) {
647
- if (eager)
648
- eagerChunks.push(chunk)
649
- }
650
- return { hasIslands: true, eagerChunks }
651
- }
652
- // Fallback only if raw HTML injected a <kay-island> without going through ssrIsland/ssrIslandStatic.
653
- if (body.includes('<kay-island'))
654
- return extractRenderedIslands(body)
655
- return { hasIslands: false, eagerChunks: [] }
656
- }
657
-
658
- async function renderFallbackPage(status: number, renderInner: (() => unknown) | undefined, text: string, url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> {
659
- if (renderInner !== undefined) {
660
- try {
661
- const effUrl = url ?? new URL(`http://localhost/${status}`)
662
- const rctx = createRenderContext()
663
- const body = await runWithRenderContext(rctx, async () => {
664
- let inner = ssrChild(await renderInner() as Html)
665
- if (rootLayoutMod !== undefined)
666
- inner = ssrChild(await rootLayoutMod.default({ children: raw(inner), url: effUrl, params: {}, locals: ctx?.locals ?? {} }) as Html)
667
- return inner
668
- })
669
- const { hasIslands, eagerChunks } = resolveRenderedIslands(rctx, body)
670
- const docHtml = renderDocument({
671
- ...fallbackDoc,
672
- body,
673
- head: renderCollectedHead(rctx),
674
- htmlAttrs: rctx.htmlAttrs,
675
- preloadChunks: eagerChunks,
676
- hasIslands,
677
- })
678
- const html = await applyHtmlTransforms(docHtml, effUrl, req, ctx)
679
- return new Response(html, { status, headers: htmlHeaders(hasIslands, false, true) })
680
- }
681
- catch (err) {
682
- if (req !== undefined)
683
- notifyError(err, req, 'route')
684
- }
685
- }
686
- return new Response(text, { status, headers: { 'content-type': 'text/plain; charset=utf-8' } })
687
- }
688
-
689
- const buildErrorResponse = (error: unknown, url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> =>
690
- renderFallbackPage(500, errorMod && (() => errorMod.default({ error })), 'Internal Server Error', url, req, ctx)
691
-
692
- const notFoundPage = notFoundMod?.default
693
- const buildNotFoundResponse = (url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> =>
694
- renderFallbackPage(404, notFoundPage && (() => notFoundPage({})), 'Not Found', url, req, ctx)
695
-
696
- async function renderError(error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext): Promise<Response> {
697
- if (wantsJson(request))
698
- return finish(Response.json({ ok: false, status: 500, error: 'Internal Server Error' }, { status: 500 }), request, cookieStore)
699
- return finish(await buildErrorResponse(error, url, request, ctx), request, cookieStore)
700
- }
169
+ const { buildNotFoundResponse, renderError } = createFallbackPages({ manifest, modules, lang, alwaysLoadRuntime, document, htmlHeaders, notifyError, finish })
701
170
 
702
171
  async function renderNotFound(cookieStore: CookieStore, url: URL, request: Request, ctx: RequestContext): Promise<Response> {
703
172
  const res = await runChain(ctx, middlewaresFor(url.pathname), () => buildNotFoundResponse(url, request, ctx))
@@ -728,6 +197,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
728
197
  // Zero-overhead path for a static route with no middleware, no <Head>/<Suspense>, and no intercepting plugin hook
729
198
  const canFastPath = fastPluginMiddlewares.length === 0
730
199
  && !hasPluginRewrites
200
+ && !hasHeadHooks
731
201
  && !hasHtmlTransformers
732
202
  && pluginRouter.match(entry.path) === undefined
733
203
  && !dynamic
@@ -742,25 +212,35 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
742
212
  const docPrefix = shell.slice(0, splitAt)
743
213
  const docSuffix = shell.slice(splitAt + 1)
744
214
  const singleLayout = layouts.length === 1 ? layouts[0]! : undefined
745
- const fastHeaders = htmlHeaders(hasIslands, false, true)
746
215
 
747
- const fail = (error: unknown, request: Request, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
216
+
217
+ const fail = (error: unknown, request: Request, url: URL, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
748
218
  notifyError(error, request, 'route')
749
- return renderError(error, cookieStore, ctx?.url ?? new URL(request.url), request, ctx)
219
+ return renderError(error, cookieStore, url, request, ctx)
750
220
  }
751
221
  const respondHtml = (body: string, request: Request, cookieStore?: CookieStore): Response => {
752
- const res = compressedHtmlResponse(docPrefix + body + docSuffix, 200, fastHeaders, request, compressCache, !entry.hasLoad)
222
+ const html = docPrefix + body + docSuffix
223
+ const res = compressedHtmlResponse(html, 200, htmlHeaders(hasIslands, false, true, inlineStyleHashes(html)), request, compressCache, !entry.hasLoad)
753
224
  return cookieStore?.hasChanges ? finish(res, request, cookieStore) : withHsts(res, request)
754
225
  }
755
- const layoutProps = (inner: string, url: URL, locals: Record<string, unknown>) => ({ children: raw(inner), url, params: {}, locals })
226
+ const layoutProps = (inner: string, url: URL, locals: KayLocals) => ({ children: raw(inner), url, params: {}, locals })
227
+
228
+ const finishSingleLayout = async (wrapped: Promise<Html | string>, request: Request, url: URL, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
229
+ try {
230
+ return respondHtml(ssrChild(await wrapped as Html), request, cookieStore)
231
+ }
232
+ catch (error) {
233
+ return fail(error, request, url, cookieStore, ctx)
234
+ }
235
+ }
756
236
 
757
- const wrapLayouts = (inner: string, request: Request, url: URL, locals: Record<string, unknown>, cookieStore?: CookieStore, ctx?: RequestContext): Response | Promise<Response> => {
237
+ const wrapLayouts = (inner: string, request: Request, url: URL, locals: KayLocals, cookieStore?: CookieStore, ctx?: RequestContext): Response | Promise<Response> => {
758
238
  if (layouts.length === 0)
759
239
  return respondHtml(inner, request, cookieStore)
760
240
  if (singleLayout !== undefined) {
761
241
  const wrapped = singleLayout.default(layoutProps(inner, url, locals))
762
242
  if (wrapped instanceof Promise)
763
- return wrapped.then(x => respondHtml(ssrChild(x as Html), request, cookieStore), error => fail(error, request, cookieStore, ctx))
243
+ return finishSingleLayout(wrapped, request, url, cookieStore, ctx)
764
244
  return respondHtml(ssrChild(wrapped as Html), request, cookieStore)
765
245
  }
766
246
  return (async () => {
@@ -771,12 +251,21 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
771
251
  return respondHtml(cur, request, cookieStore)
772
252
  }
773
253
  catch (error) {
774
- return fail(error, request, cookieStore, ctx)
254
+ return fail(error, request, url, cookieStore, ctx)
775
255
  }
776
256
  })()
777
257
  }
778
258
 
779
- const renderPage = (data: unknown, request: Request, url: URL, locals: Record<string, unknown>, cookieStore?: CookieStore, ctx?: RequestContext): Response | Promise<Response> => {
259
+ const finishAsyncPage = async (rendered: Promise<Html | string>, request: Request, url: URL, locals: KayLocals, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
260
+ try {
261
+ return await wrapLayouts(ssrChild(await rendered as Html), request, url, locals, cookieStore, ctx)
262
+ }
263
+ catch (error) {
264
+ return fail(error, request, url, cookieStore, ctx)
265
+ }
266
+ }
267
+
268
+ const renderPage = (data: unknown, request: Request, url: URL, locals: KayLocals, cookieStore?: CookieStore, ctx?: RequestContext): Response | Promise<Response> => {
780
269
  const pageProps: Record<string, unknown> = { params: {}, locals, url, ...(data !== undefined ? { data } : {}) }
781
270
  if (entry.isIsland && entry.islandChunk !== undefined) {
782
271
  return wrapLayouts(ssrIsland(
@@ -789,7 +278,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
789
278
  }
790
279
  const rendered = mod.default!(pageProps)
791
280
  if (rendered instanceof Promise)
792
- return rendered.then(r => wrapLayouts(ssrChild(r as Html), request, url, locals, cookieStore, ctx), error => fail(error, request, cookieStore, ctx))
281
+ return finishAsyncPage(rendered, request, url, locals, cookieStore, ctx)
793
282
  return wrapLayouts(ssrChild(rendered as Html), request, url, locals, cookieStore, ctx)
794
283
  }
795
284
 
@@ -799,21 +288,24 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
799
288
  return renderPage(undefined, request, url, {})
800
289
 
801
290
  const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url })
802
- const afterLoad = async (pending: unknown): Promise<Response> => {
291
+ return (async () => {
803
292
  try {
804
- const loaded = await pending
293
+ const loaded = await mod.load!(ctx)
294
+ if (isNotFound(loaded))
295
+ return finish(await buildNotFoundResponse(url, request, ctx), request, cookieStore)
805
296
  if (loaded instanceof Response)
806
297
  return finish(loaded, request, cookieStore)
807
298
  return await renderPage(loaded, request, url, ctx.locals, cookieStore, ctx)
808
299
  }
809
300
  catch (error) {
810
- return fail(error, request, cookieStore, ctx)
301
+ if (isNotFound(error))
302
+ return finish(await buildNotFoundResponse(url, request, ctx), request, cookieStore)
303
+ return fail(error, request, url, cookieStore, ctx)
811
304
  }
812
- }
813
- return afterLoad(mod.load(ctx))
305
+ })()
814
306
  }
815
307
  catch (error) {
816
- return fail(error, request)
308
+ return fail(error, request, url)
817
309
  }
818
310
  })
819
311
  }
@@ -868,7 +360,19 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
868
360
  }
869
361
  }
870
362
 
871
- const data = entry.hasLoad && typeof mod.load === 'function' ? await mod.load(ctx) : undefined
363
+ let data: unknown
364
+ if (entry.hasLoad && typeof mod.load === 'function') {
365
+ try {
366
+ data = await mod.load(ctx)
367
+ }
368
+ catch (error) {
369
+ if (isNotFound(error))
370
+ return buildNotFoundResponse(ctx.url, ctx.request, ctx)
371
+ throw error
372
+ }
373
+ }
374
+ if (isNotFound(data))
375
+ return buildNotFoundResponse(ctx.url, ctx.request, ctx)
872
376
  if (data instanceof Response)
873
377
  return data
874
378
  const pageProps: Record<string, unknown> = {
@@ -899,7 +403,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
899
403
  }
900
404
 
901
405
  const body = await runWithRenderContext(rctx, renderBody)
902
- const collectedHead = renderCollectedHead(rctx)
406
+ const docHead = await resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx)
903
407
  const renderedIslands = resolveRenderedIslands(rctx, body)
904
408
  const isStreamed = rctx.pending.length > 0
905
409
  const hasIslands = renderedIslands.hasIslands || (isStreamed && entry.islandChunks.length > 0)
@@ -910,79 +414,18 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
910
414
  if (ctx.request.method === 'HEAD')
911
415
  return new Response(null, { status: 200, headers: htmlHeaders(hasIslands, true, true) })
912
416
  disableTimeout?.()
913
- let shell = renderDocument({ ...doc, body: body + STREAM_TAIL_MARK, head: collectedHead, htmlAttrs: rctx.htmlAttrs, preloadChunks, hasIslands, hasSuspense: true })
417
+ let shell = renderDocument({ ...doc, body: body + STREAM_TAIL_MARK, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands, hasSuspense: true })
914
418
  // Transforms see the document with its initial body; boundaries resolved later stream as they render.
915
419
  for (const transform of htmlTransformers)
916
420
  shell = await transform(shell, ctx)
917
- let splitAt = shell.lastIndexOf(STREAM_TAIL_MARK)
918
- let tailOffset = STREAM_TAIL_MARK.length
919
- if (splitAt === -1) {
920
- splitAt = shell.lastIndexOf('</body>')
921
- tailOffset = 0
922
- }
923
- const openingHtml = splitAt === -1 ? shell : shell.slice(0, splitAt)
924
- const tailHtml = splitAt === -1 ? '' : shell.slice(splitAt + tailOffset)
925
-
926
- const abortCtrl = new AbortController()
927
- let closed = false
928
- const deadline = Date.now() + streamTimeout
929
-
930
- const safeEnqueue = (controller: ReadableStreamDefaultController<Uint8Array>, data: Uint8Array): void => {
931
- if (closed || abortCtrl.signal.aborted)
932
- return
933
- try {
934
- controller.enqueue(data)
935
- }
936
- catch {
937
- closed = true
938
- abortCtrl.abort()
939
- }
940
- }
941
-
942
- const stream = new ReadableStream<Uint8Array>({
943
- async start(controller) {
944
- safeEnqueue(controller, textEncoder.encode(openingHtml))
945
- // A resolved boundary can render boundaries of its own, so each flush also drains the ones it added.
946
- let flushed = 0
947
- const flushPending = async (): Promise<void> => {
948
- if (closed || abortCtrl.signal.aborted)
949
- return
950
- const chunks = rctx.pending.slice(flushed)
951
- flushed = rctx.pending.length
952
- await Promise.all(chunks.map(async (chunk) => {
953
- const settled = await settleWithin(chunk, deadline, abortCtrl.signal)
954
- if (settled === undefined || closed || abortCtrl.signal.aborted)
955
- return
956
- if ('error' in settled)
957
- notifyError(settled.error, ctx.request, 'route')
958
- safeEnqueue(controller, textEncoder.encode(streamChunkScript(chunk.id, settled.html)))
959
- await flushPending()
960
- }))
961
- }
962
- await flushPending()
963
- if (!closed && !abortCtrl.signal.aborted) {
964
- safeEnqueue(controller, textEncoder.encode(tailHtml))
965
- closed = true
966
- try {
967
- controller.close()
968
- }
969
- catch {}
970
- }
971
- },
972
- cancel() {
973
- closed = true
974
- abortCtrl.abort()
975
- },
976
- })
977
-
978
- return new Response(stream, { status: 200, headers: htmlHeaders(hasIslands, true, true) })
421
+ return new Response(streamDocument(shell, rctx, streamTimeout, error => notifyError(error, ctx.request, 'route')), { status: 200, headers: htmlHeaders(hasIslands, true, true, inlineStyleHashes(shell)) })
979
422
  }
980
423
 
981
- let html = renderDocument({ ...doc, body, head: collectedHead, htmlAttrs: rctx.htmlAttrs, preloadChunks, hasIslands })
424
+ let html = renderDocument({ ...doc, body, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands })
982
425
  for (const transform of htmlTransformers)
983
426
  html = await transform(html, ctx)
984
427
 
985
- return compressedHtmlResponse(html, 200, htmlHeaders(hasIslands, false, true), ctx.request, compressCache)
428
+ return compressedHtmlResponse(html, 200, htmlHeaders(hasIslands, false, true, inlineStyleHashes(html)), ctx.request, compressCache)
986
429
  }
987
430
 
988
431
  // `bodyLimited` is set under `serve()`, where Bun.serve already enforces maxRequestBodySize on every body, chunked ones included.
@@ -1009,14 +452,14 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
1009
452
  }
1010
453
 
1011
454
  // Actions only accept POST; other methods get 405 before any middleware runs.
1012
- const registeredAction = actionHandlers.get(pathname)
455
+ const registeredAction = actions.byUrl(pathname)
1013
456
  if (registeredAction !== undefined && request.method !== 'POST')
1014
457
  return finish(new Response('Method Not Allowed', { status: 405, headers: { allow: 'POST' } }), request)
1015
458
 
1016
459
  // Actions are origin-checked before their body is read and before any middleware runs.
1017
460
  const actionHandler = request.method === 'POST' ? registeredAction : undefined
1018
461
  if (actionHandler !== undefined) {
1019
- const originCheck = verifyOrigin(request, trustedOrigins, trustProxy)
462
+ const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
1020
463
  if (!originCheck.ok)
1021
464
  return refuseCrossSite(request, originCheck.reason)
1022
465
  }
@@ -1060,7 +503,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
1060
503
 
1061
504
  // Apply plugin URL rewrites (e.g. @kayjs/i18n stripping /fr prefix and setting ctx.locals.locale)
1062
505
  let effectivePath = pathname
1063
- for (const rewrite of pluginRewrites) {
506
+ for (const rewrite of pluginHost.rewrites) {
1064
507
  const nextPath = rewrite(effectivePath, ctx)
1065
508
  if (nextPath !== undefined)
1066
509
  effectivePath = nextPath
@@ -1074,13 +517,13 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
1074
517
  const routeDef = directPluginDef ?? headFallbackPluginDef
1075
518
  if (pluginMatch !== undefined && routeDef !== undefined) {
1076
519
  if (routeDef.csrf) {
1077
- const originCheck = verifyOrigin(req, routeDef.trustedOrigins, routeDef.trustProxy)
520
+ const originCheck = verifyOrigin(req, routeDef.trustedOrigins, routeDef.trustProxy, url)
1078
521
  if (!originCheck.ok)
1079
522
  return refuseCrossSite(req, originCheck.reason, cookieStore)
1080
523
  }
1081
524
  ctx.params = pluginMatch.params
1082
525
  try {
1083
- let res = await runChain(ctx, allPluginMiddlewares, () => routeDef.handler(ctx))
526
+ let res = await runChain(ctx, pluginHost.allMiddlewares, () => routeDef.handler(ctx))
1084
527
  if (headFallbackPluginDef !== undefined)
1085
528
  res = stripHeadBody(res)
1086
529
  else if (isEventStream(res))
@@ -1116,7 +559,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
1116
559
 
1117
560
  // CSRF verification for file-based API routes on unsafe methods (opt out via `export const csrf = false`)
1118
561
  if (typeof route.mod[method] === 'function' && route.mod.csrf !== false) {
1119
- const originCheck = verifyOrigin(req, trustedOrigins, trustProxy)
562
+ const originCheck = verifyOrigin(req, trustedOrigins, trustProxy, url)
1120
563
  if (!originCheck.ok)
1121
564
  return refuseCrossSite(req, originCheck.reason, cookieStore)
1122
565
  }
@@ -1190,18 +633,5 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
1190
633
  return srvRef
1191
634
  }
1192
635
 
1193
- let disposed = false
1194
- async function dispose(): Promise<void> {
1195
- if (disposed)
1196
- return
1197
- disposed = true
1198
- for (const hook of shutdownHooks) {
1199
- try {
1200
- await hook()
1201
- }
1202
- catch {}
1203
- }
1204
- }
1205
-
1206
- return { handle, serve, dispose }
636
+ return { handle, serve, dispose: pluginHost.dispose }
1207
637
  }