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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +617 -0
  4. package/src/build/compile.ts +27 -51
  5. package/src/build/files.ts +174 -0
  6. package/src/build/graph.ts +223 -0
  7. package/src/build/index.ts +272 -1466
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +229 -0
  10. package/src/build/plugin-host.ts +186 -0
  11. package/src/build/prerender.ts +102 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +51 -0
  14. package/src/build/routes.ts +163 -0
  15. package/src/build/server-entry.ts +38 -0
  16. package/src/build/static.ts +73 -0
  17. package/src/cli/check.ts +300 -129
  18. package/src/cli/index.ts +297 -94
  19. package/src/cli/new.ts +58 -38
  20. package/src/compiler/analyze.ts +723 -93
  21. package/src/compiler/dom.ts +848 -762
  22. package/src/compiler/mistakes.ts +354 -0
  23. package/src/compiler/patch.ts +1 -1
  24. package/src/compiler/server-only.ts +172 -23
  25. package/src/compiler/shared.ts +485 -0
  26. package/src/compiler/ssr.ts +331 -342
  27. package/src/context.ts +120 -0
  28. package/src/dev/index.ts +339 -76
  29. package/src/dom/action.ts +114 -14
  30. package/src/dom/extras.ts +121 -83
  31. package/src/dom/index.ts +122 -80
  32. package/src/dom/island.ts +71 -36
  33. package/src/dom/loop.ts +28 -20
  34. package/src/index.ts +5 -1
  35. package/src/jsx-runtime.ts +432 -93
  36. package/src/plugins/config.ts +49 -0
  37. package/src/plugins/context.ts +61 -0
  38. package/src/plugins/index.ts +10 -123
  39. package/src/plugins/load.ts +38 -0
  40. package/src/plugins/order.ts +107 -0
  41. package/src/plugins/services.ts +23 -0
  42. package/src/plugins/types.ts +197 -0
  43. package/src/reactivity/index.ts +237 -213
  44. package/src/reactivity/selector.ts +11 -9
  45. package/src/reactivity/store.ts +36 -11
  46. package/src/server/action-registry.ts +72 -0
  47. package/src/server/action.ts +157 -79
  48. package/src/server/app-entry.ts +23 -0
  49. package/src/server/assets.ts +182 -0
  50. package/src/server/compress.ts +197 -104
  51. package/src/server/cookies.ts +46 -16
  52. package/src/server/document.ts +192 -0
  53. package/src/server/env.ts +18 -13
  54. package/src/server/errors.ts +123 -0
  55. package/src/server/http.ts +203 -77
  56. package/src/server/index.ts +420 -973
  57. package/src/server/loader.ts +113 -0
  58. package/src/server/page.ts +107 -0
  59. package/src/server/plugin-host.ts +167 -0
  60. package/src/server/router.ts +69 -26
  61. package/src/server/security.ts +90 -59
  62. package/src/server/standard-schema.ts +42 -11
  63. package/src/server/static-dir.ts +163 -0
  64. package/src/server/stream.ts +94 -0
  65. package/src/ssr/context.ts +95 -10
  66. package/src/ssr/index.ts +167 -66
  67. package/src/style.ts +33 -0
  68. package/src/test/index.ts +24 -18
  69. package/src/unrenderable.ts +35 -0
@@ -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
+ }
@@ -4,7 +4,7 @@
4
4
  export type CompressionEncoding = 'zstd' | 'gzip'
5
5
  export type PrecompressedEncoding = 'br' | 'gzip'
6
6
 
7
- export const MIN_COMPRESS_BYTES = 256
7
+ const MIN_COMPRESS_BYTES = 256
8
8
  const DEFAULT_MAX_CACHE_BYTES = 2 * 1024 * 1024
9
9
  const encoder = new TextEncoder()
10
10
 
@@ -32,98 +32,52 @@ export function isCompressibleType(contentType: string | null | undefined): bool
32
32
  return mime.endsWith('+json') || mime.endsWith('+xml')
