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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/package.json +1 -1
  2. package/src/build/bundle.ts +209 -34
  3. package/src/build/compile.ts +22 -46
  4. package/src/build/files.ts +38 -0
  5. package/src/build/graph.ts +67 -2
  6. package/src/build/index.ts +75 -13
  7. package/src/build/manifest.ts +5 -0
  8. package/src/build/plugin-host.ts +2 -0
  9. package/src/build/prerender.ts +16 -7
  10. package/src/build/resolve.ts +11 -18
  11. package/src/build/routes.ts +33 -5
  12. package/src/build/server-entry.ts +38 -0
  13. package/src/cli/check.ts +102 -45
  14. package/src/cli/new.ts +6 -7
  15. package/src/compiler/analyze.ts +65 -10
  16. package/src/compiler/dom.ts +143 -122
  17. package/src/compiler/server-only.ts +14 -8
  18. package/src/compiler/shared.ts +57 -14
  19. package/src/compiler/ssr.ts +14 -12
  20. package/src/dev/index.ts +96 -29
  21. package/src/dom/action.ts +91 -1
  22. package/src/dom/index.ts +8 -3
  23. package/src/index.ts +3 -0
  24. package/src/jsx-runtime.ts +421 -93
  25. package/src/plugins/config.ts +49 -0
  26. package/src/plugins/context.ts +4 -0
  27. package/src/plugins/index.ts +7 -216
  28. package/src/plugins/load.ts +38 -0
  29. package/src/plugins/order.ts +107 -0
  30. package/src/plugins/services.ts +23 -0
  31. package/src/plugins/types.ts +197 -0
  32. package/src/server/action-registry.ts +72 -0
  33. package/src/server/action.ts +15 -8
  34. package/src/server/app-entry.ts +23 -0
  35. package/src/server/assets.ts +182 -0
  36. package/src/server/compress.ts +87 -14
  37. package/src/server/document.ts +192 -0
  38. package/src/server/errors.ts +123 -0
  39. package/src/server/http.ts +103 -30
  40. package/src/server/index.ts +131 -701
  41. package/src/server/loader.ts +62 -69
  42. package/src/server/page.ts +107 -0
  43. package/src/server/plugin-host.ts +167 -0
  44. package/src/server/router.ts +49 -20
  45. package/src/server/security.ts +44 -3
  46. package/src/server/static-dir.ts +22 -3
  47. package/src/server/stream.ts +94 -0
  48. package/src/test/index.ts +24 -19
@@ -1,12 +1,19 @@
1
1
  // Unified server actions: works as both progressive <form action={fn} method="post"> and typed island RPC.
2
2
 
3
3
  import type { Cookies } from './cookies'
4
- import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult } from './standard-schema'
4
+ import type { KayLocals } from './index'
5
5
  import type { TrustProxy } from './security'
6
+ import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult } from './standard-schema'
6
7
  import { wantsJson } from './http'
7
8
  import { isTrustedOrigin } from './security'
8
9
  import { validateSchema } from './standard-schema'
9
10
 
11
+ declare module './index' {
12
+ interface KayLocals {
13
+ actionError?: ActionErrorFlash | undefined
14
+ }
15
+ }
16
+
10
17
  export const ACTION_ERROR_COOKIE = '__kay_action_err'
11
18
 
12
19
  const MAX_FLASH_COOKIE_BYTES = 3500
@@ -25,15 +32,15 @@ export interface ActionErrorFlash {
25
32
  values?: Record<string, string> | undefined
26
33
  }
27
34
 
