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

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 (55) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +442 -0
  4. package/src/build/compile.ts +10 -10
  5. package/src/build/files.ts +136 -0
  6. package/src/build/graph.ts +158 -0
  7. package/src/build/index.ts +204 -1460
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +224 -0
  10. package/src/build/plugin-host.ts +184 -0
  11. package/src/build/prerender.ts +93 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +58 -0
  14. package/src/build/routes.ts +135 -0
  15. package/src/build/static.ts +73 -0
  16. package/src/cli/check.ts +228 -114
  17. package/src/cli/index.ts +297 -94
  18. package/src/cli/new.ts +53 -32
  19. package/src/compiler/analyze.ts +666 -91
  20. package/src/compiler/dom.ts +808 -743
  21. package/src/compiler/mistakes.ts +354 -0
  22. package/src/compiler/patch.ts +1 -1
  23. package/src/compiler/server-only.ts +164 -21
  24. package/src/compiler/shared.ts +442 -0
  25. package/src/compiler/ssr.ts +329 -342
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +271 -75
  28. package/src/dom/action.ts +23 -13
  29. package/src/dom/extras.ts +121 -83
  30. package/src/dom/index.ts +114 -77
  31. package/src/dom/island.ts +71 -36
  32. package/src/dom/loop.ts +28 -20
  33. package/src/index.ts +2 -1
  34. package/src/jsx-runtime.ts +11 -0
  35. package/src/plugins/context.ts +57 -0
  36. package/src/plugins/index.ts +114 -18
  37. package/src/reactivity/index.ts +237 -213
  38. package/src/reactivity/selector.ts +11 -9
  39. package/src/reactivity/store.ts +36 -11
  40. package/src/server/action.ts +147 -76
  41. package/src/server/compress.ts +116 -96
  42. package/src/server/cookies.ts +46 -16
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +107 -54
  45. package/src/server/index.ts +887 -870
  46. package/src/server/loader.ts +120 -0
  47. package/src/server/router.ts +22 -8
  48. package/src/server/security.ts +48 -58
  49. package/src/server/standard-schema.ts +42 -11
  50. package/src/server/static-dir.ts +144 -0
  51. package/src/ssr/context.ts +95 -10
  52. package/src/ssr/index.ts +167 -66
  53. package/src/style.ts +33 -0
  54. package/src/test/index.ts +2 -1
  55. package/src/unrenderable.ts +35 -0
@@ -2,49 +2,57 @@
2
2
  // - Static + dynamic ([param], [...catchall]) Router
3
3
  // - Composable directory-scoped _middleware.ts chains + ctx.cookies + ctx.locals
4
4
  // - Unified Standard-Schema action() endpoint handling with CSRF verification
5
- // - <Head> collection + streaming <Suspense> (0-overhead fast path when unused)
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
8
  import type { BuildManifest, RouteManifestEntry } from '../build/index'
9
9
  import type { Html, HydrateStrategy } from '../jsx-runtime'
10
- import type { KayPlugin, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI } from '../plugins/index'
11
- import type { ActionContext, ActionErrorFlash, ServerAction } from './action'
10
+ import type { KayPlugin, MiddlewareOptions, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI } from '../plugins/index'
11
+ import type { PendingChunk, SettledChunk } from '../ssr/context'
12
+ import type { DocumentOptions } from '../ssr/index'
13
+ import type { ActionErrorFlash, ActionResult, ServerAction } from './action'
12
14
  import type { CookieStore } from './cookies'
13
- import type { EmbeddedBody, EmbeddedServerConfig, KayApp, Middleware, RequestContext, ServerOptions } from './http'
14
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
15
- import { extname, join, resolve } from 'node:path'
16
- import { loadConfig } from '../plugins/index'
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'
17
20
  import { createRenderContext, renderCollectedHead, runWithRenderContext, streamChunkScript } from '../ssr/context'
18
21
  import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
19
- import { ACTION_ERROR_COOKIE, executeAction, isServerAction } from './action'
22
+ import { ACTION_ERROR_COOKIE, executeAction, invokeActionCore, isServerAction } from './action'
20
23
  import { CompressionCache, compressedHtmlResponse, isCompressibleType, maybeCompressResponse, pickEncoding, pickPrecompressedEncoding, toWeakEtag } from './compress'
21
- import { applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, extractRenderedIslands, finalizeResponse, makeRequestContext, MIME } from './http'
24
+ import { applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, etagMatches, extractRenderedIslands, finalizeResponse, makeRequestContext, MIME, wantsJson } from './http'
22
25
  import { Router } from './router'
23
26
  import { buildSecurityHeaderEntries, KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, resolveCspPolicy, resolveHstsValue, verifyOrigin, withCspHashes } from './security'
24
27
 
25
- export { defineConfig, definePlugin, loadConfig } from '../plugins/index'
26
- export type { BuildPluginContext, CheckPluginContext, KayConfig, KayPlugin, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI } from '../plugins/index'
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'
27
30
  export { action, getActionError } from './action'
28
31
  export type { ActionContext, ActionErrorFlash, ActionOptions, ActionResult, ServerAction } from './action'
29
32
  export { CompressionCache, isCompressibleType, pickEncoding, pickPrecompressedEncoding, toWeakEtag } from './compress'
30
33
  export type { CompressionEncoding, PrecompressedEncoding } from './compress'
31
34
  export type { CookieOptions, Cookies } from './cookies'
32
- export { defineEnv } from './env'
35
+ export { defineEnv, nodeEnv } from './env'
33
36
  export { DEFAULT_MAX_REQUEST_BODY_SIZE } from './http'
34
37
  export type { EmbeddedServerConfig, KayApp, Middleware, RequestContext, ServerOptions } from './http'
35
- export { DEFAULT_CSP, DEFAULT_HSTS, getClientIp, isHttpsRequest, isTrustedOrigin, KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, verifyOrigin, withCspHashes } from './security'
36
- export type { SecurityHeadersOptions } from './security'
37
- export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1 } from './standard-schema'
38
+ export { createServer } from './loader'
39
+ 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
+ export type { SecurityHeadersOptions, TrustProxy } from './security'
41
+ export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
42
+ export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult, ValidationSuccess } from './standard-schema'
38
43
 
39
44
  interface LoadedPageModule {
40
45
  default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
41
46
  load?: (ctx: RequestContext) => unknown | Promise<unknown>
47
+ clientData?: readonly string[] | ((data: unknown) => unknown) | undefined
42
48
  csrf?: boolean | undefined
43
49
  GET?: (ctx: RequestContext) => Response | Promise<Response>
44
50
  POST?: (ctx: RequestContext) => Response | Promise<Response>
45
51
  PUT?: (ctx: RequestContext) => Response | Promise<Response>
46
52
  PATCH?: (ctx: RequestContext) => Response | Promise<Response>
47
53
  DELETE?: (ctx: RequestContext) => Response | Promise<Response>
54
+ HEAD?: (ctx: RequestContext) => Response | Promise<Response>
55
+ OPTIONS?: (ctx: RequestContext) => Response | Promise<Response>
48
56
  [key: string]: unknown
49
57
  }
50
58
 
@@ -60,150 +68,433 @@ interface LoadedErrorModule {
60
68
  default: (props: { error: unknown }) => Html | string | Promise<Html | string>
61
69
  }
62
70
 
71
+ const HTTP_METHOD_EXPORTS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'] as const
72
+
63
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
+ // Matches Bun.serve's 30 s idle timeout, which a streamed page turns off.
77
+ const DEFAULT_STREAM_TIMEOUT = 30_000
78
+
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
+ type FastHandler = (req: Request, remoteIp?: string, url?: URL) => Response | Promise<Response>
107
+
108
+ interface CompiledRoute {
109
+ entry: RouteManifestEntry
110
+ mod: LoadedPageModule
111
+ layouts: LoadedLayoutModule[]
112
+ middlewares: Middleware[]
113
+ /** Dynamic segments (`:param` / `*rest`), so the path names no single URL. */
114
+ dynamic: boolean
115
+ /** Options every document of this route shares; a request adds its body, head and islands. */
116
+ doc: DocumentOptions
117
+ }
118
+
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
+ const isRead = (request: Request): boolean => request.method === 'GET' || request.method === 'HEAD'
132
+ const isEventStream = (res: Response): boolean => (res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream')
133
+ const hasActionErrorCookie = (request: Request): boolean => (request.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
134
+ // A read the pre-rendered and fast static paths may answer: nothing to flash back to the page.
135
+ const isPlainRead = (request: Request): boolean => isRead(request) && !hasActionErrorCookie(request)
136
+
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
+ }
64
150
 
65
- type PrerenderEntry = { kind: 'file', path: string, hasIslands: boolean } | { kind: 'html', html: string, hasIslands: boolean }
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
+ }
66
281
 
67
282
  export async function createServerFromEmbedded(config: EmbeddedServerConfig): Promise<KayApp> {
68
283
  const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered, prerenderedFiles = {}, lang = 'en', security, plugins = [] } = config
69
284
  const assetPrefix = (config.assetPrefix ?? '/_kay').replace(/\/$/, '')
70
- const trustedOrigins = config.trustedOrigins ? new Set(config.trustedOrigins) : undefined
71
- const trustProxy = config.trustProxy === true
285
+ const trustedOriginsList = config.trustedOrigins ?? []
286
+ const trustedOrigins = trustedOriginsList.length > 0 ? new Set(trustedOriginsList) : undefined
287
+ const trustProxy = config.trustProxy ?? false
72
288
  const maxRequestBodySize = config.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
289
+ const streamTimeout = config.streamTimeout ?? DEFAULT_STREAM_TIMEOUT
290
+ const isDev = config.dev ?? (process.env.KAY_DEV === '1')
291
+ const serverRoot = config.root ?? process.cwd()
292
+ const serverOutDir = config.outDir ?? join(serverRoot, 'dist')
293
+ const serverPublicDir = config.publicDir ?? join(serverOutDir, 'public')
294
+ const parentAppCtx = getAppContext()
295
+
73
296
  const alwaysLoadRuntime = plugins.some(p => Boolean(p.clientEntry))
74
297
  const htmlTransformers = plugins
75
298
  .map(p => p.transformHtml)
76
299
  .filter((fn): fn is NonNullable<KayPlugin['transformHtml']> => typeof fn === 'function')
77
300
 
