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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +617 -0
  4. package/src/build/compile.ts +27 -51
  5. package/src/build/files.ts +174 -0
  6. package/src/build/graph.ts +223 -0
  7. package/src/build/index.ts +272 -1466
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +229 -0
  10. package/src/build/plugin-host.ts +186 -0
  11. package/src/build/prerender.ts +102 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +51 -0
  14. package/src/build/routes.ts +163 -0
  15. package/src/build/server-entry.ts +38 -0
  16. package/src/build/static.ts +73 -0
  17. package/src/cli/check.ts +300 -129
  18. package/src/cli/index.ts +297 -94
  19. package/src/cli/new.ts +58 -38
  20. package/src/compiler/analyze.ts +723 -93
  21. package/src/compiler/dom.ts +848 -762
  22. package/src/compiler/mistakes.ts +354 -0
  23. package/src/compiler/patch.ts +1 -1
  24. package/src/compiler/server-only.ts +172 -23
  25. package/src/compiler/shared.ts +485 -0
  26. package/src/compiler/ssr.ts +331 -342
  27. package/src/context.ts +120 -0
  28. package/src/dev/index.ts +339 -76
  29. package/src/dom/action.ts +114 -14
  30. package/src/dom/extras.ts +121 -83
  31. package/src/dom/index.ts +122 -80
  32. package/src/dom/island.ts +71 -36
  33. package/src/dom/loop.ts +28 -20
  34. package/src/index.ts +5 -1
  35. package/src/jsx-runtime.ts +432 -93
  36. package/src/plugins/config.ts +49 -0
  37. package/src/plugins/context.ts +61 -0
  38. package/src/plugins/index.ts +10 -123
  39. package/src/plugins/load.ts +38 -0
  40. package/src/plugins/order.ts +107 -0
  41. package/src/plugins/services.ts +23 -0
  42. package/src/plugins/types.ts +197 -0
  43. package/src/reactivity/index.ts +237 -213
  44. package/src/reactivity/selector.ts +11 -9
  45. package/src/reactivity/store.ts +36 -11
  46. package/src/server/action-registry.ts +72 -0
  47. package/src/server/action.ts +157 -79
  48. package/src/server/app-entry.ts +23 -0
  49. package/src/server/assets.ts +182 -0
  50. package/src/server/compress.ts +197 -104
  51. package/src/server/cookies.ts +46 -16
  52. package/src/server/document.ts +192 -0
  53. package/src/server/env.ts +18 -13
  54. package/src/server/errors.ts +123 -0
  55. package/src/server/http.ts +203 -77
  56. package/src/server/index.ts +420 -973
  57. package/src/server/loader.ts +113 -0
  58. package/src/server/page.ts +107 -0
  59. package/src/server/plugin-host.ts +167 -0
  60. package/src/server/router.ts +69 -26
  61. package/src/server/security.ts +90 -59
  62. package/src/server/standard-schema.ts +42 -11
  63. package/src/server/static-dir.ts +163 -0
  64. package/src/server/stream.ts +94 -0
  65. package/src/ssr/context.ts +95 -10
  66. package/src/ssr/index.ts +167 -66
  67. package/src/style.ts +33 -0
  68. package/src/test/index.ts +24 -18
  69. package/src/unrenderable.ts +35 -0
@@ -2,512 +2,315 @@
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
- import type { BuildManifest, RouteManifestEntry } from '../build/index'
8
+ import type { RouteManifestEntry } from '../build/index'
9
9
  import type { Html, HydrateStrategy } from '../jsx-runtime'
10
- import type { KayPlugin, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI } from '../plugins/index'
11
- import type { ActionContext, ActionErrorFlash, ServerAction } from './action'
10
+ import type { DocumentOptions } from '../ssr/index'
11
+ import type { ActionErrorFlash } from './action'
12
12
  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'
17
- import { createRenderContext, renderCollectedHead, runWithRenderContext, streamChunkScript } from '../ssr/context'
13
+ import type { EmbeddedServerConfig, KayApp, Middleware, RequestContext } from './http'
14
+ import type { LoadedLayoutModule, LoadedMiddlewareModule, LoadedPageModule } from './page'
15
+ import { join } from 'node:path'
16
+ import { createAppContext, getAppContext, resolvePlugins, runWithAppContext } from '../plugins/index'
17
+ import { createRenderContext, runWithRenderContext } from '../ssr/context'
18
18
  import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
19
19
  import { ACTION_ERROR_COOKIE, executeAction, isServerAction } from './action'
20
- 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'
20
+ import { createActionRegistry } from './action-registry'
21
+ import { createAssets } from './assets'
22
+ import { CompressionCache, compressedHtmlResponse, maybeCompressResponse } from './compress'
23
+ import { createDocumentHooks, createHtmlHeaders, resolveRenderedIslands } from './document'
24
+ import { createErrorNotifier, createFallbackPages } from './errors'
25
+ import { applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, finalizeResponse, isNotFound, makeRequestContext, runChain, wantsJson } from './http'
26
+ import { allowedMethodsHeader, isPlainObject, mergedHeadTags, pickPageIslandProps, stripHeadBody } from './page'
27
+ import { allowedPluginMethodsHeader, createServerPluginHost } from './plugin-host'
22
28
  import { Router } from './router'
23
- import { buildSecurityHeaderEntries, KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, resolveCspPolicy, resolveHstsValue, verifyOrigin, withCspHashes } from './security'
29
+ import { buildSecurityHeaderEntries, inlineStyleHashes, resolveHstsValue, verifyOrigin } from './security'
30
+ import { STREAM_TAIL_MARK, streamDocument } from './stream'
24
31
 