28
- export function getActionError(locals?: Record<string, unknown>): ActionErrorFlash | undefined {
29
- return locals?.actionError as ActionErrorFlash | undefined
35
+ export function getActionError(locals?: KayLocals): ActionErrorFlash | undefined {
36
+ return locals?.actionError
30
37
  }
31
38
 
32
39
  export interface ActionContext {
33
40
  request: Request
34
41
  url: URL
35
42
  cookies: Cookies
36
- locals: Record<string, unknown>
43
+ locals: KayLocals
37
44
  ip?: string | undefined
38
45
  redirect: (location: string, status?: 301 | 302 | 303 | 307 | 308) => Response
39
46
  deny: (status: number, message: string, fieldErrors?: Record<string, string>) => Response
@@ -135,7 +142,7 @@ function isJsonBody(request: Request): boolean {
135
142
  }
136
143
 
137
144
  // The page a form came from, when its origin is one this server trusts: where a no-JS submit goes back to.
138
- function trustedReferer(request: Request, trustedOrigins: ReadonlySet<string> | undefined, trustProxy: TrustProxy): URL | undefined {
145
+ function trustedReferer(request: Request, trustedOrigins: ReadonlySet<string> | undefined, trustProxy: TrustProxy, requestUrl?: URL): URL | undefined {
139
146
  const referer = request.headers.get('referer')
140
147
  if (!referer)
141
148
  return undefined
@@ -146,7 +153,7 @@ function trustedReferer(request: Request, trustedOrigins: ReadonlySet<string> |
146
153
  catch {
147
154
  return undefined
148
155
  }
149
- return isTrustedOrigin(refUrl.origin, request, trustedOrigins, trustProxy) ? refUrl : undefined
156
+ return isTrustedOrigin(refUrl.origin, request, trustedOrigins, trustProxy, requestUrl) ? refUrl : undefined
150
157
  }
151
158
 
152
159
  function topLevelKey(issue: StandardSchemaIssue): string | undefined {
@@ -318,7 +325,7 @@ export async function executeAction(
318
325
  checked = await retryWithFormArrays(act.schema, rawBody as Record<string, unknown>, checked)
319
326
  if (!checked.ok) {
320
327
  // Zero-JS progressive HTML <form> submit: flash fieldErrors + safe submitted values (<4KB) and redirect 303 back to trusted Referer
321
- const back = json ? undefined : trustedReferer(request, trustedOrigins, trustProxy)
328
+ const back = json ? undefined : trustedReferer(request, trustedOrigins, trustProxy, ctx.url)
322
329
  if (back !== undefined) {
323
330
  ctx.cookies.set(ACTION_ERROR_COOKIE, buildActionErrorFlash(act.url, checked.fieldErrors, rawBody, act.flashFields), {
324
331
  httpOnly: true,
@@ -339,7 +346,7 @@ export async function executeAction(
339
346
  if (result instanceof Response)
340
347
  return result
341
348
 
342
- const back = json ? undefined : trustedReferer(request, trustedOrigins, trustProxy)
349
+ const back = json ? undefined : trustedReferer(request, trustedOrigins, trustProxy, ctx.url)
343
350
  if (back !== undefined)
344
351
  return new Response(null, { status: 303, headers: { location: back.href } })
345
352
 
@@ -0,0 +1,23 @@
1
+ // What the generated `dist/server/_entry.js` calls: an app from its bundled config and modules, plus what the caller serves it with.
2
+
3
+ import type { KayConfig } from '../plugins/index'
4
+ import type { EmbeddedServerConfig, KayApp } from './http'
5
+ import { resolveServerConfig } from '../plugins/index'
6
+ import { createServerFromEmbedded } from './index'
7
+
8
+ /** The manifest, assets and paths the caller read or embedded; runtime keys set here win over `kay.config.ts`. */
9
+ export type AppEntryOptions = Omit<EmbeddedServerConfig, 'modules'>
10
+
11
+ /** The exports of `dist/server/_entry.js`. */
12
+ export interface ServerEntry {
13
+ kayConfig: KayConfig
14
+ /** Bundled modules by manifest key. */
15
+ modules: Record<string, Record<string, unknown>>
16
+ /** The same modules by root-relative source path. */
17
+ sources: Record<string, Record<string, unknown>>
18
+ createApp: (options: AppEntryOptions) => Promise<KayApp>
19
+ }
20
+
21
+ export function createAppFromEntry(config: KayConfig, modules: Record<string, unknown>, options: AppEntryOptions): Promise<KayApp> {
22
+ return createServerFromEmbedded({ ...options, ...resolveServerConfig(config, options), modules })
23
+ }
@@ -0,0 +1,182 @@
1
+ // Files served as they are: hashed build assets, public files and prerendered pages, with their headers fixed at startup.
2
+
3
+ import type { RouteManifestEntry } from '../build/index'
4
+ import type { CompressionCache } from './compress'
5
+ import type { EmbeddedBody } from './http'
6
+ import { existsSync, statSync } from 'node:fs'
7
+ import { extname, join } from 'node:path'
8
+ import { isCompressibleType, pickEncoding, pickPrecompressedEncoding, toWeakEtag } from './compress'
9
+ import { etagMatches, MIME } from './http'
10
+
11
+ const textEncoder = new TextEncoder()
12
+
13
+ // A build file ready to serve: headers and compression key are fixed at startup, so a request only picks a variant.
14
+ export interface ServedFile {
15
+ key: string
16
+ headers: Record<string, string>
17
+ /** Headers of the on-the-fly compressed variant; undefined when the file is never compressed here. */
18
+ compressedHeaders: Record<string, string> | undefined
19
+ body: BodyInit
20
+ read: () => Uint8Array<ArrayBuffer> | Promise<Uint8Array<ArrayBuffer>>
21
+ }
22
+
23
+ interface Sidecar {
24
+ body: BodyInit
25
+ headers: Record<string, string>
26
+ }
27
+
28
+ export interface AssetEntry {
29
+ file: ServedFile
30
+ br: Sidecar | undefined
31
+ gz: Sidecar | undefined
32
+ }
33
+
34
+ export interface PublicEntry {
35
+ file: ServedFile
36
+ etag: string
37
+ notModifiedHeaders: Record<string, string>
38
+ }
39
+
40
+ export interface AssetsOptions {
41
+ assets: Record<string, EmbeddedBody>
42
+ assetPrefix: string
43
+ isDev: boolean
44
+ compressEnabled: boolean
45
+ compressCache: CompressionCache | undefined
46
+ nosniffHeader: Record<string, string>
47
+ withHsts: (res: Response, request: Request) => Response
48
+ }
49
+
50
+ export interface PrerenderedSources {
51
+ prerendered: Record<string, string>
52
+ prerenderedFiles: Record<string, string>
53
+ /** HTML headers of a prerendered page, before the `Vary` header compression adds. */
54
+ htmlHeaders: (route: RouteManifestEntry, urlPath: string) => Record<string, string>
55
+ /** Whether a prerendered URL may be answered before any middleware, rewrite or plugin route. */
56
+ isFast: (urlPath: string, route: RouteManifestEntry) => boolean
57
+ }
58
+
59
+ export function createAssets(options: AssetsOptions) {
60
+ const { assets, assetPrefix, isDev, compressEnabled, compressCache, nosniffHeader, withHsts } = options
61
+ const varyEncoding: Record<string, string> = compressCache !== undefined ? { vary: 'Accept-Encoding' } : {}
62
+
63
+ const toBody = (body: EmbeddedBody): BodyInit => typeof body === 'string' ? Bun.file(body) : body
64
+ const readBody = async (body: EmbeddedBody): Promise<Uint8Array<ArrayBuffer>> => typeof body === 'string' ? new Uint8Array(await Bun.file(body).arrayBuffer()) : body
65
+ const builtFile = (key: string, source: EmbeddedBody, headers: Record<string, string>, compressedHeaders: Record<string, string> | undefined): ServedFile =>
66
+ ({ key, headers, compressedHeaders, body: toBody(source), read: () => readBody(source) })
67
+
68
+ const publicMap = new Map<string, PublicEntry>()
69
+ const publicCacheControl = isDev ? 'no-cache' : 'public, max-age=3600'
70
+
71
+ const registerPublic = (rel: string, body: EmbeddedBody, explicitEtag?: string): void => {
72
+ const cleanRel = rel.replace(/^\/+/, '')
73
+ const etag = explicitEtag ?? `W/"${Bun.hash(typeof body === 'string' ? cleanRel : body).toString(36)}"`
74
+ const type = MIME[extname(cleanRel).toLowerCase()] ?? 'application/octet-stream'
75
+ const hasVary = compressCache !== undefined && isCompressibleType(type)
76
+ const validators = { etag, 'cache-control': publicCacheControl, ...(hasVary ? { vary: 'Accept-Encoding' } : {}), ...nosniffHeader }
77
+ const headers = { 'content-type': type, ...validators }
78
+ publicMap.set(`/${cleanRel}`, {
79
+ etag,
80
+ notModifiedHeaders: validators,
81
+ file: builtFile(`p:/${cleanRel}:${etag}`, body, headers, hasVary ? { ...headers, etag: toWeakEtag(etag) } : undefined),
82
+ })
83
+ }
84
+
85
+ // A file a plugin writes into the public dir at runtime, served once it exists on disk.
86
+ const registerPublicFromDisk = (publicDir: string, rel: string): void => {
87
+ const cleanRel = rel.replace(/^\/+/, '')
88
+ const abs = join(publicDir, cleanRel)
89
+ if (existsSync(abs)) {
90
+ const st = statSync(abs)
91
+ registerPublic(cleanRel, abs, `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`)
92
+ }
93
+ }
94
+
95
+ // Hashed build assets: immutable cache, precompressed .br/.gz sidecars, optional lazy compression.
96
+ // Skip `.br`/`.gz` sidecars as standalone HTTP routes when their base asset exists.
97
+ const assetMap = new Map<string, AssetEntry>()
98
+ for (const [rel, body] of Object.entries(assets)) {
99
+ if ((rel.endsWith('.br') || rel.endsWith('.gz')) && rel.slice(0, -3) in assets)
100
+ continue
101
+ const type = MIME[extname(rel).toLowerCase()] ?? 'application/octet-stream'
102
+ const compressible = compressCache !== undefined && isCompressibleType(type)
103
+ const headers: Record<string, string> = {
104
+ 'content-type': type,
105
+ 'cache-control': 'public, max-age=31536000, immutable',
106
+ ...nosniffHeader,
107
+ }
108
+ const sidecar = (ext: 'br' | 'gz', encoding: string): Sidecar | undefined => {
109
+ const source = assets[`${rel}.${ext}`] ?? (typeof body === 'string' && existsSync(`${body}.${ext}`) ? `${body}.${ext}` : undefined)
110
+ return source === undefined ? undefined : { body: toBody(source), headers: { ...headers, 'content-encoding': encoding, 'vary': 'Accept-Encoding' } }
111
+ }
112
+ const br = sidecar('br', 'br')
113
+ const gz = sidecar('gz', 'gzip')
114
+ const varyHeaders = compressible || br !== undefined || gz !== undefined ? { ...headers, vary: 'Accept-Encoding' } : headers
115
+ assetMap.set(`${assetPrefix}/${rel}`, {
116
+ file: builtFile(`a:${assetPrefix}/${rel}`, body, varyHeaders, compressible ? varyHeaders : undefined),
117
+ br,
118
+ gz,
119
+ })
120
+ }
121
+
122
+ // Prerendered pages (zero-copy file paths preferred; raw HTML strings supported). `fast` holds those nothing may intercept.
123
+ function collectPrerendered(routes: readonly RouteManifestEntry[], sources: PrerenderedSources): { all: Map<string, ServedFile>, fast: Map<string, ServedFile> } {
124
+ const all = new Map<string, ServedFile>()
125
+ const fast = new Map<string, ServedFile>()
126
+ for (const route of routes) {
127
+ if (route.prerendered === undefined)
128
+ continue
129
+ for (const [urlPath, relHtml] of Object.entries(route.prerendered)) {
130
+ const headers: Record<string, string> = { ...sources.htmlHeaders(route, urlPath), ...varyEncoding }
131
+ const compressedHeaders = compressCache !== undefined ? headers : undefined
132
+ const filePath = sources.prerenderedFiles[relHtml]
133
+ const html = sources.prerendered[relHtml]
134
+ const key = `pre:${urlPath}`
135
+ const entry: ServedFile | undefined = filePath !== undefined
136
+ ? builtFile(key, filePath, headers, compressedHeaders)
137
+ : html !== undefined
138
+ ? { key, headers, compressedHeaders, body: html, read: () => textEncoder.encode(html) }
139
+ : undefined
140
+ if (entry === undefined)
141
+ continue
142
+ all.set(urlPath, entry)
143
+ if (sources.isFast(urlPath, route))
144
+ fast.set(urlPath, entry)
145
+ }
146
+ }
147
+ return { all, fast }
148
+ }
149
+
150
+ async function serveFile(request: Request, file: ServedFile): Promise<Response> {
151
+ if (request.method === 'HEAD')
152
+ return withHsts(new Response(null, { status: 200, headers: file.headers }), request)
153
+ if (file.compressedHeaders !== undefined && compressCache !== undefined) {
154
+ const enc = pickEncoding(request.headers.get('accept-encoding'))
155
+ if (enc !== undefined) {
156
+ const compressed = await compressCache.file(file.key, enc, file.read)
157
+ if (compressed !== undefined)
158
+ return withHsts(new Response(compressed, { status: 200, headers: { ...file.compressedHeaders, 'content-encoding': enc } }), request)
159
+ }
160
+ }
161
+ return withHsts(new Response(file.body, { status: 200, headers: file.headers }), request)
162
+ }
163
+
164
+ async function serveAsset(request: Request, asset: AssetEntry): Promise<Response> {
165
+ if (compressEnabled && request.method !== 'HEAD' && (asset.br !== undefined || asset.gz !== undefined)) {
166
+ const preEnc = pickPrecompressedEncoding(request.headers.get('accept-encoding'), { br: asset.br !== undefined, gz: asset.gz !== undefined })
167
+ if (preEnc !== undefined) {
168
+ const sidecar = preEnc === 'br' ? asset.br! : asset.gz!
169
+ return withHsts(new Response(sidecar.body, { status: 200, headers: sidecar.headers }), request)
170
+ }
171
+ }
172
+ return serveFile(request, asset.file)
173
+ }
174
+
175
+ async function servePublic(request: Request, pub: PublicEntry): Promise<Response> {
176
+ if (etagMatches(request.headers.get('if-none-match'), pub.etag))
177
+ return withHsts(new Response(null, { status: 304, headers: pub.notModifiedHeaders }), request)
178
+ return serveFile(request, pub.file)
179
+ }
180
+
181
+ return { assetMap, publicMap, registerPublic, registerPublicFromDisk, collectPrerendered, serveFile, serveAsset, servePublic }
182
+ }
@@ -88,17 +88,85 @@ function hasNoTransform(cacheControl: string | null | undefined): boolean {
88
88
  return Boolean(cacheControl && /\bno-transform\b/i.test(cacheControl))
89
89
  }
90
90
 
91
- // Bun exposes no way to tell a streamed body from a buffered one without reading it, so its inspect output decides. Checked once at load: if the output no longer tells them apart, every body without a length counts as streamed and goes out uncompressed.
92
- const STREAM_MARK = 'ReadableStream {'
93
- const inspectSeesStreams = typeof Bun !== 'undefined'
94
- && Bun.inspect(new Response(new ReadableStream())).includes(STREAM_MARK)
95
- && !Bun.inspect(new Response('')).includes(STREAM_MARK)
91
+ const PENDING: unique symbol = Symbol('pending')
92
+ const MAX_BUFFERED_PROBE_CHUNKS = 32
93
+ const MAX_BUFFERED_PROBE_BYTES = 4 * 1024 * 1024
94
+
95
+ function concatChunks(chunks: readonly Uint8Array[], totalBytes: number): Uint8Array<ArrayBuffer> {
96
+ if (chunks.length === 1) {
97
+ const only = chunks[0]!
98
+ if (only.buffer instanceof ArrayBuffer && only.byteOffset === 0 && only.byteLength === only.buffer.byteLength)
99
+ return only as Uint8Array<ArrayBuffer>
100
+ }
101
+ const out = new Uint8Array(totalBytes)
102
+ let offset = 0
103
+ for (const chunk of chunks) {
104
+ out.set(chunk, offset)
105
+ offset += chunk.byteLength
106
+ }
107
+ return out
108
+ }
96
109
 
97
- function isStreamingBody(res: Response): boolean {
110
+ // Microtask-only probe: buffered bodies (string, TypedArray, JSON, closed streams) settle all chunks
111
+ // within microtasks and can be compressed; open streams stay pending and pass straight through unbuffered.
112
+ async function readBufferedOrPassThrough(
113
+ res: Response,
114
+ ): Promise<{ buffered: Uint8Array<ArrayBuffer> } | { passthrough: Response }> {
98
115
  const te = res.headers.get('transfer-encoding')
99
- if (te && te.toLowerCase().includes('chunked'))
100
- return true
101
- return !inspectSeesStreams || Bun.inspect(res).includes(STREAM_MARK)
116
+ if (te !== null && te.toLowerCase().includes('chunked'))
117
+ return { passthrough: res }
118
+ if (res.body === null)
119
+ return { buffered: new Uint8Array(0) }
120
+
121
+ const reader = res.body.getReader()
122
+ const chunks: Uint8Array[] = []
123
+ let totalBytes = 0
124
+ let pendingRead: ReturnType<typeof reader.read> | undefined
125
+
126
+ while (true) {
127
+ const readPromise = reader.read()
128
+ const tick = Promise.resolve().then(() => Promise.resolve()).then((): typeof PENDING => PENDING)
129
+ const outcome = await Promise.race([readPromise, tick])
130
+ if (outcome === PENDING) {
131
+ pendingRead = readPromise
132
+ break
133
+ }
134
+ if (outcome.done) {
135
+ reader.releaseLock()
136
+ return { buffered: concatChunks(chunks, totalBytes) }
137
+ }
138
+ chunks.push(outcome.value)
139
+ totalBytes += outcome.value.byteLength
140
+ if (chunks.length >= MAX_BUFFERED_PROBE_CHUNKS || totalBytes > MAX_BUFFERED_PROBE_BYTES)
141
+ break
142
+ }
143
+
144
+ let chunkIdx = 0
145
+ const stream = new ReadableStream<Uint8Array>({
146
+ async pull(controller) {
147
+ if (chunkIdx < chunks.length) {
148
+ controller.enqueue(chunks[chunkIdx++]!)
149
+ return
150
+ }
151
+ const next = pendingRead !== undefined ? pendingRead : reader.read()
152
+ pendingRead = undefined
153
+ const { done, value } = await next
154
+ if (done)
155
+ controller.close()
156
+ else
157
+ controller.enqueue(value)
158
+ },
159
+ cancel(reason) {
160
+ return reader.cancel(reason)
161
+ },
162
+ })
163
+ return {
164
+ passthrough: new Response(stream, {
165
+ status: res.status,
166
+ statusText: res.statusText,
167
+ headers: res.headers,
168
+ }),
169
+ }
102
170
  }
103
171
 
104
172
  function hasToken(haystack: string, token: string): boolean {
@@ -300,10 +368,6 @@ export async function maybeCompressResponse(
300
368
  return res
301
369
 
302
370
  const cl = res.headers.get('content-length')
303
- // Never buffer streaming responses that have no Content-Length (e.g. chunked streams, ReadableStream)
304
- if (cl === null && isStreamingBody(res))
305
- return res
306
-
307
371
  const enc = request.method === 'HEAD' ? undefined : pickEncoding(request.headers.get('accept-encoding'))
308
372
  if (enc === undefined) {
309
373
  try {
@@ -324,7 +388,16 @@ export async function maybeCompressResponse(
324
388
  if (res.body === null)
325
389
  return res
326
390
 
327
- const raw = new Uint8Array(await res.arrayBuffer())
391
+ let raw: Uint8Array<ArrayBuffer>
392
+ if (cl !== null) {
393
+ raw = new Uint8Array(await res.arrayBuffer())
394
+ }
395
+ else {
396
+ const probe = await readBufferedOrPassThrough(res)
397
+ if ('passthrough' in probe)
398
+ return probe.passthrough
399
+ raw = probe.buffered
400
+ }
328
401
  const compressed = cache.compress(raw, enc)
329
402
  const headers = new Headers(res.headers)
330
403
  appendVaryAcceptEncoding(headers)
@@ -0,0 +1,192 @@
1
+ // What every rendered document shares: its HTML headers, the plugins' `head` hooks and `transformHtml` passes, and the islands it rendered.
2
+
3
+ import type { DocumentHeadContext, KayPlugin, ServerErrorInfo } from '../plugins/index'
4
+ import type { RenderContext } from '../ssr/context'
5
+ import type { RequestContext } from './http'
6
+ import type { SecurityHeadersOptions, TrustProxy } from './security'
7
+ import { extractRenderedIslands, makeRequestContext } from './http'
8
+ import { KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, resolveCspPolicy, withCspHashes } from './security'
9
+
10
+ const TITLE_INNER_RE = /^<title\b[^>]*>([\s\S]*?)<\/title>$/i
11
+
12
+ /** `styleHashes` are the page's own `<style>` blocks (`inlineStyleHashes`), added to its CSP. */
13
+ export type HtmlHeaders = (hasIslands: boolean, hasSuspense: boolean, isDynamic: boolean, styleHashes?: readonly string[]) => Record<string, string>
14
+
15
+ const STYLED_HEADER_CACHE_SIZE = 256
16
+
17
+ // HTML headers, one set per (dynamic, islands, suspense) combination: the CSP only gains the hashes a page needs.
18
+ export function createHtmlHeaders(security: SecurityHeadersOptions | false | undefined, securityRecord: Record<string, string>): HtmlHeaders {
19
+ const baseCsp = resolveCspPolicy(security)
20
+ const htmlHeaderSets: Record<string, string>[] = []
21
+ const kayStyleHashes: string[][] = []
22
+ for (let i = 0; i < 8; i++) {
23
+ const isDynamic = (i & 4) !== 0
24
+ const hasIslands = (i & 2) !== 0
25
+ const hasSuspense = (i & 1) !== 0
26
+ const headers: Record<string, string> = { 'content-type': 'text/html; charset=utf-8', ...securityRecord }
27
+ if (isDynamic)
28
+ headers['cache-control'] = 'private'
29
+ const styleHashes = [...(hasIslands ? [KAY_ISLAND_STYLE_HASH] : []), ...(hasSuspense ? [KAY_SUSPENSE_STYLE_HASH] : [])]
30
+ kayStyleHashes.push(styleHashes)
31
+ if (baseCsp !== undefined && (hasIslands || hasSuspense)) {
32
+ headers['content-security-policy'] = withCspHashes(baseCsp, {
33
+ styleHashes,
34
+ scriptHashes: hasSuspense ? [KAY_STREAM_SCRIPT_HASH] : [],
35
+ })
36
+ }
37
+ htmlHeaderSets.push(headers)
38
+ }
39
+
40
+ // Pages sharing a layout share its blocks, so their header sets are kept by set and hashes; past the cap a new combination is built each time.
41
+ const styledSets = new Map<string, Record<string, string>>()
42
+ return (hasIslands, hasSuspense, isDynamic, styleHashes) => {
43
+ const index = (isDynamic ? 4 : 0) | (hasIslands ? 2 : 0) | (hasSuspense ? 1 : 0)
44
+ const base = htmlHeaderSets[index]!
45
+ if (baseCsp === undefined || styleHashes === undefined || styleHashes.length === 0)
46
+ return base
47
+ const key = `${index} ${styleHashes.join(' ')}`
48
+ let headers = styledSets.get(key)
49
+ if (headers === undefined) {
50
+ headers = {
51
+ ...base,
52
+ 'content-security-policy': withCspHashes(baseCsp, {
53
+ styleHashes: [...kayStyleHashes[index]!, ...styleHashes],
54
+ scriptHashes: hasSuspense ? [KAY_STREAM_SCRIPT_HASH] : [],
55
+ }),
56
+ }
57
+ if (styledSets.size < STYLED_HEADER_CACHE_SIZE)
58
+ styledSets.set(key, headers)
59
+ }
60
+ return headers
61
+ }
62
+ }
63
+
64
+ export function resolveRenderedIslands(rctx: RenderContext, body: string): { hasIslands: boolean, eagerChunks: string[] } {
65
+ if (rctx.hasIslands) {
66
+ const eagerChunks: string[] = []
67
+ for (const [chunk, eager] of rctx.renderedIslands) {
68
+ if (eager)
69
+ eagerChunks.push(chunk)
70
+ }
71
+ return { hasIslands: true, eagerChunks }
72
+ }
73
+ // Fallback only if raw HTML injected a <kay-island> without going through ssrIsland/ssrIslandStatic.
74
+ if (body.includes('<kay-island'))
75
+ return extractRenderedIslands(body)
76
+ return { hasIslands: false, eagerChunks: [] }
77
+ }
78
+
79
+ export interface DocumentHooksOptions {
80
+ plugins: readonly KayPlugin[]
81
+ lang: string
82
+ trustProxy: TrustProxy
83
+ notifyError: (error: unknown, request: Request, source: ServerErrorInfo['source']) => void
84
+ }
85
+
86
+ export function createDocumentHooks(options: DocumentHooksOptions) {
87
+ const { lang, trustProxy, notifyError } = options
88
+ const headHooks = options.plugins
89
+ .map(p => p.head)
90
+ .filter((fn): fn is NonNullable<KayPlugin['head']> => typeof fn === 'function')
91
+ const htmlTransformers = options.plugins
92
+ .map(p => p.transformHtml)
93
+ .filter((fn): fn is NonNullable<KayPlugin['transformHtml']> => typeof fn === 'function')
94
+ const hasHeadHooks = headHooks.length > 0
95
+ const hasHtmlTransformers = htmlTransformers.length > 0
96
+
97
+ async function resolveDocumentHead(
98
+ rctx: RenderContext,
99
+ baseHeadTags: readonly string[] | undefined,
100
+ url: URL,
101
+ req?: Request,
102
+ ctx?: RequestContext,
103
+ ): Promise<{ head: string, lang: string, htmlAttrs: Record<string, string> }> {
104
+ const collectedParts = rctx.headParts.join('')
105
+ if (!hasHeadHooks) {
106
+ return {
107
+ head: (rctx.title ?? '') + collectedParts,
108
+ lang,
109
+ htmlAttrs: rctx.htmlAttrs,
110
+ }
111
+ }
112
+
113
+ const headCtx = ctx ?? makeRequestContext(req ?? new Request(url.toString()), {}, { trustProxy, url }).ctx
114
+ const htmlAttrs: Record<string, string> = { ...rctx.htmlAttrs }
115
+ const initialTitleTag = rctx.title
116
+ const initialTitleInner = initialTitleTag !== undefined ? TITLE_INNER_RE.exec(initialTitleTag)?.[1] : undefined
117
+ let currentTitle = initialTitleInner
118
+ let titleDirty = false
119
+ let currentLang = htmlAttrs.lang ?? lang
120
+ let headBuf = (initialTitleTag ?? '') + collectedParts
121
+ if (baseHeadTags !== undefined) {
122
+ for (let i = 0; i < baseHeadTags.length; i++)
123
+ headBuf += baseHeadTags[i]
124
+ }
125
+ const added: string[] = []
126
+
127
+ const docHead: DocumentHeadContext = {
128
+ get lang() {
129
+ return currentLang
130
+ },
131
+ set lang(v: string) {
132
+ currentLang = v
133
+ htmlAttrs.lang = v
134
+ },
135
+ htmlAttrs,
136
+ get title() {
137
+ return currentTitle
138
+ },
139
+ set title(v: string | undefined) {
140
+ currentTitle = v
141
+ titleDirty = true
142
+ },
143
+ get headHtml() {
144
+ return headBuf
145
+ },
146
+ add(html: string) {
147
+ if (html !== '') {
148
+ added.push(html)
149
+ headBuf += html
150
+ }
151
+ },
152
+ }
153
+
154
+ for (const hook of headHooks) {
155
+ try {
156
+ await hook(docHead, headCtx)
157
+ }
158
+ catch (err) {
159
+ notifyError(err, req ?? headCtx.request, 'plugin')
160
+ }
161
+ }
162
+
163
+ const titleHtml = titleDirty
164
+ ? (currentTitle !== undefined ? `<title>${currentTitle}</title>` : '')
165
+ : (initialTitleTag ?? '')
166
+ return {
167
+ head: titleHtml + collectedParts + (added.length > 0 ? added.join('') : ''),
168
+ lang: currentLang,
169
+ htmlAttrs,
170
+ }
171
+ }
172
+
173
+ async function applyHtmlTransforms(html: string, url: URL, req?: Request, ctx?: RequestContext): Promise<string> {
174
+ if (!hasHtmlTransformers)
175
+ return html
176
+ const transformCtx = ctx ?? makeRequestContext(req ?? new Request(url.toString()), {}, { trustProxy, url }).ctx
177
+ let out = html
178
+ for (const transform of htmlTransformers) {
179
+ try {
180
+ out = await transform(out, transformCtx)
181
+ }
182
+ catch (err) {
183
+ notifyError(err, req ?? transformCtx.request, 'plugin')
184
+ }
185
+ }
186
+ return out
187
+ }
188
+
189
+ return { hasHeadHooks, hasHtmlTransformers, htmlTransformers, resolveDocumentHead, applyHtmlTransforms }
190
+ }
191
+
192
+ export type DocumentHooks = ReturnType<typeof createDocumentHooks>