@kayjs/kay 2.0.0-beta.0 → 2.0.0-beta.1
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/package.json +1 -1
- package/src/attrs.ts +35 -0
- package/src/build/bundle.ts +442 -0
- package/src/build/compile.ts +10 -10
- package/src/build/files.ts +136 -0
- package/src/build/graph.ts +158 -0
- package/src/build/index.ts +204 -1460
- package/src/build/islands.ts +177 -0
- package/src/build/manifest.ts +224 -0
- package/src/build/plugin-host.ts +184 -0
- package/src/build/prerender.ts +93 -0
- package/src/build/report.ts +157 -0
- package/src/build/resolve.ts +58 -0
- package/src/build/routes.ts +135 -0
- package/src/build/static.ts +73 -0
- package/src/cli/check.ts +228 -114
- package/src/cli/index.ts +297 -94
- package/src/cli/new.ts +53 -32
- package/src/compiler/analyze.ts +666 -91
- package/src/compiler/dom.ts +808 -743
- package/src/compiler/mistakes.ts +354 -0
- package/src/compiler/patch.ts +1 -1
- package/src/compiler/server-only.ts +164 -21
- package/src/compiler/shared.ts +442 -0
- package/src/compiler/ssr.ts +329 -342
- package/src/context.ts +120 -0
- package/src/dev/index.ts +271 -75
- package/src/dom/action.ts +23 -13
- package/src/dom/extras.ts +121 -83
- package/src/dom/index.ts +114 -77
- package/src/dom/island.ts +71 -36
- package/src/dom/loop.ts +28 -20
- package/src/index.ts +2 -1
- package/src/jsx-runtime.ts +11 -0
- package/src/plugins/context.ts +57 -0
- package/src/plugins/index.ts +114 -18
- package/src/reactivity/index.ts +237 -213
- package/src/reactivity/selector.ts +11 -9
- package/src/reactivity/store.ts +36 -11
- package/src/server/action.ts +147 -76
- package/src/server/compress.ts +116 -96
- package/src/server/cookies.ts +46 -16
- package/src/server/env.ts +18 -13
- package/src/server/http.ts +107 -54
- package/src/server/index.ts +887 -870
- package/src/server/loader.ts +120 -0
- package/src/server/router.ts +22 -8
- package/src/server/security.ts +48 -58
- package/src/server/standard-schema.ts +42 -11
- package/src/server/static-dir.ts +144 -0
- package/src/ssr/context.ts +95 -10
- package/src/ssr/index.ts +167 -66
- package/src/style.ts +33 -0
- package/src/test/index.ts +2 -1
- package/src/unrenderable.ts +35 -0
package/src/server/compress.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
export type CompressionEncoding = 'zstd' | 'gzip'
|
|
5
5
|
export type PrecompressedEncoding = 'br' | 'gzip'
|
|
6
6
|
|
|
7
|
-
|
|
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
|
-
|
|
36
|
-
if (!acceptEncoding)
|
|
37
|
-
return undefined
|
|
35
|
+
const Q_VALUE_RE = /;\s*q\s*=\s*([0-9.]+)/i
|
|
38
36
|
|
|
39
|
-
|
|
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,
|
|
43
|
-
return
|
|
44
|
-
|
|
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
|
|
50
|
-
let
|
|
51
|
-
const
|
|
52
|
-
|
|
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 !==
|
|
52
|
+
if (name !== first && name !== second)
|
|
59
53
|
continue
|
|
60
54
|
let q = 1
|
|
61
55
|
if (semi !== -1) {
|
|
62
|
-
const
|
|
63
|
-
if (
|
|
64
|
-
|
|
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 ===
|
|
70
|
-
|
|
60
|
+
if (name === first)
|
|
61
|
+
firstQ = q
|
|
71
62
|
else
|
|
72
|
-
|
|
63
|
+
secondQ = q
|
|
73
64
|
}
|
|
74
|
-
|
|
75
|
-
if (zstdQ <= 0 && gzipQ <= 0)
|
|
65
|
+
if (firstQ <= 0 && secondQ <= 0)
|
|
76
66
|
return undefined
|
|
77
|
-
return
|
|
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
|
|
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
|
|
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,17 @@ function hasNoTransform(cacheControl: string | null | undefined): boolean {
|
|
|
134
88
|
return Boolean(cacheControl && /\bno-transform\b/i.test(cacheControl))
|
|
135
89
|
}
|
|
136
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)
|
|
96
|
+
|
|
137
97
|
function isStreamingBody(res: Response): boolean {
|
|
138
|
-
// Check transfer-encoding or Bun's unmaterialized ReadableStream representation BEFORE touching `res.body`.
|
|
139
98
|
const te = res.headers.get('transfer-encoding')
|
|
140
99
|
if (te && te.toLowerCase().includes('chunked'))
|
|
141
100
|
return true
|
|
142
|
-
|
|
143
|
-
return Bun.inspect(res).includes('ReadableStream {')
|
|
144
|
-
return true
|
|
101
|
+
return !inspectSeesStreams || Bun.inspect(res).includes(STREAM_MARK)
|
|
145
102
|
}
|
|
146
103
|
|
|
147
104
|
function hasToken(haystack: string, token: string): boolean {
|
|
@@ -156,21 +113,40 @@ function hasToken(haystack: string, token: string): boolean {
|
|
|
156
113
|
return false
|
|
157
114
|
}
|
|
158
115
|
|
|
159
|
-
|
|
116
|
+
function compressBuffer(bytes: Uint8Array<ArrayBuffer>, encoding: CompressionEncoding): Uint8Array<ArrayBuffer> {
|
|
160
117
|
if (encoding === 'zstd')
|
|
161
118
|
return Bun.zstdCompressSync(bytes, { level: 3 }) as Uint8Array<ArrayBuffer>
|
|
162
119
|
return Bun.gzipSync(bytes, { level: 6 }) as Uint8Array<ArrayBuffer>
|
|
163
120
|
}
|
|
164
121
|
|
|
122
|
+
// `undefined` when the input is too small to be worth compressing or does not shrink.
|
|
123
|
+
function shrink(bytes: Uint8Array<ArrayBuffer>, encoding: CompressionEncoding): Uint8Array<ArrayBuffer> | undefined {
|
|
124
|
+
if (bytes.byteLength < MIN_COMPRESS_BYTES)
|
|
125
|
+
return undefined
|
|
126
|
+
const compressed = compressBuffer(bytes, encoding)
|
|
127
|
+
return compressed.byteLength < bytes.byteLength ? compressed : undefined
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const DEFAULT_MAX_FILE_CACHE_BYTES = 8 * 1024 * 1024
|
|
131
|
+
|
|
165
132
|
export class CompressionCache {
|
|
133
|
+
// Path-keyed build files (assets, public, prerendered pages): bounded byte-budget LRU + in-flight dedup. `null` marks a file that does not shrink.
|
|
134
|
+
readonly #files = new Map<string, Uint8Array<ArrayBuffer> | null>()
|
|
135
|
+
readonly #fileInflight = new Map<string, Promise<Uint8Array<ArrayBuffer> | undefined>>()
|
|
136
|
+
readonly #maxFileBytes: number
|
|
137
|
+
readonly #maxFileEntryBytes: number
|
|
138
|
+
#fileBytes = 0
|
|
139
|
+
// Content-hashed HTML of routes rendered per request: a byte-budget LRU.
|
|
166
140
|
readonly #map = new Map<string, Uint8Array<ArrayBuffer>>()
|
|
167
141
|
readonly #maxBytes: number
|
|
168
142
|
readonly #maxEntryBytes: number
|
|
169
143
|
#totalBytes = 0
|
|
170
144
|
|
|
171
|
-
constructor(maxBytes = DEFAULT_MAX_CACHE_BYTES) {
|
|
145
|
+
constructor(maxBytes = DEFAULT_MAX_CACHE_BYTES, maxFileBytes = DEFAULT_MAX_FILE_CACHE_BYTES) {
|
|
172
146
|
this.#maxBytes = maxBytes
|
|
173
147
|
this.#maxEntryBytes = Math.floor(maxBytes / 4)
|
|
148
|
+
this.#maxFileBytes = maxFileBytes
|
|
149
|
+
this.#maxFileEntryBytes = Math.floor(maxFileBytes / 4)
|
|
174
150
|
}
|
|
175
151
|
|
|
176
152
|
get(key: string): Uint8Array<ArrayBuffer> | undefined {
|
|
@@ -204,24 +180,66 @@ export class CompressionCache {
|
|
|
204
180
|
}
|
|
205
181
|
}
|
|
206
182
|
|
|
183
|
+
/** Compresses `bytes`, kept in the LRU under `staticKey` when given; without one nothing is stored. */
|
|
207
184
|
compress(bytes: Uint8Array<ArrayBuffer>, encoding: CompressionEncoding, staticKey?: string): Uint8Array<ArrayBuffer> | undefined {
|
|
208
|
-
|
|
209
|
-
|
|
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)
|
|
185
|
+
const cacheKey = staticKey !== undefined ? `${encoding}:${staticKey}` : undefined
|
|
186
|
+
const cached = cacheKey !== undefined ? this.get(cacheKey) : undefined
|
|
214
187
|
if (cached !== undefined)
|
|
215
188
|
return cached
|
|
216
|
-
const compressed =
|
|
217
|
-
if (compressed
|
|
218
|
-
|
|
219
|
-
this.set(cacheKey, compressed)
|
|
189
|
+
const compressed = shrink(bytes, encoding)
|
|
190
|
+
if (compressed !== undefined && cacheKey !== undefined)
|
|
191
|
+
this.set(cacheKey, compressed)
|
|
220
192
|
return compressed
|
|
221
193
|
}
|
|
194
|
+
|
|
195
|
+
/** The compressed variant of a build file, read and compressed on its first request only (deduped + bounded LRU); `undefined` when it does not shrink. */
|
|
196
|
+
async file(key: string, encoding: CompressionEncoding, read: () => Uint8Array<ArrayBuffer> | Promise<Uint8Array<ArrayBuffer>>): Promise<Uint8Array<ArrayBuffer> | undefined> {
|
|
197
|
+
const variantKey = `${encoding}:${key}`
|
|
198
|
+
if (this.#files.has(variantKey)) {
|
|
199
|
+
const hit = this.#files.get(variantKey)!
|
|
200
|
+
// Refresh LRU recency
|
|
201
|
+
this.#files.delete(variantKey)
|
|
202
|
+
this.#files.set(variantKey, hit)
|
|
203
|
+
return hit ?? undefined
|
|
204
|
+
}
|
|
205
|
+
const inflight = this.#fileInflight.get(variantKey)
|
|
206
|
+
if (inflight !== undefined)
|
|
207
|
+
return inflight
|
|
208
|
+
|
|
209
|
+
const task = (async () => {
|
|
210
|
+
const bytes = await read()
|
|
211
|
+
const variant = shrink(bytes, encoding) ?? null
|
|
212
|
+
if (variant === null) {
|
|
213
|
+
this.#files.set(variantKey, null)
|
|
214
|
+
return undefined
|
|
215
|
+
}
|
|
216
|
+
if (variant.byteLength <= this.#maxFileEntryBytes) {
|
|
217
|
+
this.#files.set(variantKey, variant)
|
|
218
|
+
this.#fileBytes += variant.byteLength
|
|
219
|
+
while (this.#fileBytes > this.#maxFileBytes) {
|
|
220
|
+
const oldest = this.#files.keys().next()
|
|
221
|
+
if (oldest.done)
|
|
222
|
+
break
|
|
223
|
+
const evicted = this.#files.get(oldest.value)
|
|
224
|
+
this.#files.delete(oldest.value)
|
|
225
|
+
if (evicted !== null && evicted !== undefined)
|
|
226
|
+
this.#fileBytes -= evicted.byteLength
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return variant
|
|
230
|
+
})()
|
|
231
|
+
|
|
232
|
+
this.#fileInflight.set(variantKey, task)
|
|
233
|
+
try {
|
|
234
|
+
return await task
|
|
235
|
+
}
|
|
236
|
+
finally {
|
|
237
|
+
this.#fileInflight.delete(variantKey)
|
|
238
|
+
}
|
|
239
|
+
}
|
|
222
240
|
}
|
|
223
241
|
|
|
224
|
-
|
|
242
|
+
function appendVaryAcceptEncoding(headers: Headers): void {
|
|
225
243
|
const existing = headers.get('vary')
|
|
226
244
|
if (!existing) {
|
|
227
245
|
headers.set('vary', 'Accept-Encoding')
|
|
@@ -231,28 +249,30 @@ export function appendVaryAcceptEncoding(headers: Headers): void {
|
|
|
231
249
|
}
|
|
232
250
|
}
|
|
233
251
|
|
|
252
|
+
/** `reuse` keeps the compressed page by content hash, for routes whose HTML holds nothing per visitor. */
|
|
234
253
|
export function compressedHtmlResponse(
|
|
235
254
|
html: string,
|
|
236
255
|
status: number,
|
|
237
256
|
baseHeaders: Record<string, string>,
|
|
238
257
|
request: Request,
|
|
239
258
|
cache: CompressionCache | undefined,
|
|
259
|
+
reuse = false,
|
|
240
260
|
): Response {
|
|
241
261
|
const noTransform = hasNoTransform(baseHeaders['cache-control'] ?? baseHeaders['Cache-Control'])
|
|
242
262
|
if (cache !== undefined && !noTransform && request.method !== 'HEAD') {
|
|
243
263
|
const enc = pickEncoding(request.headers.get('accept-encoding'))
|
|
244
264
|
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
|
-
|
|
249
|
-
compressed = cache.compress(bytes, enc, staticKey)
|
|
250
|
-
}
|
|
265
|
+
const staticKey = reuse ? `s:${Bun.hash.wyhash(html).toString(36)}:${html.length}` : undefined
|
|
266
|
+
let compressed = staticKey !== undefined ? cache.get(`${enc}:${staticKey}`) : undefined
|
|
267
|
+
if (compressed === undefined)
|
|
268
|
+
compressed = cache.compress(encoder.encode(html), enc, staticKey)
|
|
251
269
|
if (compressed !== undefined) {
|
|
252
270
|
const headers: Record<string, string> = { ...baseHeaders, 'content-encoding': enc, 'vary': 'Accept-Encoding' }
|
|
253
271
|
const etag = headers.etag ?? headers.ETag
|
|
254
|
-
if (etag !== undefined)
|
|
272
|
+
if (etag !== undefined) {
|
|
273
|
+
delete headers.ETag
|
|
255
274
|
headers.etag = toWeakEtag(etag)
|
|
275
|
+
}
|
|
256
276
|
return new Response(compressed, { status, headers })
|
|
257
277
|
}
|
|
258
278
|
}
|
package/src/server/cookies.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Typed cookie jar for RequestContext (
|
|
1
|
+
// Typed cookie jar for RequestContext (lazy Cookie header parsing, validated & deduplicated Set-Cookie serialization).
|
|
2
2
|
|
|
3
3
|
export interface CookieOptions {
|
|
4
4
|
path?: string | undefined
|
|
@@ -17,7 +17,10 @@ export interface Cookies {
|
|
|
17
17
|
all(): Record<string, string>
|
|
18
18
|
}
|
|
19
19
|
|
|
20
|
-
|
|
20
|
+
const VALID_COOKIE_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/
|
|
21
|
+
const UNSAFE_ATTR_VAL = /[;\r\n\u0000-\u001F\u007F]/
|
|
22
|
+
|
|
23
|
+
function parseCookieHeader(header: string | null): Map<string, string> {
|
|
21
24
|
const map = new Map<string, string>()
|
|
22
25
|
if (!header)
|
|
23
26
|
return map
|
|
@@ -28,6 +31,9 @@ export function parseCookieHeader(header: string | null): Map<string, string> {
|
|
|
28
31
|
if (eq <= 0)
|
|
29
32
|
continue
|
|
30
33
|
const name = part.slice(0, eq).trim()
|
|
34
|
+
// RFC 6265 §5.4: more specific path cookies come first, so first wins.
|
|
35
|
+
if (name === '' || map.has(name))
|
|
36
|
+
continue
|
|
31
37
|
const raw = part.slice(eq + 1).trim()
|
|
32
38
|
try {
|
|
33
39
|
map.set(name, decodeURIComponent(raw))
|
|
@@ -40,17 +46,28 @@ export function parseCookieHeader(header: string | null): Map<string, string> {
|
|
|
40
46
|
}
|
|
41
47
|
|
|
42
48
|
function serializeCookie(name: string, value: string, options: CookieOptions = {}, defaultSecure = false): string {
|
|
49
|
+
if (!VALID_COOKIE_NAME.test(name))
|
|
50
|
+
throw new TypeError(`kay: invalid cookie name "${name}"`)
|
|
51
|
+
const path = options.path ?? '/'
|
|
52
|
+
if (UNSAFE_ATTR_VAL.test(path))
|
|
53
|
+
throw new TypeError(`kay: invalid cookie path "${path}"`)
|
|
54
|
+
if (options.domain !== undefined && UNSAFE_ATTR_VAL.test(options.domain))
|
|
55
|
+
throw new TypeError(`kay: invalid cookie domain "${options.domain}"`)
|
|
56
|
+
|
|
43
57
|
const secure = options.secure ?? defaultSecure
|
|
44
58
|
const sameSite = options.sameSite ?? 'lax'
|
|
45
59
|
if (sameSite === 'none' && !secure)
|
|
46
60
|
throw new Error(`kay: Cookie "${name}" with sameSite: "none" requires secure: true`)
|
|
47
61
|
|
|
48
62
|
let out = `${name}=${encodeURIComponent(value)}`
|
|
49
|
-
out += `; Path=${
|
|
63
|
+
out += `; Path=${path}`
|
|
50
64
|
if (options.domain !== undefined)
|
|
51
65
|
out += `; Domain=${options.domain}`
|
|
52
|
-
if (options.maxAge !== undefined)
|
|
66
|
+
if (options.maxAge !== undefined) {
|
|
67
|
+
if (!Number.isFinite(options.maxAge))
|
|
68
|
+
throw new TypeError(`kay: invalid cookie maxAge "${options.maxAge}"`)
|
|
53
69
|
out += `; Max-Age=${Math.floor(options.maxAge)}`
|
|
70
|
+
}
|
|
54
71
|
if (options.expires !== undefined)
|
|
55
72
|
out += `; Expires=${options.expires.toUTCString()}`
|
|
56
73
|
if (options.httpOnly ?? true)
|
|
@@ -61,41 +78,54 @@ function serializeCookie(name: string, value: string, options: CookieOptions = {
|
|
|
61
78
|
return out
|
|
62
79
|
}
|
|
63
80
|
|
|
81
|
+
function cookieKey(name: string, options?: Pick<CookieOptions, 'path' | 'domain'>): string {
|
|
82
|
+
return `${name}\0${options?.path ?? '/'}\0${options?.domain ?? ''}`
|
|
83
|
+
}
|
|
84
|
+
|
|
64
85
|
export class CookieStore implements Cookies {
|
|
65
|
-
|
|
66
|
-
|
|
86
|
+
#rawHeader: string | null
|
|
87
|
+
#values: Map<string, string> | undefined
|
|
88
|
+
readonly #headers = new Map<string, string>()
|
|
67
89
|
readonly #isHttps: boolean
|
|
68
90
|
|
|
69
91
|
constructor(cookieHeader: string | null, isHttps = false) {
|
|
70
|
-
this.#
|
|
92
|
+
this.#rawHeader = cookieHeader
|
|
71
93
|
this.#isHttps = isHttps
|
|
72
94
|
}
|
|
73
95
|
|
|
96
|
+
#ensureValues(): Map<string, string> {
|
|
97
|
+
if (this.#values === undefined) {
|
|
98
|
+
this.#values = parseCookieHeader(this.#rawHeader)
|
|
99
|
+
this.#rawHeader = null
|
|
100
|
+
}
|
|
101
|
+
return this.#values
|
|
102
|
+
}
|
|
103
|
+
|
|
74
104
|
get(name: string): string | undefined {
|
|
75
|
-
return this.#
|
|
105
|
+
return this.#ensureValues().get(name)
|
|
76
106
|
}
|
|
77
107
|
|
|
78
108
|
set(name: string, value: string, options?: CookieOptions): void {
|
|
79
109
|
const serialized = serializeCookie(name, value, options, this.#isHttps)
|
|
80
|
-
this.#
|
|
81
|
-
this.#headers.
|
|
110
|
+
this.#ensureValues().set(name, value)
|
|
111
|
+
this.#headers.set(cookieKey(name, options), serialized)
|
|
82
112
|
}
|
|
83
113
|
|
|
84
114
|
delete(name: string, options?: Pick<CookieOptions, 'path' | 'domain' | 'secure'>): void {
|
|
85
|
-
this.#
|
|
86
|
-
this.#headers.
|
|
115
|
+
this.#ensureValues().delete(name)
|
|
116
|
+
this.#headers.set(cookieKey(name, options), serializeCookie(name, '', { ...options, maxAge: 0, expires: new Date(0) }, this.#isHttps))
|
|
87
117
|
}
|
|
88
118
|
|
|
89
119
|
all(): Record<string, string> {
|
|
90
|
-
return Object.fromEntries(this.#
|
|
120
|
+
return Object.fromEntries(this.#ensureValues())
|
|
91
121
|
}
|
|
92
122
|
|
|
93
123
|
get hasChanges(): boolean {
|
|
94
|
-
return this.#headers.
|
|
124
|
+
return this.#headers.size > 0
|
|
95
125
|
}
|
|
96
126
|
|
|
97
127
|
applyTo(headers: Headers): void {
|
|
98
|
-
for (
|
|
99
|
-
headers.append('set-cookie',
|
|
128
|
+
for (const serialized of this.#headers.values())
|
|
129
|
+
headers.append('set-cookie', serialized)
|
|
100
130
|
}
|
|
101
131
|
}
|
package/src/server/env.ts
CHANGED
|
@@ -1,27 +1,32 @@
|
|
|
1
1
|
// Typed environment variable loader using any Standard Schema validator.
|
|
2
2
|
|
|
3
3
|
import type { InferOutput, StandardSchemaV1 } from './standard-schema'
|
|
4
|
+
import { formatIssuePath, validateSchemaSync } from './standard-schema'
|
|
5
|
+
|
|
6
|
+
const NODE_ENV_KEY = 'NODE_ENV'
|
|
7
|
+
|
|
8
|
+
/** Reads NODE_ENV at runtime: the dynamic key keeps Bun.build from constant-folding it in compiled binaries. */
|
|
9
|
+
export function nodeEnv(): string | undefined {
|
|
10
|
+
return process.env[NODE_ENV_KEY]
|
|
11
|
+
}
|
|
4
12
|
|
|
5
13
|
export function defineEnv<S extends StandardSchemaV1>(
|
|
6
14
|
schema: S,
|
|
7
15
|
source: Record<string, string | undefined> = process.env,
|
|
8
16
|
): Readonly<InferOutput<S>> {
|
|
9
|
-
const result =
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
17
|
+
const result = validateSchemaSync(
|
|
18
|
+
schema,
|
|
19
|
+
source,
|
|
20
|
+
'kay: defineEnv() requires a synchronous Standard Schema validator',
|
|
21
|
+
)
|
|
22
|
+
if (!result.ok) {
|
|
14
23
|
const details = result.issues
|
|
15
|
-
.map((issue)
|
|
16
|
-
const key = issue.path && issue.path.length > 0
|
|
17
|
-
? issue.path.map(seg => (typeof seg === 'object' && seg !== null && 'key' in seg ? String(seg.key) : String(seg))).join('.')
|
|
18
|
-
: '(root)'
|
|
19
|
-
return ` - ${key}: ${issue.message}`
|
|
20
|
-
})
|
|
24
|
+
.map(issue => ` - ${formatIssuePath(issue) || '(root)'}: ${issue.message}`)
|
|
21
25
|
.join('\n')
|
|
22
26
|
throw new Error(`kay: invalid environment variables:\n${details}`)
|
|
23
27
|
}
|
|
24
28
|
|
|
25
|
-
|
|
26
|
-
|
|
29
|
+
return typeof result.value === 'object' && result.value !== null
|
|
30
|
+
? Object.freeze({ ...result.value })
|
|
31
|
+
: result.value
|
|
27
32
|
}
|