25
- export { defineConfig, definePlugin, loadConfig } from '../plugins/index'
26
- export type { BuildPluginContext, CheckPluginContext, KayConfig, KayPlugin, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI } from '../plugins/index'
32
+ /**
33
+ * Request-scoped locals bag shared across middlewares, plugins, actions, layouts, and pages.
34
+ * Augment via `declare module '@kayjs/kay/server' { interface KayLocals { ... } }`.
35
+ */
36
+ export interface KayLocals {}
37
+
38
+ export { CONTENT_IMAGE_RESOLVER_SERVICE, createAppContext, defineConfig, definePlugin, getAppContext, I18N_CONFIG_SERVICE, loadConfig, pickRuntimeConfig, resolvePlugins, resolveServerConfig, runWithAppContext } from '../plugins/index'
39
+ export type { ActiveI18nConfig, AppRuntimeContext, BuildPluginContext, BuildPluginTarget, CheckPluginContext, ContentImageResolver, ContentImageResult, CreateAppContextOptions, DocumentHeadContext, FinalizeBuildContext, KayConfig, KayPlugin, MiddlewareOptions, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from '../plugins/index'
27
40
  export { action, getActionError } from './action'
28
41
  export type { ActionContext, ActionErrorFlash, ActionOptions, ActionResult, ServerAction } from './action'
29
42
  export { CompressionCache, isCompressibleType, pickEncoding, pickPrecompressedEncoding, toWeakEtag } from './compress'
30
43
  export type { CompressionEncoding, PrecompressedEncoding } from './compress'
31
44
  export type { CookieOptions, Cookies } from './cookies'
32
- export { defineEnv } from './env'
33
- export { DEFAULT_MAX_REQUEST_BODY_SIZE } from './http'
34
- 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
-
39
- interface LoadedPageModule {
40
- default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
41
- load?: (ctx: RequestContext) => unknown | Promise<unknown>
42
- csrf?: boolean | undefined
43
- GET?: (ctx: RequestContext) => Response | Promise<Response>
44
- POST?: (ctx: RequestContext) => Response | Promise<Response>
45
- PUT?: (ctx: RequestContext) => Response | Promise<Response>
46
- PATCH?: (ctx: RequestContext) => Response | Promise<Response>
47
- DELETE?: (ctx: RequestContext) => Response | Promise<Response>
48
- [key: string]: unknown
49
- }
50
-
51
- interface LoadedLayoutModule {
52
- default: (props: { children: Html, url?: URL, params?: Record<string, string>, locals?: Record<string, unknown> }) => Html | string | Promise<Html | string>
53
- }
54
-
55
- interface LoadedMiddlewareModule {
56
- default: Middleware
57
- }
58
-
59
- interface LoadedErrorModule {
60
- default: (props: { error: unknown }) => Html | string | Promise<Html | string>
45
+ export { defineEnv, nodeEnv } from './env'
46
+ export { DEFAULT_MAX_REQUEST_BODY_SIZE, notFound } from './http'
47
+ export type { EmbeddedServerConfig, ExtractRouteParams, KayApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, RequestContext, RouteContext, ServerOptions } from './http'
48
+ export { createServer } from './loader'
49
+ export { DEFAULT_CSP, DEFAULT_HSTS, DEFAULT_PERMISSIONS_POLICY, getClientIp, isHttpsRequest, isTrustedOrigin, KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, verifyOrigin, withCspHashes } from './security'
50
+ export type { SecurityHeadersOptions, TrustProxy } from './security'
51
+ export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
52
+ export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult, ValidationSuccess } from './standard-schema'
53
+
54
+ // Matches Bun.serve's 30 s idle timeout, which a streamed page turns off.
55
+ const DEFAULT_STREAM_TIMEOUT = 30_000
56
+
57
+ type FastHandler = (req: Request, remoteIp?: string, url?: URL) => Response | Promise<Response>
58
+
59
+ interface CompiledRoute {
60
+ entry: RouteManifestEntry
61
+ mod: LoadedPageModule
62
+ layouts: LoadedLayoutModule[]
63
+ middlewares: Middleware[]
64
+ /** Dynamic segments (`:param` / `*rest`), so the path names no single URL. */
65
+ dynamic: boolean
66
+ /** Options every document of this route shares; a request adds its body, head and islands. */
67
+ doc: DocumentOptions
61
68
  }
62
69
 
63
- const textEncoder = new TextEncoder()
70
+ const isRead = (request: Request): boolean => request.method === 'GET' || request.method === 'HEAD'
71
+ const isEventStream = (res: Response): boolean => (res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream')
72
+ const hasActionErrorCookie = (request: Request): boolean => (request.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
73
+ // A read the pre-rendered and fast static paths may answer: nothing to flash back to the page.
74
+ const isPlainRead = (request: Request): boolean => isRead(request) && !hasActionErrorCookie(request)
64
75
 
65
- type PrerenderEntry = { kind: 'file', path: string, hasIslands: boolean } | { kind: 'html', html: string, hasIslands: boolean }
66
76
 
67
77
  export async function createServerFromEmbedded(config: EmbeddedServerConfig): Promise<KayApp> {
68
- const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered, prerenderedFiles = {}, lang = 'en', security, plugins = [] } = config
78
+ const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered = {}, prerenderedFiles = {}, lang = 'en', security } = config
79
+ const plugins = resolvePlugins(config.plugins)
69
80
  const assetPrefix = (config.assetPrefix ?? '/_kay').replace(/\/$/, '')
70
- const trustedOrigins = config.trustedOrigins ? new Set(config.trustedOrigins) : undefined
71
- const trustProxy = config.trustProxy === true
81
+ const site = config.site?.replace(/\/$/, '') || undefined
82
+ const trustedOriginsList = config.trustedOrigins ?? []
83
+ const trustedOrigins = trustedOriginsList.length > 0 ? new Set(trustedOriginsList) : undefined
84
+ const trustProxy = config.trustProxy ?? false
72
85
  const maxRequestBodySize = config.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
86
+ const streamTimeout = config.streamTimeout ?? DEFAULT_STREAM_TIMEOUT
87
+ const isDev = config.dev ?? (process.env.KAY_DEV === '1')
88
+ const serverRoot = config.root ?? process.cwd()
89
+ const serverOutDir = config.outDir ?? join(serverRoot, 'dist')
90
+ const serverPublicDir = config.publicDir ?? join(serverOutDir, 'public')
91
+ const parentAppCtx = getAppContext()
92
+
73
93
  const alwaysLoadRuntime = plugins.some(p => Boolean(p.clientEntry))
74
- const htmlTransformers = plugins
75
- .map(p => p.transformHtml)
76
- .filter((fn): fn is NonNullable<KayPlugin['transformHtml']> => typeof fn === 'function')
94
+ const notifyError = createErrorNotifier(config.onError, plugins)
95
+ const document = createDocumentHooks({ plugins, lang, trustProxy, notifyError })
96
+ const { hasHeadHooks, hasHtmlTransformers, htmlTransformers, resolveDocumentHead } = document
77
97
 
78
98
  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)
99
+ const securityRecord: Record<string, string> = Object.fromEntries(securityEntries)
100
+ const nosniffHeader: Record<string, string> = security !== false && (security?.contentTypeOptions ?? true) ? { 'x-content-type-options': 'nosniff' } : {}
85
101
  const hstsValue = resolveHstsValue(security)
86
- const withHsts = (res: Response, request: Request): Response => applyHstsHeader(res, request, hstsValue, trustProxy)
87
-
88
- const htmlBaseHeaders: Record<string, string> = { 'content-type': 'text/html; charset=utf-8', ...securityRecord }
89
- 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)
103
- }
104
- return { ...base, 'content-security-policy': withCspHashes(baseCsp, { styleHashes, scriptHashes }) }
105
- }
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')
102
+ const withHsts = (res: Response, request: Request): Response => applyHstsHeader(res, request, hstsValue, trustProxy, isDev)
103
+ // The one way out of every response not built with the security headers already in place.
104
+ const finish = (res: Response, request: Request, cookieStore?: CookieStore): Response => withHsts(finalizeResponse(res, cookieStore, securityEntries), request)
105
+ const serverError = (): Response => new Response('Internal Server Error', {
106
+ status: 500,
107
+ headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord },
108
+ })
109
+ const htmlHeaders = createHtmlHeaders(security, securityRecord)
110
+
111
+ const compressEnabled = config.compress ?? !isDev
125
112
  const compressCache = compressEnabled ? new CompressionCache() : undefined
