@kayjs/kay 2.0.0-alpha.5 → 2.0.0-alpha.7

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.
@@ -5,6 +5,19 @@ import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1 } f
5
5
  import { isTrustedOrigin, verifyOrigin } from './security'
6
6
  import { validateSchema } from './standard-schema'
7
7
 
8
+ export const ACTION_ERROR_COOKIE = '__kay_action_err'
9
+
10
+ export interface ActionErrorFlash {
11
+ action: string
12
+ error: string
13
+ fieldErrors?: Record<string, string> | undefined
14
+ values?: Record<string, string> | undefined
15
+ }
16
+
17
+ export function getActionError(locals?: Record<string, unknown>): ActionErrorFlash | undefined {
18
+ return locals?.actionError as ActionErrorFlash | undefined
19
+ }
20
+
8
21
  export interface ActionContext {
9
22
  request: Request
10
23
  url: URL
@@ -126,6 +139,40 @@ export async function executeAction(
126
139
 
127
140
  const checked = await validateSchema(act.schema, rawBody)
128
141
  if (!checked.ok) {
142
+ // Zero-JS progressive HTML <form> submit: flash fieldErrors + submitted string values and redirect 303 back to trusted Referer
143
+ if (!wantsJson) {
144
+ const referer = request.headers.get('referer')
145
+ if (referer) {
146
+ let refUrl: URL | undefined
147
+ try {
148
+ refUrl = new URL(referer)
149
+ }
150
+ catch {
151
+ refUrl = undefined
152
+ }
153
+ if (refUrl !== undefined && isTrustedOrigin(refUrl.origin, request, trustedOrigins)) {
154
+ const values: Record<string, string> = {}
155
+ if (rawBody !== null && typeof rawBody === 'object') {
156
+ for (const [k, v] of Object.entries(rawBody as Record<string, unknown>)) {
157
+ if (typeof v === 'string' && !/password|secret|token/i.test(k) && v.length <= 512)
158
+ values[k] = v
159
+ }
160
+ }
161
+ const flash: ActionErrorFlash = {
162
+ action: act.url,
163
+ error: 'Validation failed',
164
+ fieldErrors: checked.fieldErrors,
165
+ ...(Object.keys(values).length > 0 ? { values } : {}),
166
+ }
167
+ ctx.cookies.set(ACTION_ERROR_COOKIE, JSON.stringify(flash), {
168
+ httpOnly: true,
169
+ sameSite: 'lax',
170
+ maxAge: 60,
171
+ })
172
+ return Response.redirect(refUrl.href, 303)
173
+ }
174
+ }
175
+ }
129
176
  return Response.json(
130
177
  { ok: false, status: 400, error: 'Validation failed', fieldErrors: checked.fieldErrors, issues: checked.issues },
131
178
  { status: 400 },
@@ -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]!)
@@ -1,11 +1,11 @@
1
1
  // HTTP helpers, MIME table, RequestContext factory, and island tag scanner for Kay v2 server.
2
2
 
3
3
  import type { BuildManifest } from '../build/index'
4
- import type { KayPlugin } from '../plugins/index'
4
+ import type { KayPlugin, ServerErrorInfo } 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,8 @@ export interface ServerOptions {
15
15
  lang?: string | undefined
16
16
  security?: SecurityHeadersOptions | false | undefined
17
17
  trustedOrigins?: string[] | undefined
18
+ compress?: boolean | undefined
19
+ onError?: ((info: ServerErrorInfo) => void) | undefined
18
20
  plugins?: KayPlugin[] | undefined
19
21
  }
20
22
 
@@ -34,7 +36,7 @@ export type Middleware = (ctx: RequestContext, next: () => Promise<Response>) =>
34
36
 
35
37
  export interface KayApp {
36
38
  handle: (request: Request) => Promise<Response>
37
- serve: (port?: number) => ReturnType<typeof Bun.serve>
39
+ serve: (port?: number, hostname?: string) => ReturnType<typeof Bun.serve>
38
40
  }
39
41
 
40
42
  export type EmbeddedBody = Uint8Array<ArrayBuffer> | string
@@ -46,10 +48,13 @@ export interface EmbeddedServerConfig {
46
48
  publicAssets?: Record<string, EmbeddedBody> | undefined
47
49
  publicEtags?: Record<string, string> | undefined
48
50
  prerendered: Record<string, string>
51
+ prerenderedFiles?: Record<string, string> | undefined
49
52
  assetPrefix?: string | undefined
50
53
  lang?: string | undefined
51
54
  security?: SecurityHeadersOptions | false | undefined
52
55
  trustedOrigins?: string[] | undefined
56
+ compress?: boolean | undefined
57
+ onError?: ((info: ServerErrorInfo) => void) | undefined
53
58
  plugins?: KayPlugin[] | undefined
54
59
  }
55
60
 
@@ -114,10 +119,40 @@ export function makeRequestContext(request: Request, params: Record<string, stri
114
119
  return { ctx, cookieStore }
115
120
  }
116
121
 
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 })
122
+ export function finalizeResponse(
123
+ res: Response,
124
+ cookieStore: CookieStore,
125
+ securityEntries: readonly [string, string][] | SecurityHeadersOptions | false | undefined,
126
+ ): Response {
127
+ const entries: readonly [string, string][] = Array.isArray(securityEntries)
128
+ ? securityEntries
129
+ : buildSecurityHeaderEntries(securityEntries as SecurityHeadersOptions | false | undefined)
130
+
131
+ if (!cookieStore.hasChanges && entries.length === 0)
132
+ return res
133
+
134
+ // Fast path: mutate Response.headers in place (zero Response/Headers copy in Bun!)
135
+ try {
136
+ const h = res.headers
137
+ if (cookieStore.hasChanges)
138
+ cookieStore.applyTo(h)
139
+ for (let i = 0; i < entries.length; i++) {
140
+ const [k, v] = entries[i]!
141
+ if (!h.has(k))
142
+ h.set(k, v)
143
+ }
144
+ return res
145
+ }
146
+ catch {
147
+ // Fallback for immutable headers (e.g. proxied upstream fetch Response)
148
+ const headers = new Headers(res.headers)
149
+ if (cookieStore.hasChanges)
150
+ cookieStore.applyTo(headers)
151
+ for (let i = 0; i < entries.length; i++) {
152
+ const [k, v] = entries[i]!
153
+ if (!headers.has(k))
154
+ headers.set(k, v)
155
+ }
156
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
157
+ }
123
158
  }