33
33
  }
34
34
 
35
- export function pickEncoding(acceptEncoding: string | null): CompressionEncoding | undefined {
36
- if (!acceptEncoding)
37
- return undefined
35
+ const Q_VALUE_RE = /;\s*q\s*=\s*([0-9.]+)/i
38
36
 
39
- // Fast path: standard browser headers without q-values (e.g. "gzip, deflate, br, zstd")
37
+ // The `first` token wins ties; a token the header omits or gives q=0 never wins. Headers without q-values (the usual browser ones) take the allocation-free path.
38
+ function pickToken<A extends string, B extends string>(acceptEncoding: string, first: A | undefined, second: B | undefined): A | B | undefined {
40
39
  if (!acceptEncoding.includes(';')) {
41
40
  const lower = acceptEncoding.toLowerCase()
42
- if (hasToken(lower, 'zstd'))
43
- return 'zstd'
44
- if (hasToken(lower, 'gzip'))
45
- return 'gzip'
46
- return undefined
41
+ if (first !== undefined && hasToken(lower, first))
42
+ return first
43
+ return second !== undefined && hasToken(lower, second) ? second : undefined
47
44
  }
48
45
 
49
- let zstdQ = -1
50
- let gzipQ = -1
51
- const parts = acceptEncoding.split(',')
52
- for (let i = 0; i < parts.length; i++) {
53
- const part = parts[i]!.trim()
54
- if (!part)
55
- continue
46
+ let firstQ = -1
47
+ let secondQ = -1
48
+ for (const rawPart of acceptEncoding.split(',')) {
49
+ const part = rawPart.trim()
56
50
  const semi = part.indexOf(';')
57
51
  const name = (semi === -1 ? part : part.slice(0, semi)).trim().toLowerCase()
58
- if (name !== 'zstd' && name !== 'gzip')
52
+ if (name !== first && name !== second)
59
53
  continue
60
54
  let q = 1
61
55
  if (semi !== -1) {
62
- const m = /;\s*q\s*=\s*([0-9.]+)/i.exec(part.slice(semi))
63
- if (m !== null) {
64
- const parsed = Number(m[1])
65
- if (!Number.isNaN(parsed))
66
- q = parsed
67
- }
56
+ const parsed = Number(Q_VALUE_RE.exec(part.slice(semi))?.[1])
57
+ if (!Number.isNaN(parsed))
58
+ q = parsed
68
59
  }
69
- if (name === 'zstd')
70
- zstdQ = q
60
+ if (name === first)
61
+ firstQ = q
71
62
  else
72
- gzipQ = q
63
+ secondQ = q
73
64
  }
74
-
75
- if (zstdQ <= 0 && gzipQ <= 0)
65
+ if (firstQ <= 0 && secondQ <= 0)
76
66
  return undefined
77
- return zstdQ >= gzipQ ? 'zstd' : 'gzip'
67
+ return firstQ >= secondQ ? first : second
68
+ }
69
+
70
+ export function pickEncoding(acceptEncoding: string | null): CompressionEncoding | undefined {
71
+ return acceptEncoding ? pickToken(acceptEncoding, 'zstd', 'gzip') : undefined
78
72
  }
79
73
 
80
74
  export function pickPrecompressedEncoding(
81
75
  acceptEncoding: string | null,
82
76
  available: { br?: boolean, gz?: boolean },
83
77
  ): PrecompressedEncoding | undefined {
84
- if (!acceptEncoding || (!available.br && !available.gz))
85
- return undefined
86
-
87
- if (!acceptEncoding.includes(';')) {
88
- const lower = acceptEncoding.toLowerCase()
89
- if (available.br && hasToken(lower, 'br'))
90
- return 'br'
91
- if (available.gz && hasToken(lower, 'gzip'))
92
- return 'gzip'
93
- return undefined
94
- }
95
-
96
- let brQ = -1
97
- let gzipQ = -1
98
- const parts = acceptEncoding.split(',')
99
- for (let i = 0; i < parts.length; i++) {
100
- const part = parts[i]!.trim()
101
- if (!part)
102
- continue
103
- const semi = part.indexOf(';')
104
- const name = (semi === -1 ? part : part.slice(0, semi)).trim().toLowerCase()
105
- if (name !== 'br' && name !== 'gzip')
106
- continue
107
- let q = 1
108
- if (semi !== -1) {
109
- const m = /;\s*q\s*=\s*([0-9.]+)/i.exec(part.slice(semi))
110
- if (m !== null) {
111
- const parsed = Number(m[1])
112
- if (!Number.isNaN(parsed))
113
- q = parsed
114
- }
115
- }
116
- if (name === 'br')
117
- brQ = q
118
- else
119
- gzipQ = q
120
- }
121
-
122
- const effBr = available.br ? brQ : -1
123
- const effGz = available.gz ? gzipQ : -1
124
- if (effBr <= 0 && effGz <= 0)
78
+ if (!acceptEncoding)
125
79
  return undefined
126
- return effBr >= effGz ? 'br' : 'gzip'
80
+ return pickToken(acceptEncoding, available.br ? 'br' : undefined, available.gz ? 'gzip' : undefined)
127
81
  }
128
82
 
129
83
  export function toWeakEtag(etag: string): string {
@@ -134,14 +88,85 @@ function hasNoTransform(cacheControl: string | null | undefined): boolean {
134
88
  return Boolean(cacheControl && /\bno-transform\b/i.test(cacheControl))
135
89
  }
136
90
 
137
- function isStreamingBody(res: Response): boolean {
138
- // Check transfer-encoding or Bun's unmaterialized ReadableStream representation BEFORE touching `res.body`.
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
+ }
109
+
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 }> {
139
115
  const te = res.headers.get('transfer-encoding')
140
- if (te && te.toLowerCase().includes('chunked'))
141
- return true
142
- if (typeof Bun !== 'undefined')
143
- return Bun.inspect(res).includes('ReadableStream {')
144
- return true
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
+ }
145
170
  }
146
171
 
147
172
  function hasToken(haystack: string, token: string): boolean {
@@ -156,21 +181,40 @@ function hasToken(haystack: string, token: string): boolean {
156
181
  return false
157
182
  }
158
183
 
159
- export function compressBuffer(bytes: Uint8Array<ArrayBuffer>, encoding: CompressionEncoding): Uint8Array<ArrayBuffer> {
184
+ function compressBuffer(bytes: Uint8Array<ArrayBuffer>, encoding: CompressionEncoding): Uint8Array<ArrayBuffer> {
160
185
  if (encoding === 'zstd')
161
186
  return Bun.zstdCompressSync(bytes, { level: 3 }) as Uint8Array<ArrayBuffer>
162
187
  return Bun.gzipSync(bytes, { level: 6 }) as Uint8Array<ArrayBuffer>
163
188
  }
164
189
 
190
+ // `undefined` when the input is too small to be worth compressing or does not shrink.
191
+ function shrink(bytes: Uint8Array<ArrayBuffer>, encoding: CompressionEncoding): Uint8Array<ArrayBuffer> | undefined {
192
+ if (bytes.byteLength < MIN_COMPRESS_BYTES)
193
+ return undefined
194
+ const compressed = compressBuffer(bytes, encoding)
195
+ return compressed.byteLength < bytes.byteLength ? compressed : undefined
196
+ }
197
+
198
+ const DEFAULT_MAX_FILE_CACHE_BYTES = 8 * 1024 * 1024
199
+
165
200
  export class CompressionCache {
201
+ // Path-keyed build files (assets, public, prerendered pages): bounded byte-budget LRU + in-flight dedup. `null` marks a file that does not shrink.
202
+ readonly #files = new Map<string, Uint8Array<ArrayBuffer> | null>()
203
+ readonly #fileInflight = new Map<string, Promise<Uint8Array<ArrayBuffer> | undefined>>()
204
+ readonly #maxFileBytes: number
205
+ readonly #maxFileEntryBytes: number
206
+ #fileBytes = 0
207
+ // Content-hashed HTML of routes rendered per request: a byte-budget LRU.
166
208
  readonly #map = new Map<string, Uint8Array<ArrayBuffer>>()
167
209
  readonly #maxBytes: number
168
210
  readonly #maxEntryBytes: number
169
211
  #totalBytes = 0
170
212
 
171
- constructor(maxBytes = DEFAULT_MAX_CACHE_BYTES) {
213
+ constructor(maxBytes = DEFAULT_MAX_CACHE_BYTES, maxFileBytes = DEFAULT_MAX_FILE_CACHE_BYTES) {
172
214
  this.#maxBytes = maxBytes
173
215
  this.#maxEntryBytes = Math.floor(maxBytes / 4)
216
+ this.#maxFileBytes = maxFileBytes
217
+ this.#maxFileEntryBytes = Math.floor(maxFileBytes / 4)
174
218
  }
175
219
 
176
220
  get(key: string): Uint8Array<ArrayBuffer> | undefined {
@@ -204,24 +248,66 @@ export class CompressionCache {
204
248
  }
205
249
  }
206
250
 
251
+ /** Compresses `bytes`, kept in the LRU under `staticKey` when given; without one nothing is stored. */
207
252
  compress(bytes: Uint8Array<ArrayBuffer>, encoding: CompressionEncoding, staticKey?: string): Uint8Array<ArrayBuffer> | undefined {
208
- if (bytes.byteLength < MIN_COMPRESS_BYTES)
209
- return undefined
210
- const cacheKey = staticKey !== undefined
211
- ? `${encoding}:${staticKey}`
212
- : `${encoding}:h:${Bun.hash.wyhash(bytes).toString(36)}:${bytes.byteLength}`
213
- const cached = this.get(cacheKey)
253
+ const cacheKey = staticKey !== undefined ? `${encoding}:${staticKey}` : undefined
254
+ const cached = cacheKey !== undefined ? this.get(cacheKey) : undefined
214
255
  if (cached !== undefined)
215
256
  return cached
216
- const compressed = compressBuffer(bytes, encoding)
217
- if (compressed.byteLength >= bytes.byteLength)
218
- return undefined
219
- this.set(cacheKey, compressed)
257
+ const compressed = shrink(bytes, encoding)
258
+ if (compressed !== undefined && cacheKey !== undefined)
259
+ this.set(cacheKey, compressed)
220
260
  return compressed
221
261
  }
262
+
263
+ /** The compressed variant of a build file, read and compressed on its first request only (deduped + bounded LRU); `undefined` when it does not shrink. */
264
+ async file(key: string, encoding: CompressionEncoding, read: () => Uint8Array<ArrayBuffer> | Promise<Uint8Array<ArrayBuffer>>): Promise<Uint8Array<ArrayBuffer> | undefined> {
265
+ const variantKey = `${encoding}:${key}`
266
+ if (this.#files.has(variantKey)) {
267
+ const hit = this.#files.get(variantKey)!
268
+ // Refresh LRU recency
269
+ this.#files.delete(variantKey)
270
+ this.#files.set(variantKey, hit)
271
+ return hit ?? undefined
272
+ }
273
+ const inflight = this.#fileInflight.get(variantKey)
274
+ if (inflight !== undefined)
275
+ return inflight
276
+
277
+ const task = (async () => {
278
+ const bytes = await read()
279
+ const variant = shrink(bytes, encoding) ?? null
280
+ if (variant === null) {
281
+ this.#files.set(variantKey, null)
282
+ return undefined
283
+ }
284
+ if (variant.byteLength <= this.#maxFileEntryBytes) {
285
+ this.#files.set(variantKey, variant)
286
+ this.#fileBytes += variant.byteLength
287
+ while (this.#fileBytes > this.#maxFileBytes) {
288
+ const oldest = this.#files.keys().next()
289
+ if (oldest.done)
290
+ break
291
+ const evicted = this.#files.get(oldest.value)
292
+ this.#files.delete(oldest.value)
293
+ if (evicted !== null && evicted !== undefined)
294
+ this.#fileBytes -= evicted.byteLength
295
+ }
296
+ }
297
+ return variant
298
+ })()
299
+
300
+ this.#fileInflight.set(variantKey, task)
301
+ try {
302
+ return await task
303
+ }
304
+ finally {
305
+ this.#fileInflight.delete(variantKey)
306
+ }
307
+ }
222
308
  }
223
309
 
224
- export function appendVaryAcceptEncoding(headers: Headers): void {
310
+ function appendVaryAcceptEncoding(headers: Headers): void {
225
311
  const existing = headers.get('vary')
226
312
  if (!existing) {
227
313
  headers.set('vary', 'Accept-Encoding')
@@ -231,28 +317,30 @@ export function appendVaryAcceptEncoding(headers: Headers): void {
231
317
  }
232
318
  }
233
319
 
320
+ /** `reuse` keeps the compressed page by content hash, for routes whose HTML holds nothing per visitor. */
234
321
  export function compressedHtmlResponse(
235
322
  html: string,
236
323
  status: number,
237
324
  baseHeaders: Record<string, string>,
238
325
  request: Request,
239
326
  cache: CompressionCache | undefined,
327
+ reuse = false,
240
328
  ): Response {
241
329
  const noTransform = hasNoTransform(baseHeaders['cache-control'] ?? baseHeaders['Cache-Control'])
242
330
  if (cache !== undefined && !noTransform && request.method !== 'HEAD') {
243
331
  const enc = pickEncoding(request.headers.get('accept-encoding'))
244
332
  if (enc !== undefined && html.length >= MIN_COMPRESS_BYTES) {
245
- const staticKey = `s:${Bun.hash.wyhash(html).toString(36)}:${html.length}`
246
- let compressed = cache.get(`${enc}:${staticKey}`)
247
- if (compressed === undefined) {
248
- const bytes = encoder.encode(html)
249
- compressed = cache.compress(bytes, enc, staticKey)
250
- }
333
+ const staticKey = reuse ? `s:${Bun.hash.wyhash(html).toString(36)}:${html.length}` : undefined
334
+ let compressed = staticKey !== undefined ? cache.get(`${enc}:${staticKey}`) : undefined
335
+ if (compressed === undefined)
336
+ compressed = cache.compress(encoder.encode(html), enc, staticKey)
251
337
  if (compressed !== undefined) {
252
338
  const headers: Record<string, string> = { ...baseHeaders, 'content-encoding': enc, 'vary': 'Accept-Encoding' }
253
339
  const etag = headers.etag ?? headers.ETag
254
- if (etag !== undefined)
340
+ if (etag !== undefined) {
341
+ delete headers.ETag
255
342
  headers.etag = toWeakEtag(etag)
343
+ }
256
344
  return new Response(compressed, { status, headers })
257
345
  }
258
346
  }
@@ -280,10 +368,6 @@ export async function maybeCompressResponse(
280
368
  return res
281
369
 
282
370
  const cl = res.headers.get('content-length')
283
- // Never buffer streaming responses that have no Content-Length (e.g. chunked streams, ReadableStream)
284
- if (cl === null && isStreamingBody(res))
285
- return res
286
-
287
371
  const enc = request.method === 'HEAD' ? undefined : pickEncoding(request.headers.get('accept-encoding'))
288
372
  if (enc === undefined) {
289
373
  try {
@@ -304,7 +388,16 @@ export async function maybeCompressResponse(
304
388
  if (res.body === null)
305
389
  return res
306
390
 
307
- 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
+ }
308
401
  const compressed = cache.compress(raw, enc)
309
402
  const headers = new Headers(res.headers)
310
403
  appendVaryAcceptEncoding(headers)