126
113
 
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
131
- }
132
- const globalMiddlewares: Middleware[] = []
133
- const pluginRewrites: ((pathname: string, ctx: RequestContext) => string | undefined)[] = []
134
- const pluginRouter = new Router<Map<string, PluginRouteDef>>()
135
- const pluginRouteEntries = new Map<string, Map<string, PluginRouteDef>>()
136
-
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)
114
+ const files = createAssets({ assets, assetPrefix, isDev, compressEnabled, compressCache, nosniffHeader, withHsts })
115
+ const { assetMap, publicMap, serveFile, serveAsset, servePublic } = files
116
+ for (const [rel, body] of Object.entries(publicAssets))
117
+ files.registerPublic(rel, body, publicEtags[rel])
118
+
119
+ const serverAppCtx = createAppContext({
120
+ root: serverRoot,
121
+ outDir: serverOutDir,
122
+ publicDir: serverPublicDir,
123
+ assetPrefix,
124
+ site,
125
+ dev: isDev,
126
+ onRegisterPublicFile: (rel) => {
127
+ parentAppCtx?.registerPublicFile(rel)
128
+ files.registerPublicFromDisk(serverPublicDir, rel)
152
129
  },
153
- }
154
-
155
- for (const plugin of plugins) {
156
- if (plugin.server !== undefined)
157
- await plugin.server(pluginApi)
158
- }
159
-
160
- const hasGlobalMiddleware = globalMiddlewares.length > 0
161
- const hasPluginRewrites = pluginRewrites.length > 0
162
- const hasHtmlTransformers = htmlTransformers.length > 0
163
-
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' } : {}),
184
- }
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
- }
191
-
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
- }
205
-
206
- const toResponseBody = (body: EmbeddedBody) => typeof body === 'string' ? Bun.file(body) : body
207
- const errorHooks: ((info: ServerErrorInfo) => void)[] = []
208
- if (config.onError !== undefined)
209
- errorHooks.push(config.onError)
210
- for (const p of plugins) {
211
- if (p.onError !== undefined)
212
- errorHooks.push(p.onError)
213
- }
214
- const notifyError = (error: unknown, request: Request, source: ServerErrorInfo['source']) => {
215
- for (let i = 0; i < errorHooks.length; i++) {
216
- try {
217
- errorHooks[i]!({ error, request, source })
218
- }
219
- catch {}
220
- }
221
- }
222
-
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
- }
240
- }
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
- }
260
- }
261
-
262
- return withHsts(new Response(toResponseBody(asset.body), { status: 200, headers: asset.varyHeaders }), request)
263
- }
264
-
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
-
280
- if (request.method === 'HEAD')
281
- return withHsts(new Response(null, { status: 200, headers: baseHeaders }), request)
282
-
283
- if (hasVary) {
284
- const enc = pickEncoding(request.headers.get('accept-encoding'))
285
- 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)
300
- }
301
- }
302
-
303
- return withHsts(new Response(toResponseBody(pub.body), { status: 200, headers: baseHeaders }), request)
304
- }
305
-
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)
332
- }
333
- }
130
+ })
334
131
 
