@kayjs/kay 2.0.0-alpha.8 → 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.
Files changed (55) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +442 -0
  4. package/src/build/compile.ts +20 -11
  5. package/src/build/files.ts +136 -0
  6. package/src/build/graph.ts +158 -0
  7. package/src/build/index.ts +231 -1296
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +224 -0
  10. package/src/build/plugin-host.ts +184 -0
  11. package/src/build/prerender.ts +93 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +58 -0
  14. package/src/build/routes.ts +135 -0
  15. package/src/build/static.ts +73 -0
  16. package/src/cli/check.ts +228 -114
  17. package/src/cli/index.ts +298 -79
  18. package/src/cli/new.ts +67 -35
  19. package/src/compiler/analyze.ts +666 -91
  20. package/src/compiler/dom.ts +822 -629
  21. package/src/compiler/mistakes.ts +354 -0
  22. package/src/compiler/patch.ts +1 -1
  23. package/src/compiler/server-only.ts +164 -21
  24. package/src/compiler/shared.ts +442 -0
  25. package/src/compiler/ssr.ts +390 -324
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +291 -76
  28. package/src/dom/action.ts +23 -13
  29. package/src/dom/extras.ts +157 -84
  30. package/src/dom/index.ts +154 -33
  31. package/src/dom/island.ts +117 -39
  32. package/src/dom/loop.ts +34 -21
  33. package/src/index.ts +2 -1
  34. package/src/jsx-runtime.ts +11 -0
  35. package/src/plugins/context.ts +57 -0
  36. package/src/plugins/index.ts +120 -17
  37. package/src/reactivity/index.ts +250 -157
  38. package/src/reactivity/selector.ts +11 -9
  39. package/src/reactivity/store.ts +37 -12
  40. package/src/server/action.ts +217 -74
  41. package/src/server/compress.ts +155 -56
  42. package/src/server/cookies.ts +59 -22
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +201 -33
  45. package/src/server/index.ts +964 -737
  46. package/src/server/loader.ts +120 -0
  47. package/src/server/router.ts +27 -8
  48. package/src/server/security.ts +87 -39
  49. package/src/server/standard-schema.ts +42 -11
  50. package/src/server/static-dir.ts +144 -0
  51. package/src/ssr/context.ts +96 -10
  52. package/src/ssr/index.ts +225 -56
  53. package/src/style.ts +33 -0
  54. package/src/test/index.ts +5 -0
  55. package/src/unrenderable.ts +35 -0
@@ -3,9 +3,12 @@
3
3
  import type { BuildManifest } from '../build/index'
4
4
  import type { KayPlugin, ServerErrorInfo } from '../plugins/index'
5
5
  import type { Cookies } from './cookies'
6
- import type { SecurityHeadersOptions } from './security'
6
+ import type { SecurityHeadersOptions, TrustProxy } from './security'
7
7
  import { CookieStore } from './cookies'
8
- import { buildSecurityHeaderEntries } from './security'
8
+ import { nodeEnv } from './env'
9
+ import { getClientIp, isHttpsRequest } from './security'
10
+
11
+ export const DEFAULT_MAX_REQUEST_BODY_SIZE = 1024 * 1024
9
12
 