78
301
  const securityEntries = buildSecurityHeaderEntries(security)
79
- const securityRecord: Record<string, string> = {}
80
- for (let i = 0; i < securityEntries.length; i++) {
81
- const [k, v] = securityEntries[i]!
82
- securityRecord[k] = v
83
- }
84
- const nosniffEnabled = security !== false && (security?.contentTypeOptions ?? true)
302
+ const securityRecord: Record<string, string> = Object.fromEntries(securityEntries)
303
+ const nosniffHeader: Record<string, string> = security !== false && (security?.contentTypeOptions ?? true) ? { 'x-content-type-options': 'nosniff' } : {}
85
304
  const hstsValue = resolveHstsValue(security)
86
- const withHsts = (res: Response, request: Request): Response => applyHstsHeader(res, request, hstsValue, trustProxy)
305
+ const withHsts = (res: Response, request: Request): Response => applyHstsHeader(res, request, hstsValue, trustProxy, isDev)
306
+ // The one way out of every response not built with the security headers already in place.
307
+ const finish = (res: Response, request: Request, cookieStore?: CookieStore): Response => withHsts(finalizeResponse(res, cookieStore, securityEntries), request)
308
+ const serverError = (): Response => new Response('Internal Server Error', {
309
+ status: 500,
310
+ headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord },
311
+ })
87
312
 
88
- const htmlBaseHeaders: Record<string, string> = { 'content-type': 'text/html; charset=utf-8', ...securityRecord }
313
+ // HTML headers, one set per (dynamic, islands, suspense) combination: the CSP only gains the hashes a page needs.
89
314
  const baseCsp = resolveCspPolicy(security)
90
- const makeHtmlHeaders = (hasIslands: boolean, hasSuspense: boolean, isDynamic: boolean): Record<string, string> => {
91
- const base = isDynamic
92
- ? { ...htmlBaseHeaders, 'cache-control': 'private' }
93
- : htmlBaseHeaders
94
- if (baseCsp === undefined || (!hasIslands && !hasSuspense))
95
- return base
96
- const styleHashes: string[] = []
97
- const scriptHashes: string[] = []
98
- if (hasIslands)
99
- styleHashes.push(KAY_ISLAND_STYLE_HASH)
100
- if (hasSuspense) {
101
- styleHashes.push(KAY_SUSPENSE_STYLE_HASH)
102
- scriptHashes.push(KAY_STREAM_SCRIPT_HASH)
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
+ })
103
328
  }
104
- return { ...base, 'content-security-policy': withCspHashes(baseCsp, { styleHashes, scriptHashes }) }
329
+ htmlHeaderSets.push(headers)
105
330
  }
106
- const htmlHeadersPlain = makeHtmlHeaders(false, false, false)
107
- const htmlHeadersIslands = makeHtmlHeaders(true, false, false)
108
- const htmlHeadersSuspense = makeHtmlHeaders(false, true, false)
109
- const htmlHeadersBoth = makeHtmlHeaders(true, true, false)
110
- const selectHtmlHeaders = (hasIslands: boolean, hasSuspense: boolean): Record<string, string> =>
111
- hasIslands
112
- ? (hasSuspense ? htmlHeadersBoth : htmlHeadersIslands)
113
- : (hasSuspense ? htmlHeadersSuspense : htmlHeadersPlain)
114
-
115
- const dynHeadersPlain = makeHtmlHeaders(false, false, true)
116
- const dynHeadersIslands = makeHtmlHeaders(true, false, true)
117
- const dynHeadersSuspense = makeHtmlHeaders(false, true, true)
118
- const dynHeadersBoth = makeHtmlHeaders(true, true, true)
119
- const selectDynamicHtmlHeaders = (hasIslands: boolean, hasSuspense: boolean): Record<string, string> =>
120
- hasIslands
121
- ? (hasSuspense ? dynHeadersBoth : dynHeadersIslands)
122
- : (hasSuspense ? dynHeadersSuspense : dynHeadersPlain)
123
-
124
- const compressEnabled = config.compress ?? (process.env.KAY_DEV !== '1')
331
+ const htmlHeaders = (hasIslands: boolean, hasSuspense: boolean, isDynamic: boolean): Record<string, string> =>
332
+ htmlHeaderSets[(isDynamic ? 4 : 0) | (hasIslands ? 2 : 0) | (hasSuspense ? 1 : 0)]!
333
+
334
+ const compressEnabled = config.compress ?? !isDev
125
335
  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) })
126
342
 
127
- // Collect plugin server hooks (supports both sync and async plugin setup)
128
- interface PluginRouteDef {
129
- handler: (ctx: RequestContext) => Response | Promise<Response>
130
- csrf: boolean
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
+ })
131
358
  }
132
- const globalMiddlewares: Middleware[] = []
359
+
360
+ for (const [rel, body] of Object.entries(publicAssets))
361
+ registerPublicEntry(rel, body, publicEtags[rel])
362
+
363
+ const serverAppCtx = createAppContext({
364
+ root: serverRoot,
365
+ outDir: serverOutDir,
366
+ publicDir: serverPublicDir,
367
+ assetPrefix,
368
+ dev: isDev,
369
+ onRegisterPublicFile: (rel) => {
370
+ 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
+ }
377
+ },
378
+ })
379
+
380
+ // Plugin server hooks (plugin setup may be sync or async)
381
+ const scopedMiddlewares: ScopedMiddleware[] = []
382
+ const shutdownHooks: (() => void | Promise<void>)[] = []
133
383
  const pluginRewrites: ((pathname: string, ctx: RequestContext) => string | undefined)[] = []
134
384
  const pluginRouter = new Router<Map<string, PluginRouteDef>>()
135
385
  const pluginRouteEntries = new Map<string, Map<string, PluginRouteDef>>()
136
386
 
137
- const pluginApi: ServerPluginAPI = {
138
- use(mw) {
139
- globalMiddlewares.push(mw)
140
- },
141
- route(method, path, handler, options?: PluginRouteOptions) {
142
- let byMethod = pluginRouteEntries.get(path)
143
- if (byMethod === undefined) {
144
- byMethod = new Map()
145
- pluginRouteEntries.set(path, byMethod)
146
- pluginRouter.add(path, byMethod)
147
- }
148
- byMethod.set(method.toUpperCase(), { handler, csrf: options?.csrf ?? true })
149
- },
150
- rewrite(fn) {
151
- pluginRewrites.push(fn)
152
- },
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
+ })
153
413
  }
154
414
 
155
- for (const plugin of plugins) {
156
- if (plugin.server !== undefined)
157
- await plugin.server(pluginApi)
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
+ }
158
445
  }
159
446
 
160
- const hasGlobalMiddleware = globalMiddlewares.length > 0
161
- const hasPluginRewrites = pluginRewrites.length > 0
162
- const hasHtmlTransformers = htmlTransformers.length > 0
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 })
163
458
 
164
- // Hashed build asset table (immutable cache + precompressed .br/.gz sidecars + optional lazy compression)
165
- interface AssetEntry {
166
- body: EmbeddedBody
167
- br?: EmbeddedBody | undefined
168
- gz?: EmbeddedBody | undefined
169
- type: string
170
- compressible: boolean
171
- headers: Record<string, string>
172
- varyHeaders: Record<string, string>
173
- }
174
- const assetMap = new Map<string, AssetEntry>()
175
- for (const [rel, body] of Object.entries(assets)) {
176
- const brSidecar = assets[`${rel}.br`] ?? (typeof body === 'string' && existsSync(`${body}.br`) ? `${body}.br` : undefined)
177
- const gzSidecar = assets[`${rel}.gz`] ?? (typeof body === 'string' && existsSync(`${body}.gz`) ? `${body}.gz` : undefined)
178
- const type = MIME[extname(rel).toLowerCase()] ?? 'application/octet-stream'
179
- const compressible = isCompressibleType(type)
180
- const headers: Record<string, string> = {
181
- 'content-type': type,
182
- 'cache-control': 'public, max-age=31536000, immutable',
183
- ...(nosniffEnabled ? { 'x-content-type-options': 'nosniff' } : {}),
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))
184
489
  }
185
- const canVary = (compressible && compressCache !== undefined) || brSidecar !== undefined || gzSidecar !== undefined
186
- const varyHeaders: Record<string, string> = canVary
187
- ? { ...headers, vary: 'Accept-Encoding' }
188
- : headers
189
- assetMap.set(`${assetPrefix}/${rel}`, { body, br: brSidecar, gz: gzSidecar, type, compressible, headers, varyHeaders })
190
490
  }
191
491
 
192
- // Static public/ file table (ETag + 304 + zero-copy Bun.file + optional lazy compression)
193
- interface PublicEntry {
194
- body: EmbeddedBody
195
- type: string
196
- etag: string
197
- compressible: boolean
198
- }
199
- const publicMap = new Map<string, PublicEntry>()
200
- for (const [rel, body] of Object.entries(publicAssets)) {
201
- const etag = publicEtags[rel] ?? (typeof body === 'string' ? `W/"${Bun.hash(rel).toString(36)}"` : `W/"${Bun.hash(body).toString(36)}"`)
202
- const type = MIME[extname(rel).toLowerCase()] ?? 'application/octet-stream'
203
- publicMap.set(`/${rel}`, { body, type, etag, compressible: isCompressibleType(type) })
204
- }
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
205
497
 
206
- const toResponseBody = (body: EmbeddedBody) => typeof body === 'string' ? Bun.file(body) : body
207
498
  const errorHooks: ((info: ServerErrorInfo) => void)[] = []
208
499
  if (config.onError !== undefined)
209
500
  errorHooks.push(config.onError)
@@ -212,302 +503,322 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
212
503
  errorHooks.push(p.onError)
213
504
  }