335
- const body = pre.kind === 'file' ? Bun.file(pre.path) : pre.html
336
- return withHsts(new Response(body, { status: 200, headers }), request)
337
- }
132
+ const actions = createActionRegistry()
133
+ const pluginHost = await createServerPluginHost({
134
+ plugins,
135
+ config,
136
+ manifest,
137
+ appCtx: serverAppCtx,
138
+ root: serverRoot,
139
+ outDir: serverOutDir,
140
+ assetPrefix,
141
+ site,
142
+ dev: isDev,
143
+ trustProxy,
144
+ trustedOriginsList,
145
+ trustedOrigins,
146
+ invokeAction: actions.invoke,
147
+ })
148
+ const { router: pluginRouter, middlewaresFor } = pluginHost
149
+ const hasPluginRewrites = pluginHost.rewrites.length > 0
338
150
 
339
- // Register server actions and assign their live URLs
340
- const actionHandlers = new Map<string, { act: ServerAction<unknown, unknown>, middlewares: Middleware[] }>()
151
+ // Server actions and their live URLs
341
152
  for (const entry of manifest.actions) {
342
153
  const mod = modules[entry.file] as Record<string, unknown> | undefined
343
154
  const act = mod?.[entry.exportName]
344
- if (isServerAction(act)) {
345
- ;(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] })
348
- }
155
+ if (isServerAction(act))
156
+ actions.register(act, entry.url, entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default), middlewaresFor(entry.url))
349
157
  }
350
158
 
351
- const errorMod = manifest.errorFile ? modules[manifest.errorFile] as LoadedErrorModule : undefined
352
- const notFoundMod = manifest.notFoundFile ? modules[manifest.notFoundFile] as LoadedPageModule : undefined
353
-
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>()
357
- 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
- }
373
- }
374
- }
375
- }
159
+ const { all: prerenderedMap, fast: fastPrerenderedMap } = files.collectPrerendered(manifest.routes, {
160
+ prerendered,
161
+ prerenderedFiles,
162
+ htmlHeaders: (route, urlPath) => htmlHeaders(route.islandChunks.length > 0, false, false, route.prerenderedStyleHashes?.[urlPath]),
163
+ isFast: (urlPath, route) => route.middlewares.length === 0 && middlewaresFor(urlPath, true).length === 0 && !hasPluginRewrites && pluginRouter.match(urlPath) === undefined,
164
+ })
165
+
166
+ const router = new Router<CompiledRoute>()
167
+ const fastStaticPages = new Map<string, FastHandler>()
168
+
169
+ const { buildNotFoundResponse, renderError } = createFallbackPages({ manifest, modules, lang, alwaysLoadRuntime, document, htmlHeaders, notifyError, finish })
376
170
 
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
171
+ async function renderNotFound(cookieStore: CookieStore, url: URL, request: Request, ctx: RequestContext): Promise<Response> {
172
+ const res = await runChain(ctx, middlewaresFor(url.pathname), () => buildNotFoundResponse(url, request, ctx))
173
+ return finish(res, request, cookieStore)
385
174
  }
386
175
 
387
- const router = new Router<CompiledRoute>()
388
- const fastStaticPages = new Map<string, (req: Request, remoteIp?: string) => Response | Promise<Response>>()
176
+ function refuseCrossSite(request: Request, reason: string, cookieStore?: CookieStore): Response {
177
+ return finish(Response.json({ ok: false, status: 403, error: reason }, { status: 403 }), request, cookieStore)
178
+ }
389
179
 
390
180
  for (const entry of manifest.routes) {
391
181
  const mod = modules[entry.file] as LoadedPageModule
392
182
  const layouts = entry.layouts.map(l => modules[l] as LoadedLayoutModule)
393
- const middlewares = entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default)
394
-
183
+ const dirMiddlewares = entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default)
184
+ const routePluginMiddlewares = middlewaresFor(entry.path)
185
+ const fastPluginMiddlewares = middlewaresFor(entry.path, true)
186
+ const dynamic = entry.path.includes(':') || entry.path.includes('*')
395
187
  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,
188
+ const doc: DocumentOptions = {
189
+ body: '',
190
+ headTags: mergedHeadTags(manifest, entry),
403
191
  lang,
404
192
  runtimeScript: manifest.runtimeScript,
405
193
  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)
194
+ styles: entry.styles ?? manifest.styles,
195
+ }
413
196
 
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
197
+ // Zero-overhead path for a static route with no middleware, no <Head>/<Suspense>, and no intercepting plugin hook
198
+ const canFastPath = fastPluginMiddlewares.length === 0
416
199
  && !hasPluginRewrites
200
+ && !hasHeadHooks
417
201
  && !hasHtmlTransformers
418
202
  && pluginRouter.match(entry.path) === undefined
419
- && !entry.path.includes(':')
420
- && !entry.path.includes('*')
421
- && middlewares.length === 0
203
+ && !dynamic
204
+ && dirMiddlewares.length === 0
422
205
  && !entry.usesRenderContext
423
206
  && typeof mod.default === 'function'
424
207
  && mod.GET === undefined
425
208
 
426
- let fastHandler: ((req: Request, remoteIp?: string) => Response | Promise<Response>) | undefined
427
209
  if (canFastPath) {
210
+ const shell = renderDocument({ ...doc, body: '\0', preloadChunks: entry.eagerIslandChunks ?? entry.islandChunks, hasIslands })
211
+ const splitAt = shell.indexOf('\0')
212
+ const docPrefix = shell.slice(0, splitAt)
213
+ const docSuffix = shell.slice(splitAt + 1)
428
214
  const singleLayout = layouts.length === 1 ? layouts[0]! : undefined
429
- const fastHeaders = selectDynamicHtmlHeaders(hasIslands, false)
430
215
 
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)
435
- }
216
+
217
+ const fail = (error: unknown, request: Request, url: URL, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
218
+ notifyError(error, request, 'route')
219
+ return renderError(error, cookieStore, url, request, ctx)
220
+ }
221
+ const respondHtml = (body: string, request: Request, cookieStore?: CookieStore): Response => {
222
+ const html = docPrefix + body + docSuffix
223
+ const res = compressedHtmlResponse(html, 200, htmlHeaders(hasIslands, false, true, inlineStyleHashes(html)), request, compressCache, !entry.hasLoad)
224
+ return cookieStore?.hasChanges ? finish(res, request, cookieStore) : withHsts(res, request)
225
+ }
226
+ const layoutProps = (inner: string, url: URL, locals: KayLocals) => ({ children: raw(inner), url, params: {}, locals })
227
+
228
+ const finishSingleLayout = async (wrapped: Promise<Html | string>, request: Request, url: URL, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
436
229
  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)
