@kayjs/kay 2.0.0-alpha.5 → 2.0.0-alpha.6
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.
- package/package.json +1 -1
- package/src/build/compile.ts +10 -6
- package/src/build/index.ts +400 -25
- package/src/cli/check.ts +165 -4
- package/src/cli/index.ts +2 -1
- package/src/cli/new.ts +1 -1
- package/src/dev/index.ts +135 -22
- package/src/dom/extras.ts +67 -11
- package/src/dom/index.ts +3 -3
- package/src/dom/island.ts +97 -75
- package/src/plugins/index.ts +25 -2
- package/src/server/action.ts +47 -0
- package/src/server/compress.ts +241 -0
- package/src/server/cookies.ts +4 -0
- package/src/server/http.ts +40 -7
- package/src/server/index.ts +435 -158
- package/src/server/security.ts +81 -1
- package/src/ssr/context.ts +5 -2
- package/src/ssr/index.ts +30 -3
package/src/server/index.ts
CHANGED
|
@@ -11,24 +11,28 @@ import type { KayPlugin, ServerPluginAPI } from '../plugins/index'
|
|
|
11
11
|
import type { ActionContext, ServerAction } from './action'
|
|
12
12
|
import type { CookieStore } from './cookies'
|
|
13
13
|
import type { EmbeddedBody, EmbeddedServerConfig, KayApp, Middleware, RequestContext, ServerOptions } from './http'
|
|
14
|
-
import { existsSync, readFileSync } from 'node:fs'
|
|
14
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
15
15
|
import { extname, join, resolve } from 'node:path'
|
|
16
16
|
import { loadConfig } from '../plugins/index'
|
|
17
17
|
import { createRenderContext, renderCollectedHead, runWithRenderContext, streamChunkScript } from '../ssr/context'
|
|
18
18
|
import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
|
|
19
|
-
import { executeAction, isServerAction } from './action'
|
|
19
|
+
import { ACTION_ERROR_COOKIE, executeAction, isServerAction } from './action'
|
|
20
|
+
import type { ActionErrorFlash } from './action'
|
|
21
|
+
import { CompressionCache, compressedHtmlResponse, isCompressibleType, maybeCompressResponse, pickEncoding } from './compress'
|
|
20
22
|
import { extractRenderedIslands, finalizeResponse, makeRequestContext, MIME } from './http'
|
|
21
23
|
import { Router } from './router'
|
|
22
|
-
import {
|
|
24
|
+
import { buildSecurityHeaderEntries, KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, withCspHashes } from './security'
|
|
23
25
|
|
|
24
26
|
export { defineConfig, definePlugin, loadConfig } from '../plugins/index'
|
|
25
|
-
export type { BuildPluginContext, KayConfig, KayPlugin, ServerPluginAPI } from '../plugins/index'
|
|
26
|
-
export { action } from './action'
|
|
27
|
-
export type { ActionContext, ActionResult, ServerAction } from './action'
|
|
27
|
+
export type { BuildPluginContext, CheckPluginContext, KayConfig, KayPlugin, ServerPluginAPI } from '../plugins/index'
|
|
28
|
+
export { action, getActionError } from './action'
|
|
29
|
+
export type { ActionContext, ActionErrorFlash, ActionResult, ServerAction } from './action'
|
|
30
|
+
export { CompressionCache, isCompressibleType, pickEncoding } from './compress'
|
|
31
|
+
export type { CompressionEncoding } from './compress'
|
|
28
32
|
export type { CookieOptions, Cookies } from './cookies'
|
|
29
33
|
export { defineEnv } from './env'
|
|
30
34
|
export type { EmbeddedServerConfig, KayApp, Middleware, RequestContext, ServerOptions } from './http'
|
|
31
|
-
export { verifyOrigin } from './security'
|
|
35
|
+
export { KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, verifyOrigin, withCspHashes } from './security'
|
|
32
36
|
export type { SecurityHeadersOptions } from './security'
|
|
33
37
|
export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1 } from './standard-schema'
|
|
34
38
|
|
|
@@ -55,8 +59,12 @@ interface LoadedErrorModule {
|
|
|
55
59
|
default: (props: { error: unknown }) => Html | string | Promise<Html | string>
|
|
56
60
|
}
|
|
57
61
|
|
|
62
|
+
const textEncoder = new TextEncoder()
|
|
63
|
+
|
|
64
|
+
type PrerenderEntry = { kind: 'file', path: string, hasIslands: boolean } | { kind: 'html', html: string, hasIslands: boolean }
|
|
65
|
+
|
|
58
66
|
export async function createServerFromEmbedded(config: EmbeddedServerConfig): Promise<KayApp> {
|
|
59
|
-
const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered, lang = 'en', security, plugins = [] } = config
|
|
67
|
+
const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered, prerenderedFiles = {}, lang = 'en', security, plugins = [] } = config
|
|
60
68
|
const assetPrefix = (config.assetPrefix ?? '/_kay').replace(/\/$/, '')
|
|
61
69
|
const trustedOrigins = config.trustedOrigins ? new Set(config.trustedOrigins) : undefined
|
|
62
70
|
const alwaysLoadRuntime = plugins.some(p => Boolean(p.clientEntry))
|
|
@@ -64,6 +72,38 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
64
72
|
.map(p => p.transformHtml)
|
|
65
73
|
.filter((fn): fn is NonNullable<KayPlugin['transformHtml']> => typeof fn === 'function')
|
|
66
74
|
|
|
75
|
+
const securityEntries = buildSecurityHeaderEntries(security)
|
|
76
|
+
const securityRecord: Record<string, string> = {}
|
|
77
|
+
for (let i = 0; i < securityEntries.length; i++) {
|
|
78
|
+
const [k, v] = securityEntries[i]!
|
|
79
|
+
securityRecord[k] = v
|
|
80
|
+
}
|
|
81
|
+
const htmlBaseHeaders: Record<string, string> = { 'content-type': 'text/html; charset=utf-8', ...securityRecord }
|
|
82
|
+
const baseCsp = security !== false ? security?.csp : undefined
|
|
83
|
+
const makeHtmlHeaders = (hasIslands: boolean, hasSuspense: boolean): Record<string, string> => {
|
|
84
|
+
if (baseCsp === undefined || (!hasIslands && !hasSuspense))
|
|
85
|
+
return htmlBaseHeaders
|
|
86
|
+
const styleHashes: string[] = []
|
|
87
|
+
const scriptHashes: string[] = []
|
|
88
|
+
if (hasIslands)
|
|
89
|
+
styleHashes.push(KAY_ISLAND_STYLE_HASH)
|
|
90
|
+
if (hasSuspense) {
|
|
91
|
+
styleHashes.push(KAY_SUSPENSE_STYLE_HASH)
|
|
92
|
+
scriptHashes.push(KAY_STREAM_SCRIPT_HASH)
|
|
93
|
+
}
|
|
94
|
+
return { ...htmlBaseHeaders, 'content-security-policy': withCspHashes(baseCsp, { styleHashes, scriptHashes }) }
|
|
95
|
+
}
|
|
96
|
+
const htmlHeadersPlain = makeHtmlHeaders(false, false)
|
|
97
|
+
const htmlHeadersIslands = makeHtmlHeaders(true, false)
|
|
98
|
+
const htmlHeadersSuspense = makeHtmlHeaders(false, true)
|
|
99
|
+
const htmlHeadersBoth = makeHtmlHeaders(true, true)
|
|
100
|
+
const selectHtmlHeaders = (hasIslands: boolean, hasSuspense: boolean): Record<string, string> =>
|
|
101
|
+
hasIslands
|
|
102
|
+
? (hasSuspense ? htmlHeadersBoth : htmlHeadersIslands)
|
|
103
|
+
: (hasSuspense ? htmlHeadersSuspense : htmlHeadersPlain)
|
|
104
|
+
const compressEnabled = config.compress ?? (process.env.KAY_DEV !== '1')
|
|
105
|
+
const compressCache = compressEnabled ? new CompressionCache() : undefined
|
|
106
|
+
|
|
67
107
|
// Collect plugin server hooks (supports both sync and async plugin setup)
|
|
68
108
|
const globalMiddlewares: Middleware[] = []
|
|
69
109
|
const pluginRewrites: ((pathname: string, ctx: RequestContext) => string | undefined)[] = []
|
|
@@ -93,23 +133,148 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
93
133
|
await plugin.server(pluginApi)
|
|
94
134
|
}
|
|
95
135
|
|
|
96
|
-
const
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
136
|
+
const hasGlobalMiddleware = globalMiddlewares.length > 0
|
|
137
|
+
const hasPluginRewrites = pluginRewrites.length > 0
|
|
138
|
+
const hasHtmlTransformers = htmlTransformers.length > 0
|
|
139
|
+
|
|
140
|
+
// Hashed build asset table (immutable cache + optional lazy compression)
|
|
141
|
+
interface AssetEntry {
|
|
142
|
+
body: EmbeddedBody
|
|
143
|
+
type: string
|
|
144
|
+
compressible: boolean
|
|
145
|
+
headers: Record<string, string>
|
|
146
|
+
varyHeaders: Record<string, string>
|
|
147
|
+
}
|
|
148
|
+
const assetMap = new Map<string, AssetEntry>()
|
|
100
149
|
for (const [rel, body] of Object.entries(assets)) {
|
|
101
|
-
|
|
150
|
+
const type = MIME[extname(rel).toLowerCase()] ?? 'application/octet-stream'
|
|
151
|
+
const compressible = isCompressibleType(type)
|
|
152
|
+
const headers: Record<string, string> = {
|
|
153
|
+
'content-type': type,
|
|
154
|
+
'cache-control': 'public, max-age=31536000, immutable',
|
|
155
|
+
}
|
|
156
|
+
const varyHeaders: Record<string, string> = compressible && compressCache !== undefined
|
|
157
|
+
? { ...headers, vary: 'Accept-Encoding' }
|
|
158
|
+
: headers
|
|
159
|
+
assetMap.set(`${assetPrefix}/${rel}`, { body, type, compressible, headers, varyHeaders })
|
|
102
160
|
}
|
|
103
161
|
|
|
104
|
-
// Static public/ file table (ETag + 304
|
|
105
|
-
|
|
162
|
+
// Static public/ file table (ETag + 304 + zero-copy Bun.file + optional lazy compression)
|
|
163
|
+
interface PublicEntry {
|
|
164
|
+
body: EmbeddedBody
|
|
165
|
+
type: string
|
|
166
|
+
etag: string
|
|
167
|
+
compressible: boolean
|
|
168
|
+
}
|
|
169
|
+
const publicMap = new Map<string, PublicEntry>()
|
|
106
170
|
for (const [rel, body] of Object.entries(publicAssets)) {
|
|
107
171
|
const etag = publicEtags[rel] ?? (typeof body === 'string' ? `W/"${Bun.hash(rel).toString(36)}"` : `W/"${Bun.hash(body).toString(36)}"`)
|
|
108
|
-
|
|
172
|
+
const type = MIME[extname(rel).toLowerCase()] ?? 'application/octet-stream'
|
|
173
|
+
publicMap.set(`/${rel}`, { body, type, etag, compressible: isCompressibleType(type) })
|
|
109
174
|
}
|
|
110
175
|
|
|
111
176
|
const toResponseBody = (body: EmbeddedBody) => typeof body === 'string' ? Bun.file(body) : body
|
|
112
177
|
|
|
178
|
+
async function serveAsset(request: Request, pathname: string, asset: AssetEntry): Promise<Response> {
|
|
179
|
+
if (request.method === 'HEAD')
|
|
180
|
+
return new Response(null, { status: 200, headers: asset.varyHeaders })
|
|
181
|
+
|
|
182
|
+
if (compressCache !== undefined && asset.compressible) {
|
|
183
|
+
const enc = pickEncoding(request.headers.get('accept-encoding'))
|
|
184
|
+
if (enc !== undefined) {
|
|
185
|
+
const key = `${enc}:a:${pathname}`
|
|
186
|
+
let compressed = compressCache.get(key)
|
|
187
|
+
if (compressed === undefined) {
|
|
188
|
+
const rawBytes = typeof asset.body === 'string'
|
|
189
|
+
? new Uint8Array(await Bun.file(asset.body).arrayBuffer())
|
|
190
|
+
: asset.body
|
|
191
|
+
compressed = compressCache.compress(rawBytes, enc, `a:${pathname}`)
|
|
192
|
+
if (compressed === undefined)
|
|
193
|
+
return new Response(rawBytes, { status: 200, headers: asset.varyHeaders })
|
|
194
|
+
}
|
|
195
|
+
return new Response(compressed, {
|
|
196
|
+
status: 200,
|
|
197
|
+
headers: { ...asset.headers, 'content-encoding': enc, vary: 'Accept-Encoding' },
|
|
198
|
+
})
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
return new Response(toResponseBody(asset.body), { status: 200, headers: asset.varyHeaders })
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function servePublic(request: Request, pathname: string, pub: PublicEntry): Promise<Response> {
|
|
206
|
+
const cacheControl = process.env.KAY_DEV === '1' ? 'no-cache' : 'public, max-age=3600'
|
|
207
|
+
const hasVary = pub.compressible && compressCache !== undefined
|
|
208
|
+
if (request.headers.get('if-none-match') === pub.etag) {
|
|
209
|
+
const h: Record<string, string> = hasVary
|
|
210
|
+
? { 'etag': pub.etag, 'cache-control': cacheControl, 'vary': 'Accept-Encoding' }
|
|
211
|
+
: { 'etag': pub.etag, 'cache-control': cacheControl }
|
|
212
|
+
return new Response(null, { status: 304, headers: h })
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const baseHeaders: Record<string, string> = hasVary
|
|
216
|
+
? { 'content-type': pub.type, 'etag': pub.etag, 'cache-control': cacheControl, 'vary': 'Accept-Encoding' }
|
|
217
|
+
: { 'content-type': pub.type, 'etag': pub.etag, 'cache-control': cacheControl }
|
|
218
|
+
|
|
219
|
+
if (request.method === 'HEAD')
|
|
220
|
+
return new Response(null, { status: 200, headers: baseHeaders })
|
|
221
|
+
|
|
222
|
+
if (hasVary) {
|
|
223
|
+
const enc = pickEncoding(request.headers.get('accept-encoding'))
|
|
224
|
+
if (enc !== undefined) {
|
|
225
|
+
const staticKey = `p:${pathname}:${pub.etag}`
|
|
226
|
+
let compressed = compressCache.get(`${enc}:${staticKey}`)
|
|
227
|
+
if (compressed === undefined) {
|
|
228
|
+
const rawBytes = typeof pub.body === 'string'
|
|
229
|
+
? new Uint8Array(await Bun.file(pub.body).arrayBuffer())
|
|
230
|
+
: pub.body
|
|
231
|
+
compressed = compressCache.compress(rawBytes, enc, staticKey)
|
|
232
|
+
if (compressed === undefined)
|
|
233
|
+
return new Response(rawBytes, { status: 200, headers: baseHeaders })
|
|
234
|
+
}
|
|
235
|
+
return new Response(compressed, {
|
|
236
|
+
status: 200,
|
|
237
|
+
headers: { ...baseHeaders, 'content-encoding': enc },
|
|
238
|
+
})
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
return new Response(toResponseBody(pub.body), { status: 200, headers: baseHeaders })
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function servePrerendered(request: Request, pathname: string, pre: PrerenderEntry): Promise<Response> {
|
|
246
|
+
const base = selectHtmlHeaders(pre.hasIslands, false)
|
|
247
|
+
const headers = compressCache !== undefined
|
|
248
|
+
? { ...base, vary: 'Accept-Encoding' }
|
|
249
|
+
: base
|
|
250
|
+
|
|
251
|
+
if (request.method === 'HEAD')
|
|
252
|
+
return new Response(null, { status: 200, headers })
|
|
253
|
+
|
|
254
|
+
if (compressCache !== undefined) {
|
|
255
|
+
const enc = pickEncoding(request.headers.get('accept-encoding'))
|
|
256
|
+
if (enc !== undefined) {
|
|
257
|
+
const staticKey = `pre:${pathname}`
|
|
258
|
+
let compressed = compressCache.get(`${enc}:${staticKey}`)
|
|
259
|
+
if (compressed === undefined) {
|
|
260
|
+
const rawBytes = pre.kind === 'file'
|
|
261
|
+
? new Uint8Array(await Bun.file(pre.path).arrayBuffer())
|
|
262
|
+
: textEncoder.encode(pre.html)
|
|
263
|
+
compressed = compressCache.compress(rawBytes, enc, staticKey)
|
|
264
|
+
if (compressed === undefined)
|
|
265
|
+
return new Response(rawBytes, { status: 200, headers })
|
|
266
|
+
}
|
|
267
|
+
return new Response(compressed, {
|
|
268
|
+
status: 200,
|
|
269
|
+
headers: { ...headers, 'content-encoding': enc },
|
|
270
|
+
})
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
const body = pre.kind === 'file' ? Bun.file(pre.path) : pre.html
|
|
275
|
+
return new Response(body, { status: 200, headers })
|
|
276
|
+
}
|
|
277
|
+
|
|
113
278
|
// Register server actions and assign their live URLs
|
|
114
279
|
const actionHandlers = new Map<string, ServerAction<unknown, unknown>>()
|
|
115
280
|
for (const entry of manifest.actions) {
|
|
@@ -124,14 +289,25 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
124
289
|
const errorMod = manifest.errorFile ? modules[manifest.errorFile] as LoadedErrorModule : undefined
|
|
125
290
|
const notFoundMod = manifest.notFoundFile ? modules[manifest.notFoundFile] as LoadedPageModule : undefined
|
|
126
291
|
|
|
127
|
-
// Static prerendered pages table
|
|
128
|
-
const prerenderedMap = new Map<string,
|
|
292
|
+
// Static prerendered pages table (zero-copy file paths preferred; raw HTML strings supported)
|
|
293
|
+
const prerenderedMap = new Map<string, PrerenderEntry>()
|
|
294
|
+
const fastPrerenderedMap = new Map<string, PrerenderEntry>()
|
|
129
295
|
for (const route of manifest.routes) {
|
|
130
296
|
if (route.prerendered) {
|
|
297
|
+
const routeHasIslands = route.islandChunks.length > 0
|
|
131
298
|
for (const [urlPath, relHtml] of Object.entries(route.prerendered)) {
|
|
299
|
+
const filePath = prerenderedFiles[relHtml]
|
|
132
300
|
const html = prerendered[relHtml]
|
|
133
|
-
|
|
134
|
-
|
|
301
|
+
const entry: PrerenderEntry | undefined = filePath !== undefined
|
|
302
|
+
? { kind: 'file', path: filePath, hasIslands: routeHasIslands }
|
|
303
|
+
: html !== undefined
|
|
304
|
+
? { kind: 'html', html, hasIslands: routeHasIslands }
|
|
305
|
+
: undefined
|
|
306
|
+
if (entry !== undefined) {
|
|
307
|
+
prerenderedMap.set(urlPath, entry)
|
|
308
|
+
if (route.middlewares.length === 0 && !hasGlobalMiddleware && pluginRouter.match(urlPath) === undefined)
|
|
309
|
+
fastPrerenderedMap.set(urlPath, entry)
|
|
310
|
+
}
|
|
135
311
|
}
|
|
136
312
|
}
|
|
137
313
|
}
|
|
@@ -155,22 +331,29 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
155
331
|
const middlewares = entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default)
|
|
156
332
|
|
|
157
333
|
const hasIslands = entry.islandChunks.length > 0
|
|
334
|
+
const routeStyles = entry.styles ?? manifest.styles
|
|
335
|
+
const routeHeadTags = entry.headTags !== undefined && entry.headTags.length > 0
|
|
336
|
+
? [...(manifest.headTags ?? []), ...entry.headTags]
|
|
337
|
+
: manifest.headTags
|
|
158
338
|
const shell = renderDocument({
|
|
159
339
|
body: '\0',
|
|
160
|
-
headTags:
|
|
340
|
+
headTags: routeHeadTags,
|
|
161
341
|
lang,
|
|
162
342
|
runtimeScript: manifest.runtimeScript,
|
|
163
343
|
alwaysLoadRuntime,
|
|
164
344
|
preloadChunks: entry.eagerIslandChunks ?? entry.islandChunks,
|
|
165
|
-
styles:
|
|
345
|
+
styles: routeStyles,
|
|
166
346
|
hasIslands,
|
|
167
347
|
})
|
|
168
348
|
const splitAt = shell.indexOf('\0')
|
|
169
349
|
const docPrefix = shell.slice(0, splitAt)
|
|
170
350
|
const docSuffix = shell.slice(splitAt + 1)
|
|
171
351
|
|
|
172
|
-
// Ultra-fast zero-overhead path when route is static, has no middleware, no <Head>/<Suspense>, no
|
|
173
|
-
const canFastPath = !
|
|
352
|
+
// Ultra-fast zero-overhead path when route is static, has no middleware, no <Head>/<Suspense>, and no intercepting plugin hooks
|
|
353
|
+
const canFastPath = !hasGlobalMiddleware
|
|
354
|
+
&& !hasPluginRewrites
|
|
355
|
+
&& !hasHtmlTransformers
|
|
356
|
+
&& pluginRouter.match(entry.path) === undefined
|
|
174
357
|
&& !entry.path.includes(':')
|
|
175
358
|
&& !entry.path.includes('*')
|
|
176
359
|
&& middlewares.length === 0
|
|
@@ -180,40 +363,44 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
180
363
|
|
|
181
364
|
let fastHandler: ((req: Request) => Response | Promise<Response>) | undefined
|
|
182
365
|
if (canFastPath) {
|
|
183
|
-
const headers: Record<string, string> = { 'content-type': 'text/html; charset=utf-8' }
|
|
184
|
-
if (security !== false) {
|
|
185
|
-
const h = new Headers(headers)
|
|
186
|
-
applySecurityHeaders(h, security)
|
|
187
|
-
h.forEach((v, k) => { headers[k] = v })
|
|
188
|
-
}
|
|
189
366
|
const singleLayout = layouts.length === 1 ? layouts[0]! : undefined
|
|
367
|
+
const fastHeaders = selectHtmlHeaders(hasIslands, false)
|
|
190
368
|
|
|
191
369
|
fastHandler = (request: Request): Response | Promise<Response> => {
|
|
192
370
|
const reqUrl = new URL(request.url)
|
|
371
|
+
const respondHtml = (body: string): Response =>
|
|
372
|
+
compressedHtmlResponse(docPrefix + body + docSuffix, 200, fastHeaders, request, compressCache)
|
|
373
|
+
|
|
193
374
|
const wrapLayouts = (inner: string): Response | Promise<Response> => {
|
|
194
375
|
if (layouts.length === 0)
|
|
195
|
-
return
|
|
376
|
+
return respondHtml(inner)
|
|
196
377
|
if (singleLayout !== undefined) {
|
|
197
378
|
const w = singleLayout.default({ children: raw(inner), url: reqUrl, params: {}, locals: {} })
|
|
198
379
|
if (w instanceof Promise)
|
|
199
|
-
return w.then(x =>
|
|
200
|
-
return
|
|
380
|
+
return w.then(x => respondHtml(ssrChild(x as Html)))
|
|
381
|
+
return respondHtml(ssrChild(w as Html))
|
|
201
382
|
}
|
|
202
383
|
return (async () => {
|
|
203
384
|
let cur = inner
|
|
204
385
|
for (let i = layouts.length - 1; i >= 0; i--)
|
|
205
386
|
cur = ssrChild(await layouts[i]!.default({ children: raw(cur), url: reqUrl, params: {}, locals: {} }) as Html)
|
|
206
|
-
return
|
|
387
|
+
return respondHtml(cur)
|
|
207
388
|
})()
|
|
208
389
|
}
|
|
209
390
|
|
|
210
|
-
const renderPage = (
|
|
391
|
+
const renderPage = (data: unknown): Response | Promise<Response> => {
|
|
392
|
+
const pageProps: Record<string, unknown> = {
|
|
393
|
+
params: {},
|
|
394
|
+
locals: {},
|
|
395
|
+
url: reqUrl,
|
|
396
|
+
...(data !== undefined ? { data } : {}),
|
|
397
|
+
}
|
|
211
398
|
if (entry.isIsland && entry.islandChunk !== undefined) {
|
|
212
399
|
const inner = ssrIsland(
|
|
213
400
|
entry.path,
|
|
214
401
|
entry.islandChunk,
|
|
215
402
|
() => ssrChild(mod.default!(pageProps) as Html),
|
|
216
|
-
|
|
403
|
+
data !== undefined ? { data } : {},
|
|
217
404
|
entry.islandHydrate as HydrateStrategy | undefined,
|
|
218
405
|
)
|
|
219
406
|
return wrapLayouts(inner)
|
|
@@ -225,18 +412,25 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
225
412
|
}
|
|
226
413
|
|
|
227
414
|
if (entry.hasLoad && typeof mod.load === 'function') {
|
|
228
|
-
const { ctx } = makeRequestContext(request, {})
|
|
415
|
+
const { ctx, cookieStore } = makeRequestContext(request, {})
|
|
416
|
+
const finish = (res: Response | Promise<Response>): Response | Promise<Response> => {
|
|
417
|
+
if (!cookieStore.hasChanges)
|
|
418
|
+
return res
|
|
419
|
+
if (res instanceof Promise)
|
|
420
|
+
return res.then(r => finalizeResponse(r, cookieStore, securityEntries))
|
|
421
|
+
return finalizeResponse(res, cookieStore, securityEntries)
|
|
422
|
+
}
|
|
229
423
|
const loaded = mod.load(ctx)
|
|
230
424
|
if (loaded instanceof Promise) {
|
|
231
425
|
return loaded.then(data =>
|
|
232
|
-
data instanceof Response ? data : renderPage(data
|
|
426
|
+
finish(data instanceof Response ? data : renderPage(data)),
|
|
233
427
|
)
|
|
234
428
|
}
|
|
235
429
|
if (loaded instanceof Response)
|
|
236
|
-
return loaded
|
|
237
|
-
return renderPage(loaded
|
|
430
|
+
return finish(loaded)
|
|
431
|
+
return finish(renderPage(loaded))
|
|
238
432
|
}
|
|
239
|
-
return renderPage(
|
|
433
|
+
return renderPage(undefined)
|
|
240
434
|
}
|
|
241
435
|
fastStaticPages.set(entry.path, fastHandler)
|
|
242
436
|
}
|
|
@@ -244,22 +438,29 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
244
438
|
router.add(entry.path, { entry, mod, layouts, middlewares, fastHandler, docPrefix, docSuffix })
|
|
245
439
|
}
|
|
246
440
|
|
|
247
|
-
async function renderCompiledRoute(route: CompiledRoute, ctx: RequestContext
|
|
441
|
+
async function renderCompiledRoute(route: CompiledRoute, ctx: RequestContext): Promise<Response> {
|
|
248
442
|
const { entry, mod, layouts } = route
|
|
249
443
|
|
|
444
|
+
// Serve prerendered HTML after middlewares have passed (when route had middlewares)
|
|
445
|
+
if (ctx.request.method === 'GET' || ctx.request.method === 'HEAD') {
|
|
446
|
+
const pre = prerenderedMap.get(ctx.url.pathname)
|
|
447
|
+
if (pre !== undefined)
|
|
448
|
+
return servePrerendered(ctx.request, ctx.url.pathname, pre)
|
|
449
|
+
}
|
|
450
|
+
|
|
250
451
|
// API route (.ts exporting GET/POST/etc.)
|
|
251
452
|
const methodHandler = mod[ctx.request.method]
|
|
252
453
|
if (typeof methodHandler === 'function') {
|
|
253
454
|
const res = await (methodHandler as (c: RequestContext) => Response | Promise<Response>)(ctx)
|
|
254
|
-
return
|
|
455
|
+
return maybeCompressResponse(res, ctx.request, compressCache)
|
|
255
456
|
}
|
|
256
457
|
|
|
257
458
|
if (typeof mod.default !== 'function')
|
|
258
|
-
return
|
|
459
|
+
return new Response('Method Not Allowed', { status: 405 })
|
|
259
460
|
|
|
260
461
|
const data = entry.hasLoad && typeof mod.load === 'function' ? await mod.load(ctx) : undefined
|
|
261
462
|
if (data instanceof Response)
|
|
262
|
-
return
|
|
463
|
+
return data
|
|
263
464
|
const pageProps: Record<string, unknown> = {
|
|
264
465
|
params: ctx.params,
|
|
265
466
|
locals: ctx.locals,
|
|
@@ -293,69 +494,67 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
293
494
|
const hasIslands = renderedIslands.hasIslands || rctx.pending.length > 0 && entry.islandChunks.length > 0
|
|
294
495
|
const preloadChunks = rctx.pending.length > 0 ? entry.islandChunks : renderedIslands.eagerChunks
|
|
295
496
|
|
|
296
|
-
|
|
497
|
+
const routeStyles = entry.styles ?? manifest.styles
|
|
498
|
+
const routeHeadTags = entry.headTags !== undefined && entry.headTags.length > 0
|
|
499
|
+
? [...(manifest.headTags ?? []), ...entry.headTags]
|
|
500
|
+
: manifest.headTags
|
|
501
|
+
|
|
502
|
+
// Streaming SSR path when <Suspense> boundaries are pending (never buffered for compression)!
|
|
297
503
|
if (rctx.pending.length > 0) {
|
|
298
504
|
const shell = renderDocument({
|
|
299
505
|
body: '\0',
|
|
300
506
|
head: collectedHead,
|
|
301
|
-
headTags:
|
|
507
|
+
headTags: routeHeadTags,
|
|
302
508
|
lang,
|
|
303
509
|
runtimeScript: manifest.runtimeScript,
|
|
304
510
|
alwaysLoadRuntime,
|
|
305
511
|
preloadChunks,
|
|
306
|
-
styles:
|
|
512
|
+
styles: routeStyles,
|
|
307
513
|
hasIslands,
|
|
514
|
+
hasSuspense: true,
|
|
308
515
|
})
|
|
309
516
|
const splitAt = shell.indexOf('\0')
|
|
310
517
|
const headHtml = shell.slice(0, splitAt)
|
|
311
518
|
const tailHtml = shell.slice(splitAt + 1)
|
|
312
|
-
const encoder = new TextEncoder()
|
|
313
519
|
|
|
314
520
|
const stream = new ReadableStream<Uint8Array>({
|
|
315
521
|
async start(controller) {
|
|
316
|
-
controller.enqueue(
|
|
522
|
+
controller.enqueue(textEncoder.encode(headHtml + body))
|
|
317
523
|
await Promise.all(
|
|
318
524
|
rctx.pending.map(async (chunk) => {
|
|
319
525
|
const resolved = await chunk.promise
|
|
320
|
-
controller.enqueue(
|
|
526
|
+
controller.enqueue(textEncoder.encode(streamChunkScript(chunk.id, resolved)))
|
|
321
527
|
}),
|
|
322
528
|
)
|
|
323
|
-
controller.enqueue(
|
|
529
|
+
controller.enqueue(textEncoder.encode(tailHtml))
|
|
324
530
|
controller.close()
|
|
325
531
|
},
|
|
326
532
|
})
|
|
327
533
|
|
|
328
|
-
|
|
329
|
-
cookieStore.applyTo(headers)
|
|
330
|
-
if (security !== false)
|
|
331
|
-
applySecurityHeaders(headers, security)
|
|
332
|
-
return new Response(stream, { status: 200, headers })
|
|
534
|
+
return new Response(stream, { status: 200, headers: { ...selectHtmlHeaders(hasIslands, true) } })
|
|
333
535
|
}
|
|
334
536
|
|
|
335
537
|
let html = renderDocument({
|
|
336
538
|
body,
|
|
337
539
|
head: collectedHead,
|
|
338
|
-
headTags:
|
|
540
|
+
headTags: routeHeadTags,
|
|
339
541
|
lang,
|
|
340
542
|
runtimeScript: manifest.runtimeScript,
|
|
341
543
|
alwaysLoadRuntime,
|
|
342
544
|
preloadChunks,
|
|
343
|
-
styles:
|
|
545
|
+
styles: routeStyles,
|
|
344
546
|
hasIslands,
|
|
345
547
|
})
|
|
346
548
|
|
|
347
549
|
for (let i = 0; i < htmlTransformers.length; i++)
|
|
348
550
|
html = await htmlTransformers[i]!(html, ctx)
|
|
349
551
|
|
|
350
|
-
|
|
351
|
-
cookieStore.applyTo(headers)
|
|
352
|
-
if (security !== false)
|
|
353
|
-
applySecurityHeaders(headers, security)
|
|
354
|
-
return new Response(html, { status: 200, headers })
|
|
552
|
+
return compressedHtmlResponse(html, 200, selectHtmlHeaders(hasIslands, false), ctx.request, compressCache)
|
|
355
553
|
}
|
|
356
554
|
|
|
357
555
|
const rootLayoutFile = manifest.routes.find(r => r.layouts.length > 0)?.layouts[0]
|
|
358
556
|
const rootLayoutMod = rootLayoutFile !== undefined ? modules[rootLayoutFile] as LoadedLayoutModule | undefined : undefined
|
|
557
|
+
const fallbackStyles = manifest.globalStyles ?? manifest.styles
|
|
359
558
|
|
|
360
559
|
async function renderError(error: unknown, cookieStore: CookieStore, url?: URL): Promise<Response> {
|
|
361
560
|
if (errorMod !== undefined) {
|
|
@@ -366,10 +565,10 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
366
565
|
inner = ssrChild(await rootLayoutMod.default({ children: raw(inner), url: url ?? new URL('http://localhost/500'), params: {}, locals: {} }) as Html)
|
|
367
566
|
return inner
|
|
368
567
|
})
|
|
369
|
-
const html = renderDocument({ body, head: renderCollectedHead(rctx), headTags: manifest.headTags, styles:
|
|
370
|
-
return finalizeResponse(new Response(html, { status: 500, headers: { 'content-type': 'text/html; charset=utf-8' } }), cookieStore,
|
|
568
|
+
const html = renderDocument({ body, head: renderCollectedHead(rctx), headTags: manifest.headTags, styles: fallbackStyles, runtimeScript: manifest.runtimeScript, alwaysLoadRuntime, lang })
|
|
569
|
+
return finalizeResponse(new Response(html, { status: 500, headers: { 'content-type': 'text/html; charset=utf-8' } }), cookieStore, securityEntries)
|
|
371
570
|
}
|
|
372
|
-
return finalizeResponse(new Response('Internal Server Error', { status: 500 }), cookieStore,
|
|
571
|
+
return finalizeResponse(new Response('Internal Server Error', { status: 500 }), cookieStore, securityEntries)
|
|
373
572
|
}
|
|
374
573
|
|
|
375
574
|
async function renderNotFound(cookieStore: CookieStore, url?: URL): Promise<Response> {
|
|
@@ -382,43 +581,27 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
382
581
|
inner = ssrChild(await rootLayoutMod.default({ children: raw(inner), url: url ?? new URL('http://localhost/404'), params: {}, locals: {} }) as Html)
|
|
383
582
|
return inner
|
|
384
583
|
})
|
|
385
|
-
const html = renderDocument({ body, head: renderCollectedHead(rctx), headTags: manifest.headTags, styles:
|
|
386
|
-
return finalizeResponse(new Response(html, { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }), cookieStore,
|
|
584
|
+
const html = renderDocument({ body, head: renderCollectedHead(rctx), headTags: manifest.headTags, styles: fallbackStyles, runtimeScript: manifest.runtimeScript, alwaysLoadRuntime, lang })
|
|
585
|
+
return finalizeResponse(new Response(html, { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }), cookieStore, securityEntries)
|
|
387
586
|
}
|
|
388
|
-
return finalizeResponse(new Response('Not Found', { status: 404 }), cookieStore,
|
|
587
|
+
return finalizeResponse(new Response('Not Found', { status: 404 }), cookieStore, securityEntries)
|
|
389
588
|
}
|
|
390
589
|
|
|
391
590
|
async function handle(request: Request): Promise<Response> {
|
|
392
591
|
const pathname = new URL(request.url).pathname
|
|
393
592
|
|
|
394
593
|
// 1. Static client assets
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
headers: {
|
|
400
|
-
'content-type': asset.type,
|
|
401
|
-
'cache-control': 'public, max-age=31536000, immutable',
|
|
402
|
-
},
|
|
403
|
-
})
|
|
594
|
+
if (request.method === 'GET' || request.method === 'HEAD') {
|
|
595
|
+
const asset = assetMap.get(pathname)
|
|
596
|
+
if (asset !== undefined)
|
|
597
|
+
return serveAsset(request, pathname, asset)
|
|
404
598
|
}
|
|
405
599
|
|
|
406
600
|
// 1b. Static public/ files (no-cache in dev so edits/plugins never get stuck in browser cache)
|
|
407
601
|
if (request.method === 'GET' || request.method === 'HEAD') {
|
|
408
602
|
const pub = publicMap.get(pathname)
|
|
409
|
-
if (pub !== undefined)
|
|
410
|
-
|
|
411
|
-
if (request.headers.get('if-none-match') === pub.etag)
|
|
412
|
-
return new Response(null, { status: 304, headers: { 'etag': pub.etag, 'cache-control': cacheControl } })
|
|
413
|
-
return new Response(request.method === 'HEAD' ? null : toResponseBody(pub.body), {
|
|
414
|
-
status: 200,
|
|
415
|
-
headers: {
|
|
416
|
-
'content-type': pub.type,
|
|
417
|
-
'etag': pub.etag,
|
|
418
|
-
'cache-control': cacheControl,
|
|
419
|
-
},
|
|
420
|
-
})
|
|
421
|
-
}
|
|
603
|
+
if (pub !== undefined)
|
|
604
|
+
return servePublic(request, pathname, pub)
|
|
422
605
|
}
|
|
423
606
|
|
|
424
607
|
// 2. Server actions (POST /_kay/action/<id>) — run global plugin middlewares first so ctx.locals (e.g. auth user) is populated
|
|
@@ -440,7 +623,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
440
623
|
}
|
|
441
624
|
if (globalMiddlewares.length === 0) {
|
|
442
625
|
const res = await runAction()
|
|
443
|
-
return finalizeResponse(res, cookieStore,
|
|
626
|
+
return finalizeResponse(res, cookieStore, securityEntries)
|
|
444
627
|
}
|
|
445
628
|
let index = -1
|
|
446
629
|
const dispatch = async (i: number): Promise<Response> => {
|
|
@@ -452,23 +635,21 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
452
635
|
return runAction()
|
|
453
636
|
}
|
|
454
637
|
const res = await dispatch(0)
|
|
455
|
-
return finalizeResponse(res, cookieStore,
|
|
638
|
+
return finalizeResponse(res, cookieStore, securityEntries)
|
|
456
639
|
}
|
|
457
640
|
}
|
|
458
641
|
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
return new Response(pre, { status: 200, headers })
|
|
467
|
-
}
|
|
642
|
+
const hasActionErrorFlash = (request.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
|
|
643
|
+
|
|
644
|
+
// 3. Prerendered static HTML (safe even when plugins add routes or build-time transformHtml!)
|
|
645
|
+
if (!hasActionErrorFlash && (request.method === 'GET' || request.method === 'HEAD')) {
|
|
646
|
+
const pre = fastPrerenderedMap.get(pathname)
|
|
647
|
+
if (pre !== undefined)
|
|
648
|
+
return servePrerendered(request, pathname, pre)
|
|
468
649
|
}
|
|
469
650
|
|
|
470
651
|
// 4. Ultra-fast static route path
|
|
471
|
-
if (request.method === 'GET') {
|
|
652
|
+
if (!hasActionErrorFlash && (request.method === 'GET' || request.method === 'HEAD')) {
|
|
472
653
|
const fast = fastStaticPages.get(pathname)
|
|
473
654
|
if (fast !== undefined)
|
|
474
655
|
return fast(request)
|
|
@@ -477,6 +658,18 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
477
658
|
// 5. Full Router + Plugin Rewrites + Plugin Routes + Middleware + Streaming/Head/Error pipeline
|
|
478
659
|
const { ctx, cookieStore } = makeRequestContext(request, {})
|
|
479
660
|
|
|
661
|
+
// Hydrate & clear one-shot progressive form validation flash cookie
|
|
662
|
+
if (hasActionErrorFlash && request.method === 'GET') {
|
|
663
|
+
const rawFlash = ctx.cookies.get(ACTION_ERROR_COOKIE)
|
|
664
|
+
if (rawFlash !== undefined) {
|
|
665
|
+
try {
|
|
666
|
+
ctx.locals.actionError = JSON.parse(rawFlash) as ActionErrorFlash
|
|
667
|
+
}
|
|
668
|
+
catch {}
|
|
669
|
+
ctx.cookies.delete(ACTION_ERROR_COOKIE)
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
|
|
480
673
|
// Apply plugin URL rewrites (e.g. @kayjs/i18n stripping /fr prefix and setting ctx.locals.locale)
|
|
481
674
|
let effectivePath = pathname
|
|
482
675
|
for (let i = 0; i < pluginRewrites.length; i++) {
|
|
@@ -492,21 +685,23 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
492
685
|
const methodHandler = pluginMatch.data.get(request.method.toUpperCase()) ?? pluginMatch.data.get('ALL')
|
|
493
686
|
if (methodHandler !== undefined) {
|
|
494
687
|
ctx.params = pluginMatch.params
|
|
688
|
+
let res: Response
|
|
495
689
|
if (globalMiddlewares.length === 0) {
|
|
496
|
-
|
|
497
|
-
return finalizeResponse(res, cookieStore, security)
|
|
690
|
+
res = await methodHandler(ctx)
|
|
498
691
|
}
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
692
|
+
else {
|
|
693
|
+
let index = -1
|
|
694
|
+
const dispatch = async (i: number): Promise<Response> => {
|
|
695
|
+
if (i <= index)
|
|
696
|
+
throw new Error('kay: middleware called next() multiple times')
|
|
697
|
+
index = i
|
|
698
|
+
if (i < globalMiddlewares.length)
|
|
699
|
+
return globalMiddlewares[i]!(ctx, () => dispatch(i + 1))
|
|
700
|
+
return methodHandler(ctx)
|
|
701
|
+
}
|
|
702
|
+
res = await dispatch(0)
|
|
507
703
|
}
|
|
508
|
-
|
|
509
|
-
return finalizeResponse(res, cookieStore, security)
|
|
704
|
+
return finalizeResponse(await maybeCompressResponse(res, request, compressCache), cookieStore, securityEntries)
|
|
510
705
|
}
|
|
511
706
|
}
|
|
512
707
|
|
|
@@ -528,10 +723,10 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
528
723
|
index = i
|
|
529
724
|
if (i < allMiddlewares.length)
|
|
530
725
|
return allMiddlewares[i]!(ctx, () => dispatch(i + 1))
|
|
531
|
-
return renderCompiledRoute(route, ctx
|
|
726
|
+
return renderCompiledRoute(route, ctx)
|
|
532
727
|
}
|
|
533
728
|
const res = await dispatch(0)
|
|
534
|
-
return finalizeResponse(res, cookieStore,
|
|
729
|
+
return finalizeResponse(res, cookieStore, securityEntries)
|
|
535
730
|
}
|
|
536
731
|
catch (error) {
|
|
537
732
|
return renderError(error, cookieStore, ctx.url)
|
|
@@ -539,47 +734,30 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
539
734
|
}
|
|
540
735
|
|
|
541
736
|
function serve(port = 3000) {
|
|
542
|
-
const routes: Record<string,
|
|
737
|
+
const routes: Record<string, (req: Request) => Response | Promise<Response>> = {}
|
|
543
738
|
|
|
544
|
-
for (const [path, asset] of assetMap)
|
|
545
|
-
|
|
546
|
-
'content-type': asset.type,
|
|
547
|
-
'cache-control': 'public, max-age=31536000, immutable',
|
|
548
|
-
}
|
|
549
|
-
routes[path] = typeof asset.body === 'string'
|
|
550
|
-
? () => new Response(Bun.file(asset.body as string), { status: 200, headers })
|
|
551
|
-
: new Response(asset.body, { status: 200, headers })
|
|
552
|
-
}
|
|
739
|
+
for (const [path, asset] of assetMap)
|
|
740
|
+
routes[path] = req => serveAsset(req, path, asset)
|
|
553
741
|
|
|
554
|
-
const pubCache = process.env.KAY_DEV === '1' ? 'no-cache' : 'public, max-age=3600'
|
|
555
742
|
for (const [path, pub] of publicMap) {
|
|
556
|
-
if (!(path in routes))
|
|
557
|
-
|
|
558
|
-
'content-type': pub.type,
|
|
559
|
-
'etag': pub.etag,
|
|
560
|
-
'cache-control': pubCache,
|
|
561
|
-
}
|
|
562
|
-
routes[path] = (req: Request) => {
|
|
563
|
-
if (req.headers.get('if-none-match') === pub.etag)
|
|
564
|
-
return new Response(null, { status: 304, headers: { 'etag': pub.etag, 'cache-control': pubCache } })
|
|
565
|
-
const body = typeof pub.body === 'string' ? Bun.file(pub.body) : pub.body
|
|
566
|
-
return new Response(req.method === 'HEAD' ? null : body, { status: 200, headers })
|
|
567
|
-
}
|
|
568
|
-
}
|
|
743
|
+
if (!(path in routes))
|
|
744
|
+
routes[path] = req => servePublic(req, path, pub)
|
|
569
745
|
}
|
|
570
746
|
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
routes[path] = new Response(pre, { status: 200, headers })
|
|
747
|
+
for (const [path, pre] of fastPrerenderedMap) {
|
|
748
|
+
if (!(path in routes)) {
|
|
749
|
+
routes[path] = req => (req.method === 'GET' || req.method === 'HEAD') && !(req.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
|
|
750
|
+
? servePrerendered(req, path, pre)
|
|
751
|
+
: handle(req)
|
|
577
752
|
}
|
|
578
753
|
}
|
|
579
754
|
|
|
580
755
|
for (const [path, handler] of fastStaticPages) {
|
|
581
|
-
if (!(path in routes))
|
|
582
|
-
routes[path] =
|
|
756
|
+
if (!(path in routes)) {
|
|
757
|
+
routes[path] = req => (req.method === 'GET' || req.method === 'HEAD') && !(req.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
|
|
758
|
+
? handler(req)
|
|
759
|
+
: handle(req)
|
|
760
|
+
}
|
|
583
761
|
}
|
|
584
762
|
|
|
585
763
|
return Bun.serve({
|
|
@@ -593,6 +771,87 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
593
771
|
return { handle, serve }
|
|
594
772
|
}
|
|
595
773
|
|
|
774
|
+
function createStaticDirServer(
|
|
775
|
+
outDir: string,
|
|
776
|
+
assetPrefix: string,
|
|
777
|
+
securityEntries: readonly [string, string][],
|
|
778
|
+
compressEnabled: boolean,
|
|
779
|
+
): KayApp {
|
|
780
|
+
const cleanPrefix = `${assetPrefix.replace(/\/$/, '')}/`
|
|
781
|
+
const absRoot = resolve(outDir)
|
|
782
|
+
const compressCache = compressEnabled ? new CompressionCache() : undefined
|
|
783
|
+
|
|
784
|
+
function resolveStaticFile(pathname: string): string | undefined {
|
|
785
|
+
let decoded: string
|
|
786
|
+
try {
|
|
787
|
+
decoded = decodeURIComponent(pathname)
|
|
788
|
+
}
|
|
789
|
+
catch {
|
|
790
|
+
return undefined
|
|
791
|
+
}
|
|
792
|
+
const rel = decoded.replace(/^\/+/, '').replace(/\/+$/, '')
|
|
793
|
+
const candidates = rel === ''
|
|
794
|
+
? ['index.html']
|
|
795
|
+
: [rel, `${rel}.html`, `${rel}/index.html`]
|
|
796
|
+
for (const c of candidates) {
|
|
797
|
+
const abs = resolve(absRoot, c)
|
|
798
|
+
if (abs !== absRoot && !abs.startsWith(`${absRoot}/`) && !abs.startsWith(`${absRoot}\\`))
|
|
799
|
+
continue
|
|
800
|
+
if (existsSync(abs) && statSync(abs).isFile())
|
|
801
|
+
return abs
|
|
802
|
+
}
|
|
803
|
+
return undefined
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
const initHeaders = (): Headers => {
|
|
807
|
+
const headers = new Headers()
|
|
808
|
+
for (let i = 0; i < securityEntries.length; i++)
|
|
809
|
+
headers.set(securityEntries[i]![0], securityEntries[i]![1])
|
|
810
|
+
return headers
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
const handle = async (req: Request): Promise<Response> => {
|
|
814
|
+
if (req.method !== 'GET' && req.method !== 'HEAD')
|
|
815
|
+
return new Response('Method Not Allowed', { status: 405 })
|
|
816
|
+
|
|
817
|
+
const url = new URL(req.url)
|
|
818
|
+
const filePath = resolveStaticFile(url.pathname)
|
|
819
|
+
if (filePath === undefined) {
|
|
820
|
+
const notFoundPath = join(absRoot, '404.html')
|
|
821
|
+
if (existsSync(notFoundPath) && statSync(notFoundPath).isFile()) {
|
|
822
|
+
const headers = initHeaders()
|
|
823
|
+
headers.set('content-type', 'text/html; charset=utf-8')
|
|
824
|
+
return new Response(req.method === 'HEAD' ? null : Bun.file(notFoundPath), { status: 404, headers })
|
|
825
|
+
}
|
|
826
|
+
return new Response('Not Found', { status: 404 })
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
const st = statSync(filePath)
|
|
830
|
+
const etag = `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
|
|
831
|
+
const isImmutable = url.pathname.startsWith(cleanPrefix)
|
|
832
|
+
const cacheControl = isImmutable ? 'public, max-age=31536000, immutable' : 'public, max-age=0, must-revalidate'
|
|
833
|
+
const headers = initHeaders()
|
|
834
|
+
headers.set('content-type', MIME[extname(filePath).toLowerCase()] ?? 'application/octet-stream')
|
|
835
|
+
headers.set('cache-control', cacheControl)
|
|
836
|
+
headers.set('etag', etag)
|
|
837
|
+
|
|
838
|
+
if (req.headers.get('if-none-match') === etag)
|
|
839
|
+
return new Response(null, { status: 304, headers })
|
|
840
|
+
|
|
841
|
+
const res = new Response(req.method === 'HEAD' ? null : Bun.file(filePath), { status: 200, headers })
|
|
842
|
+
if (!compressEnabled || req.method === 'HEAD')
|
|
843
|
+
return res
|
|
844
|
+
return maybeCompressResponse(res, req, compressCache)
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
return {
|
|
848
|
+
handle,
|
|
849
|
+
serve(port = 3000) {
|
|
850
|
+
return Bun.serve({ port, fetch: handle })
|
|
851
|
+
},
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
|
|
596
855
|
export async function createServer(options: ServerOptions): Promise<KayApp> {
|
|
597
856
|
const root = resolve(options.root)
|
|
598
857
|
const fileConfig = await loadConfig(root)
|
|
@@ -601,28 +860,43 @@ export async function createServer(options: ServerOptions): Promise<KayApp> {
|
|
|
601
860
|
const clientDir = join(outDir, 'client')
|
|
602
861
|
const manifestPath = join(outDir, 'manifest.json')
|
|
603
862
|
|
|
604
|
-
if (!existsSync(manifestPath))
|
|
863
|
+
if (!existsSync(manifestPath)) {
|
|
864
|
+
if (existsSync(outDir) && readdirSync(outDir).length > 0) {
|
|
865
|
+
const securityOpt = options.security ?? fileConfig.security
|
|
866
|
+
const securityEntries = securityOpt === false ? [] : buildSecurityHeaderEntries(securityOpt ?? {})
|
|
867
|
+
return createStaticDirServer(
|
|
868
|
+
outDir,
|
|
869
|
+
options.assetPrefix ?? fileConfig.assetPrefix ?? '/_kay',
|
|
870
|
+
securityEntries,
|
|
871
|
+
(options.compress ?? fileConfig.compress) !== false,
|
|
872
|
+
)
|
|
873
|
+
}
|
|
605
874
|
throw new Error(`kay server: missing ${manifestPath}. Run build() first.`)
|
|
875
|
+
}
|
|
606
876
|
|
|
607
877
|
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as BuildManifest
|
|
608
878
|
const modules: Record<string, unknown> = {}
|
|
609
879
|
const assets: Record<string, EmbeddedBody> = {}
|
|
610
880
|
const publicAssets: Record<string, EmbeddedBody> = {}
|
|
611
|
-
const
|
|
612
|
-
const
|
|
881
|
+
const publicEtags: Record<string, string> = {}
|
|
882
|
+
const prerenderedFiles: Record<string, string> = {}
|
|
613
883
|
const srcPublicDir = resolve(root, fileConfig.publicDir ?? 'public')
|
|
614
884
|
|
|
885
|
+
// Store file paths only (zero-copy Bun.file() serving, zero startup RAM bloat!)
|
|
615
886
|
for (const rel of manifest.assets) {
|
|
616
887
|
const abs = join(clientDir, rel)
|
|
617
888
|
if (existsSync(abs))
|
|
618
|
-
assets[rel] =
|
|
889
|
+
assets[rel] = abs
|
|
619
890
|
}
|
|
620
891
|
|
|
621
892
|
for (const rel of manifest.publicFiles ?? []) {
|
|
622
893
|
const outAbs = join(outDir, 'public', rel)
|
|
623
894
|
const abs = existsSync(outAbs) ? outAbs : join(srcPublicDir, rel)
|
|
624
|
-
if (existsSync(abs))
|
|
625
|
-
publicAssets[rel] =
|
|
895
|
+
if (existsSync(abs)) {
|
|
896
|
+
publicAssets[rel] = abs
|
|
897
|
+
const st = statSync(abs)
|
|
898
|
+
publicEtags[rel] = `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
|
|
899
|
+
}
|
|
626
900
|
}
|
|
627
901
|
|
|
628
902
|
const loadStamp = Date.now()
|
|
@@ -639,7 +913,7 @@ export async function createServer(options: ServerOptions): Promise<KayApp> {
|
|
|
639
913
|
for (const [, relHtml] of Object.entries(r.prerendered)) {
|
|
640
914
|
const abs = join(outDir, relHtml)
|
|
641
915
|
if (existsSync(abs))
|
|
642
|
-
|
|
916
|
+
prerenderedFiles[relHtml] = abs
|
|
643
917
|
}
|
|
644
918
|
}
|
|
645
919
|
}
|
|
@@ -652,11 +926,14 @@ export async function createServer(options: ServerOptions): Promise<KayApp> {
|
|
|
652
926
|
modules,
|
|
653
927
|
assets,
|
|
654
928
|
publicAssets,
|
|
655
|
-
|
|
929
|
+
publicEtags,
|
|
930
|
+
prerendered: {},
|
|
931
|
+
prerenderedFiles,
|
|
656
932
|
assetPrefix: options.assetPrefix ?? fileConfig.assetPrefix,
|
|
657
933
|
lang: options.lang ?? fileConfig.lang,
|
|
658
934
|
security: options.security ?? fileConfig.security,
|
|
659
935
|
trustedOrigins: options.trustedOrigins ?? fileConfig.trustedOrigins,
|
|
936
|
+
compress: options.compress ?? fileConfig.compress,
|
|
660
937
|
plugins,
|
|
661
938
|
})
|
|
662
939
|
}
|