214
505
  const notifyError = (error: unknown, request: Request, source: ServerErrorInfo['source']) => {
215
- for (let i = 0; i < errorHooks.length; i++) {
506
+ for (const hook of errorHooks) {
216
507
  try {
217
- errorHooks[i]!({ error, request, source })
508
+ hook({ error, request, source })
218
509
  }
219
510
  catch {}
220
511
  }
221
512
  }
222
513
 
223
- async function serveAsset(request: Request, pathname: string, asset: AssetEntry): Promise<Response> {
224
- if (request.method === 'HEAD')
225
- return withHsts(new Response(null, { status: 200, headers: asset.varyHeaders }), request)
226
-
227
- // Serve precompressed .br / .gz sidecars directly without on-the-fly recompression
228
- if (compressEnabled && (asset.br !== undefined || asset.gz !== undefined)) {
229
- const preEnc = pickPrecompressedEncoding(request.headers.get('accept-encoding'), {
230
- br: asset.br !== undefined,
231
- gz: asset.gz !== undefined,
232
- })
233
- if (preEnc !== undefined) {
234
- const sidecar = preEnc === 'br' ? asset.br! : asset.gz!
235
- const headers: Record<string, string> = { ...asset.headers, 'content-encoding': preEnc, 'vary': 'Accept-Encoding' }
236
- if (headers.etag !== undefined)
237
- headers.etag = toWeakEtag(headers.etag)
238
- return withHsts(new Response(toResponseBody(sidecar), { status: 200, headers }), request)
239
- }
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,
240
526
  }
241
-
242
- if (compressCache !== undefined && asset.compressible) {
243
- const enc = pickEncoding(request.headers.get('accept-encoding'))
244
- if (enc !== undefined) {
245
- const key = `${enc}:a:${pathname}`
246
- let compressed = compressCache.get(key)
247
- if (compressed === undefined) {
248
- const rawBytes = typeof asset.body === 'string'
249
- ? new Uint8Array(await Bun.file(asset.body).arrayBuffer())
250
- : asset.body
251
- compressed = compressCache.compress(rawBytes, enc, `a:${pathname}`)
252
- if (compressed === undefined)
253
- return withHsts(new Response(rawBytes, { status: 200, headers: asset.varyHeaders }), request)
254
- }
255
- return withHsts(new Response(compressed, {
256
- status: 200,
257
- headers: { ...asset.headers, 'content-encoding': enc, vary: 'Accept-Encoding' },
258
- }), request)
259
- }
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' } }
260
530
  }
261
-
262
- return withHsts(new Response(toResponseBody(asset.body), { status: 200, headers: asset.varyHeaders }), request)
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
+ })
263
539
  }
264
540
 
265
- async function servePublic(request: Request, pathname: string, pub: PublicEntry): Promise<Response> {
266
- const cacheControl = process.env.KAY_DEV === '1' ? 'no-cache' : 'public, max-age=3600'
267
- const hasVary = pub.compressible && compressCache !== undefined
268
- const nosniffHeader: Record<string, string> = nosniffEnabled ? { 'x-content-type-options': 'nosniff' } : {}
269
- if (request.headers.get('if-none-match') === pub.etag) {
270
- const h: Record<string, string> = hasVary
271
- ? { 'etag': pub.etag, 'cache-control': cacheControl, 'vary': 'Accept-Encoding', ...nosniffHeader }
272
- : { 'etag': pub.etag, 'cache-control': cacheControl, ...nosniffHeader }
273
- return withHsts(new Response(null, { status: 304, headers: h }), request)
274
- }
275
-
276
- const baseHeaders: Record<string, string> = hasVary
277
- ? { 'content-type': pub.type, 'etag': pub.etag, 'cache-control': cacheControl, 'vary': 'Accept-Encoding', ...nosniffHeader }
278
- : { 'content-type': pub.type, 'etag': pub.etag, 'cache-control': cacheControl, ...nosniffHeader }
279
-
541
+ async function serveFile(request: Request, file: ServedFile): Promise<Response> {
280
542
  if (request.method === 'HEAD')
281
- return withHsts(new Response(null, { status: 200, headers: baseHeaders }), request)
282
-
283
- if (hasVary) {
543
+ return withHsts(new Response(null, { status: 200, headers: file.headers }), request)
544
+ if (file.compressedHeaders !== undefined && compressCache !== undefined) {
284
545
  const enc = pickEncoding(request.headers.get('accept-encoding'))
285
546
  if (enc !== undefined) {
286
- const staticKey = `p:${pathname}:${pub.etag}`
287
- let compressed = compressCache.get(`${enc}:${staticKey}`)
288
- if (compressed === undefined) {
289
- const rawBytes = typeof pub.body === 'string'
290
- ? new Uint8Array(await Bun.file(pub.body).arrayBuffer())
291
- : pub.body
292
- compressed = compressCache.compress(rawBytes, enc, staticKey)
293
- if (compressed === undefined)
294
- return withHsts(new Response(rawBytes, { status: 200, headers: baseHeaders }), request)
295
- }
296
- return withHsts(new Response(compressed, {
297
- status: 200,
298
- headers: { ...baseHeaders, 'etag': toWeakEtag(pub.etag), 'content-encoding': enc },
299
- }), request)
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)
300
550
  }
301
551
  }
302
-
303
- return withHsts(new Response(toResponseBody(pub.body), { status: 200, headers: baseHeaders }), request)
552
+ return withHsts(new Response(file.body, { status: 200, headers: file.headers }), request)
304
553
  }
305
554
 
306
- async function servePrerendered(request: Request, pathname: string, pre: PrerenderEntry): Promise<Response> {
307
- const base = selectHtmlHeaders(pre.hasIslands, false)
308
- const headers = compressCache !== undefined
309
- ? { ...base, vary: 'Accept-Encoding' }
310
- : base
311
-
312
- if (request.method === 'HEAD')
313
- return withHsts(new Response(null, { status: 200, headers }), request)
314
-
315
- if (compressCache !== undefined) {
316
- const enc = pickEncoding(request.headers.get('accept-encoding'))
317
- if (enc !== undefined) {
318
- const staticKey = `pre:${pathname}`
319
- let compressed = compressCache.get(`${enc}:${staticKey}`)
320
- if (compressed === undefined) {
321
- const rawBytes = pre.kind === 'file'
322
- ? new Uint8Array(await Bun.file(pre.path).arrayBuffer())
323
- : textEncoder.encode(pre.html)
324
- compressed = compressCache.compress(rawBytes, enc, staticKey)
325
- if (compressed === undefined)
326
- return withHsts(new Response(rawBytes, { status: 200, headers }), request)
327
- }
328
- return withHsts(new Response(compressed, {
329
- status: 200,
330
- headers: { ...headers, 'content-encoding': enc },
331
- }), request)
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)
332
561
  }
333
562
  }
563
+ return serveFile(request, asset.file)
564
+ }
334
565
 
335
- const body = pre.kind === 'file' ? Bun.file(pre.path) : pre.html
336
- return withHsts(new Response(body, { status: 200, headers }), request)
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)
337
570
  }
338
571
 
339
- // Register server actions and assign their live URLs
340
- const actionHandlers = new Map<string, { act: ServerAction<unknown, unknown>, middlewares: Middleware[] }>()
572
+ // Server actions and their live URLs
341
573
  for (const entry of manifest.actions) {
342
574
  const mod = modules[entry.file] as Record<string, unknown> | undefined
343
575
  const act = mod?.[entry.exportName]
344
576
  if (isServerAction(act)) {
345
577
  ;(act as { url: string }).url = entry.url
346
- const middlewares = entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default)
347
- actionHandlers.set(entry.url, { act, middlewares: [...globalMiddlewares, ...middlewares] })
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] })
348
581
  }
349
582
  }
350
583
 
351
584
  const errorMod = manifest.errorFile ? modules[manifest.errorFile] as LoadedErrorModule : undefined
352
585
  const notFoundMod = manifest.notFoundFile ? modules[manifest.notFoundFile] as LoadedPageModule : undefined
353
586
 
354
- // Static prerendered pages table (zero-copy file paths preferred; raw HTML strings supported)
355
- const prerenderedMap = new Map<string, PrerenderEntry>()
356
- const fastPrerenderedMap = new Map<string, PrerenderEntry>()
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>()
357
590
  for (const route of manifest.routes) {
358
- if (route.prerendered) {
359
- const routeHasIslands = route.islandChunks.length > 0
360
- for (const [urlPath, relHtml] of Object.entries(route.prerendered)) {
361
- const filePath = prerenderedFiles[relHtml]
362
- const html = prerendered[relHtml]
363
- const entry: PrerenderEntry | undefined = filePath !== undefined
364
- ? { kind: 'file', path: filePath, hasIslands: routeHasIslands }
365
- : html !== undefined
366
- ? { kind: 'html', html, hasIslands: routeHasIslands }
367
- : undefined
368
- if (entry !== undefined) {
369
- prerenderedMap.set(urlPath, entry)
370
- if (route.middlewares.length === 0 && !hasGlobalMiddleware && pluginRouter.match(urlPath) === undefined)
371
- fastPrerenderedMap.set(urlPath, entry)
372
- }
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
+ }
611
+
612
+ const router = new Router<CompiledRoute>()
613
+ const fastStaticPages = new Map<string, FastHandler>()
614
+
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')
373
638
  }
374
639
  }
640
+ return out
375
641
  }
376
642
 
377
- interface CompiledRoute {
378
- entry: RouteManifestEntry
379
- mod: LoadedPageModule
380
- layouts: LoadedLayoutModule[]
381
- middlewares: Middleware[]
382
- fastHandler: ((req: Request, remoteIp?: string) => Response | Promise<Response>) | undefined
383
- docPrefix: string
384
- docSuffix: string
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: [] }
385
656
  }
386
657
 
387
- const router = new Router<CompiledRoute>()
388
- const fastStaticPages = new Map<string, (req: Request, remoteIp?: string) => Response | Promise<Response>>()
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
+ }
701
+
702
+ async function renderNotFound(cookieStore: CookieStore, url: URL, request: Request, ctx: RequestContext): Promise<Response> {
703
+ const res = await runChain(ctx, middlewaresFor(url.pathname), () => buildNotFoundResponse(url, request, ctx))
704
+ return finish(res, request, cookieStore)
705
+ }
706
+
707
+ function refuseCrossSite(request: Request, reason: string, cookieStore?: CookieStore): Response {
708
+ return finish(Response.json({ ok: false, status: 403, error: reason }, { status: 403 }), request, cookieStore)
709
+ }
389
710
 
390
711
  for (const entry of manifest.routes) {
391
712
  const mod = modules[entry.file] as LoadedPageModule
392
713
  const layouts = entry.layouts.map(l => modules[l] as LoadedLayoutModule)
393
- const middlewares = entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default)
394
-
714
+ const dirMiddlewares = entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default)
715
+ const routePluginMiddlewares = middlewaresFor(entry.path)
716
+ const fastPluginMiddlewares = middlewaresFor(entry.path, true)
717
+ const dynamic = entry.path.includes(':') || entry.path.includes('*')
395
718
  const hasIslands = entry.islandChunks.length > 0