456
- }
230
+ return respondHtml(ssrChild(await wrapped as Html), request, cookieStore)
231
+ }
232
+ catch (error) {
233
+ return fail(error, request, url, cookieStore, ctx)
234
+ }
235
+ }
457
236
 
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))
237
+ const wrapLayouts = (inner: string, request: Request, url: URL, locals: KayLocals, cookieStore?: CookieStore, ctx?: RequestContext): Response | Promise<Response> => {
238
+ if (layouts.length === 0)
239
+ return respondHtml(inner, request, cookieStore)
240
+ if (singleLayout !== undefined) {
241
+ const wrapped = singleLayout.default(layoutProps(inner, url, locals))
242
+ if (wrapped instanceof Promise)
243
+ return finishSingleLayout(wrapped, request, url, cookieStore, ctx)
244
+ return respondHtml(ssrChild(wrapped as Html), request, cookieStore)
245
+ }
246
+ return (async () => {
247
+ try {
248
+ let cur = inner
249
+ for (let i = layouts.length - 1; i >= 0; i--)
250
+ cur = ssrChild(await layouts[i]!.default(layoutProps(cur, url, locals)) as Html)
251
+ return respondHtml(cur, request, cookieStore)
252
+ }
253
+ catch (error) {
254
+ return fail(error, request, url, cookieStore, ctx)
479
255
  }
256
+ })()
257
+ }
258
+
259
+ const finishAsyncPage = async (rendered: Promise<Html | string>, request: Request, url: URL, locals: KayLocals, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
260
+ try {
261
+ return await wrapLayouts(ssrChild(await rendered as Html), request, url, locals, cookieStore, ctx)
262
+ }
263
+ catch (error) {
264
+ return fail(error, request, url, cookieStore, ctx)
265
+ }
266
+ }
267
+
268
+ const renderPage = (data: unknown, request: Request, url: URL, locals: KayLocals, cookieStore?: CookieStore, ctx?: RequestContext): Response | Promise<Response> => {
269
+ const pageProps: Record<string, unknown> = { params: {}, locals, url, ...(data !== undefined ? { data } : {}) }
270
+ if (entry.isIsland && entry.islandChunk !== undefined) {
271
+ return wrapLayouts(ssrIsland(
272
+ entry.islandChunk,
273
+ () => ssrChild(mod.default!(pageProps) as Html),
274
+ pickPageIslandProps(data, entry, mod),
275
+ entry.islandHydrate as HydrateStrategy | undefined,
276
+ true,
277
+ ), request, url, locals, cookieStore, ctx)
278
+ }
279
+ const rendered = mod.default!(pageProps)
280
+ if (rendered instanceof Promise)
281
+ return finishAsyncPage(rendered, request, url, locals, cookieStore, ctx)
282
+ return wrapLayouts(ssrChild(rendered as Html), request, url, locals, cookieStore, ctx)
283
+ }
480
284
 
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)
285
+ fastStaticPages.set(entry.path, (request, remoteIp, url = new URL(request.url)) => {
286
+ try {
287
+ if (!entry.hasLoad || typeof mod.load !== 'function')
288
+ return renderPage(undefined, request, url, {})
289
+
290
+ const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url })
291
+ return (async () => {
292
+ try {
293
+ const loaded = await mod.load!(ctx)
294
+ if (isNotFound(loaded))
295
+ return finish(await buildNotFoundResponse(url, request, ctx), request, cookieStore)
296
+ if (loaded instanceof Response)
297
+ return finish(loaded, request, cookieStore)
298
+ return await renderPage(loaded, request, url, ctx.locals, cookieStore, ctx)
489
299
  }
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
- )
300
+ catch (error) {
301
+ if (isNotFound(error))
302
+ return finish(await buildNotFoundResponse(url, request, ctx), request, cookieStore)
303
+ return fail(error, request, url, cookieStore, ctx)
496
304
  }
497
- if (loaded instanceof Response)
498
- return finish(loaded)
499
- return finish(renderPage(loaded))
500
- }
501
- return renderPage(undefined)
305
+ })()
502
306
  }
503
307
  catch (error) {
504
- return handleErr(error)
308
+ return fail(error, request, url)
505
309
  }
506
- }
507
- fastStaticPages.set(entry.path, fastHandler)
310
+ })
508
311
  }
509
312
 
510
- router.add(entry.path, { entry, mod, layouts, middlewares, fastHandler, docPrefix, docSuffix })
313
+ router.add(entry.path, { entry, mod, layouts, middlewares: [...routePluginMiddlewares, ...dirMiddlewares], dynamic, doc })
511
314
  }
512
315
 
