@kayjs/kay 2.0.0-beta.2 → 2.0.0-beta.4
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/llms.txt +42 -0
- package/package.json +24 -13
- package/src/build/bundle.ts +15 -53
- package/src/build/client-plugin.ts +108 -0
- package/src/build/compile.ts +9 -44
- package/src/build/graph.ts +16 -3
- package/src/build/index.ts +45 -25
- package/src/build/islands.ts +28 -30
- package/src/build/manifest.ts +9 -4
- package/src/build/prerender.ts +15 -7
- package/src/build/report.ts +82 -13
- package/src/build/resolve.ts +6 -7
- package/src/build/routes.ts +12 -21
- package/src/build/server-entry.ts +38 -0
- package/src/cli/check.ts +49 -43
- package/src/cli/commands.ts +224 -0
- package/src/cli/index.ts +46 -302
- package/src/cli/new.ts +15 -509
- package/src/cli/upgrade-plugins.ts +168 -0
- package/src/cli/upgrade.ts +220 -0
- package/src/compiler/analyze.ts +319 -565
- package/src/compiler/ast.ts +39 -0
- package/src/compiler/data-keys.ts +233 -0
- package/src/compiler/dom.ts +18 -15
- package/src/compiler/interactivity.ts +174 -0
- package/src/compiler/mistakes.ts +19 -1
- package/src/compiler/server-only.ts +4 -1
- package/src/compiler/shared.ts +1 -1
- package/src/compiler/ssr.ts +28 -28
- package/src/context.ts +1 -1
- package/src/dev/index.ts +19 -46
- package/src/dom/extras.ts +43 -12
- package/src/dom/index.ts +25 -1
- package/src/index.ts +0 -13
- package/src/jsx-runtime.ts +1 -1
- package/src/plugins/config.ts +49 -0
- package/src/plugins/context.ts +8 -28
- package/src/plugins/index.ts +10 -385
- package/src/plugins/load.ts +61 -0
- package/src/plugins/order.ts +107 -0
- package/src/plugins/public.ts +6 -0
- package/src/plugins/services.ts +35 -0
- package/src/plugins/types.ts +193 -0
- package/src/server/action-registry.ts +78 -0
- package/src/server/action.ts +8 -2
- package/src/server/app-entry.ts +23 -0
- package/src/server/assets.ts +182 -0
- package/src/server/document.ts +204 -0
- package/src/server/errors.ts +125 -0
- package/src/server/http.ts +14 -0
- package/src/server/index.ts +66 -766
- package/src/server/lifecycle.ts +22 -0
- package/src/server/loader.ts +60 -85
- package/src/server/page.ts +107 -0
- package/src/server/plugin-host.ts +165 -0
- package/src/server/public.ts +15 -0
- package/src/server/request-scope.ts +22 -0
- package/src/server/security.ts +40 -1
- package/src/server/static-dir.ts +22 -3
- package/src/server/stream.ts +95 -0
- package/src/ssr/context.ts +25 -0
- package/src/ssr/index.ts +10 -7
- package/src/test/browser.ts +180 -0
- package/src/test/index.ts +25 -6
- package/templates/_shared/AGENTS.md +5 -0
- package/templates/_shared/CLAUDE.md +1 -0
- package/templates/_shared/public/robots.txt +2 -0
- package/templates/_shared/tsconfig.json +19 -0
- package/templates/app/.env.example +4 -0
- package/templates/app/kay.config.ts +11 -0
- package/templates/app/package.json +20 -0
- package/templates/app/src/auth.ts +14 -0
- package/templates/app/src/routes/_layout.tsx +32 -0
- package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
- package/templates/app/src/routes/dashboard/index.tsx +13 -0
- package/templates/app/src/routes/index.tsx +15 -0
- package/templates/app/src/routes/login.tsx +34 -0
- package/templates/app/src/styles/app.css +7 -0
- package/templates/blog/content/posts/welcome.md +9 -0
- package/templates/blog/kay.config.ts +23 -0
- package/templates/blog/package.json +21 -0
- package/templates/blog/src/posts.ts +26 -0
- package/templates/blog/src/routes/_layout.tsx +20 -0
- package/templates/blog/src/routes/blog/[slug].tsx +31 -0
- package/templates/blog/src/routes/index.tsx +29 -0
- package/templates/blog/src/styles/app.css +10 -0
- package/templates/fullstack/kay.config.ts +6 -0
- package/templates/fullstack/package.json +18 -0
- package/templates/fullstack/src/actions/greet.ts +19 -0
- package/templates/fullstack/src/components/Counter.tsx +10 -0
- package/templates/fullstack/src/components/GreetForm.tsx +26 -0
- package/templates/fullstack/src/routes/_layout.tsx +14 -0
- package/templates/fullstack/src/routes/api/health.ts +5 -0
- package/templates/fullstack/src/routes/index.tsx +13 -0
- package/templates/fullstack/src/styles/app.css +29 -0
- package/templates/minimal/kay.config.ts +6 -0
- package/templates/minimal/package.json +18 -0
- package/templates/minimal/src/components/Counter.tsx +10 -0
- package/templates/minimal/src/routes/_layout.tsx +14 -0
- package/templates/minimal/src/routes/index.tsx +11 -0
- package/templates/minimal/src/styles/app.css +22 -0
package/src/server/index.ts
CHANGED
|
@@ -5,25 +5,29 @@
|
|
|
5
5
|
// - <Head> collection + cancel-safe streaming <Suspense> (0-overhead fast path when unused)
|
|
6
6
|
// - Hybrid prerendered HTML serving + embedded single-executable mode
|
|
7
7
|
|
|
8
|
-
import type {
|
|
8
|
+
import type { RouteManifestEntry } from '../build/index'
|
|
9
9
|
import type { Html, HydrateStrategy } from '../jsx-runtime'
|
|
10
|
-
import type { DocumentHeadContext, KayPlugin, MiddlewareOptions, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI } from '../plugins/index'
|
|
11
|
-
import type { PendingChunk, RenderContext, SettledChunk } from '../ssr/context'
|
|
12
10
|
import type { DocumentOptions } from '../ssr/index'
|
|
13
|
-
import type { ActionErrorFlash
|
|
11
|
+
import type { ActionErrorFlash } from './action'
|
|
14
12
|
import type { CookieStore } from './cookies'
|
|
15
|
-
import type {
|
|
16
|
-
import type {
|
|
17
|
-
import {
|
|
18
|
-
import { extname, join } from 'node:path'
|
|
13
|
+
import type { EmbeddedServerConfig, KayApp, Middleware, RequestContext } from './http'
|
|
14
|
+
import type { LoadedLayoutModule, LoadedMiddlewareModule, LoadedPageModule } from './page'
|
|
15
|
+
import { join } from 'node:path'
|
|
19
16
|
import { createAppContext, getAppContext, resolvePlugins, runWithAppContext } from '../plugins/index'
|
|
20
|
-
import { createRenderContext, runWithRenderContext
|
|
17
|
+
import { createRenderContext, runWithRenderContext } from '../ssr/context'
|
|
21
18
|
import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
|
|
22
|
-
import { ACTION_ERROR_COOKIE, executeAction,
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
19
|
+
import { ACTION_ERROR_COOKIE, executeAction, isServerAction } from './action'
|
|
20
|
+
import { createActionRegistry } from './action-registry'
|
|
21
|
+
import { createAssets } from './assets'
|
|
22
|
+
import { CompressionCache, compressedHtmlResponse, maybeCompressResponse } from './compress'
|
|
23
|
+
import { createDocumentHooks, createHtmlHeaders, resolveRenderedIslands, withPluginHtmlCsp } from './document'
|
|
24
|
+
import { createErrorNotifier, createFallbackPages } from './errors'
|
|
25
|
+
import { applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, finalizeResponse, isNotFound, makeRequestContext, runChain, wantsJson } from './http'
|
|
26
|
+
import { allowedMethodsHeader, isPlainObject, mergedHeadTags, pickPageIslandProps, stripHeadBody } from './page'
|
|
27
|
+
import { allowedPluginMethodsHeader, createServerPluginHost } from './plugin-host'
|
|
25
28
|
import { Router } from './router'
|
|
26
|
-
import { buildSecurityHeaderEntries,
|
|
29
|
+
import { buildSecurityHeaderEntries, inlineStyleHashes, resolveHstsValue, verifyOrigin } from './security'
|
|
30
|
+
import { STREAM_TAIL_MARK, streamDocument } from './stream'
|
|
27
31
|
|
|
28
32
|
/**
|
|
29
33
|
* Request-scoped locals bag shared across middlewares, plugins, actions, layouts, and pages.
|
|
@@ -47,68 +51,9 @@ export type { SecurityHeadersOptions, TrustProxy } from './security'
|
|
|
47
51
|
export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
|
|
48
52
|
export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult, ValidationSuccess } from './standard-schema'
|
|
49
53
|
|
|
50
|
-
interface LoadedPageModule {
|
|
51
|
-
default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
|
|
52
|
-
load?: (ctx: RequestContext) => unknown | Promise<unknown>
|
|
53
|
-
clientData?: readonly string[] | ((data: unknown) => unknown) | undefined
|
|
54
|
-
csrf?: boolean | undefined
|
|
55
|
-
GET?: (ctx: RequestContext) => Response | Promise<Response>
|
|
56
|
-
POST?: (ctx: RequestContext) => Response | Promise<Response>
|
|
57
|
-
PUT?: (ctx: RequestContext) => Response | Promise<Response>
|
|
58
|
-
PATCH?: (ctx: RequestContext) => Response | Promise<Response>
|
|
59
|
-
DELETE?: (ctx: RequestContext) => Response | Promise<Response>
|
|
60
|
-
HEAD?: (ctx: RequestContext) => Response | Promise<Response>
|
|
61
|
-
OPTIONS?: (ctx: RequestContext) => Response | Promise<Response>
|
|
62
|
-
[key: string]: unknown
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
interface LoadedLayoutModule {
|
|
66
|
-
default: (props: { children: Html, url?: URL, params?: Record<string, string>, locals?: KayLocals }) => Html | string | Promise<Html | string>
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
interface LoadedMiddlewareModule {
|
|
70
|
-
default: Middleware
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
interface LoadedErrorModule {
|
|
74
|
-
default: (props: { error: unknown }) => Html | string | Promise<Html | string>
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
const HTTP_METHOD_EXPORTS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'] as const
|
|
78
|
-
|
|
79
|
-
const textEncoder = new TextEncoder()
|
|
80
|
-
// Where a streamed page's document splits: everything before it flushes first, resolved boundaries go in between.
|
|
81
|
-
const STREAM_TAIL_MARK = '<!--kay:stream-tail-->'
|
|
82
54
|
// Matches Bun.serve's 30 s idle timeout, which a streamed page turns off.
|
|
83
55
|
const DEFAULT_STREAM_TIMEOUT = 30_000
|
|
84
56
|
|
|
85
|
-
// A build file ready to serve: headers and compression key are fixed at startup, so a request only picks a variant.
|
|
86
|
-
interface ServedFile {
|
|
87
|
-
key: string
|
|
88
|
-
headers: Record<string, string>
|
|
89
|
-
/** Headers of the on-the-fly compressed variant; undefined when the file is never compressed here. */
|
|
90
|
-
compressedHeaders: Record<string, string> | undefined
|
|
91
|
-
body: BodyInit
|
|
92
|
-
read: () => Uint8Array<ArrayBuffer> | Promise<Uint8Array<ArrayBuffer>>
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
interface Sidecar {
|
|
96
|
-
body: BodyInit
|
|
97
|
-
headers: Record<string, string>
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
interface AssetEntry {
|
|
101
|
-
file: ServedFile
|
|
102
|
-
br: Sidecar | undefined
|
|
103
|
-
gz: Sidecar | undefined
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
interface PublicEntry {
|
|
107
|
-
file: ServedFile
|
|
108
|
-
etag: string
|
|
109
|
-
notModifiedHeaders: Record<string, string>
|
|
110
|
-
}
|
|
111
|
-
|
|
112
57
|
type FastHandler = (req: Request, remoteIp?: string, url?: URL) => Response | Promise<Response>
|
|
113
58
|
|
|
114
59
|
interface CompiledRoute {
|
|
@@ -122,155 +67,12 @@ interface CompiledRoute {
|
|
|
122
67
|
doc: DocumentOptions
|
|
123
68
|
}
|
|
124
69
|
|
|
125
|
-
interface PluginRouteDef {
|
|
126
|
-
handler: (ctx: RequestContext) => Response | Promise<Response>
|
|
127
|
-
csrf: boolean
|
|
128
|
-
trustedOrigins: Set<string> | undefined
|
|
129
|
-
trustProxy: TrustProxy
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
interface ScopedMiddleware {
|
|
133
|
-
mw: Middleware
|
|
134
|
-
scope: 'all' | 'dynamic' | string
|
|
135
|
-
}
|
|
136
|
-
|
|
137
70
|
const isRead = (request: Request): boolean => request.method === 'GET' || request.method === 'HEAD'
|
|
138
71
|
const isEventStream = (res: Response): boolean => (res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream')
|
|
139
72
|
const hasActionErrorCookie = (request: Request): boolean => (request.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
|
|
140
73
|
// A read the pre-rendered and fast static paths may answer: nothing to flash back to the page.
|
|
141
74
|
const isPlainRead = (request: Request): boolean => isRead(request) && !hasActionErrorCookie(request)
|
|
142
75
|
|
|
143
|
-
/** Runs `middlewares` in order around `last`; each calls `next` at most once. */
|
|
144
|
-
async function runChain(ctx: RequestContext, middlewares: readonly Middleware[], last: () => Response | Promise<Response>): Promise<Response> {
|
|
145
|
-
if (middlewares.length === 0)
|
|
146
|
-
return last()
|
|
147
|
-
let index = -1
|
|
148
|
-
const dispatch = async (i: number): Promise<Response> => {
|
|
149
|
-
if (i <= index)
|
|
150
|
-
throw new Error('kay: middleware called next() multiple times')
|
|
151
|
-
index = i
|
|
152
|
-
return i < middlewares.length ? middlewares[i]!(ctx, () => dispatch(i + 1)) : last()
|
|
153
|
-
}
|
|
154
|
-
return dispatch(0)
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
async function settleWithin(chunk: PendingChunk, deadlineMs: number, signal: AbortSignal): Promise<SettledChunk | undefined> {
|
|
158
|
-
if (signal.aborted)
|
|
159
|
-
return undefined
|
|
160
|
-
const remaining = Math.max(0, deadlineMs - Date.now())
|
|
161
|
-
let timer: ReturnType<typeof setTimeout> | undefined
|
|
162
|
-
const abortedOrTimedOut = new Promise<SettledChunk | undefined>((resolve) => {
|
|
163
|
-
const onAbort = () => resolve(undefined)
|
|
164
|
-
signal.addEventListener('abort', onAbort, { once: true })
|
|
165
|
-
timer = setTimeout(() => {
|
|
166
|
-
signal.removeEventListener('abort', onAbort)
|
|
167
|
-
const error = new Error(`<Suspense> boundary ${chunk.id} did not resolve within ${remaining} ms`)
|
|
168
|
-
resolve({ html: chunk.renderError(error), error })
|
|
169
|
-
}, remaining)
|
|
170
|
-
})
|
|
171
|
-
try {
|
|
172
|
-
return await Promise.race([chunk.settled, abortedOrTimedOut])
|
|
173
|
-
}
|
|
174
|
-
finally {
|
|
175
|
-
clearTimeout(timer)
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
function mergedHeadTags(manifest: BuildManifest, entry: RouteManifestEntry): string[] | undefined {
|
|
180
|
-
return entry.headTags !== undefined && entry.headTags.length > 0
|
|
181
|
-
? [...(manifest.headTags ?? []), ...entry.headTags]
|
|
182
|
-
: manifest.headTags
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
function allowedMethodsHeader(mod: LoadedPageModule): string {
|
|
186
|
-
const allowed = new Set<string>()
|
|
187
|
-
if (typeof mod.default === 'function') {
|
|
188
|
-
allowed.add('GET')
|
|
189
|
-
allowed.add('HEAD')
|
|
190
|
-
}
|
|
191
|
-
for (const m of HTTP_METHOD_EXPORTS) {
|
|
192
|
-
if (typeof mod[m] === 'function')
|
|
193
|
-
allowed.add(m)
|
|
194
|
-
}
|
|
195
|
-
if (allowed.has('GET'))
|
|
196
|
-
allowed.add('HEAD')
|
|
197
|
-
return [...allowed].join(', ')
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
function allowedPluginMethodsHeader(methods: ReadonlyMap<string, PluginRouteDef>): string {
|
|
201
|
-
const allowed = new Set<string>()
|
|
202
|
-
for (const m of methods.keys()) {
|
|
203
|
-
if (m === 'ALL')
|
|
204
|
-
continue
|
|
205
|
-
allowed.add(m)
|
|
206
|
-
}
|
|
207
|
-
if (allowed.has('GET'))
|
|
208
|
-
allowed.add('HEAD')
|
|
209
|
-
return [...allowed].join(', ')
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
async function cancelBodyQuietly(body: ReadableStream<Uint8Array>): Promise<void> {
|
|
213
|
-
try {
|
|
214
|
-
await body.cancel()
|
|
215
|
-
}
|
|
216
|
-
catch {}
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
function stripHeadBody(res: Response): Response {
|
|
220
|
-
if (res.body !== null)
|
|
221
|
-
void cancelBodyQuietly(res.body)
|
|
222
|
-
return new Response(null, { status: res.status, statusText: res.statusText, headers: res.headers })
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
function isPlainObject(v: unknown): v is Record<string, unknown> {
|
|
226
|
-
return typeof v === 'object' && v !== null && !Array.isArray(v)
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
function pickObjectKeys(obj: Record<string, unknown>, keys: readonly string[]): Record<string, unknown> | undefined {
|
|
230
|
-
if (keys.length === 0)
|
|
231
|
-
return undefined
|
|
232
|
-
const picked: Record<string, unknown> = {}
|
|
233
|
-
let count = 0
|
|
234
|
-
for (const k of keys) {
|
|
235
|
-
if (Object.hasOwn(obj, k)) {
|
|
236
|
-
Object.defineProperty(picked, k, { value: obj[k], enumerable: true, writable: true, configurable: true })
|
|
237
|
-
count++
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
return count > 0 ? picked : undefined
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
function pickPageIslandProps(data: unknown, entry: RouteManifestEntry, mod: LoadedPageModule): Record<string, unknown> {
|
|
244
|
-
if (data === undefined)
|
|
245
|
-
return {}
|
|
246
|
-
if (typeof mod.clientData === 'function') {
|
|
247
|
-
const subset = mod.clientData(data)
|
|
248
|
-
return subset === undefined ? {} : { data: subset }
|
|
249
|
-
}
|
|
250
|
-
if (Array.isArray(mod.clientData)) {
|
|
251
|
-
if (!isPlainObject(data))
|
|
252
|
-
return {}
|
|
253
|
-
const subset = pickObjectKeys(data, mod.clientData)
|
|
254
|
-
return subset === undefined ? {} : { data: subset }
|
|
255
|
-
}
|
|
256
|
-
if (entry.islandDataKeys !== undefined) {
|
|
257
|
-
if (entry.islandDataKeys.length === 0)
|
|
258
|
-
return {}
|
|
259
|
-
if (isPlainObject(data)) {
|
|
260
|
-
const subset = pickObjectKeys(data, entry.islandDataKeys)
|
|
261
|
-
return subset === undefined ? {} : { data: subset }
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
return { data }
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
function middlewareAppliesToPath(scope: ScopedMiddleware['scope'], path: string, isStaticFast: boolean): boolean {
|
|
268
|
-
if (scope === 'all')
|
|
269
|
-
return true
|
|
270
|
-
if (scope === 'dynamic')
|
|
271
|
-
return !isStaticFast
|
|
272
|
-
return path === scope || path.startsWith(scope.endsWith('/') ? scope : `${scope}/`)
|
|
273
|
-
}
|
|
274
76
|
|
|
275
77
|
export async function createServerFromEmbedded(config: EmbeddedServerConfig): Promise<KayApp> {
|
|
276
78
|
const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered = {}, prerenderedFiles = {}, lang = 'en', security } = config
|
|
@@ -289,12 +91,9 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
289
91
|
const parentAppCtx = getAppContext()
|
|
290
92
|
|
|
291
93
|
const alwaysLoadRuntime = plugins.some(p => Boolean(p.clientEntry))
|
|
292
|
-
const
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
const htmlTransformers = plugins
|
|
296
|
-
.map(p => p.transformHtml)
|
|
297
|
-
.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
|
|
298
97
|
|
|
299
98
|
const securityEntries = buildSecurityHeaderEntries(security)
|
|
300
99
|
const securityRecord: Record<string, string> = Object.fromEntries(securityEntries)
|
|
@@ -307,56 +106,15 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
307
106
|
status: 500,
|
|
308
107
|
headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord },
|
|
309
108
|
})
|
|
310
|
-
|
|
311
|
-
// HTML headers, one set per (dynamic, islands, suspense) combination: the CSP only gains the hashes a page needs.
|
|
312
|
-
const baseCsp = resolveCspPolicy(security)
|
|
313
|
-
const htmlHeaderSets: Record<string, string>[] = []
|
|
314
|
-
for (let i = 0; i < 8; i++) {
|
|
315
|
-
const isDynamic = (i & 4) !== 0
|
|
316
|
-
const hasIslands = (i & 2) !== 0
|
|
317
|
-
const hasSuspense = (i & 1) !== 0
|
|
318
|
-
const headers: Record<string, string> = { 'content-type': 'text/html; charset=utf-8', ...securityRecord }
|
|
319
|
-
if (isDynamic)
|
|
320
|
-
headers['cache-control'] = 'private'
|
|
321
|
-
if (baseCsp !== undefined && (hasIslands || hasSuspense)) {
|
|
322
|
-
headers['content-security-policy'] = withCspHashes(baseCsp, {
|
|
323
|
-
styleHashes: [...(hasIslands ? [KAY_ISLAND_STYLE_HASH] : []), ...(hasSuspense ? [KAY_SUSPENSE_STYLE_HASH] : [])],
|
|
324
|
-
scriptHashes: hasSuspense ? [KAY_STREAM_SCRIPT_HASH] : [],
|
|
325
|
-
})
|
|
326
|
-
}
|
|
327
|
-
htmlHeaderSets.push(headers)
|
|
328
|
-
}
|
|
329
|
-
const htmlHeaders = (hasIslands: boolean, hasSuspense: boolean, isDynamic: boolean): Record<string, string> =>
|
|
330
|
-
htmlHeaderSets[(isDynamic ? 4 : 0) | (hasIslands ? 2 : 0) | (hasSuspense ? 1 : 0)]!
|
|
109
|
+
const htmlHeaders = createHtmlHeaders(security, securityRecord)
|
|
331
110
|
|
|
332
111
|
const compressEnabled = config.compress ?? !isDev
|
|
333
112
|
const compressCache = compressEnabled ? new CompressionCache() : undefined
|
|
334
|
-
const varyEncoding: Record<string, string> = compressCache !== undefined ? { vary: 'Accept-Encoding' } : {}
|
|
335
|
-
|
|
336
|
-
const toBody = (body: EmbeddedBody): BodyInit => typeof body === 'string' ? Bun.file(body) : body
|
|
337
|
-
const readBody = async (body: EmbeddedBody): Promise<Uint8Array<ArrayBuffer>> => typeof body === 'string' ? new Uint8Array(await Bun.file(body).arrayBuffer()) : body
|
|
338
|
-
const builtFile = (key: string, source: EmbeddedBody, headers: Record<string, string>, compressedHeaders: Record<string, string> | undefined): ServedFile =>
|
|
339
|
-
({ key, headers, compressedHeaders, body: toBody(source), read: () => readBody(source) })
|
|
340
|
-
|
|
341
|
-
const publicMap = new Map<string, PublicEntry>()
|
|
342
|
-
const publicCacheControl = isDev ? 'no-cache' : 'public, max-age=3600'
|
|
343
|
-
|
|
344
|
-
const registerPublicEntry = (rel: string, body: EmbeddedBody, explicitEtag?: string): void => {
|
|
345
|
-
const cleanRel = rel.replace(/^\/+/, '')
|
|
346
|
-
const etag = explicitEtag ?? `W/"${Bun.hash(typeof body === 'string' ? cleanRel : body).toString(36)}"`
|
|
347
|
-
const type = MIME[extname(cleanRel).toLowerCase()] ?? 'application/octet-stream'
|
|
348
|
-
const hasVary = compressCache !== undefined && isCompressibleType(type)
|
|
349
|
-
const validators = { etag, 'cache-control': publicCacheControl, ...(hasVary ? { vary: 'Accept-Encoding' } : {}), ...nosniffHeader }
|
|
350
|
-
const headers = { 'content-type': type, ...validators }
|
|
351
|
-
publicMap.set(`/${cleanRel}`, {
|
|
352
|
-
etag,
|
|
353
|
-
notModifiedHeaders: validators,
|
|
354
|
-
file: builtFile(`p:/${cleanRel}:${etag}`, body, headers, hasVary ? { ...headers, etag: toWeakEtag(etag) } : undefined),
|
|
355
|
-
})
|
|
356
|
-
}
|
|
357
113
|
|
|
114
|
+
const files = createAssets({ assets, assetPrefix, isDev, compressEnabled, compressCache, nosniffHeader, withHsts })
|
|
115
|
+
const { assetMap, publicMap, serveFile, serveAsset, servePublic } = files
|
|
358
116
|
for (const [rel, body] of Object.entries(publicAssets))
|
|
359
|
-
|
|
117
|
+
files.registerPublic(rel, body, publicEtags[rel])
|
|
360
118
|
|
|
361
119
|
const serverAppCtx = createAppContext({
|
|
362
120
|
root: serverRoot,
|
|
@@ -367,432 +125,47 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
367
125
|
dev: isDev,
|
|
368
126
|
onRegisterPublicFile: (rel) => {
|
|
369
127
|
parentAppCtx?.registerPublicFile(rel)
|
|
370
|
-
|
|
371
|
-
const abs = join(serverPublicDir, cleanRel)
|
|
372
|
-
if (existsSync(abs)) {
|
|
373
|
-
const st = statSync(abs)
|
|
374
|
-
registerPublicEntry(cleanRel, abs, `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`)
|
|
375
|
-
}
|
|
128
|
+
files.registerPublicFromDisk(serverPublicDir, rel)
|
|
376
129
|
},
|
|
377
130
|
})
|
|
378
131
|
|
|
379
|
-
|
|
380
|
-
const
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
let byMethod = pluginRouteEntries.get(normPath)
|
|
397
|
-
if (byMethod === undefined) {
|
|
398
|
-
byMethod = new Map()
|
|
399
|
-
pluginRouteEntries.set(normPath, byMethod)
|
|
400
|
-
pluginRouter.add(normPath, byMethod)
|
|
401
|
-
}
|
|
402
|
-
let routeTrustedOrigins = trustedOrigins
|
|
403
|
-
if (options?.trustedOrigins !== undefined && options.trustedOrigins.length > 0) {
|
|
404
|
-
routeTrustedOrigins = new Set([...(trustedOrigins ?? []), ...options.trustedOrigins])
|
|
405
|
-
}
|
|
406
|
-
byMethod.set(method.toUpperCase(), {
|
|
407
|
-
handler,
|
|
408
|
-
csrf: options?.csrf ?? true,
|
|
409
|
-
trustedOrigins: routeTrustedOrigins,
|
|
410
|
-
trustProxy: options?.trustProxy ?? trustProxy,
|
|
411
|
-
})
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
async function invokeRegisteredAction<I, O>(act: ServerAction<I, O>, input: I, ctx: RequestContext): Promise<ActionResult<O>> {
|
|
415
|
-
const dirMiddlewares = actionByRef.get(act as unknown as ServerAction<unknown, unknown>) ?? []
|
|
416
|
-
if (dirMiddlewares.length === 0)
|
|
417
|
-
return invokeActionCore(act, input, ctx)
|
|
418
|
-
|
|
419
|
-
let actionResult: ActionResult<O> | undefined
|
|
420
|
-
const res = await runChain(ctx, dirMiddlewares, async () => {
|
|
421
|
-
actionResult = await invokeActionCore(act, input, ctx)
|
|
422
|
-
return new Response(null, { status: actionResult.ok ? 200 : actionResult.status })
|
|
423
|
-
})
|
|
424
|
-
if (actionResult !== undefined)
|
|
425
|
-
return actionResult
|
|
426
|
-
// A directory `_middleware.ts` short-circuited the request (e.g. 401/403 auth guard).
|
|
427
|
-
const ct = res.headers.get('content-type') ?? ''
|
|
428
|
-
if (ct.includes('application/json')) {
|
|
429
|
-
try {
|
|
430
|
-
const body = await res.clone().json() as Record<string, unknown>
|
|
431
|
-
return {
|
|
432
|
-
ok: false,
|
|
433
|
-
status: res.status,
|
|
434
|
-
error: typeof body.error === 'string' ? body.error : res.statusText || 'Forbidden',
|
|
435
|
-
}
|
|
436
|
-
}
|
|
437
|
-
catch {}
|
|
438
|
-
}
|
|
439
|
-
let text = ''
|
|
440
|
-
try {
|
|
441
|
-
text = await res.clone().text()
|
|
442
|
-
}
|
|
443
|
-
catch {}
|
|
444
|
-
return {
|
|
445
|
-
ok: false,
|
|
446
|
-
status: res.status,
|
|
447
|
-
error: text || res.statusText || 'Forbidden',
|
|
448
|
-
}
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
const {
|
|
452
|
-
manifest: _m,
|
|
453
|
-
modules: _mods,
|
|
454
|
-
assets: _a,
|
|
455
|
-
publicAssets: _pa,
|
|
456
|
-
publicEtags: _pe,
|
|
457
|
-
prerendered: _pr,
|
|
458
|
-
prerenderedFiles: _pf,
|
|
459
|
-
...forwardedConfig
|
|
460
|
-
} = config as EmbeddedServerConfig & Record<string, unknown>
|
|
461
|
-
const readonlyRuntimeConfig: Readonly<Record<string, unknown>> = Object.freeze({ ...forwardedConfig })
|
|
462
|
-
|
|
463
|
-
for (const plugin of plugins) {
|
|
464
|
-
if (plugin.dispose !== undefined)
|
|
465
|
-
shutdownHooks.push(() => plugin.dispose!())
|
|
466
|
-
if (plugin.server !== undefined) {
|
|
467
|
-
const pluginApi: ServerPluginAPI = {
|
|
468
|
-
root: serverRoot,
|
|
469
|
-
outDir: serverOutDir,
|
|
470
|
-
assetPrefix,
|
|
471
|
-
site,
|
|
472
|
-
dev: isDev,
|
|
473
|
-
trustProxy,
|
|
474
|
-
trustedOrigins: trustedOriginsList,
|
|
475
|
-
config: readonlyRuntimeConfig,
|
|
476
|
-
use(mw: Middleware, options?: MiddlewareOptions) {
|
|
477
|
-
scopedMiddlewares.push({ mw, scope: options?.scope ?? 'all' })
|
|
478
|
-
},
|
|
479
|
-
route: registerPluginRoute,
|
|
480
|
-
rewrite(fn) {
|
|
481
|
-
pluginRewrites.push(fn)
|
|
482
|
-
},
|
|
483
|
-
provide: serverAppCtx.provide,
|
|
484
|
-
inject: serverAppCtx.inject,
|
|
485
|
-
getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined {
|
|
486
|
-
return manifest.pluginData?.[pluginName ?? plugin.name] as T | undefined
|
|
487
|
-
},
|
|
488
|
-
onShutdown(fn) {
|
|
489
|
-
shutdownHooks.push(fn)
|
|
490
|
-
},
|
|
491
|
-
invokeAction: invokeRegisteredAction,
|
|
492
|
-
}
|
|
493
|
-
await runWithAppContext(serverAppCtx, () => plugin.server!(pluginApi))
|
|
494
|
-
}
|
|
495
|
-
}
|
|
496
|
-
|
|
497
|
-
const allPluginMiddlewares: readonly Middleware[] = scopedMiddlewares.map(m => m.mw)
|
|
498
|
-
const staticFastPluginMiddlewares: readonly Middleware[] = scopedMiddlewares
|
|
499
|
-
.filter(m => m.scope === 'all')
|
|
500
|
-
.map(m => m.mw)
|
|
501
|
-
const hasPathScopedMiddlewares = scopedMiddlewares.some(m => m.scope !== 'all' && m.scope !== 'dynamic')
|
|
502
|
-
const middlewaresFor = (path: string, isStaticFast = false): readonly Middleware[] => {
|
|
503
|
-
if (scopedMiddlewares.length === 0)
|
|
504
|
-
return allPluginMiddlewares
|
|
505
|
-
if (!hasPathScopedMiddlewares)
|
|
506
|
-
return isStaticFast ? staticFastPluginMiddlewares : allPluginMiddlewares
|
|
507
|
-
return scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, path, isStaticFast)).map(m => m.mw)
|
|
508
|
-
}
|
|
509
|
-
const hasPluginRewrites = pluginRewrites.length > 0
|
|
510
|
-
const hasHeadHooks = headHooks.length > 0
|
|
511
|
-
const hasHtmlTransformers = htmlTransformers.length > 0
|
|
512
|
-
|
|
513
|
-
const errorHooks: ((info: ServerErrorInfo) => void)[] = []
|
|
514
|
-
if (config.onError !== undefined)
|
|
515
|
-
errorHooks.push(config.onError)
|
|
516
|
-
for (const p of plugins) {
|
|
517
|
-
if (p.onError !== undefined)
|
|
518
|
-
errorHooks.push(p.onError)
|
|
519
|
-
}
|
|
520
|
-
const notifyError = (error: unknown, request: Request, source: ServerErrorInfo['source']) => {
|
|
521
|
-
for (const hook of errorHooks) {
|
|
522
|
-
try {
|
|
523
|
-
hook({ error, request, source })
|
|
524
|
-
}
|
|
525
|
-
catch {}
|
|
526
|
-
}
|
|
527
|
-
}
|
|
528
|
-
|
|
529
|
-
// Hashed build assets: immutable cache, precompressed .br/.gz sidecars, optional lazy compression.
|
|
530
|
-
// Skip `.br`/`.gz` sidecars as standalone HTTP routes when their base asset exists.
|
|
531
|
-
const assetMap = new Map<string, AssetEntry>()
|
|
532
|
-
for (const [rel, body] of Object.entries(assets)) {
|
|
533
|
-
if ((rel.endsWith('.br') || rel.endsWith('.gz')) && rel.slice(0, -3) in assets)
|
|
534
|
-
continue
|
|
535
|
-
const type = MIME[extname(rel).toLowerCase()] ?? 'application/octet-stream'
|
|
536
|
-
const compressible = compressCache !== undefined && isCompressibleType(type)
|
|
537
|
-
const headers: Record<string, string> = {
|
|
538
|
-
'content-type': type,
|
|
539
|
-
'cache-control': 'public, max-age=31536000, immutable',
|
|
540
|
-
...nosniffHeader,
|
|
541
|
-
}
|
|
542
|
-
const sidecar = (ext: 'br' | 'gz', encoding: string): Sidecar | undefined => {
|
|
543
|
-
const source = assets[`${rel}.${ext}`] ?? (typeof body === 'string' && existsSync(`${body}.${ext}`) ? `${body}.${ext}` : undefined)
|
|
544
|
-
return source === undefined ? undefined : { body: toBody(source), headers: { ...headers, 'content-encoding': encoding, 'vary': 'Accept-Encoding' } }
|
|
545
|
-
}
|
|
546
|
-
const br = sidecar('br', 'br')
|
|
547
|
-
const gz = sidecar('gz', 'gzip')
|
|
548
|
-
const varyHeaders = compressible || br !== undefined || gz !== undefined ? { ...headers, vary: 'Accept-Encoding' } : headers
|
|
549
|
-
assetMap.set(`${assetPrefix}/${rel}`, {
|
|
550
|
-
file: builtFile(`a:${assetPrefix}/${rel}`, body, varyHeaders, compressible ? varyHeaders : undefined),
|
|
551
|
-
br,
|
|
552
|
-
gz,
|
|
553
|
-
})
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
async function serveFile(request: Request, file: ServedFile): Promise<Response> {
|
|
557
|
-
if (request.method === 'HEAD')
|
|
558
|
-
return withHsts(new Response(null, { status: 200, headers: file.headers }), request)
|
|
559
|
-
if (file.compressedHeaders !== undefined && compressCache !== undefined) {
|
|
560
|
-
const enc = pickEncoding(request.headers.get('accept-encoding'))
|
|
561
|
-
if (enc !== undefined) {
|
|
562
|
-
const compressed = await compressCache.file(file.key, enc, file.read)
|
|
563
|
-
if (compressed !== undefined)
|
|
564
|
-
return withHsts(new Response(compressed, { status: 200, headers: { ...file.compressedHeaders, 'content-encoding': enc } }), request)
|
|
565
|
-
}
|
|
566
|
-
}
|
|
567
|
-
return withHsts(new Response(file.body, { status: 200, headers: file.headers }), request)
|
|
568
|
-
}
|
|
569
|
-
|
|
570
|
-
async function serveAsset(request: Request, asset: AssetEntry): Promise<Response> {
|
|
571
|
-
if (compressEnabled && request.method !== 'HEAD' && (asset.br !== undefined || asset.gz !== undefined)) {
|
|
572
|
-
const preEnc = pickPrecompressedEncoding(request.headers.get('accept-encoding'), { br: asset.br !== undefined, gz: asset.gz !== undefined })
|
|
573
|
-
if (preEnc !== undefined) {
|
|
574
|
-
const sidecar = preEnc === 'br' ? asset.br! : asset.gz!
|
|
575
|
-
return withHsts(new Response(sidecar.body, { status: 200, headers: sidecar.headers }), request)
|
|
576
|
-
}
|
|
577
|
-
}
|
|
578
|
-
return serveFile(request, asset.file)
|
|
579
|
-
}
|
|
580
|
-
|
|
581
|
-
async function servePublic(request: Request, pub: PublicEntry): Promise<Response> {
|
|
582
|
-
if (etagMatches(request.headers.get('if-none-match'), pub.etag))
|
|
583
|
-
return withHsts(new Response(null, { status: 304, headers: pub.notModifiedHeaders }), request)
|
|
584
|
-
return serveFile(request, pub.file)
|
|
585
|
-
}
|
|
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
|
+
})
|
|
147
|
+
const { router: pluginRouter, middlewaresFor } = pluginHost
|
|
148
|
+
const hasPluginRewrites = pluginHost.rewrites.length > 0
|
|
586
149
|
|
|
587
150
|
// Server actions and their live URLs
|
|
588
151
|
for (const entry of manifest.actions) {
|
|
589
152
|
const mod = modules[entry.file] as Record<string, unknown> | undefined
|
|
590
153
|
const act = mod?.[entry.exportName]
|
|
591
|
-
if (isServerAction(act))
|
|
592
|
-
|
|
593
|
-
const dirMiddlewares = entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default)
|
|
594
|
-
actionByRef.set(act, dirMiddlewares)
|
|
595
|
-
actionHandlers.set(entry.url, { act, middlewares: [...middlewaresFor(entry.url), ...dirMiddlewares] })
|
|
596
|
-
}
|
|
154
|
+
if (isServerAction(act))
|
|
155
|
+
actions.register(act, entry.exportName, entry.url, entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default), middlewaresFor(entry.url))
|
|
597
156
|
}
|
|
598
157
|
|
|
599
|
-
const
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
for (const route of manifest.routes) {
|
|
606
|
-
if (route.prerendered === undefined)
|
|
607
|
-
continue
|
|
608
|
-
const headers: Record<string, string> = { ...htmlHeaders(route.islandChunks.length > 0, false, false), ...varyEncoding }
|
|
609
|
-
const compressedHeaders = compressCache !== undefined ? headers : undefined
|
|
610
|
-
for (const [urlPath, relHtml] of Object.entries(route.prerendered)) {
|
|
611
|
-
const filePath = prerenderedFiles[relHtml]
|
|
612
|
-
const html = prerendered[relHtml]
|
|
613
|
-
const key = `pre:${urlPath}`
|
|
614
|
-
const entry: ServedFile | undefined = filePath !== undefined
|
|
615
|
-
? builtFile(key, filePath, headers, compressedHeaders)
|
|
616
|
-
: html !== undefined
|
|
617
|
-
? { key, headers, compressedHeaders, body: html, read: () => textEncoder.encode(html) }
|
|
618
|
-
: undefined
|
|
619
|
-
if (entry === undefined)
|
|
620
|
-
continue
|
|
621
|
-
prerenderedMap.set(urlPath, entry)
|
|
622
|
-
if (route.middlewares.length === 0 && middlewaresFor(urlPath, true).length === 0 && !hasPluginRewrites && pluginRouter.match(urlPath) === undefined)
|
|
623
|
-
fastPrerenderedMap.set(urlPath, entry)
|
|
624
|
-
}
|
|
625
|
-
}
|
|
158
|
+
const { all: prerenderedMap, fast: fastPrerenderedMap } = files.collectPrerendered(manifest.routes, {
|
|
159
|
+
prerendered,
|
|
160
|
+
prerenderedFiles,
|
|
161
|
+
htmlHeaders: (route, urlPath) => htmlHeaders(route.islandChunks.length > 0, false, false, route.prerenderedStyleHashes?.[urlPath]),
|
|
162
|
+
isFast: (urlPath, route) => route.middlewares.length === 0 && middlewaresFor(urlPath, true).length === 0 && !hasPluginRewrites && pluginRouter.match(urlPath) === undefined,
|
|
163
|
+
})
|
|
626
164
|
|
|
627
165
|
const router = new Router<CompiledRoute>()
|
|
628
166
|
const fastStaticPages = new Map<string, FastHandler>()
|
|
629
167
|
|
|
630
|
-
|
|
631
|
-
const rootLayoutFile = manifest.rootLayoutFile
|
|
632
|
-
const rootLayoutMod = rootLayoutFile !== undefined ? modules[rootLayoutFile] as LoadedLayoutModule | undefined : undefined
|
|
633
|
-
const fallbackDoc: DocumentOptions = {
|
|
634
|
-
body: '',
|
|
635
|
-
headTags: manifest.headTags,
|
|
636
|
-
styles: manifest.globalStyles ?? manifest.styles,
|
|
637
|
-
runtimeScript: manifest.runtimeScript,
|
|
638
|
-
alwaysLoadRuntime,
|
|
639
|
-
lang,
|
|
640
|
-
}
|
|
641
|
-
|
|
642
|
-
const TITLE_INNER_RE = /^<title\b[^>]*>([\s\S]*?)<\/title>$/i
|
|
643
|
-
|
|
644
|
-
async function resolveDocumentHead(
|
|
645
|
-
rctx: RenderContext,
|
|
646
|
-
baseHeadTags: readonly string[] | undefined,
|
|
647
|
-
url: URL,
|
|
648
|
-
req?: Request,
|
|
649
|
-
ctx?: RequestContext,
|
|
650
|
-
): Promise<{ head: string, lang: string, htmlAttrs: Record<string, string> }> {
|
|
651
|
-
const collectedParts = rctx.headParts.join('')
|
|
652
|
-
if (!hasHeadHooks) {
|
|
653
|
-
return {
|
|
654
|
-
head: (rctx.title ?? '') + collectedParts,
|
|
655
|
-
lang,
|
|
656
|
-
htmlAttrs: rctx.htmlAttrs,
|
|
657
|
-
}
|
|
658
|
-
}
|
|
659
|
-
|
|
660
|
-
const headCtx = ctx ?? makeRequestContext(req ?? new Request(url.toString()), {}, { trustProxy, url }).ctx
|
|
661
|
-
const htmlAttrs: Record<string, string> = { ...rctx.htmlAttrs }
|
|
662
|
-
const initialTitleTag = rctx.title
|
|
663
|
-
const initialTitleInner = initialTitleTag !== undefined ? TITLE_INNER_RE.exec(initialTitleTag)?.[1] : undefined
|
|
664
|
-
let currentTitle = initialTitleInner
|
|
665
|
-
let titleDirty = false
|
|
666
|
-
let currentLang = htmlAttrs.lang ?? lang
|
|
667
|
-
let headBuf = (initialTitleTag ?? '') + collectedParts
|
|
668
|
-
if (baseHeadTags !== undefined) {
|
|
669
|
-
for (let i = 0; i < baseHeadTags.length; i++)
|
|
670
|
-
headBuf += baseHeadTags[i]
|
|
671
|
-
}
|
|
672
|
-
const added: string[] = []
|
|
673
|
-
|
|
674
|
-
const docHead: DocumentHeadContext = {
|
|
675
|
-
get lang() {
|
|
676
|
-
return currentLang
|
|
677
|
-
},
|
|
678
|
-
set lang(v: string) {
|
|
679
|
-
currentLang = v
|
|
680
|
-
htmlAttrs.lang = v
|
|
681
|
-
},
|
|
682
|
-
htmlAttrs,
|
|
683
|
-
get title() {
|
|
684
|
-
return currentTitle
|
|
685
|
-
},
|
|
686
|
-
set title(v: string | undefined) {
|
|
687
|
-
currentTitle = v
|
|
688
|
-
titleDirty = true
|
|
689
|
-
},
|
|
690
|
-
get headHtml() {
|
|
691
|
-
return headBuf
|
|
692
|
-
},
|
|
693
|
-
add(html: string) {
|
|
694
|
-
if (html !== '') {
|
|
695
|
-
added.push(html)
|
|
696
|
-
headBuf += html
|
|
697
|
-
}
|
|
698
|
-
},
|
|
699
|
-
}
|
|
700
|
-
|
|
701
|
-
for (const hook of headHooks) {
|
|
702
|
-
try {
|
|
703
|
-
await hook(docHead, headCtx)
|
|
704
|
-
}
|
|
705
|
-
catch (err) {
|
|
706
|
-
notifyError(err, req ?? headCtx.request, 'plugin')
|
|
707
|
-
}
|
|
708
|
-
}
|
|
709
|
-
|
|
710
|
-
const titleHtml = titleDirty
|
|
711
|
-
? (currentTitle !== undefined ? `<title>${currentTitle}</title>` : '')
|
|
712
|
-
: (initialTitleTag ?? '')
|
|
713
|
-
return {
|
|
714
|
-
head: titleHtml + collectedParts + (added.length > 0 ? added.join('') : ''),
|
|
715
|
-
lang: currentLang,
|
|
716
|
-
htmlAttrs,
|
|
717
|
-
}
|
|
718
|
-
}
|
|
719
|
-
|
|
720
|
-
async function applyHtmlTransforms(html: string, url: URL, req?: Request, ctx?: RequestContext): Promise<string> {
|
|
721
|
-
if (!hasHtmlTransformers)
|
|
722
|
-
return html
|
|
723
|
-
const transformCtx = ctx ?? makeRequestContext(req ?? new Request(url.toString()), {}, { trustProxy, url }).ctx
|
|
724
|
-
let out = html
|
|
725
|
-
for (const transform of htmlTransformers) {
|
|
726
|
-
try {
|
|
727
|
-
out = await transform(out, transformCtx)
|
|
728
|
-
}
|
|
729
|
-
catch (err) {
|
|
730
|
-
notifyError(err, req ?? transformCtx.request, 'plugin')
|
|
731
|
-
}
|
|
732
|
-
}
|
|
733
|
-
return out
|
|
734
|
-
}
|
|
735
|
-
|
|
736
|
-
function resolveRenderedIslands(rctx: ReturnType<typeof createRenderContext>, body: string): { hasIslands: boolean, eagerChunks: string[] } {
|
|
737
|
-
if (rctx.hasIslands) {
|
|
738
|
-
const eagerChunks: string[] = []
|
|
739
|
-
for (const [chunk, eager] of rctx.renderedIslands) {
|
|
740
|
-
if (eager)
|
|
741
|
-
eagerChunks.push(chunk)
|
|
742
|
-
}
|
|
743
|
-
return { hasIslands: true, eagerChunks }
|
|
744
|
-
}
|
|
745
|
-
// Fallback only if raw HTML injected a <kay-island> without going through ssrIsland/ssrIslandStatic.
|
|
746
|
-
if (body.includes('<kay-island'))
|
|
747
|
-
return extractRenderedIslands(body)
|
|
748
|
-
return { hasIslands: false, eagerChunks: [] }
|
|
749
|
-
}
|
|
750
|
-
|
|
751
|
-
async function renderFallbackPage(status: number, renderInner: (() => unknown) | undefined, text: string, url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> {
|
|
752
|
-
if (renderInner !== undefined) {
|
|
753
|
-
try {
|
|
754
|
-
const effUrl = url ?? new URL(`http://localhost/${status}`)
|
|
755
|
-
const rctx = createRenderContext()
|
|
756
|
-
const body = await runWithRenderContext(rctx, async () => {
|
|
757
|
-
let inner = ssrChild(await renderInner() as Html)
|
|
758
|
-
if (rootLayoutMod !== undefined)
|
|
759
|
-
inner = ssrChild(await rootLayoutMod.default({ children: raw(inner), url: effUrl, params: {}, locals: ctx?.locals ?? {} }) as Html)
|
|
760
|
-
return inner
|
|
761
|
-
})
|
|
762
|
-
const { hasIslands, eagerChunks } = resolveRenderedIslands(rctx, body)
|
|
763
|
-
const docHead = await resolveDocumentHead(rctx, manifest.headTags, effUrl, req, ctx)
|
|
764
|
-
const docHtml = renderDocument({
|
|
765
|
-
...fallbackDoc,
|
|
766
|
-
body,
|
|
767
|
-
head: docHead.head,
|
|
768
|
-
lang: docHead.lang,
|
|
769
|
-
htmlAttrs: docHead.htmlAttrs,
|
|
770
|
-
preloadChunks: eagerChunks,
|
|
771
|
-
hasIslands,
|
|
772
|
-
})
|
|
773
|
-
const html = await applyHtmlTransforms(docHtml, effUrl, req, ctx)
|
|
774
|
-
return new Response(html, { status, headers: htmlHeaders(hasIslands, false, true) })
|
|
775
|
-
}
|
|
776
|
-
catch (err) {
|
|
777
|
-
if (req !== undefined)
|
|
778
|
-
notifyError(err, req, 'route')
|
|
779
|
-
}
|
|
780
|
-
}
|
|
781
|
-
return new Response(text, { status, headers: { 'content-type': 'text/plain; charset=utf-8' } })
|
|
782
|
-
}
|
|
783
|
-
|
|
784
|
-
const buildErrorResponse = (error: unknown, url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> =>
|
|
785
|
-
renderFallbackPage(500, errorMod && (() => errorMod.default({ error })), 'Internal Server Error', url, req, ctx)
|
|
786
|
-
|
|
787
|
-
const notFoundPage = notFoundMod?.default
|
|
788
|
-
const buildNotFoundResponse = (url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> =>
|
|
789
|
-
renderFallbackPage(404, notFoundPage && (() => notFoundPage({})), 'Not Found', url, req, ctx)
|
|
790
|
-
|
|
791
|
-
async function renderError(error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext): Promise<Response> {
|
|
792
|
-
if (wantsJson(request))
|
|
793
|
-
return finish(Response.json({ ok: false, status: 500, error: 'Internal Server Error' }, { status: 500 }), request, cookieStore)
|
|
794
|
-
return finish(await buildErrorResponse(error, url, request, ctx), request, cookieStore)
|
|
795
|
-
}
|
|
168
|
+
const { buildNotFoundResponse, renderError } = createFallbackPages({ manifest, modules, lang, alwaysLoadRuntime, document, htmlHeaders, notifyError, finish })
|
|
796
169
|
|
|
797
170
|
async function renderNotFound(cookieStore: CookieStore, url: URL, request: Request, ctx: RequestContext): Promise<Response> {
|
|
798
171
|
const res = await runChain(ctx, middlewaresFor(url.pathname), () => buildNotFoundResponse(url, request, ctx))
|
|
@@ -838,14 +211,15 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
838
211
|
const docPrefix = shell.slice(0, splitAt)
|
|
839
212
|
const docSuffix = shell.slice(splitAt + 1)
|
|
840
213
|
const singleLayout = layouts.length === 1 ? layouts[0]! : undefined
|
|
841
|
-
|
|
214
|
+
|
|
842
215
|
|
|
843
216
|
const fail = (error: unknown, request: Request, url: URL, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
|
|
844
217
|
notifyError(error, request, 'route')
|
|
845
218
|
return renderError(error, cookieStore, url, request, ctx)
|
|
846
219
|
}
|
|
847
220
|
const respondHtml = (body: string, request: Request, cookieStore?: CookieStore): Response => {
|
|
848
|
-
const
|
|
221
|
+
const html = docPrefix + body + docSuffix
|
|
222
|
+
const res = compressedHtmlResponse(html, 200, htmlHeaders(hasIslands, false, true, inlineStyleHashes(html)), request, compressCache, !entry.hasLoad)
|
|
849
223
|
return cookieStore?.hasChanges ? finish(res, request, cookieStore) : withHsts(res, request)
|
|
850
224
|
}
|
|
851
225
|
const layoutProps = (inner: string, url: URL, locals: KayLocals) => ({ children: raw(inner), url, params: {}, locals })
|
|
@@ -898,7 +272,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
898
272
|
() => ssrChild(mod.default!(pageProps) as Html),
|
|
899
273
|
pickPageIslandProps(data, entry, mod),
|
|
900
274
|
entry.islandHydrate as HydrateStrategy | undefined,
|
|
901
|
-
true,
|
|
275
|
+
true, mod.default!.name,
|
|
902
276
|
), request, url, locals, cookieStore, ctx)
|
|
903
277
|
}
|
|
904
278
|
const rendered = mod.default!(pageProps)
|
|
@@ -915,7 +289,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
915
289
|
const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url })
|
|
916
290
|
return (async () => {
|
|
917
291
|
try {
|
|
918
|
-
const loaded = await mod.load!(ctx)
|
|
292
|
+
const loaded = await actions.run(ctx, () => mod.load!(ctx))
|
|
919
293
|
if (isNotFound(loaded))
|
|
920
294
|
return finish(await buildNotFoundResponse(url, request, ctx), request, cookieStore)
|
|
921
295
|
if (loaded instanceof Response)
|
|
@@ -1016,7 +390,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
1016
390
|
() => ssrChild(mod.default!(pageProps) as Html),
|
|
1017
391
|
pickPageIslandProps(data, entry, mod),
|
|
1018
392
|
entry.islandHydrate as HydrateStrategy | undefined,
|
|
1019
|
-
true,
|
|
393
|
+
true, mod.default!.name,
|
|
1020
394
|
)
|
|
1021
395
|
}
|
|
1022
396
|
else {
|
|
@@ -1043,75 +417,14 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
1043
417
|
// Transforms see the document with its initial body; boundaries resolved later stream as they render.
|
|
1044
418
|
for (const transform of htmlTransformers)
|
|
1045
419
|
shell = await transform(shell, ctx)
|
|
1046
|
-
|
|
1047
|
-
let tailOffset = STREAM_TAIL_MARK.length
|
|
1048
|
-
if (splitAt === -1) {
|
|
1049
|
-
splitAt = shell.lastIndexOf('</body>')
|
|
1050
|
-
tailOffset = 0
|
|
1051
|
-
}
|
|
1052
|
-
const openingHtml = splitAt === -1 ? shell : shell.slice(0, splitAt)
|
|
1053
|
-
const tailHtml = splitAt === -1 ? '' : shell.slice(splitAt + tailOffset)
|
|
1054
|
-
|
|
1055
|
-
const abortCtrl = new AbortController()
|
|
1056
|
-
let closed = false
|
|
1057
|
-
const deadline = Date.now() + streamTimeout
|
|
1058
|
-
|
|
1059
|
-
const safeEnqueue = (controller: ReadableStreamDefaultController<Uint8Array>, data: Uint8Array): void => {
|
|
1060
|
-
if (closed || abortCtrl.signal.aborted)
|
|
1061
|
-
return
|
|
1062
|
-
try {
|
|
1063
|
-
controller.enqueue(data)
|
|
1064
|
-
}
|
|
1065
|
-
catch {
|
|
1066
|
-
closed = true
|
|
1067
|
-
abortCtrl.abort()
|
|
1068
|
-
}
|
|
1069
|
-
}
|
|
1070
|
-
|
|
1071
|
-
const stream = new ReadableStream<Uint8Array>({
|
|
1072
|
-
async start(controller) {
|
|
1073
|
-
safeEnqueue(controller, textEncoder.encode(openingHtml))
|
|
1074
|
-
// A resolved boundary can render boundaries of its own, so each flush also drains the ones it added.
|
|
1075
|
-
let flushed = 0
|
|
1076
|
-
const flushPending = async (): Promise<void> => {
|
|
1077
|
-
if (closed || abortCtrl.signal.aborted)
|
|
1078
|
-
return
|
|
1079
|
-
const chunks = rctx.pending.slice(flushed)
|
|
1080
|
-
flushed = rctx.pending.length
|
|
1081
|
-
await Promise.all(chunks.map(async (chunk) => {
|
|
1082
|
-
const settled = await settleWithin(chunk, deadline, abortCtrl.signal)
|
|
1083
|
-
if (settled === undefined || closed || abortCtrl.signal.aborted)
|
|
1084
|
-
return
|
|
1085
|
-
if ('error' in settled)
|
|
1086
|
-
notifyError(settled.error, ctx.request, 'route')
|
|
1087
|
-
safeEnqueue(controller, textEncoder.encode(streamChunkScript(chunk.id, settled.html)))
|
|
1088
|
-
await flushPending()
|
|
1089
|
-
}))
|
|
1090
|
-
}
|
|
1091
|
-
await flushPending()
|
|
1092
|
-
if (!closed && !abortCtrl.signal.aborted) {
|
|
1093
|
-
safeEnqueue(controller, textEncoder.encode(tailHtml))
|
|
1094
|
-
closed = true
|
|
1095
|
-
try {
|
|
1096
|
-
controller.close()
|
|
1097
|
-
}
|
|
1098
|
-
catch {}
|
|
1099
|
-
}
|
|
1100
|
-
},
|
|
1101
|
-
cancel() {
|
|
1102
|
-
closed = true
|
|
1103
|
-
abortCtrl.abort()
|
|
1104
|
-
},
|
|
1105
|
-
})
|
|
1106
|
-
|
|
1107
|
-
return new Response(stream, { status: 200, headers: htmlHeaders(hasIslands, true, true) })
|
|
420
|
+
return new Response(streamDocument(shell, rctx, streamTimeout, error => notifyError(error, ctx.request, 'route')), { status: 200, headers: htmlHeaders(hasIslands, true, true, inlineStyleHashes(shell)) })
|
|
1108
421
|
}
|
|
1109
422
|
|
|
1110
423
|
let html = renderDocument({ ...doc, body, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands })
|
|
1111
424
|
for (const transform of htmlTransformers)
|
|
1112
425
|
html = await transform(html, ctx)
|
|
1113
426
|
|
|
1114
|
-
return compressedHtmlResponse(html, 200, htmlHeaders(hasIslands, false, true), ctx.request, compressCache)
|
|
427
|
+
return compressedHtmlResponse(html, 200, htmlHeaders(hasIslands, false, true, inlineStyleHashes(html)), ctx.request, compressCache)
|
|
1115
428
|
}
|
|
1116
429
|
|
|
1117
430
|
// `bodyLimited` is set under `serve()`, where Bun.serve already enforces maxRequestBodySize on every body, chunked ones included.
|
|
@@ -1138,7 +451,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
1138
451
|
}
|
|
1139
452
|
|
|
1140
453
|
// Actions only accept POST; other methods get 405 before any middleware runs.
|
|
1141
|
-
const registeredAction =
|
|
454
|
+
const registeredAction = actions.byUrl(pathname)
|
|
1142
455
|
if (registeredAction !== undefined && request.method !== 'POST')
|
|
1143
456
|
return finish(new Response('Method Not Allowed', { status: 405, headers: { allow: 'POST' } }), request)
|
|
1144
457
|
|
|
@@ -1165,7 +478,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
1165
478
|
const { act, middlewares } = actionHandler
|
|
1166
479
|
const { ctx, cookieStore } = makeRequestContext(req, {}, { trustProxy, remoteIp, url })
|
|
1167
480
|
try {
|
|
1168
|
-
return finish(await runChain(ctx, middlewares, () => executeAction(act, req, ctx, trustedOrigins, trustProxy)), req, cookieStore)
|
|
481
|
+
return finish(await actions.run(ctx, () => runChain(ctx, middlewares, () => executeAction(act, req, ctx, trustedOrigins, trustProxy))), req, cookieStore)
|
|
1169
482
|
}
|
|
1170
483
|
catch (error) {
|
|
1171
484
|
notifyError(error, req, 'action')
|
|
@@ -1189,7 +502,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
1189
502
|
|
|
1190
503
|
// Apply plugin URL rewrites (e.g. @kayjs/i18n stripping /fr prefix and setting ctx.locals.locale)
|
|
1191
504
|
let effectivePath = pathname
|
|
1192
|
-
for (const rewrite of
|
|
505
|
+
for (const rewrite of pluginHost.rewrites) {
|
|
1193
506
|
const nextPath = rewrite(effectivePath, ctx)
|
|
1194
507
|
if (nextPath !== undefined)
|
|
1195
508
|
effectivePath = nextPath
|
|
@@ -1209,12 +522,12 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
1209
522
|
}
|
|
1210
523
|
ctx.params = pluginMatch.params
|
|
1211
524
|
try {
|
|
1212
|
-
let res = await runChain(ctx,
|
|
525
|
+
let res = await actions.run(ctx, () => runChain(ctx, pluginHost.allMiddlewares, () => routeDef.handler(ctx)))
|
|
1213
526
|
if (headFallbackPluginDef !== undefined)
|
|
1214
527
|
res = stripHeadBody(res)
|
|
1215
528
|
else if (isEventStream(res))
|
|
1216
529
|
disableTimeout?.()
|
|
1217
|
-
return finish(await maybeCompressResponse(res, req, compressCache), req, cookieStore)
|
|
530
|
+
return finish(await maybeCompressResponse(await withPluginHtmlCsp(res, htmlHeaders), req, compressCache), req, cookieStore)
|
|
1218
531
|
}
|
|
1219
532
|
catch (error) {
|
|
1220
533
|
notifyError(error, req, 'plugin')
|
|
@@ -1251,7 +564,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
1251
564
|
}
|
|
1252
565
|
|
|
1253
566
|
try {
|
|
1254
|
-
const res = await runChain(ctx, route.middlewares, () => renderCompiledRoute(route, ctx, disableTimeout))
|
|
567
|
+
const res = await actions.run(ctx, () => runChain(ctx, route.middlewares, () => renderCompiledRoute(route, ctx, disableTimeout)))
|
|
1255
568
|
if (isEventStream(res))
|
|
1256
569
|
disableTimeout?.()
|
|
1257
570
|
// Compress uncompressed API/middleware responses after the middleware chain unwinds.
|
|
@@ -1319,18 +632,5 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
1319
632
|
return srvRef
|
|
1320
633
|
}
|
|
1321
634
|
|
|
1322
|
-
|
|
1323
|
-
async function dispose(): Promise<void> {
|
|
1324
|
-
if (disposed)
|
|
1325
|
-
return
|
|
1326
|
-
disposed = true
|
|
1327
|
-
for (const hook of shutdownHooks) {
|
|
1328
|
-
try {
|
|
1329
|
-
await hook()
|
|
1330
|
-
}
|
|
1331
|
-
catch {}
|
|
1332
|
-
}
|
|
1333
|
-
}
|
|
1334
|
-
|
|
1335
|
-
return { handle, serve, dispose }
|
|
635
|
+
return { handle, serve, dispose: pluginHost.dispose }
|
|
1336
636
|
}
|