396
- const routeStyles = entry.styles ?? manifest.styles
397
- const routeHeadTags = entry.headTags !== undefined && entry.headTags.length > 0
398
- ? [...(manifest.headTags ?? []), ...entry.headTags]
399
- : manifest.headTags
400
- const shell = renderDocument({
401
- body: '\0',
402
- headTags: routeHeadTags,
719
+ const doc: DocumentOptions = {
720
+ body: '',
721
+ headTags: mergedHeadTags(manifest, entry),
403
722
  lang,
404
723
  runtimeScript: manifest.runtimeScript,
405
724
  alwaysLoadRuntime,
406
- preloadChunks: entry.eagerIslandChunks ?? entry.islandChunks,
407
- styles: routeStyles,
408
- hasIslands,
409
- })
410
- const splitAt = shell.indexOf('\0')
411
- const docPrefix = shell.slice(0, splitAt)
412
- const docSuffix = shell.slice(splitAt + 1)
725
+ styles: entry.styles ?? manifest.styles,
726
+ }
413
727
 
414
- // Ultra-fast zero-overhead path when route is static, has no middleware, no <Head>/<Suspense>, and no intercepting plugin hooks
415
- const canFastPath = !hasGlobalMiddleware
728
+ // Zero-overhead path for a static route with no middleware, no <Head>/<Suspense>, and no intercepting plugin hook
729
+ const canFastPath = fastPluginMiddlewares.length === 0
416
730
  && !hasPluginRewrites
417
731
  && !hasHtmlTransformers
418
732
  && pluginRouter.match(entry.path) === undefined
419
- && !entry.path.includes(':')
420
- && !entry.path.includes('*')
421
- && middlewares.length === 0
733
+ && !dynamic
734
+ && dirMiddlewares.length === 0
422
735
  && !entry.usesRenderContext
423
736
  && typeof mod.default === 'function'
424
737
  && mod.GET === undefined
425
738
 
426
- let fastHandler: ((req: Request, remoteIp?: string) => Response | Promise<Response>) | undefined
427
739
  if (canFastPath) {
740
+ const shell = renderDocument({ ...doc, body: '\0', preloadChunks: entry.eagerIslandChunks ?? entry.islandChunks, hasIslands })
741
+ const splitAt = shell.indexOf('\0')
742
+ const docPrefix = shell.slice(0, splitAt)
743
+ const docSuffix = shell.slice(splitAt + 1)
428
744
  const singleLayout = layouts.length === 1 ? layouts[0]! : undefined
429
- const fastHeaders = selectDynamicHtmlHeaders(hasIslands, false)
745
+ const fastHeaders = htmlHeaders(hasIslands, false, true)
430
746
 
431
- fastHandler = (request: Request, remoteIp?: string): Response | Promise<Response> => {
432
- const handleErr = (error: unknown): Promise<Response> => {
433
- notifyError(error, request, 'route')
434
- return renderError(error, makeRequestContext(request, {}, { trustProxy, remoteIp }).cookieStore, new URL(request.url), request)
747
+ const fail = (error: unknown, request: Request, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
748
+ notifyError(error, request, 'route')
749
+ return renderError(error, cookieStore, ctx?.url ?? new URL(request.url), request, ctx)
750
+ }
751
+ const respondHtml = (body: string, request: Request, cookieStore?: CookieStore): Response => {
752
+ const res = compressedHtmlResponse(docPrefix + body + docSuffix, 200, fastHeaders, request, compressCache, !entry.hasLoad)
753
+ return cookieStore?.hasChanges ? finish(res, request, cookieStore) : withHsts(res, request)
754
+ }
755
+ const layoutProps = (inner: string, url: URL, locals: Record<string, unknown>) => ({ children: raw(inner), url, params: {}, locals })
756
+
757
+ const wrapLayouts = (inner: string, request: Request, url: URL, locals: Record<string, unknown>, cookieStore?: CookieStore, ctx?: RequestContext): Response | Promise<Response> => {
758
+ if (layouts.length === 0)
759
+ return respondHtml(inner, request, cookieStore)
760
+ if (singleLayout !== undefined) {
761
+ const wrapped = singleLayout.default(layoutProps(inner, url, locals))
762
+ if (wrapped instanceof Promise)
763
+ return wrapped.then(x => respondHtml(ssrChild(x as Html), request, cookieStore), error => fail(error, request, cookieStore, ctx))
764
+ return respondHtml(ssrChild(wrapped as Html), request, cookieStore)
435
765
  }
436
- try {
437
- const reqUrl = new URL(request.url)
438
- const respondHtml = (body: string): Response =>
439
- withHsts(compressedHtmlResponse(docPrefix + body + docSuffix, 200, fastHeaders, request, compressCache), request)
440
-
441
- const wrapLayouts = (inner: string): Response | Promise<Response> => {
442
- if (layouts.length === 0)
443
- return respondHtml(inner)
444
- if (singleLayout !== undefined) {
445
- const w = singleLayout.default({ children: raw(inner), url: reqUrl, params: {}, locals: {} })
446
- if (w instanceof Promise)
447
- return w.then(x => respondHtml(ssrChild(x as Html)), handleErr)
448
- return respondHtml(ssrChild(w as Html))
449
- }
450
- return (async () => {
451
- let cur = inner
452
- for (let i = layouts.length - 1; i >= 0; i--)
453
- cur = ssrChild(await layouts[i]!.default({ children: raw(cur), url: reqUrl, params: {}, locals: {} }) as Html)
454
- return respondHtml(cur)
455
- })().catch(handleErr)
766
+ return (async () => {
767
+ try {
768
+ let cur = inner
769
+ for (let i = layouts.length - 1; i >= 0; i--)
770
+ cur = ssrChild(await layouts[i]!.default(layoutProps(cur, url, locals)) as Html)
771
+ return respondHtml(cur, request, cookieStore)
456
772
  }
457
-
458
- const renderPage = (data: unknown): Response | Promise<Response> => {
459
- const pageProps: Record<string, unknown> = {
460
- params: {},
461
- locals: {},
462
- url: reqUrl,
463
- ...(data !== undefined ? { data } : {}),
464
- }
465
- if (entry.isIsland && entry.islandChunk !== undefined) {
466
- const inner = ssrIsland(
467
- entry.path,
468
- entry.islandChunk,
469
- () => ssrChild(mod.default!(pageProps) as Html),
470
- data !== undefined ? { data } : {},
471
- entry.islandHydrate as HydrateStrategy | undefined,
472
- )
473
- return wrapLayouts(inner)
474
- }
475
- const rendered = mod.default!(pageProps)
476
- if (rendered instanceof Promise)
477
- return rendered.then(r => wrapLayouts(ssrChild(r as Html)), handleErr)
478
- return wrapLayouts(ssrChild(rendered as Html))
773
+ catch (error) {
774
+ return fail(error, request, cookieStore, ctx)
479
775
  }
776
+ })()
777
+ }
480
778
 
481
- if (entry.hasLoad && typeof mod.load === 'function') {
482
- const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp })
483
- const finish = (res: Response | Promise<Response>): Response | Promise<Response> => {
484
- if (!cookieStore.hasChanges)
485
- return res instanceof Promise ? res.then(r => withHsts(r, request), handleErr) : withHsts(res, request)
486
- if (res instanceof Promise)
487
- return res.then(r => withHsts(finalizeResponse(r, cookieStore, securityEntries), request), handleErr)
488
- return withHsts(finalizeResponse(res, cookieStore, securityEntries), request)
779
+ const renderPage = (data: unknown, request: Request, url: URL, locals: Record<string, unknown>, cookieStore?: CookieStore, ctx?: RequestContext): Response | Promise<Response> => {
780
+ const pageProps: Record<string, unknown> = { params: {}, locals, url, ...(data !== undefined ? { data } : {}) }
781
+ if (entry.isIsland && entry.islandChunk !== undefined) {
782
+ return wrapLayouts(ssrIsland(
783
+ entry.islandChunk,
784
+ () => ssrChild(mod.default!(pageProps) as Html),
785
+ pickPageIslandProps(data, entry, mod),
786
+ entry.islandHydrate as HydrateStrategy | undefined,
787
+ true,
788
+ ), request, url, locals, cookieStore, ctx)
789
+ }
790
+ const rendered = mod.default!(pageProps)
791
+ 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))
793
+ return wrapLayouts(ssrChild(rendered as Html), request, url, locals, cookieStore, ctx)
794
+ }
795
+
796
+ fastStaticPages.set(entry.path, (request, remoteIp, url = new URL(request.url)) => {
797
+ try {
798
+ if (!entry.hasLoad || typeof mod.load !== 'function')
799
+ return renderPage(undefined, request, url, {})
800
+
801
+ const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url })
802
+ const afterLoad = async (pending: unknown): Promise<Response> => {
803
+ try {
804
+ const loaded = await pending
805
+ if (loaded instanceof Response)
806
+ return finish(loaded, request, cookieStore)
807
+ return await renderPage(loaded, request, url, ctx.locals, cookieStore, ctx)
489
808
  }
490
- const loaded = mod.load(ctx)
491
- if (loaded instanceof Promise) {
492
- return loaded.then(
493
- data => finish(data instanceof Response ? data : renderPage(data)),
494
- handleErr,
495
- )
809
+ catch (error) {
810
+ return fail(error, request, cookieStore, ctx)
496
811
  }
497
- if (loaded instanceof Response)
498
- return finish(loaded)
499
- return finish(renderPage(loaded))
500
812
  }
501
- return renderPage(undefined)
813
+ return afterLoad(mod.load(ctx))
502
814
  }
503
815
  catch (error) {
504
- return handleErr(error)
816
+ return fail(error, request)
505
817
  }
506
- }
507
- fastStaticPages.set(entry.path, fastHandler)
818
+ })
508
819
  }
509
820
 
510
- router.add(entry.path, { entry, mod, layouts, middlewares, fastHandler, docPrefix, docSuffix })
821
+ router.add(entry.path, { entry, mod, layouts, middlewares: [...routePluginMiddlewares, ...dirMiddlewares], dynamic, doc })
511
822
  }