513
316
  async function renderCompiledRoute(
@@ -515,33 +318,61 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
515
318
  ctx: RequestContext,
516
319
  disableTimeout?: () => void,
517
320
  ): Promise<Response> {
518
- const { entry, mod, layouts } = route
321
+ const { entry, mod, layouts, doc } = route
519
322
 
520
323
  // Serve prerendered HTML after middlewares have passed (when route had middlewares)
521
- if (ctx.request.method === 'GET' || ctx.request.method === 'HEAD') {
324
+ if (isRead(ctx.request)) {
522
325
  const rawPath = ctx.url.pathname
523
326
  const normPath = rawPath.length > 1 && rawPath.endsWith('/') ? rawPath.slice(0, -1) : rawPath
524
327
  const pre = prerenderedMap.get(rawPath) ?? prerenderedMap.get(normPath)
525
328
  if (pre !== undefined)
526
- return servePrerendered(ctx.request, rawPath, pre)
329
+ return serveFile(ctx.request, pre)
527
330
  // 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)
331
+ if (entry.prerender === true && entry.prerendered !== undefined && route.dynamic)
332
+ return buildNotFoundResponse(ctx.url, ctx.request, ctx)
530
333
  }
531
334
 
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)
335
+ // API route (.ts exporting GET/POST/etc.) — HEAD falls back to GET without a body
336
+ const method = ctx.request.method.toUpperCase()
337
+ const methodHandler = mod[method]
338
+ if (typeof methodHandler === 'function')
339
+ return await (methodHandler as (c: RequestContext) => Response | Promise<Response>)(ctx)
340
+ if (method === 'HEAD' && typeof mod.GET === 'function')
341
+ return stripHeadBody(await mod.GET(ctx))
342
+
343
+ // Page routes only handle GET/HEAD; unsafe methods (POST/PUT/PATCH/DELETE) without a method export get 405.
344
+ if (typeof mod.default !== 'function' || !isRead(ctx.request)) {
345
+ const allow = allowedMethodsHeader(mod)
346
+ return new Response('Method Not Allowed', allow ? { status: 405, headers: { allow } } : { status: 405 })
539
347
  }
540
348
 
541
- if (typeof mod.default !== 'function')
542
- return new Response('Method Not Allowed', { status: 405 })
349
+ // Hydrate & clear one-shot progressive form validation flash cookie only on page GETs (never API/plugin GETs)
350
+ if (ctx.request.method === 'GET' && hasActionErrorCookie(ctx.request)) {
351
+ const rawFlash = ctx.cookies.get(ACTION_ERROR_COOKIE)
352
+ if (rawFlash !== undefined) {
353
+ try {
354
+ const parsed: unknown = JSON.parse(rawFlash)
355
+ if (isPlainObject(parsed))
356
+ ctx.locals.actionError = parsed as unknown as ActionErrorFlash
357
+ }
358
+ catch {}
359
+ ctx.cookies.delete(ACTION_ERROR_COOKIE)
360
+ }
361
+ }
543
362
 
544
- const data = entry.hasLoad && typeof mod.load === 'function' ? await mod.load(ctx) : undefined
363
+ let data: unknown
364
+ if (entry.hasLoad && typeof mod.load === 'function') {
365
+ try {
366
+ data = await mod.load(ctx)
367
+ }
368
+ catch (error) {
369
+ if (isNotFound(error))
370
+ return buildNotFoundResponse(ctx.url, ctx.request, ctx)
371
+ throw error
372
+ }
373
+ }
374
+ if (isNotFound(data))
375
+ return buildNotFoundResponse(ctx.url, ctx.request, ctx)
545
376
  if (data instanceof Response)
546
377
  return data
547
378
  const pageProps: Record<string, unknown> = {
@@ -556,11 +387,11 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
556
387
  let inner: string
557
388
  if (entry.isIsland && entry.islandChunk !== undefined) {
558
389
  inner = ssrIsland(
559
- entry.path,
560
390
  entry.islandChunk,
561
391
  () => ssrChild(mod.default!(pageProps) as Html),
562
- data !== undefined ? { data } : {},
392
+ pickPageIslandProps(data, entry, mod),
563
393
  entry.islandHydrate as HydrateStrategy | undefined,
394
+ true,
564
395
  )
565
396
  }
566
397
  else {
@@ -572,384 +403,218 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
572
403
  }
573
404
 
574
405
  const body = await runWithRenderContext(rctx, renderBody)
575
- 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
579
-
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
584
-
585
- // Streaming SSR path when <Suspense> boundaries are pending (never buffered for compression)!
586
- if (rctx.pending.length > 0) {
406
+ const docHead = await resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx)
407
+ const renderedIslands = resolveRenderedIslands(rctx, body)
408
+ const isStreamed = rctx.pending.length > 0
409
+ const hasIslands = renderedIslands.hasIslands || (isStreamed && entry.islandChunks.length > 0)
410
+ const preloadChunks = isStreamed ? entry.islandChunks : renderedIslands.eagerChunks
411
+
412
+ // Streaming SSR when <Suspense> boundaries are pending (never buffered for compression)
413
+ if (isStreamed) {
414
+ if (ctx.request.method === 'HEAD')
415
+ return new Response(null, { status: 200, headers: htmlHeaders(hasIslands, true, true) })
587
416
  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)
603
-
604
- const stream = new ReadableStream<Uint8Array>({
605
- 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()
615
- },
616
- })
617
-
618
- return new Response(stream, { status: 200, headers: { ...selectDynamicHtmlHeaders(hasIslands, true) } })
619
- }
620
-
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 {}
417
+ let shell = renderDocument({ ...doc, body: body + STREAM_TAIL_MARK, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands, hasSuspense: true })
418
+ // Transforms see the document with its initial body; boundaries resolved later stream as they render.
419
+ for (const transform of htmlTransformers)
420
+ shell = await transform(shell, ctx)
421
+ return new Response(streamDocument(shell, rctx, streamTimeout, error => notifyError(error, ctx.request, 'route')), { status: 200, headers: htmlHeaders(hasIslands, true, true, inlineStyleHashes(shell)) })
657
422
  }
658
- return new Response('Internal Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
659
- }
660
423
 
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
- }
424
+ let html = renderDocument({ ...doc, body, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands })
425
+ for (const transform of htmlTransformers)
426
+ html = await transform(html, ctx)
665
427
 
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' } })
428
+ return compressedHtmlResponse(html, 200, htmlHeaders(hasIslands, false, true, inlineStyleHashes(html)), ctx.request, compressCache)
683
429
  }
