@kayjs/kay 2.0.0-alpha.4 → 2.0.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,241 @@
1
+ // Zero-dependency native HTTP compression (Bun.zstdCompressSync / Bun.gzipSync) with bounded byte-budget LRU.
2
+ // Never imports `node:zlib` so server RSS stays minimal.
3
+
4
+ export type CompressionEncoding = 'zstd' | 'gzip'
5
+
6
+ export const MIN_COMPRESS_BYTES = 256
7
+ const DEFAULT_MAX_CACHE_BYTES = 2 * 1024 * 1024
8
+ const encoder = new TextEncoder()
9
+
10
+ const COMPRESSIBLE_EXACT = new Set([
11
+ 'application/javascript',
12
+ 'application/json',
13
+ 'application/xml',
14
+ 'application/xhtml+xml',
15
+ 'application/manifest+json',
16
+ 'application/rss+xml',
17
+ 'application/atom+xml',
18
+ 'application/wasm',
19
+ 'image/svg+xml',
20
+ ])
21
+
22
+ export function isCompressibleType(contentType: string | null | undefined): boolean {
23
+ if (!contentType)
24
+ return false
25
+ const semi = contentType.indexOf(';')
26
+ const mime = (semi === -1 ? contentType : contentType.slice(0, semi)).trim().toLowerCase()
27
+ if (mime.startsWith('text/'))
28
+ return mime !== 'text/event-stream'
29
+ if (COMPRESSIBLE_EXACT.has(mime))
30
+ return true
31
+ return mime.endsWith('+json') || mime.endsWith('+xml')
32
+ }
33
+
34
+ export function pickEncoding(acceptEncoding: string | null): CompressionEncoding | undefined {
35
+ if (!acceptEncoding)
36
+ return undefined
37
+
38
+ // Fast path: standard browser headers without q-values (e.g. "gzip, deflate, br, zstd")
39
+ if (!acceptEncoding.includes(';')) {
40
+ const lower = acceptEncoding.toLowerCase()
41
+ if (hasToken(lower, 'zstd'))
42
+ return 'zstd'
43
+ if (hasToken(lower, 'gzip'))
44
+ return 'gzip'
45
+ return undefined
46
+ }
47
+
48
+ let zstdQ = -1
49
+ let gzipQ = -1
50
+ const parts = acceptEncoding.split(',')
51
+ for (let i = 0; i < parts.length; i++) {
52
+ const part = parts[i]!.trim()
53
+ if (!part)
54
+ continue
55
+ const semi = part.indexOf(';')
56
+ const name = (semi === -1 ? part : part.slice(0, semi)).trim().toLowerCase()
57
+ if (name !== 'zstd' && name !== 'gzip')
58
+ continue
59
+ let q = 1
60
+ if (semi !== -1) {
61
+ const m = /;\s*q\s*=\s*([0-9.]+)/i.exec(part.slice(semi))
62
+ if (m !== null) {
63
+ const parsed = Number(m[1])
64
+ if (!Number.isNaN(parsed))
65
+ q = parsed
66
+ }
67
+ }
68
+ if (name === 'zstd')
69
+ zstdQ = q
70
+ else
71
+ gzipQ = q
72
+ }
73
+
74
+ if (zstdQ <= 0 && gzipQ <= 0)
75
+ return undefined
76
+ return zstdQ >= gzipQ ? 'zstd' : 'gzip'
77
+ }
78
+
79
+ function hasToken(haystack: string, token: string): boolean {
80
+ let idx = haystack.indexOf(token)
81
+ while (idx !== -1) {
82
+ const before = idx === 0 ? ',' : haystack[idx - 1]!
83
+ const after = idx + token.length === haystack.length ? ',' : haystack[idx + token.length]!
84
+ if ((before === ',' || before === ' ' || before === '\t') && (after === ',' || after === ' ' || after === '\t'))
85
+ return true
86
+ idx = haystack.indexOf(token, idx + token.length)
87
+ }
88
+ return false
89
+ }
90
+
91
+ export function compressBuffer(bytes: Uint8Array<ArrayBuffer>, encoding: CompressionEncoding): Uint8Array<ArrayBuffer> {
92
+ if (encoding === 'zstd')
93
+ return Bun.zstdCompressSync(bytes, { level: 3 }) as Uint8Array<ArrayBuffer>
94
+ return Bun.gzipSync(bytes, { level: 6 }) as Uint8Array<ArrayBuffer>
95
+ }
96
+
97
+ export class CompressionCache {
98
+ readonly #map = new Map<string, Uint8Array<ArrayBuffer>>()
99
+ readonly #maxBytes: number
100
+ readonly #maxEntryBytes: number
101
+ #totalBytes = 0
102
+
103
+ constructor(maxBytes = DEFAULT_MAX_CACHE_BYTES) {
104
+ this.#maxBytes = maxBytes
105
+ this.#maxEntryBytes = Math.floor(maxBytes / 4)
106
+ }
107
+
108
+ get(key: string): Uint8Array<ArrayBuffer> | undefined {
109
+ const hit = this.#map.get(key)
110
+ if (hit === undefined)
111
+ return undefined
112
+ // Refresh recency
113
+ this.#map.delete(key)
114
+ this.#map.set(key, hit)
115
+ return hit
116
+ }
117
+
118
+ set(key: string, value: Uint8Array<ArrayBuffer>): void {
119
+ const size = value.byteLength
120
+ if (size > this.#maxEntryBytes)
121
+ return
122
+ const prev = this.#map.get(key)
123
+ if (prev !== undefined) {
124
+ this.#totalBytes -= prev.byteLength
125
+ this.#map.delete(key)
126
+ }
127
+ this.#map.set(key, value)
128
+ this.#totalBytes += size
129
+ while (this.#totalBytes > this.#maxBytes) {
130
+ const oldest = this.#map.keys().next()
131
+ if (oldest.done)
132
+ break
133
+ const evicted = this.#map.get(oldest.value)!
134
+ this.#map.delete(oldest.value)
135
+ this.#totalBytes -= evicted.byteLength
136
+ }
137
+ }
138
+
139
+ compress(bytes: Uint8Array<ArrayBuffer>, encoding: CompressionEncoding, staticKey?: string): Uint8Array<ArrayBuffer> | undefined {
140
+ if (bytes.byteLength < MIN_COMPRESS_BYTES)
141
+ return undefined
142
+ const cacheKey = staticKey !== undefined
143
+ ? `${encoding}:${staticKey}`
144
+ : `${encoding}:h:${Bun.hash.wyhash(bytes).toString(36)}:${bytes.byteLength}`
145
+ const cached = this.get(cacheKey)
146
+ if (cached !== undefined)
147
+ return cached
148
+ const compressed = compressBuffer(bytes, encoding)
149
+ if (compressed.byteLength >= bytes.byteLength)
150
+ return undefined
151
+ this.set(cacheKey, compressed)
152
+ return compressed
153
+ }
154
+ }
155
+
156
+ export function appendVaryAcceptEncoding(headers: Headers): void {
157
+ const existing = headers.get('vary')
158
+ if (!existing) {
159
+ headers.set('vary', 'Accept-Encoding')
160
+ }
161
+ else if (!existing.toLowerCase().includes('accept-encoding')) {
162
+ headers.set('vary', `${existing}, Accept-Encoding`)
163
+ }
164
+ }
165
+
166
+ export function compressedHtmlResponse(
167
+ html: string,
168
+ status: number,
169
+ baseHeaders: Record<string, string>,
170
+ request: Request,
171
+ cache: CompressionCache | undefined,
172
+ ): Response {
173
+ if (cache !== undefined && request.method !== 'HEAD') {
174
+ const enc = pickEncoding(request.headers.get('accept-encoding'))
175
+ if (enc !== undefined && html.length >= MIN_COMPRESS_BYTES) {
176
+ const staticKey = `s:${Bun.hash.wyhash(html).toString(36)}:${html.length}`
177
+ let compressed = cache.get(`${enc}:${staticKey}`)
178
+ if (compressed === undefined) {
179
+ const bytes = encoder.encode(html)
180
+ compressed = cache.compress(bytes, enc, staticKey)
181
+ }
182
+ if (compressed !== undefined) {
183
+ return new Response(compressed, {
184
+ status,
185
+ headers: { ...baseHeaders, 'content-encoding': enc, 'vary': 'Accept-Encoding' },
186
+ })
187
+ }
188
+ }
189
+ }
190
+ return new Response(request.method === 'HEAD' ? null : html, {
191
+ status,
192
+ headers: cache !== undefined ? { ...baseHeaders, vary: 'Accept-Encoding' } : baseHeaders,
193
+ })
194
+ }
195
+
196
+ export async function maybeCompressResponse(
197
+ res: Response,
198
+ request: Request,
199
+ cache: CompressionCache | undefined,
200
+ ): Promise<Response> {
201
+ if (cache === undefined)
202
+ return res
203
+ if (res.status === 204 || res.status === 304 || (res.status >= 300 && res.status < 400))
204
+ return res
205
+ if (res.headers.has('content-encoding'))
206
+ return res
207
+ if (!isCompressibleType(res.headers.get('content-type')))
208
+ return res
209
+
210
+ const enc = request.method === 'HEAD' ? undefined : pickEncoding(request.headers.get('accept-encoding'))
211
+ if (enc === undefined) {
212
+ try {
213
+ appendVaryAcceptEncoding(res.headers)
214
+ }
215
+ catch {}
216
+ return res
217
+ }
218
+
219
+ const cl = res.headers.get('content-length')
220
+ if (cl !== null && Number(cl) < MIN_COMPRESS_BYTES) {
221
+ try {
222
+ appendVaryAcceptEncoding(res.headers)
223
+ }
224
+ catch {}
225
+ return res
226
+ }
227
+
228
+ if (res.body === null)
229
+ return res
230
+
231
+ const raw = new Uint8Array(await res.arrayBuffer())
232
+ const compressed = cache.compress(raw, enc)
233
+ const headers = new Headers(res.headers)
234
+ appendVaryAcceptEncoding(headers)
235
+ if (compressed === undefined)
236
+ return new Response(raw, { status: res.status, statusText: res.statusText, headers })
237
+
238
+ headers.set('content-encoding', enc)
239
+ headers.delete('content-length')
240
+ return new Response(compressed, { status: res.status, statusText: res.statusText, headers })
241
+ }
@@ -83,6 +83,10 @@ export class CookieStore implements Cookies {
83
83
  return Object.fromEntries(this.#values)
84
84
  }
85
85
 
86
+ get hasChanges(): boolean {
87
+ return this.#headers.length > 0
88
+ }
89
+
86
90
  applyTo(headers: Headers): void {
87
91
  for (let i = 0; i < this.#headers.length; i++)
88
92
  headers.append('set-cookie', this.#headers[i]!)
@@ -5,7 +5,7 @@ import type { KayPlugin } from '../plugins/index'
5
5
  import type { Cookies } from './cookies'
6
6
  import type { SecurityHeadersOptions } from './security'
7
7
  import { CookieStore } from './cookies'
8
- import { applySecurityHeaders } from './security'
8
+ import { buildSecurityHeaderEntries } from './security'
9
9
 
10
10
  export interface ServerOptions {
11
11
  root: string
@@ -15,6 +15,7 @@ export interface ServerOptions {
15
15
  lang?: string | undefined
16
16
  security?: SecurityHeadersOptions | false | undefined
17
17
  trustedOrigins?: string[] | undefined
18
+ compress?: boolean | undefined
18
19
  plugins?: KayPlugin[] | undefined
19
20
  }
20
21
 
@@ -46,10 +47,12 @@ export interface EmbeddedServerConfig {
46
47
  publicAssets?: Record<string, EmbeddedBody> | undefined
47
48
  publicEtags?: Record<string, string> | undefined
48
49
  prerendered: Record<string, string>
50
+ prerenderedFiles?: Record<string, string> | undefined
49
51
  assetPrefix?: string | undefined
50
52
  lang?: string | undefined
51
53
  security?: SecurityHeadersOptions | false | undefined
52
54
  trustedOrigins?: string[] | undefined
55
+ compress?: boolean | undefined
53
56
  plugins?: KayPlugin[] | undefined
54
57
  }
55
58
 
@@ -114,10 +117,40 @@ export function makeRequestContext(request: Request, params: Record<string, stri
114
117
  return { ctx, cookieStore }
115
118
  }
116
119
 
117
- export function finalizeResponse(res: Response, cookieStore: CookieStore, security: SecurityHeadersOptions | false | undefined): Response {
118
- const headers = new Headers(res.headers)
119
- cookieStore.applyTo(headers)
120
- if (security !== false)
121
- applySecurityHeaders(headers, security)
122
- return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
120
+ export function finalizeResponse(
121
+ res: Response,
122
+ cookieStore: CookieStore,
123
+ securityEntries: readonly [string, string][] | SecurityHeadersOptions | false | undefined,
124
+ ): Response {
125
+ const entries: readonly [string, string][] = Array.isArray(securityEntries)
126
+ ? securityEntries
127
+ : buildSecurityHeaderEntries(securityEntries as SecurityHeadersOptions | false | undefined)
128
+
129
+ if (!cookieStore.hasChanges && entries.length === 0)
130
+ return res
131
+
132
+ // Fast path: mutate Response.headers in place (zero Response/Headers copy in Bun!)
133
+ try {
134
+ const h = res.headers
135
+ if (cookieStore.hasChanges)
136
+ cookieStore.applyTo(h)
137
+ for (let i = 0; i < entries.length; i++) {
138
+ const [k, v] = entries[i]!
139
+ if (!h.has(k))
140
+ h.set(k, v)
141
+ }
142
+ return res
143
+ }
144
+ catch {
145
+ // Fallback for immutable headers (e.g. proxied upstream fetch Response)
146
+ const headers = new Headers(res.headers)
147
+ if (cookieStore.hasChanges)
148
+ cookieStore.applyTo(headers)
149
+ for (let i = 0; i < entries.length; i++) {
150
+ const [k, v] = entries[i]!
151
+ if (!headers.has(k))
152
+ headers.set(k, v)
153
+ }
154
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
155
+ }
123
156
  }