512
823
 
513
824
  async function renderCompiledRoute(
@@ -515,31 +826,47 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
515
826
  ctx: RequestContext,
516
827
  disableTimeout?: () => void,
517
828
  ): Promise<Response> {
518
- const { entry, mod, layouts } = route
829
+ const { entry, mod, layouts, doc } = route
519
830
 
520
831
  // Serve prerendered HTML after middlewares have passed (when route had middlewares)
521
- if (ctx.request.method === 'GET' || ctx.request.method === 'HEAD') {
832
+ if (isRead(ctx.request)) {
522
833
  const rawPath = ctx.url.pathname
523
834
  const normPath = rawPath.length > 1 && rawPath.endsWith('/') ? rawPath.slice(0, -1) : rawPath
524
835
  const pre = prerenderedMap.get(rawPath) ?? prerenderedMap.get(normPath)
525
836
  if (pre !== undefined)
526
- return servePrerendered(ctx.request, rawPath, pre)
837
+ return serveFile(ctx.request, pre)
527
838
  // Prerendered dynamic route: unlisted param returns 404 (never falls back to SSR)
528
- if (entry.prerender === true && entry.prerendered !== undefined && (entry.path.includes(':') || entry.path.includes('*')))
529
- return buildNotFoundResponse(ctx.url)
839
+ if (entry.prerender === true && entry.prerendered !== undefined && route.dynamic)
840
+ return buildNotFoundResponse(ctx.url, ctx.request, ctx)
530
841
  }
531
842
 
532
- // API route (.ts exporting GET/POST/etc.)
533
- const methodHandler = mod[ctx.request.method]
534
- if (typeof methodHandler === 'function') {
535
- const res = await (methodHandler as (c: RequestContext) => Response | Promise<Response>)(ctx)
536
- if ((res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream'))
537
- disableTimeout?.()
538
- return maybeCompressResponse(res, ctx.request, compressCache)
843
+ // API route (.ts exporting GET/POST/etc.) — HEAD falls back to GET without a body
844
+ const method = ctx.request.method.toUpperCase()
845
+ const methodHandler = mod[method]
846
+ if (typeof methodHandler === 'function')
847
+ return await (methodHandler as (c: RequestContext) => Response | Promise<Response>)(ctx)
848
+ if (method === 'HEAD' && typeof mod.GET === 'function')
849
+ return stripHeadBody(await mod.GET(ctx))
850
+
851
+ // Page routes only handle GET/HEAD; unsafe methods (POST/PUT/PATCH/DELETE) without a method export get 405.
852
+ if (typeof mod.default !== 'function' || !isRead(ctx.request)) {
853
+ const allow = allowedMethodsHeader(mod)
854
+ return new Response('Method Not Allowed', allow ? { status: 405, headers: { allow } } : { status: 405 })
539
855
  }
540
856
 
541
- if (typeof mod.default !== 'function')
542
- return new Response('Method Not Allowed', { status: 405 })
857
+ // Hydrate & clear one-shot progressive form validation flash cookie only on page GETs (never API/plugin GETs)
858
+ if (ctx.request.method === 'GET' && hasActionErrorCookie(ctx.request)) {
859
+ const rawFlash = ctx.cookies.get(ACTION_ERROR_COOKIE)
860
+ if (rawFlash !== undefined) {
861
+ try {
862
+ const parsed: unknown = JSON.parse(rawFlash)
863
+ if (isPlainObject(parsed))
864
+ ctx.locals.actionError = parsed as unknown as ActionErrorFlash
865
+ }
866
+ catch {}
867
+ ctx.cookies.delete(ACTION_ERROR_COOKIE)
868
+ }
869
+ }
543
870
 
544
871
  const data = entry.hasLoad && typeof mod.load === 'function' ? await mod.load(ctx) : undefined
545
872
  if (data instanceof Response)
@@ -556,11 +883,11 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
556
883
  let inner: string
557
884
  if (entry.isIsland && entry.islandChunk !== undefined) {
558
885
  inner = ssrIsland(
559
- entry.path,
560
886
  entry.islandChunk,
561
887
  () => ssrChild(mod.default!(pageProps) as Html),
562
- data !== undefined ? { data } : {},
888
+ pickPageIslandProps(data, entry, mod),
563
889
  entry.islandHydrate as HydrateStrategy | undefined,
890
+ true,
564
891
  )
565
892
  }
566
893
  else {
@@ -573,383 +900,278 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
573
900
 
574
901
  const body = await runWithRenderContext(rctx, renderBody)
575
902
  const collectedHead = renderCollectedHead(rctx)
576
- const renderedIslands = extractRenderedIslands(body)
577
- const hasIslands = renderedIslands.hasIslands || rctx.pending.length > 0 && entry.islandChunks.length > 0
578
- const preloadChunks = rctx.pending.length > 0 ? entry.islandChunks : renderedIslands.eagerChunks
903
+ const renderedIslands = resolveRenderedIslands(rctx, body)
904
+ const isStreamed = rctx.pending.length > 0
905
+ const hasIslands = renderedIslands.hasIslands || (isStreamed && entry.islandChunks.length > 0)
906
+ const preloadChunks = isStreamed ? entry.islandChunks : renderedIslands.eagerChunks
907
+
908
+ // Streaming SSR when <Suspense> boundaries are pending (never buffered for compression)
909
+ if (isStreamed) {
910
+ if (ctx.request.method === 'HEAD')
911
+ return new Response(null, { status: 200, headers: htmlHeaders(hasIslands, true, true) })
912
+ disableTimeout?.()
913
+ let shell = renderDocument({ ...doc, body: body + STREAM_TAIL_MARK, head: collectedHead, htmlAttrs: rctx.htmlAttrs, preloadChunks, hasIslands, hasSuspense: true })
914
+ // Transforms see the document with its initial body; boundaries resolved later stream as they render.
915
+ for (const transform of htmlTransformers)
916
+ 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)
579
925
 
580
- const routeStyles = entry.styles ?? manifest.styles
581
- const routeHeadTags = entry.headTags !== undefined && entry.headTags.length > 0
582
- ? [...(manifest.headTags ?? []), ...entry.headTags]
583
- : manifest.headTags
926
+ const abortCtrl = new AbortController()
927
+ let closed = false
928
+ const deadline = Date.now() + streamTimeout
584
929
 
585
- // Streaming SSR path when <Suspense> boundaries are pending (never buffered for compression)!
586
- if (rctx.pending.length > 0) {
587
- disableTimeout?.()
588
- const shell = renderDocument({
589
- body: '\0',
590
- head: collectedHead,
591
- headTags: routeHeadTags,
592
- lang,
593
- runtimeScript: manifest.runtimeScript,
594
- alwaysLoadRuntime,
595
- preloadChunks,
596
- styles: routeStyles,
597
- hasIslands,
598
- hasSuspense: true,
599
- })
600
- const splitAt = shell.indexOf('\0')
601
- const headHtml = shell.slice(0, splitAt)
602
- const tailHtml = shell.slice(splitAt + 1)
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
+ }
603
941
 
604
942
  const stream = new ReadableStream<Uint8Array>({
605
943
  async start(controller) {
606
- controller.enqueue(textEncoder.encode(headHtml + body))
607
- await Promise.all(
608
- rctx.pending.map(async (chunk) => {
609
- const resolved = await chunk.promise
610
- controller.enqueue(textEncoder.encode(streamChunkScript(chunk.id, resolved)))
611
- }),
612
- )
613
- controller.enqueue(textEncoder.encode(tailHtml))
614
- controller.close()
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()
615
975
  },
616
976
  })
617
977
 
618
- return new Response(stream, { status: 200, headers: { ...selectDynamicHtmlHeaders(hasIslands, true) } })
978
+ return new Response(stream, { status: 200, headers: htmlHeaders(hasIslands, true, true) })
619
979
  }
620
980
 
621
- let html = renderDocument({
622
- body,
623
- head: collectedHead,
624
- headTags: routeHeadTags,
625
- lang,
626
- runtimeScript: manifest.runtimeScript,
627
- alwaysLoadRuntime,
628
- preloadChunks,
629
- styles: routeStyles,
630
- hasIslands,
631
- })
632
-
633
- for (let i = 0; i < htmlTransformers.length; i++)
634
- html = await htmlTransformers[i]!(html, ctx)
635
-
636
- return compressedHtmlResponse(html, 200, selectDynamicHtmlHeaders(hasIslands, false), ctx.request, compressCache)
637
- }
638
-
639
- const rootLayoutFile = manifest.routes.find(r => r.layouts.length > 0)?.layouts[0]
640
- const rootLayoutMod = rootLayoutFile !== undefined ? modules[rootLayoutFile] as LoadedLayoutModule | undefined : undefined
641
- const fallbackStyles = manifest.globalStyles ?? manifest.styles
642
-
643
- async function buildErrorResponse(error: unknown, url?: URL): Promise<Response> {
644
- if (errorMod !== undefined) {
645
- try {
646
- const rctx = createRenderContext()
647
- const body = await runWithRenderContext(rctx, async () => {
648
- let inner = ssrChild(await errorMod.default({ error }) as Html)
649
- if (rootLayoutMod !== undefined)
650
- inner = ssrChild(await rootLayoutMod.default({ children: raw(inner), url: url ?? new URL('http://localhost/500'), params: {}, locals: {} }) as Html)
651
- return inner
652
- })
653
- const html = renderDocument({ body, head: renderCollectedHead(rctx), headTags: manifest.headTags, styles: fallbackStyles, runtimeScript: manifest.runtimeScript, alwaysLoadRuntime, lang })
654
- return new Response(html, { status: 500, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'private' } })
655
- }
656
- catch {}
657
- }
658
- return new Response('Internal Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
659
- }
660
-
661
- async function renderError(error: unknown, cookieStore: CookieStore, url?: URL, request?: Request): Promise<Response> {
662
- const base = finalizeResponse(await buildErrorResponse(error, url), cookieStore, securityEntries)
663
- return request !== undefined ? withHsts(base, request) : base
664
- }
665
-
666
- async function buildNotFoundResponse(url?: URL): Promise<Response> {
667
- const notFoundFn = notFoundMod?.default
668
- if (notFoundFn !== undefined) {
669
- try {
670
- const rctx = createRenderContext()
671
- const body = await runWithRenderContext(rctx, async () => {
672
- let inner = ssrChild(await notFoundFn({}) as Html)
673
- if (rootLayoutMod !== undefined)
674
- inner = ssrChild(await rootLayoutMod.default({ children: raw(inner), url: url ?? new URL('http://localhost/404'), params: {}, locals: {} }) as Html)
675
- return inner
676
- })
677
- const html = renderDocument({ body, head: renderCollectedHead(rctx), headTags: manifest.headTags, styles: fallbackStyles, runtimeScript: manifest.runtimeScript, alwaysLoadRuntime, lang })
678
- return new Response(html, { status: 404, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'private' } })
679
- }
680
- catch {}
681
- }
682
- return new Response('Not Found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' } })
683
- }
981
+ let html = renderDocument({ ...doc, body, head: collectedHead, htmlAttrs: rctx.htmlAttrs, preloadChunks, hasIslands })
982
+ for (const transform of htmlTransformers)
983
+ html = await transform(html, ctx)
684
984
 
685
- async function renderNotFound(cookieStore: CookieStore, url?: URL, request?: Request): Promise<Response> {
686
- const base = finalizeResponse(await buildNotFoundResponse(url), cookieStore, securityEntries)
687
- return request !== undefined ? withHsts(base, request) : base
985
+ return compressedHtmlResponse(html, 200, htmlHeaders(hasIslands, false, true), ctx.request, compressCache)
688
986
  }
689
987
 
690
- function requestWantsJson(request: Request): boolean {
691
- return (request.headers.get('accept') ?? '').includes('application/json')
692
- || (request.headers.get('content-type') ?? '').includes('application/json')
693
- }
694
-
695
- async function handleInternal(request: Request, remoteIp?: string, disableTimeout?: () => void): Promise<Response> {
988
+ // `bodyLimited` is set under `serve()`, where Bun.serve already enforces maxRequestBodySize on every body, chunked ones included.
989
+ async function handleInternal(request: Request, remoteIp?: string, disableTimeout?: () => void, bodyLimited = false): Promise<Response> {
696
990
  try {
697
- const pathname = new URL(request.url).pathname
991
+ const url = new URL(request.url)
992
+ const pathname = url.pathname
993
+ const read = isRead(request)
698
994
 
699
- // 1. Static client assets
700
- if (request.method === 'GET' || request.method === 'HEAD') {
995
+ // 1. Static client assets, then public/ files (explicit plugin routes take precedence over public/ files)
996
+ if (read) {
701
997
  const asset = assetMap.get(pathname)
702
998
  if (asset !== undefined)
703
- return serveAsset(request, pathname, asset)
999
+ return serveAsset(request, asset)
1000
+ const pub = publicMap.get(pathname)
1001
+ if (pub !== undefined) {
1002
+ const matchedPlugin = pluginRouter.match(pathname)
1003
+ const reqMethod = request.method.toUpperCase()
1004
+ const shadowedByPlugin = matchedPlugin !== undefined
1005
+ && (matchedPlugin.data.has(reqMethod) || (reqMethod === 'HEAD' && matchedPlugin.data.has('GET')) || matchedPlugin.data.has('ALL'))
1006
+ if (!shadowedByPlugin)
1007
+ return servePublic(request, pub)
1008
+ }
704
1009
  }
705
1010
 
706
- // 1b. Static public/ files (no-cache in dev so edits/plugins never get stuck in browser cache)
707
- if (request.method === 'GET' || request.method === 'HEAD') {
708
- const pub = publicMap.get(pathname)
709
- if (pub !== undefined)
710
- return servePublic(request, pathname, pub)
1011
+ // Actions only accept POST; other methods get 405 before any middleware runs.
1012
+ const registeredAction = actionHandlers.get(pathname)
1013
+ if (registeredAction !== undefined && request.method !== 'POST')
1014
+ return finish(new Response('Method Not Allowed', { status: 405, headers: { allow: 'POST' } }), request)
1015
+
1016
+ // Actions are origin-checked before their body is read and before any middleware runs.
1017
+ const actionHandler = request.method === 'POST' ? registeredAction : undefined
1018
+ if (actionHandler !== undefined) {
1019
+ const originCheck = verifyOrigin(request, trustedOrigins, trustProxy)
1020
+ if (!originCheck.ok)
1021
+ return refuseCrossSite(request, originCheck.reason)
711
1022
  }
712
1023
 
713
1024
  // Enforce request body size cap before actions, plugin routes, and API routes
714
- const bounded = await enforceRequestBodyLimit(request, maxRequestBodySize)
1025
+ const bounded = bodyLimited ? { ok: true as const, request } : await enforceRequestBodyLimit(request, maxRequestBodySize)
715
1026
  if (!bounded.ok) {
716
- const res413 = requestWantsJson(request)
1027
+ const res413 = wantsJson(request)
717
1028
  ? Response.json({ ok: false, status: 413, error: 'Payload Too Large' }, { status: 413 })
718
1029
  : new Response('Payload Too Large', { status: 413, headers: { 'content-type': 'text/plain; charset=utf-8' } })
719
- return withHsts(finalizeResponse(res413, makeRequestContext(request, {}, { trustProxy, remoteIp }).cookieStore, securityEntries), request)
1030
+ return finish(res413, request)
720
1031
  }
721
1032
  const req = bounded.request
722
1033
 
723
- // 2. Server actions (POST /_kay/action/<id>): global plugin middlewares, then the _middleware.ts chain of the action's folder
724
- if (req.method === 'POST') {
725
- const handler = actionHandlers.get(pathname)
726
- if (handler !== undefined) {
727
- const { act, middlewares } = handler
728
- const { ctx, cookieStore } = makeRequestContext(req, {}, { trustProxy, remoteIp })
729
- const runAction = async (): Promise<Response> => {
730
- const actionCtx: ActionContext = {
731
- request: ctx.request,
732
- url: ctx.url,
733
- params: ctx.params,
734
- cookies: ctx.cookies,
735
- locals: ctx.locals,
736
- ip: ctx.ip,
737
- redirect: ctx.redirect,
738
- deny: ctx.deny,
739
- }
740
- return executeAction(act, req, actionCtx, trustedOrigins, trustProxy, maxRequestBodySize)
741
- }
742
- let index = -1
743
- const dispatch = async (i: number): Promise<Response> => {
744
- if (i <= index)
745
- throw new Error('kay: middleware called next() multiple times')
746
- index = i
747
- if (i < middlewares.length)
748
- return middlewares[i]!(ctx, () => dispatch(i + 1))
749
- return runAction()
750
- }
751
- try {
752
- const res = await dispatch(0)
753
- return withHsts(finalizeResponse(res, cookieStore, securityEntries), req)
754
- }
755
- catch (error) {
756
- notifyError(error, req, 'action')
757
- if (requestWantsJson(req)) {
758
- return withHsts(
759
- finalizeResponse(
760
- Response.json({ ok: false, status: 500, error: 'Internal Server Error' }, { status: 500 }),
761
- cookieStore,
762
- securityEntries,
763
- ),
764
- req,
765
- )
766
- }
767
- return renderError(error, cookieStore, ctx.url, req)
768
- }
1034
+ // 2. Server actions (POST /_kay/action/<id>): plugin middlewares, then the _middleware.ts chain of the action's folder
1035
+ if (actionHandler !== undefined) {
1036
+ const { act, middlewares } = actionHandler
1037
+ const { ctx, cookieStore } = makeRequestContext(req, {}, { trustProxy, remoteIp, url })
1038
+ try {
1039
+ return finish(await runChain(ctx, middlewares, () => executeAction(act, req, ctx, trustedOrigins, trustProxy)), req, cookieStore)
1040
+ }
1041
+ catch (error) {
1042
+ notifyError(error, req, 'action')
1043
+ return renderError(error, cookieStore, ctx.url, req, ctx)
769
1044
  }
770
1045
  }
771
1046
 
772
- const hasActionErrorFlash = (req.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
773
-
774
- // 3. Prerendered static HTML (safe even when plugins add routes or build-time transformHtml!)
775
- if (!hasActionErrorFlash && (req.method === 'GET' || req.method === 'HEAD')) {
1047
+ // 3. Prerendered static HTML, then 4. the zero-overhead static route path
1048
+ const plainRead = isPlainRead(req)
1049
+ if (plainRead) {
776
1050
  const pre = fastPrerenderedMap.get(pathname)
777
1051
  if (pre !== undefined)
778
- return servePrerendered(req, pathname, pre)
779
- }
780
-
781
- // 4. Ultra-fast static route path
782
- if (!hasActionErrorFlash && (req.method === 'GET' || req.method === 'HEAD')) {
1052
+ return serveFile(req, pre)
783
1053
  const fast = fastStaticPages.get(pathname)
784
1054
  if (fast !== undefined)
785
- return fast(req, remoteIp)
1055
+ return fast(req, remoteIp, url)
786
1056
  }
787
1057
 
788
1058
  // 5. Full Router + Plugin Rewrites + Plugin Routes + Middleware + Streaming/Head/Error pipeline
789
- const { ctx, cookieStore } = makeRequestContext(req, {}, { trustProxy, remoteIp })
790
-
791
- // Hydrate & clear one-shot progressive form validation flash cookie
792
- if (hasActionErrorFlash && req.method === 'GET') {
793
- const rawFlash = ctx.cookies.get(ACTION_ERROR_COOKIE)
794
- if (rawFlash !== undefined) {
795
- try {
796
- ctx.locals.actionError = JSON.parse(rawFlash) as ActionErrorFlash
797
- }
798
- catch {}
799
- ctx.cookies.delete(ACTION_ERROR_COOKIE)
800
- }
801
- }
1059
+ const { ctx, cookieStore } = makeRequestContext(req, {}, { trustProxy, remoteIp, url })
802
1060
 
803
1061
  // Apply plugin URL rewrites (e.g. @kayjs/i18n stripping /fr prefix and setting ctx.locals.locale)
804
1062
  let effectivePath = pathname
805
- for (let i = 0; i < pluginRewrites.length; i++) {
806
- const nextPath = pluginRewrites[i]!(effectivePath, ctx)
1063
+ for (const rewrite of pluginRewrites) {
1064
+ const nextPath = rewrite(effectivePath, ctx)
807
1065
  if (nextPath !== undefined)
808
1066
  effectivePath = nextPath
809
1067
  }
810
1068
 
811
- // Check custom plugin routes first (e.g. GET /sitemap.xml, POST /auth/callback, GET /api/board)
812
- // Run global plugin middlewares so ctx.locals (e.g. auth user/session) is available in plugin routes too.
1069
+ // Custom plugin routes run behind plugin middlewares so ctx.locals (e.g. auth user/session) is available.
1070
+ const method = req.method.toUpperCase()
813
1071
  const pluginMatch = pluginRouter.match(effectivePath)
814
- if (pluginMatch !== undefined) {
815
- const routeDef = pluginMatch.data.get(req.method.toUpperCase()) ?? pluginMatch.data.get('ALL')
816
- if (routeDef !== undefined) {
817
- if (routeDef.csrf) {
818
- const originCheck = verifyOrigin(req, trustedOrigins, trustProxy)
819
- if (!originCheck.ok) {
820
- return withHsts(
821
- finalizeResponse(
822
- Response.json({ ok: false, status: 403, error: originCheck.reason }, { status: 403 }),
823
- cookieStore,
824
- securityEntries,
825
- ),
826
- req,
827
- )
828
- }
829
- }
830
- ctx.params = pluginMatch.params
831
- let res: Response
832
- try {
833
- if (globalMiddlewares.length === 0) {
834
- res = await routeDef.handler(ctx)
835
- }
836
- else {
837
- let index = -1
838
- const dispatch = async (i: number): Promise<Response> => {
839
- if (i <= index)
840
- throw new Error('kay: middleware called next() multiple times')
841
- index = i
842
- if (i < globalMiddlewares.length)
843
- return globalMiddlewares[i]!(ctx, () => dispatch(i + 1))
844
- return routeDef.handler(ctx)
845
- }
846
- res = await dispatch(0)
847
- }
848
- if ((res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream'))
849
- disableTimeout?.()
850
- return withHsts(finalizeResponse(await maybeCompressResponse(res, req, compressCache), cookieStore, securityEntries), req)
851
- }
852
- catch (error) {
853
- notifyError(error, req, 'plugin')
854
- return renderError(error, cookieStore, ctx.url, req)
855
- }
1072
+ const directPluginDef = pluginMatch?.data.get(method) ?? pluginMatch?.data.get('ALL')
1073
+ const headFallbackPluginDef = directPluginDef === undefined && method === 'HEAD' ? pluginMatch?.data.get('GET') : undefined
1074
+ const routeDef = directPluginDef ?? headFallbackPluginDef
1075
+ if (pluginMatch !== undefined && routeDef !== undefined) {
1076
+ if (routeDef.csrf) {
1077
+ const originCheck = verifyOrigin(req, routeDef.trustedOrigins, routeDef.trustProxy)
1078
+ if (!originCheck.ok)
1079
+ return refuseCrossSite(req, originCheck.reason, cookieStore)
1080
+ }
1081
+ ctx.params = pluginMatch.params
1082
+ try {
1083
+ let res = await runChain(ctx, allPluginMiddlewares, () => routeDef.handler(ctx))
1084
+ if (headFallbackPluginDef !== undefined)
1085
+ res = stripHeadBody(res)
1086
+ else if (isEventStream(res))
1087
+ disableTimeout?.()
1088
+ return finish(await maybeCompressResponse(res, req, compressCache), req, cookieStore)
1089
+ }
1090
+ catch (error) {
1091
+ notifyError(error, req, 'plugin')
1092
+ return renderError(error, cookieStore, ctx.url, req, ctx)
856
1093
  }
857
1094
  }
858
1095
 
859
1096
  const matched = router.match(effectivePath)
860
- if (matched === undefined)
861
- return renderNotFound(cookieStore, ctx.url, req)
1097
+ if (matched === undefined) {
1098
+ if (pluginMatch !== undefined) {
1099
+ const allow = allowedPluginMethodsHeader(pluginMatch.data)
1100
+ return finish(new Response('Method Not Allowed', allow ? { status: 405, headers: { allow } } : { status: 405 }), req)
1101
+ }
1102
+ return renderNotFound(cookieStore, ctx.url, req, ctx)
1103
+ }
862
1104
 
863
1105
  ctx.params = matched.params
864
1106
  const route = matched.data
865
1107
 
1108
+ // Reject unsupported HTTP methods with 405 + Allow BEFORE any middleware or CSRF check runs.
1109
+ const supportsMethod = typeof route.mod[method] === 'function'
1110
+ || (method === 'HEAD' && typeof route.mod.GET === 'function')
1111
+ || (typeof route.mod.default === 'function' && (method === 'GET' || method === 'HEAD'))
1112
+ if (!supportsMethod) {
1113
+ const allow = allowedMethodsHeader(route.mod)
1114
+ return finish(new Response('Method Not Allowed', allow ? { status: 405, headers: { allow } } : { status: 405 }), req)
1115
+ }
1116
+
866
1117
  // CSRF verification for file-based API routes on unsafe methods (opt out via `export const csrf = false`)
867
- if (typeof route.mod[req.method] === 'function' && route.mod.csrf !== false) {
1118
+ if (typeof route.mod[method] === 'function' && route.mod.csrf !== false) {
868
1119
  const originCheck = verifyOrigin(req, trustedOrigins, trustProxy)
869
- if (!originCheck.ok) {
870
- return withHsts(
871
- finalizeResponse(
872
- Response.json({ ok: false, status: 403, error: originCheck.reason }, { status: 403 }),
873
- cookieStore,
874
- securityEntries,
875
- ),
876
- req,
877
- )
878
- }
1120
+ if (!originCheck.ok)
1121
+ return refuseCrossSite(req, originCheck.reason, cookieStore)
879
1122
  }
880
1123
 
881
- const allMiddlewares = globalMiddlewares.length > 0
882
- ? [...globalMiddlewares, ...route.middlewares]
883
- : route.middlewares
884
-
885
1124
  try {
886
- let index = -1
887
- const dispatch = async (i: number): Promise<Response> => {
888
- if (i <= index)
889
- throw new Error('kay: middleware called next() multiple times')
890
- index = i
891
- if (i < allMiddlewares.length)
892
- return allMiddlewares[i]!(ctx, () => dispatch(i + 1))
893
- return renderCompiledRoute(route, ctx, disableTimeout)
894
- }
895
- const res = await dispatch(0)
896
- if ((res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream'))
1125
+ const res = await runChain(ctx, route.middlewares, () => renderCompiledRoute(route, ctx, disableTimeout))
1126
+ if (isEventStream(res))
897
1127
  disableTimeout?.()
898
- return withHsts(finalizeResponse(res, cookieStore, securityEntries), req)
1128
+ // Compress uncompressed API/middleware responses after the middleware chain unwinds.
1129
+ const finalRes = res.headers.has('content-encoding') ? res : await maybeCompressResponse(res, req, compressCache)
1130
+ return finish(finalRes, req, cookieStore)
899
1131
  }
900
1132
  catch (error) {
901
1133
  notifyError(error, req, 'route')
902
- return renderError(error, cookieStore, ctx.url, req)
1134
+ return renderError(error, cookieStore, ctx.url, req, ctx)
903
1135
  }
904
1136
  }
905
1137
  catch (error) {
906
1138
  notifyError(error, request, 'route')
907
- return withHsts(
908
- new Response('Internal Server Error', {
909
- status: 500,
910
- headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord },
911
- }),
912
- request,
913
- )
1139
+ return withHsts(serverError(), request)
914
1140
  }
915
1141
  }
916
1142
 
917
1143
  function handle(request: Request, remoteIp?: string): Promise<Response> {
918
- return handleInternal(request, remoteIp)
1144
+ return runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp))
919
1145
  }
920
1146
 
921
1147
  function serve(port = 3000, hostname = '127.0.0.1') {
922
1148
  let srvRef: ReturnType<typeof Bun.serve> | undefined
923
- const fetchReq = (req: Request) => handleInternal(
1149
+ const ipOf = (req: Request) => srvRef?.requestIP(req)?.address
1150
+ const fetchReq = (req: Request) => runWithAppContext(serverAppCtx, () => handleInternal(
924
1151
  req,
925
- srvRef?.requestIP(req)?.address,
1152
+ ipOf(req),
926
1153
  srvRef ? () => srvRef!.timeout(req, 0) : undefined,
927
- )
1154
+ true,
1155
+ ))
928
1156
 
929
1157
  const routes: Record<string, (req: Request) => Response | Promise<Response>> = {}
930
1158
 
931
1159
  for (const [path, asset] of assetMap)
932
- routes[path] = req => serveAsset(req, path, asset)
1160
+ routes[path] = req => isRead(req) ? serveAsset(req, asset) : fetchReq(req)
933
1161
 
934
1162
  for (const [path, pub] of publicMap) {
935
- if (!(path in routes))
936
- routes[path] = req => servePublic(req, path, pub)
1163
+ if (!(path in routes) && pluginRouter.match(path) === undefined)
1164
+ routes[path] = req => isRead(req) ? servePublic(req, pub) : fetchReq(req)
937
1165
  }
938
1166
 
939
1167
  for (const [path, pre] of fastPrerenderedMap) {
940
- if (!(path in routes)) {
941
- routes[path] = req => (req.method === 'GET' || req.method === 'HEAD') && !(req.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
942
- ? servePrerendered(req, path, pre)
943
- : fetchReq(req)
944
- }
1168
+ if (!(path in routes))
1169
+ routes[path] = req => isPlainRead(req) ? serveFile(req, pre) : fetchReq(req)
945
1170
  }
946
1171
 
947
1172
  for (const [path, handler] of fastStaticPages) {
948
- if (!(path in routes)) {
949
- routes[path] = req => (req.method === 'GET' || req.method === 'HEAD') && !(req.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
950
- ? handler(req, srvRef?.requestIP(req)?.address)
951
- : fetchReq(req)
952
- }
1173
+ if (!(path in routes))
1174
+ routes[path] = req => isPlainRead(req) ? runWithAppContext(serverAppCtx, () => handler(req, ipOf(req))) : fetchReq(req)
953
1175
  }
954
1176
 
955
1177
  srvRef = Bun.serve({
@@ -962,229 +1184,24 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
962
1184
  fetch: fetchReq,
963
1185
  error(err) {
964
1186
  notifyError(err, new Request('http://localhost/'), 'route')
965
- return new Response('Internal Server Error', {
966
- status: 500,
967
- headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord },
968
- })
1187
+ return serverError()
969
1188
  },
970
1189
  })
971
1190
  return srvRef
972
1191
  }
973
1192
 
974
- return { handle, serve }
975
- }
976
-
977
- function createStaticDirServer(
978
- outDir: string,
979
- assetPrefix: string,
980
- securityEntries: readonly [string, string][],
981
- compressEnabled: boolean,
982
- hstsValue: string | undefined,
983
- trustProxy: boolean,
984
- ): KayApp {
985
- const cleanPrefix = `${assetPrefix.replace(/\/$/, '')}/`
986
- const absRoot = resolve(outDir)
987
- const compressCache = compressEnabled ? new CompressionCache() : undefined
988
- const securityRecord: Record<string, string> = {}
989
- for (let i = 0; i < securityEntries.length; i++)
990
- securityRecord[securityEntries[i]![0]] = securityEntries[i]![1]
991
- const withHsts = (res: Response, req: Request) => applyHstsHeader(res, req, hstsValue, trustProxy)
992
-
993
- function resolveStaticFile(pathname: string): string | undefined {
994
- let decoded: string
995
- try {
996
- decoded = decodeURIComponent(pathname)
997
- }
998
- catch {
999
- return undefined
1000
- }
1001
- const rel = decoded.replace(/^\/+/, '').replace(/\/+$/, '')
1002
- const candidates = rel === ''
1003
- ? ['index.html']
1004
- : [rel, `${rel}.html`, `${rel}/index.html`]
1005
- for (const c of candidates) {
1006
- const abs = resolve(absRoot, c)
1007
- if (abs !== absRoot && !abs.startsWith(`${absRoot}/`) && !abs.startsWith(`${absRoot}\\`))
1008
- continue
1009
- if (existsSync(abs) && statSync(abs).isFile())
1010
- return abs
1011
- }
1012
- return undefined
1013
- }
1014
-
1015
- const initHeaders = (): Headers => {
1016
- const headers = new Headers()
1017
- for (let i = 0; i < securityEntries.length; i++)
1018
- headers.set(securityEntries[i]![0], securityEntries[i]![1])
1019
- return headers
1020
- }
1021
-
1022
- const handle = async (req: Request): Promise<Response> => {
1023
- if (req.method !== 'GET' && req.method !== 'HEAD')
1024
- return withHsts(new Response('Method Not Allowed', { status: 405, headers: initHeaders() }), req)
1025
-
1026
- const url = new URL(req.url)
1027
- const filePath = resolveStaticFile(url.pathname)
1028
- if (filePath === undefined) {
1029
- const notFoundPath = join(absRoot, '404.html')
1030
- if (existsSync(notFoundPath) && statSync(notFoundPath).isFile()) {
1031
- const headers = initHeaders()
1032
- headers.set('content-type', 'text/html; charset=utf-8')
1033
- return withHsts(new Response(req.method === 'HEAD' ? null : Bun.file(notFoundPath), { status: 404, headers }), req)
1034
- }
1035
- return withHsts(new Response('Not Found', { status: 404, headers: initHeaders() }), req)
1036
- }
1037
-
1038
- const st = statSync(filePath)
1039
- const etag = `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
1040
- const isImmutable = url.pathname.startsWith(cleanPrefix)
1041
- const cacheControl = isImmutable ? 'public, max-age=31536000, immutable' : 'public, max-age=0, must-revalidate'
1042
- const headers = initHeaders()
1043
- headers.set('content-type', MIME[extname(filePath).toLowerCase()] ?? 'application/octet-stream')
1044
- headers.set('cache-control', cacheControl)
1045
- headers.set('etag', etag)
1046
-
1047
- if (req.headers.get('if-none-match') === etag)
1048
- return withHsts(new Response(null, { status: 304, headers }), req)
1049
-
1050
- if (compressEnabled && req.method !== 'HEAD') {
1051
- const hasBr = existsSync(`${filePath}.br`)
1052
- const hasGz = existsSync(`${filePath}.gz`)
1053
- if (hasBr || hasGz) {
1054
- const preEnc = pickPrecompressedEncoding(req.headers.get('accept-encoding'), { br: hasBr, gz: hasGz })
1055
- if (preEnc !== undefined) {
1056
- headers.set('content-encoding', preEnc)
1057
- headers.set('vary', 'Accept-Encoding')
1058
- headers.set('etag', toWeakEtag(etag))
1059
- return withHsts(new Response(Bun.file(`${filePath}.${preEnc === 'br' ? 'br' : 'gz'}`), { status: 200, headers }), req)
1060
- }
1061
- }
1062
- }
1063
-
1064
- headers.set('content-length', String(st.size))
1065
- const res = new Response(req.method === 'HEAD' ? null : Bun.file(filePath), { status: 200, headers })
1066
- if (!compressEnabled || req.method === 'HEAD')
1067
- return withHsts(res, req)
1068
- return withHsts(await maybeCompressResponse(res, req, compressCache), req)
1069
- }
1070
-
1071
- return {
1072
- handle,
1073
- serve(port = 3000, hostname = '127.0.0.1') {
1074
- return Bun.serve({
1075
- port,
1076
- hostname,
1077
- idleTimeout: 30,
1078
- development: false,
1079
- fetch: handle,
1080
- error() {
1081
- return new Response('Internal Server Error', {
1082
- status: 500,
1083
- headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord },
1084
- })
1085
- },
1086
- })
1087
- },
1088
- }
1089
- }
1090
-
1091
- export async function createServer(options: ServerOptions): Promise<KayApp> {
1092
- const root = resolve(options.root)
1093
- const fileConfig = await loadConfig(root)
1094
- const plugins = options.plugins ?? fileConfig.plugins ?? []
1095
- const outDir = resolve(root, options.outDir ?? fileConfig.outDir ?? 'dist')
1096
- const clientDir = join(outDir, 'client')
1097
- const manifestPath = join(outDir, 'manifest.json')
1098
- const securityOpt = options.security ?? fileConfig.security
1099
- const trustProxy = (options.trustProxy ?? fileConfig.trustProxy) === true
1100
- const maxRequestBodySize = options.maxRequestBodySize ?? fileConfig.maxRequestBodySize
1101
-
1102
- if (!existsSync(manifestPath)) {
1103
- if (existsSync(outDir) && readdirSync(outDir).length > 0) {
1104
- const securityEntries = securityOpt === false ? [] : buildSecurityHeaderEntries(securityOpt ?? {})
1105
- return createStaticDirServer(
1106
- outDir,
1107
- options.assetPrefix ?? fileConfig.assetPrefix ?? '/_kay',
1108
- securityEntries,
1109
- (options.compress ?? fileConfig.compress) !== false,
1110
- resolveHstsValue(securityOpt),
1111
- trustProxy,
1112
- )
1113
- }
1114
- throw new Error(`kay server: missing ${manifestPath}. Run build() first.`)
1115
- }
1116
-
1117
- const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as BuildManifest
1118
- const modules: Record<string, unknown> = {}
1119
- const assets: Record<string, EmbeddedBody> = {}
1120
- const publicAssets: Record<string, EmbeddedBody> = {}
1121
- const publicEtags: Record<string, string> = {}
1122
- const prerenderedFiles: Record<string, string> = {}
1123
- const srcPublicDir = resolve(root, fileConfig.publicDir ?? 'public')
1124
-
1125
- // Store file paths only (zero-copy Bun.file() serving, zero startup RAM bloat!)
1126
- for (const rel of manifest.assets) {
1127
- const abs = join(clientDir, rel)
1128
- if (existsSync(abs)) {
1129
- assets[rel] = abs
1130
- if (existsSync(`${abs}.br`))
1131
- assets[`${rel}.br`] = `${abs}.br`
1132
- if (existsSync(`${abs}.gz`))
1133
- assets[`${rel}.gz`] = `${abs}.gz`
1134
- }
1135
- }
1136
-
1137
- for (const rel of manifest.publicFiles ?? []) {
1138
- const outAbs = join(outDir, 'public', rel)
1139
- const abs = existsSync(outAbs) ? outAbs : join(srcPublicDir, rel)
1140
- if (existsSync(abs)) {
1141
- publicAssets[rel] = abs
1142
- const st = statSync(abs)
1143
- publicEtags[rel] = `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
1144
- }
1145
- }
1146
-
1147
- const loadStamp = Date.now()
1148
- const loadMod = async (rel: string) => {
1149
- if (!(rel in modules))
1150
- modules[rel] = await import(`${join(outDir, rel)}?v=${loadStamp}`)
1151
- }
1152
-
1153
- for (const r of manifest.routes) {
1154
- await loadMod(r.file)
1155
- for (const l of r.layouts) await loadMod(l)
1156
- for (const m of r.middlewares) await loadMod(m)
1157
- if (r.prerendered) {
1158
- for (const [, relHtml] of Object.entries(r.prerendered)) {
1159
- const abs = join(outDir, relHtml)
1160
- if (existsSync(abs))
1161
- prerenderedFiles[relHtml] = abs
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()
1162
1201
  }
1202
+ catch {}
1163
1203
  }
1164
1204
  }
1165
- if (manifest.errorFile) await loadMod(manifest.errorFile)
1166
- if (manifest.notFoundFile) await loadMod(manifest.notFoundFile)
1167
- for (const a of manifest.actions) {
1168
- await loadMod(a.file)
1169
- for (const m of a.middlewares) await loadMod(m)
1170
- }
1171
1205
 
1172
- return createServerFromEmbedded({
1173
- manifest,
1174
- modules,
1175
- assets,
1176
- publicAssets,
1177
- publicEtags,
1178
- prerendered: {},
1179
- prerenderedFiles,
1180
- assetPrefix: options.assetPrefix ?? fileConfig.assetPrefix,
1181
- lang: options.lang ?? fileConfig.lang,
1182
- security: securityOpt,
1183
- trustedOrigins: options.trustedOrigins ?? fileConfig.trustedOrigins,
1184
- trustProxy,
1185
- maxRequestBodySize,
1186
- compress: options.compress ?? fileConfig.compress,
1187
- onError: options.onError ?? fileConfig.onError,
1188
- plugins,
1189
- })
1206
+ return { handle, serve, dispose }
1190
1207
  }