684
430
 
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
688
- }
689
-
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> {
431
+ // `bodyLimited` is set under `serve()`, where Bun.serve already enforces maxRequestBodySize on every body, chunked ones included.
432
+ async function handleInternal(request: Request, remoteIp?: string, disableTimeout?: () => void, bodyLimited = false): Promise<Response> {
696
433
  try {
697
- const pathname = new URL(request.url).pathname
434
+ const url = new URL(request.url)
435
+ const pathname = url.pathname
436
+ const read = isRead(request)
698
437
 
699
- // 1. Static client assets
700
- if (request.method === 'GET' || request.method === 'HEAD') {
438
+ // 1. Static client assets, then public/ files (explicit plugin routes take precedence over public/ files)
439
+ if (read) {
701
440
  const asset = assetMap.get(pathname)
702
441
  if (asset !== undefined)
703
- return serveAsset(request, pathname, asset)
442
+ return serveAsset(request, asset)
443
+ const pub = publicMap.get(pathname)
444
+ if (pub !== undefined) {
445
+ const matchedPlugin = pluginRouter.match(pathname)
446
+ const reqMethod = request.method.toUpperCase()
447
+ const shadowedByPlugin = matchedPlugin !== undefined
448
+ && (matchedPlugin.data.has(reqMethod) || (reqMethod === 'HEAD' && matchedPlugin.data.has('GET')) || matchedPlugin.data.has('ALL'))
449
+ if (!shadowedByPlugin)
450
+ return servePublic(request, pub)
451
+ }
704
452
  }
705
453
 
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)
454
+ // Actions only accept POST; other methods get 405 before any middleware runs.
455
+ const registeredAction = actions.byUrl(pathname)
456
+ if (registeredAction !== undefined && request.method !== 'POST')
457
+ return finish(new Response('Method Not Allowed', { status: 405, headers: { allow: 'POST' } }), request)
458
+
459
+ // Actions are origin-checked before their body is read and before any middleware runs.
460
+ const actionHandler = request.method === 'POST' ? registeredAction : undefined
461
+ if (actionHandler !== undefined) {
462
+ const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
463
+ if (!originCheck.ok)
464
+ return refuseCrossSite(request, originCheck.reason)
711
465
  }
712
466
 
713
467
  // Enforce request body size cap before actions, plugin routes, and API routes
714
- const bounded = await enforceRequestBodyLimit(request, maxRequestBodySize)
468
+ const bounded = bodyLimited ? { ok: true as const, request } : await enforceRequestBodyLimit(request, maxRequestBodySize)
715
469
  if (!bounded.ok) {
716
- const res413 = requestWantsJson(request)
470
+ const res413 = wantsJson(request)
717
471
  ? Response.json({ ok: false, status: 413, error: 'Payload Too Large' }, { status: 413 })
718
472
  : 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)
473
+ return finish(res413, request)
720
474
  }
721
475
  const req = bounded.request
722
476
 
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
- }
477
+ // 2. Server actions (POST /_kay/action/<id>): plugin middlewares, then the _middleware.ts chain of the action's folder
478
+ if (actionHandler !== undefined) {
479
+ const { act, middlewares } = actionHandler
480
+ const { ctx, cookieStore } = makeRequestContext(req, {}, { trustProxy, remoteIp, url })
481
+ try {
482
+ return finish(await runChain(ctx, middlewares, () => executeAction(act, req, ctx, trustedOrigins, trustProxy)), req, cookieStore)
483
+ }
484
+ catch (error) {
485
+ notifyError(error, req, 'action')
486
+ return renderError(error, cookieStore, ctx.url, req, ctx)
769
487
  }
770
488
  }
771
489
 
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')) {
490
+ // 3. Prerendered static HTML, then 4. the zero-overhead static route path
491
+ const plainRead = isPlainRead(req)
492
+ if (plainRead) {
776
493
  const pre = fastPrerenderedMap.get(pathname)
777
494
  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')) {
495
+ return serveFile(req, pre)
783
496
  const fast = fastStaticPages.get(pathname)
784
497
  if (fast !== undefined)
785
- return fast(req, remoteIp)
498
+ return fast(req, remoteIp, url)
786
499
  }
787
500
 
788
501
  // 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
- }
502
+ const { ctx, cookieStore } = makeRequestContext(req, {}, { trustProxy, remoteIp, url })
802
503
 
803
504
  // Apply plugin URL rewrites (e.g. @kayjs/i18n stripping /fr prefix and setting ctx.locals.locale)
804
505
  let effectivePath = pathname
805
- for (let i = 0; i < pluginRewrites.length; i++) {
806
- const nextPath = pluginRewrites[i]!(effectivePath, ctx)
506
+ for (const rewrite of pluginHost.rewrites) {
507
+ const nextPath = rewrite(effectivePath, ctx)
807
508
  if (nextPath !== undefined)
808
509
  effectivePath = nextPath
809
510
  }
810
511
 
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.
512
+ // Custom plugin routes run behind plugin middlewares so ctx.locals (e.g. auth user/session) is available.
513
+ const method = req.method.toUpperCase()
813
514
  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
- }
515
+ const directPluginDef = pluginMatch?.data.get(method) ?? pluginMatch?.data.get('ALL')
516
+ const headFallbackPluginDef = directPluginDef === undefined && method === 'HEAD' ? pluginMatch?.data.get('GET') : undefined
517
+ const routeDef = directPluginDef ?? headFallbackPluginDef
518
+ if (pluginMatch !== undefined && routeDef !== undefined) {
519
+ if (routeDef.csrf) {
520
+ const originCheck = verifyOrigin(req, routeDef.trustedOrigins, routeDef.trustProxy, url)
521
+ if (!originCheck.ok)
522
+ return refuseCrossSite(req, originCheck.reason, cookieStore)
523
+ }
524
+ ctx.params = pluginMatch.params
525
+ try {
526
+ let res = await runChain(ctx, pluginHost.allMiddlewares, () => routeDef.handler(ctx))
527
+ if (headFallbackPluginDef !== undefined)
528
+ res = stripHeadBody(res)
529
+ else if (isEventStream(res))
530
+ disableTimeout?.()
531
+ return finish(await maybeCompressResponse(res, req, compressCache), req, cookieStore)
532
+ }
533
+ catch (error) {
534
+ notifyError(error, req, 'plugin')
535
+ return renderError(error, cookieStore, ctx.url, req, ctx)
856
536
  }
857
537
  }