10
13
  export interface ServerOptions {
11
14
  root: string
@@ -15,9 +18,16 @@ export interface ServerOptions {
15
18
  lang?: string | undefined
16
19
  security?: SecurityHeadersOptions | false | undefined
17
20
  trustedOrigins?: string[] | undefined
21
+ trustProxy?: TrustProxy | undefined
22
+ maxRequestBodySize?: number | undefined
23
+ /** Milliseconds a streamed `<Suspense>` boundary may take before it renders its error and the response ends (default 30000). */
24
+ streamTimeout?: number | undefined
18
25
  compress?: boolean | undefined
26
+ dev?: boolean | undefined
19
27
  onError?: ((info: ServerErrorInfo) => void) | undefined
20
28
  plugins?: KayPlugin[] | undefined
29
+ /** @internal Imports a built server module by absolute path; `kay dev` passes one that keeps unchanged modules loaded. */
30
+ importModule?: ((path: string) => Promise<Record<string, unknown>>) | undefined
21
31
  }
22
32
 
23
33
  export interface RequestContext {
@@ -26,6 +36,7 @@ export interface RequestContext {
26
36
  params: Record<string, string>
27
37
  cookies: Cookies
28
38
  locals: Record<string, unknown>
39
+ ip?: string | undefined
29
40
  json: (data: unknown, init?: ResponseInit) => Response
30
41
  text: (body: string, init?: ResponseInit) => Response
31
42
  redirect: (location: string, status?: 301 | 302 | 303 | 307 | 308) => Response
@@ -35,8 +46,10 @@ export interface RequestContext {
35
46
  export type Middleware = (ctx: RequestContext, next: () => Promise<Response>) => Response | Promise<Response>
36
47
 
37
48
  export interface KayApp {
38
- handle: (request: Request) => Promise<Response>
49
+ handle: (request: Request, remoteIp?: string) => Promise<Response>
39
50
  serve: (port?: number, hostname?: string) => ReturnType<typeof Bun.serve>
51
+ /** Runs plugin shutdown hooks and releases timers/resources (safe to call multiple times). */
52
+ dispose?: () => Promise<void>
40
53
  }
41
54
 
42
55
  export type EmbeddedBody = Uint8Array<ArrayBuffer> | string
@@ -49,11 +62,19 @@ export interface EmbeddedServerConfig {
49
62
  publicEtags?: Record<string, string> | undefined
50
63
  prerendered: Record<string, string>
51
64
  prerenderedFiles?: Record<string, string> | undefined
65
+ root?: string | undefined
66
+ outDir?: string | undefined
67
+ publicDir?: string | undefined
52
68
  assetPrefix?: string | undefined
53
69
  lang?: string | undefined
54
70
  security?: SecurityHeadersOptions | false | undefined
55
71
  trustedOrigins?: string[] | undefined
72
+ trustProxy?: TrustProxy | undefined
73
+ maxRequestBodySize?: number | undefined
74
+ /** Milliseconds a streamed `<Suspense>` boundary may take before it renders its error and the response ends (default 30000). */
75
+ streamTimeout?: number | undefined
56
76
  compress?: boolean | undefined
77
+ dev?: boolean | undefined
57
78
  onError?: ((info: ServerErrorInfo) => void) | undefined
58
79
  plugins?: KayPlugin[] | undefined
59
80
  }
@@ -102,57 +123,204 @@ export function extractRenderedIslands(html: string): { hasIslands: boolean, eag
102
123
  return { hasIslands, eagerChunks: [...eager] }
103
124
  }
104
125
 
105
- export function makeRequestContext(request: Request, params: Record<string, string>): { ctx: RequestContext, cookieStore: CookieStore } {
106
- const url = new URL(request.url)
107
- const cookieStore = new CookieStore(request.headers.get('cookie'))
126
+ export interface RequestContextOptions {
127
+ trustProxy?: TrustProxy | undefined
128
+ remoteIp?: string | undefined
129
+ /** The parsed `request.url`, when the caller already has it. */
130
+ url?: URL | undefined
131
+ }
132
+
133
+ // None of these read the request, so every context shares them.
134
+ const json: RequestContext['json'] = (data, init) => {
135
+ const payload = JSON.stringify(data)
136
+ const headers = new Headers(init?.headers)
137
+ if (!headers.has('content-type'))
138
+ headers.set('content-type', 'application/json; charset=utf-8')
139
+ if (!headers.has('content-length'))
140
+ headers.set('content-length', String(Buffer.byteLength(payload, 'utf8')))
141
+ return new Response(payload, { ...init, headers })
142
+ }
143
+ const text: RequestContext['text'] = (body, init) => {
144
+ const headers = new Headers(init?.headers)
145
+ if (!headers.has('content-type'))
146
+ headers.set('content-type', 'text/plain; charset=utf-8')
147
+ if (!headers.has('content-length'))
148
+ headers.set('content-length', String(Buffer.byteLength(body, 'utf8')))
149
+ return new Response(body, { ...init, headers })
150
+ }
151
+ const redirect: RequestContext['redirect'] = (location, status = 302) => new Response(null, { status, headers: { location } })
152
+ const deny: RequestContext['deny'] = (status, message, fieldErrors) => Response.json({ ok: false, status, error: message, fieldErrors }, { status })
153
+
154
+ /** RFC 9110 weak ETag comparison supporting `*`, comma-separated lists, and `W/` prefixes. */
155
+ export function etagMatches(ifNoneMatch: string | null, etag: string): boolean {
156
+ if (!ifNoneMatch)
157
+ return false
158
+ const trimmed = ifNoneMatch.trim()
159
+ if (trimmed === '*')
160
+ return true
161
+ const stripWeak = (v: string) => (v.startsWith('W/') || v.startsWith('w/') ? v.slice(2) : v)
162
+ const target = stripWeak(etag)
163
+ for (const part of trimmed.split(',')) {
164
+ if (stripWeak(part.trim()) === target)
165
+ return true
166
+ }
167
+ return false
168
+ }
169
+
170
+ export function makeRequestContext(
171
+ request: Request,
172
+ params: Record<string, string>,
173
+ opts?: RequestContextOptions,
174
+ ): { ctx: RequestContext, cookieStore: CookieStore } {
175
+ const trustProxy = opts?.trustProxy ?? false
176
+ const remoteIp = opts?.remoteIp
177
+ const cookieStore = new CookieStore(request.headers.get('cookie'), isHttpsRequest(request, trustProxy))
178
+ let cachedIp: string | undefined
179
+ let ipComputed = false
108
180
  const ctx: RequestContext = {
109
181
  request,
110
- url,
182
+ url: opts?.url ?? new URL(request.url),
111
183
  params,
112
184
  cookies: cookieStore,
113
185
  locals: {},
114
- json: (data, init) => Response.json(data, init),
115
- text: (body, init) => new Response(body, { ...init, headers: { 'content-type': 'text/plain; charset=utf-8', ...init?.headers } }),
116
- redirect: (location, status = 302) => new Response(null, { status, headers: { location } }),
117
- deny: (status, message, fieldErrors) => Response.json({ ok: false, status, error: message, fieldErrors }, { status }),
186
+ get ip() {
187
+ if (!ipComputed) {
188
+ ipComputed = true
189
+ cachedIp = getClientIp(request, trustProxy, remoteIp)
190
+ }
191
+ return cachedIp
192
+ },
193
+ set ip(val: string | undefined) {
194
+ ipComputed = true
195
+ cachedIp = val
196
+ },
197
+ json,
198
+ text,
199
+ redirect,
200
+ deny,
118
201
  }
119
202
  return { ctx, cookieStore }
120
203
  }
121
204
 
122
- export function finalizeResponse(
205
+ /** True when the client sent or asked for JSON: such requests get JSON errors, not pages. */
206
+ export function wantsJson(request: Request): boolean {
207
+ return (request.headers.get('accept') ?? '').includes('application/json')
208
+ || (request.headers.get('content-type') ?? '').includes('application/json')
209
+ }
210
+
211
+ /** Enforces `maxBytes` on incoming request bodies (both Content-Length and streaming body reads). */
212
+ export async function enforceRequestBodyLimit(
213
+ request: Request,
214
+ maxBytes: number,
215
+ ): Promise<{ ok: true, request: Request } | { ok: false }> {
216
+ if (request.method === 'GET' || request.method === 'HEAD' || !Number.isFinite(maxBytes) || maxBytes <= 0)
217
+ return { ok: true, request }
218
+
219
+ const clHeader = request.headers.get('content-length')
220
+ if (clHeader !== null) {
221
+ const cl = Number(clHeader)
222
+ if (Number.isFinite(cl) && cl > maxBytes)
223
+ return { ok: false }
224
+ }
225
+
226
+ // Capture headers BEFORE accessing request.body so Bun preserves FormData multipart boundaries.
227
+ const headers = new Headers(request.headers)
228
+ const body = request.body
229
+ if (body === null)
230
+ return { ok: true, request }
231
+
232
+ const reader = body.getReader()
233
+ const chunks: Uint8Array[] = []
234
+ let total = 0
235
+ try {
236
+ while (true) {
237
+ const { done, value } = await reader.read()
238
+ if (done)
239
+ break
240
+ total += value.byteLength
241
+ if (total > maxBytes) {
242
+ try {
243
+ await reader.cancel()
244
+ }
245
+ catch {}
246
+ return { ok: false }
247
+ }
248
+ chunks.push(value)
249
+ }
250
+ }
251
+ finally {
252
+ reader.releaseLock()
253
+ }
254
+
255
+ const combined = new Uint8Array(total)
256
+ let offset = 0
257
+ for (let i = 0; i < chunks.length; i++) {
258
+ const chunk = chunks[i]!
259
+ combined.set(chunk, offset)
260
+ offset += chunk.byteLength
261
+ }
262
+
263
+ headers.delete('transfer-encoding')
264
+ return {
265
+ ok: true,
266
+ request: new Request(request.url, {
267
+ method: request.method,
268
+ headers,
269
+ body: combined,
270
+ signal: request.signal,
271
+ }),
272
+ }
273
+ }
274
+
275
+ export function applyHstsHeader(
123
276
  res: Response,
124
- cookieStore: CookieStore,
125
- securityEntries: readonly [string, string][] | SecurityHeadersOptions | false | undefined,
277
+ request: Request,
278
+ hstsValue: string | undefined,
279
+ trustProxy: TrustProxy,
280
+ isDev = false,
126
281
  ): Response {
127
- const entries: readonly [string, string][] = Array.isArray(securityEntries)
128
- ? securityEntries
129
- : buildSecurityHeaderEntries(securityEntries as SecurityHeadersOptions | false | undefined)
282
+ const env = nodeEnv()
283
+ if (hstsValue === undefined || isDev || env === 'development' || env === 'test' || !isHttpsRequest(request, trustProxy))
284
+ return res
285
+ if (res.headers.has('strict-transport-security'))
286
+ return res
287
+ try {
288
+ res.headers.set('strict-transport-security', hstsValue)
289
+ return res
290
+ }
291
+ catch {
292
+ const headers = new Headers(res.headers)
293
+ headers.set('strict-transport-security', hstsValue)
294
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
295
+ }
296
+ }
130
297
 
131
- if (!cookieStore.hasChanges && entries.length === 0)
298
+ /** Adds the pending cookies (when any) and the security headers the response does not set itself. */
299
+ export function finalizeResponse(
300
+ res: Response,
301
+ cookieStore: CookieStore | undefined,
302
+ entries: readonly [string, string][],
303
+ ): Response {
304
+ const hasCookies = cookieStore?.hasChanges === true
305
+ if (!hasCookies && entries.length === 0)
132
306
  return res
133
307
 
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]!
308
+ const apply = (h: Headers): void => {
309
+ if (hasCookies)
310
+ cookieStore!.applyTo(h)
311
+ for (const [k, v] of entries) {
141
312
  if (!h.has(k))
142
313
  h.set(k, v)
143
314
  }
315
+ }
316
+ // Mutate in place (no copy in Bun); a response with immutable headers (e.g. a proxied upstream fetch) is rebuilt.
317
+ try {
318
+ apply(res.headers)
144
319
  return res
145
320
  }
146
321
  catch {
147
- // Fallback for immutable headers (e.g. proxied upstream fetch Response)
148
322
  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
- }
323
+ apply(headers)
156
324
  return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
157
325
  }
158
326
  }