858
538
 
859
539
  const matched = router.match(effectivePath)
860
- if (matched === undefined)
861
- return renderNotFound(cookieStore, ctx.url, req)
540
+ if (matched === undefined) {
541
+ if (pluginMatch !== undefined) {
542
+ const allow = allowedPluginMethodsHeader(pluginMatch.data)
543
+ return finish(new Response('Method Not Allowed', allow ? { status: 405, headers: { allow } } : { status: 405 }), req)
544
+ }
545
+ return renderNotFound(cookieStore, ctx.url, req, ctx)
546
+ }
862
547
 
863
548
  ctx.params = matched.params
864
549
  const route = matched.data
865
550
 
866
- // 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) {
868
- 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
- }
551
+ // Reject unsupported HTTP methods with 405 + Allow BEFORE any middleware or CSRF check runs.
552
+ const supportsMethod = typeof route.mod[method] === 'function'
553
+ || (method === 'HEAD' && typeof route.mod.GET === 'function')
554
+ || (typeof route.mod.default === 'function' && (method === 'GET' || method === 'HEAD'))
555
+ if (!supportsMethod) {
556
+ const allow = allowedMethodsHeader(route.mod)
557
+ return finish(new Response('Method Not Allowed', allow ? { status: 405, headers: { allow } } : { status: 405 }), req)
879
558
  }
880
559
 
881
- const allMiddlewares = globalMiddlewares.length > 0
882
- ? [...globalMiddlewares, ...route.middlewares]
883
- : route.middlewares
560
+ // CSRF verification for file-based API routes on unsafe methods (opt out via `export const csrf = false`)
561
+ if (typeof route.mod[method] === 'function' && route.mod.csrf !== false) {
562
+ const originCheck = verifyOrigin(req, trustedOrigins, trustProxy, url)
563
+ if (!originCheck.ok)
564
+ return refuseCrossSite(req, originCheck.reason, cookieStore)
565
+ }
884
566
 
885
567
  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'))
568
+ const res = await runChain(ctx, route.middlewares, () => renderCompiledRoute(route, ctx, disableTimeout))
569
+ if (isEventStream(res))
897
570
  disableTimeout?.()
898
- return withHsts(finalizeResponse(res, cookieStore, securityEntries), req)
571
+ // Compress uncompressed API/middleware responses after the middleware chain unwinds.
572
+ const finalRes = res.headers.has('content-encoding') ? res : await maybeCompressResponse(res, req, compressCache)
573
+ return finish(finalRes, req, cookieStore)
899
574
  }
900
575
  catch (error) {
901
576
  notifyError(error, req, 'route')
902
- return renderError(error, cookieStore, ctx.url, req)
577
+ return renderError(error, cookieStore, ctx.url, req, ctx)
903
578
  }
904
579
  }
905
580
  catch (error) {
906
581
  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
- )
582
+ return withHsts(serverError(), request)
914
583
  }
915
584
  }
916
585
 
917
586
  function handle(request: Request, remoteIp?: string): Promise<Response> {
918
- return handleInternal(request, remoteIp)
587
+ return runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp))
919
588
  }
920
589
 
921
590
  function serve(port = 3000, hostname = '127.0.0.1') {
922
591
  let srvRef: ReturnType<typeof Bun.serve> | undefined
923
- const fetchReq = (req: Request) => handleInternal(
592
+ const ipOf = (req: Request) => srvRef?.requestIP(req)?.address
593
+ const fetchReq = (req: Request) => runWithAppContext(serverAppCtx, () => handleInternal(
924
594
  req,
925
- srvRef?.requestIP(req)?.address,
595
+ ipOf(req),
926
596
  srvRef ? () => srvRef!.timeout(req, 0) : undefined,
927
- )
597
+ true,
598
+ ))
928
599
 
929
600
  const routes: Record<string, (req: Request) => Response | Promise<Response>> = {}
930
601
 
931
602
  for (const [path, asset] of assetMap)
932
- routes[path] = req => serveAsset(req, path, asset)
603
+ routes[path] = req => isRead(req) ? serveAsset(req, asset) : fetchReq(req)
933
604
 
934
605
  for (const [path, pub] of publicMap) {
935
- if (!(path in routes))
936
- routes[path] = req => servePublic(req, path, pub)
606
+ if (!(path in routes) && pluginRouter.match(path) === undefined)
607
+ routes[path] = req => isRead(req) ? servePublic(req, pub) : fetchReq(req)
937
608
  }
938
609
 
939
610
  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
- }
611
+ if (!(path in routes))
612
+ routes[path] = req => isPlainRead(req) ? serveFile(req, pre) : fetchReq(req)
945
613
  }
946
614
 
947
615
  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
- }
616
+ if (!(path in routes))
617
+ routes[path] = req => isPlainRead(req) ? runWithAppContext(serverAppCtx, () => handler(req, ipOf(req))) : fetchReq(req)
953
618
  }
954
619
 
955
620
  srvRef = Bun.serve({
@@ -962,229 +627,11 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
962
627
  fetch: fetchReq,
963
628
  error(err) {
964
629
  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
- })
630
+ return serverError()
969
631
  },
970
632
  })
971
633
  return srvRef
972
634
  }
973
635
 
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
1162
- }
1163
- }
1164
- }
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
-
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
- })
636
+ return { handle, serve, dispose: pluginHost.dispose }
1190
637
  }