@kayjs/kay 2.0.0-beta.0 → 2.0.0-beta.2
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 +615 -0
- package/src/build/compile.ts +32 -19
- package/src/build/files.ts +174 -0
- package/src/build/graph.ts +223 -0
- package/src/build/index.ts +255 -1461
- package/src/build/islands.ts +177 -0
- package/src/build/manifest.ts +227 -0
- package/src/build/plugin-host.ts +186 -0
- package/src/build/prerender.ts +94 -0
- package/src/build/report.ts +157 -0
- package/src/build/resolve.ts +51 -0
- package/src/build/routes.ts +163 -0
- package/src/build/static.ts +73 -0
- package/src/cli/check.ts +300 -129
- package/src/cli/index.ts +297 -94
- package/src/cli/new.ts +58 -38
- package/src/compiler/analyze.ts +723 -93
- package/src/compiler/dom.ts +848 -762
- package/src/compiler/mistakes.ts +354 -0
- package/src/compiler/patch.ts +1 -1
- package/src/compiler/server-only.ts +172 -23
- package/src/compiler/shared.ts +485 -0
- package/src/compiler/ssr.ts +331 -342
- package/src/context.ts +120 -0
- package/src/dev/index.ts +358 -76
- package/src/dom/action.ts +114 -14
- package/src/dom/extras.ts +121 -83
- package/src/dom/index.ts +122 -80
- package/src/dom/island.ts +71 -36
- package/src/dom/loop.ts +28 -20
- package/src/index.ts +5 -1
- package/src/jsx-runtime.ts +432 -93
- package/src/plugins/context.ts +83 -0
- package/src/plugins/index.ts +285 -23
- 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 +157 -79
- package/src/server/compress.ts +197 -104
- package/src/server/cookies.ts +46 -16
- package/src/server/env.ts +18 -13
- package/src/server/http.ts +189 -77
- package/src/server/index.ts +1024 -878
- package/src/server/loader.ts +138 -0
- package/src/server/router.ts +69 -26
- package/src/server/security.ts +50 -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 +5 -15
- package/src/unrenderable.ts +35 -0
package/src/server/http.ts
CHANGED
|
@@ -1,35 +1,108 @@
|
|
|
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 {
|
|
4
|
+
import type { KayChild } from '../jsx-runtime'
|
|
5
|
+
import type { ServerRuntimeConfig } from '../plugins/index'
|
|
5
6
|
import type { Cookies } from './cookies'
|
|
6
|
-
import type {
|
|
7
|
+
import type { KayLocals } from './index'
|
|
8
|
+
import type { TrustProxy } from './security'
|
|
7
9
|
import { CookieStore } from './cookies'
|
|
8
|
-
import {
|
|
10
|
+
import { nodeEnv } from './env'
|
|
11
|
+
import { getClientIp, isHttpsRequest } from './security'
|
|
9
12
|
|
|
10
13
|
export const DEFAULT_MAX_REQUEST_BODY_SIZE = 1024 * 1024
|
|
11
14
|
|
|
12
|
-
|
|
15
|
+
const NOT_FOUND_SYMBOL = Symbol.for('kay.notFound')
|
|
16
|
+
declare const NOT_FOUND_BRAND: unique symbol
|
|
17
|
+
|
|
18
|
+
export interface NotFoundResult {
|
|
19
|
+
readonly [NOT_FOUND_BRAND]: true
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Return (or throw) from `load()` to render `_404.tsx` with HTTP status 404. */
|
|
23
|
+
export function notFound(): NotFoundResult {
|
|
24
|
+
return { [NOT_FOUND_SYMBOL]: true } as unknown as NotFoundResult
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function isNotFound(value: unknown): value is NotFoundResult {
|
|
28
|
+
return typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[NOT_FOUND_SYMBOL] === true
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
type SegmentParam<Seg extends string> =
|
|
32
|
+
Seg extends `[...${infer Name}]`
|
|
33
|
+
? { [K in Name]: string }
|
|
34
|
+
: Seg extends `[${infer Name}]`
|
|
35
|
+
? { [K in Name]: string }
|
|
36
|
+
: Seg extends `*${infer Name}`
|
|
37
|
+
? { [K in Name extends '' ? 'rest' : Name]: string }
|
|
38
|
+
: Seg extends `:${infer Name}`
|
|
39
|
+
? { [K in Name]: string }
|
|
40
|
+
: unknown
|
|
41
|
+
|
|
42
|
+
type MergeParams<A, B> = {
|
|
43
|
+
[K in keyof A | keyof B]: K extends keyof B ? B[K] : K extends keyof A ? A[K] : never
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
type ExtractRouteParamsRec<Path extends string, Acc = {}> =
|
|
47
|
+
Path extends `${infer Seg}/${infer Rest}`
|
|
48
|
+
? ExtractRouteParamsRec<Rest, Seg extends '' ? Acc : MergeParams<Acc, SegmentParam<Seg>>>
|
|
49
|
+
: Path extends ''
|
|
50
|
+
? Acc
|
|
51
|
+
: MergeParams<Acc, SegmentParam<Path>>
|
|
52
|
+
|
|
53
|
+
/** Extracts typed route params from a Kay route path (`'/notices/[id]'` -> `{ id: string }`, `'/docs/[...rest]'` -> `{ rest: string }`). */
|
|
54
|
+
export type ExtractRouteParams<Path extends string> =
|
|
55
|
+
string extends Path
|
|
56
|
+
? Record<string, string>
|
|
57
|
+
: ExtractRouteParamsRec<Path>
|
|
58
|
+
|
|
59
|
+
export type LoaderFn = (...args: never[]) => unknown
|
|
60
|
+
|
|
61
|
+
/** Infers the resolved page `data` type returned by a route's `load()` function, excluding `Response` and `notFound()`. */
|
|
62
|
+
export type LoaderData<T extends LoaderFn> = Exclude<Awaited<ReturnType<T>>, Response | NotFoundResult>
|
|
63
|
+
|
|
64
|
+
type InferLoaderParams<T extends LoaderFn> =
|
|
65
|
+
Parameters<T> extends [ctx: { params: infer P }, ...unknown[]]
|
|
66
|
+
? P
|
|
67
|
+
: Record<string, string>
|
|
68
|
+
|
|
69
|
+
/** Props passed to a Kay route page component. Pass `typeof load` to infer `data` (and `params` when `load` uses `RouteContext<Path>`), or a route path string when there is no `load`. */
|
|
70
|
+
export type PageProps<
|
|
71
|
+
TLoadOrPath extends LoaderFn | string | undefined = undefined,
|
|
72
|
+
TPath extends string = string,
|
|
73
|
+
> = {
|
|
74
|
+
params: TLoadOrPath extends string
|
|
75
|
+
? ExtractRouteParams<TLoadOrPath>
|
|
76
|
+
: string extends TPath
|
|
77
|
+
? (TLoadOrPath extends LoaderFn ? InferLoaderParams<TLoadOrPath> : Record<string, string>)
|
|
78
|
+
: ExtractRouteParams<TPath>
|
|
79
|
+
locals: KayLocals
|
|
80
|
+
url: URL
|
|
81
|
+
} & (TLoadOrPath extends LoaderFn ? { data: LoaderData<TLoadOrPath> } : { data?: undefined })
|
|
82
|
+
|
|
83
|
+
/** Props passed to a Kay `_layout.tsx` component. */
|
|
84
|
+
export interface LayoutProps<Path extends string = string> {
|
|
85
|
+
children: KayChild
|
|
86
|
+
params: ExtractRouteParams<Path>
|
|
87
|
+
locals: KayLocals
|
|
88
|
+
url: URL
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export interface ServerOptions extends ServerRuntimeConfig {
|
|
13
92
|
root: string
|
|
14
93
|
outDir?: string | undefined
|
|
15
|
-
assetPrefix?: string | undefined
|
|
16
94
|
port?: number | undefined
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
trustProxy?: boolean | undefined
|
|
21
|
-
maxRequestBodySize?: number | undefined
|
|
22
|
-
compress?: boolean | undefined
|
|
23
|
-
onError?: ((info: ServerErrorInfo) => void) | undefined
|
|
24
|
-
plugins?: KayPlugin[] | undefined
|
|
95
|
+
dev?: boolean | undefined
|
|
96
|
+
/** @internal Imports a built server module by absolute path; `kay dev` passes one that keeps unchanged modules loaded. */
|
|
97
|
+
importModule?: ((path: string) => Promise<Record<string, unknown>>) | undefined
|
|
25
98
|
}
|
|
26
99
|
|
|
27
|
-
export interface RequestContext {
|
|
100
|
+
export interface RequestContext<Params = Record<string, string>> {
|
|
28
101
|
request: Request
|
|
29
102
|
url: URL
|
|
30
|
-
params:
|
|
103
|
+
params: Params
|
|
31
104
|
cookies: Cookies
|
|
32
|
-
locals:
|
|
105
|
+
locals: KayLocals
|
|
33
106
|
ip?: string | undefined
|
|
34
107
|
json: (data: unknown, init?: ResponseInit) => Response
|
|
35
108
|
text: (body: string, init?: ResponseInit) => Response
|
|
@@ -37,32 +110,32 @@ export interface RequestContext {
|
|
|
37
110
|
deny: (status: number, message: string, fieldErrors?: Record<string, string>) => Response
|
|
38
111
|
}
|
|
39
112
|
|
|
113
|
+
/** `RequestContext` with `params` inferred from a Kay route pattern (e.g. `RouteContext<'/notices/[id]'>`). */
|
|
114
|
+
export type RouteContext<Path extends string = string> = RequestContext<ExtractRouteParams<Path>>
|
|
115
|
+
|
|
40
116
|
export type Middleware = (ctx: RequestContext, next: () => Promise<Response>) => Response | Promise<Response>
|
|
41
117
|
|
|
42
118
|
export interface KayApp {
|
|
43
119
|
handle: (request: Request, remoteIp?: string) => Promise<Response>
|
|
44
120
|
serve: (port?: number, hostname?: string) => ReturnType<typeof Bun.serve>
|
|
121
|
+
/** Runs plugin shutdown hooks and releases timers/resources (safe to call multiple times). */
|
|
122
|
+
dispose?: () => Promise<void>
|
|
45
123
|
}
|
|
46
124
|
|
|
47
125
|
export type EmbeddedBody = Uint8Array<ArrayBuffer> | string
|
|
48
126
|
|
|
49
|
-
export interface EmbeddedServerConfig {
|
|
127
|
+
export interface EmbeddedServerConfig extends ServerRuntimeConfig {
|
|
50
128
|
manifest: BuildManifest
|
|
51
129
|
modules: Record<string, unknown>
|
|
52
130
|
assets: Record<string, EmbeddedBody>
|
|
53
131
|
publicAssets?: Record<string, EmbeddedBody> | undefined
|
|
54
132
|
publicEtags?: Record<string, string> | undefined
|
|
55
|
-
prerendered
|
|
133
|
+
prerendered?: Record<string, string> | undefined
|
|
56
134
|
prerenderedFiles?: Record<string, string> | undefined
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
trustProxy?: boolean | undefined
|
|
62
|
-
maxRequestBodySize?: number | undefined
|
|
63
|
-
compress?: boolean | undefined
|
|
64
|
-
onError?: ((info: ServerErrorInfo) => void) | undefined
|
|
65
|
-
plugins?: KayPlugin[] | undefined
|
|
135
|
+
root?: string | undefined
|
|
136
|
+
outDir?: string | undefined
|
|
137
|
+
publicDir?: string | undefined
|
|
138
|
+
dev?: boolean | undefined
|
|
66
139
|
}
|
|
67
140
|
|
|
68
141
|
export const MIME: Record<string, string> = {
|
|
@@ -110,8 +183,47 @@ export function extractRenderedIslands(html: string): { hasIslands: boolean, eag
|
|
|
110
183
|
}
|
|
111
184
|
|
|
112
185
|
export interface RequestContextOptions {
|
|
113
|
-
trustProxy?:
|
|
186
|
+
trustProxy?: TrustProxy | undefined
|
|
114
187
|
remoteIp?: string | undefined
|
|
188
|
+
/** The parsed `request.url`, when the caller already has it. */
|
|
189
|
+
url?: URL | undefined
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// None of these read the request, so every context shares them.
|
|
193
|
+
const json: RequestContext['json'] = (data, init) => {
|
|
194
|
+
const payload = JSON.stringify(data)
|
|
195
|
+
const headers = new Headers(init?.headers)
|
|
196
|
+
if (!headers.has('content-type'))
|
|
197
|
+
headers.set('content-type', 'application/json; charset=utf-8')
|
|
198
|
+
if (!headers.has('content-length'))
|
|
199
|
+
headers.set('content-length', String(Buffer.byteLength(payload, 'utf8')))
|
|
200
|
+
return new Response(payload, { ...init, headers })
|
|
201
|
+
}
|
|
202
|
+
const text: RequestContext['text'] = (body, init) => {
|
|
203
|
+
const headers = new Headers(init?.headers)
|
|
204
|
+
if (!headers.has('content-type'))
|
|
205
|
+
headers.set('content-type', 'text/plain; charset=utf-8')
|
|
206
|
+
if (!headers.has('content-length'))
|
|
207
|
+
headers.set('content-length', String(Buffer.byteLength(body, 'utf8')))
|
|
208
|
+
return new Response(body, { ...init, headers })
|
|
209
|
+
}
|
|
210
|
+
const redirect: RequestContext['redirect'] = (location, status = 302) => new Response(null, { status, headers: { location } })
|
|
211
|
+
const deny: RequestContext['deny'] = (status, message, fieldErrors) => Response.json({ ok: false, status, error: message, fieldErrors }, { status })
|
|
212
|
+
|
|
213
|
+
/** RFC 9110 weak ETag comparison supporting `*`, comma-separated lists, and `W/` prefixes. */
|
|
214
|
+
export function etagMatches(ifNoneMatch: string | null, etag: string): boolean {
|
|
215
|
+
if (!ifNoneMatch)
|
|
216
|
+
return false
|
|
217
|
+
const trimmed = ifNoneMatch.trim()
|
|
218
|
+
if (trimmed === '*')
|
|
219
|
+
return true
|
|
220
|
+
const stripWeak = (v: string) => (v.startsWith('W/') || v.startsWith('w/') ? v.slice(2) : v)
|
|
221
|
+
const target = stripWeak(etag)
|
|
222
|
+
for (const part of trimmed.split(',')) {
|
|
223
|
+
if (stripWeak(part.trim()) === target)
|
|
224
|
+
return true
|
|
225
|
+
}
|
|
226
|
+
return false
|
|
115
227
|
}
|
|
116
228
|
|
|
117
229
|
export function makeRequestContext(
|
|
@@ -119,41 +231,42 @@ export function makeRequestContext(
|
|
|
119
231
|
params: Record<string, string>,
|
|
120
232
|
opts?: RequestContextOptions,
|
|
121
233
|
): { ctx: RequestContext, cookieStore: CookieStore } {
|
|
122
|
-
const
|
|
123
|
-
const
|
|
124
|
-
const
|
|
125
|
-
|
|
126
|
-
|
|
234
|
+
const trustProxy = opts?.trustProxy ?? false
|
|
235
|
+
const remoteIp = opts?.remoteIp
|
|
236
|
+
const cookieStore = new CookieStore(request.headers.get('cookie'), isHttpsRequest(request, trustProxy))
|
|
237
|
+
let cachedIp: string | undefined
|
|
238
|
+
let ipComputed = false
|
|
127
239
|
const ctx: RequestContext = {
|
|
128
240
|
request,
|
|
129
|
-
url,
|
|
241
|
+
url: opts?.url ?? new URL(request.url),
|
|
130
242
|
params,
|
|
131
243
|
cookies: cookieStore,
|
|
132
244
|
locals: {},
|
|
133
|
-
ip
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
if (!headers.has('content-length'))
|
|
140
|
-
headers.set('content-length', String(Buffer.byteLength(payload, 'utf8')))
|
|
141
|
-
return new Response(payload, { ...init, headers })
|
|
245
|
+
get ip() {
|
|
246
|
+
if (!ipComputed) {
|
|
247
|
+
ipComputed = true
|
|
248
|
+
cachedIp = getClientIp(request, trustProxy, remoteIp)
|
|
249
|
+
}
|
|
250
|
+
return cachedIp
|
|
142
251
|
},
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
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 })
|
|
252
|
+
set ip(val: string | undefined) {
|
|
253
|
+
ipComputed = true
|
|
254
|
+
cachedIp = val
|
|
150
255
|
},
|
|
151
|
-
|
|
152
|
-
|
|
256
|
+
json,
|
|
257
|
+
text,
|
|
258
|
+
redirect,
|
|
259
|
+
deny,
|
|
153
260
|
}
|
|
154
261
|
return { ctx, cookieStore }
|
|
155
262
|
}
|
|
156
263
|
|
|
264
|
+
/** True when the client sent or asked for JSON: such requests get JSON errors, not pages. */
|
|
265
|
+
export function wantsJson(request: Request): boolean {
|
|
266
|
+
return (request.headers.get('accept') ?? '').includes('application/json')
|
|
267
|
+
|| (request.headers.get('content-type') ?? '').includes('application/json')
|
|
268
|
+
}
|
|
269
|
+
|
|
157
270
|
/** Enforces `maxBytes` on incoming request bodies (both Content-Length and streaming body reads). */
|
|
158
271
|
export async function enforceRequestBodyLimit(
|
|
159
272
|
request: Request,
|
|
@@ -185,7 +298,10 @@ export async function enforceRequestBodyLimit(
|
|
|
185
298
|
break
|
|
186
299
|
total += value.byteLength
|
|
187
300
|
if (total > maxBytes) {
|
|
188
|
-
|
|
301
|
+
try {
|
|
302
|
+
await reader.cancel()
|
|
303
|
+
}
|
|
304
|
+
catch {}
|
|
189
305
|
return { ok: false }
|
|
190
306
|
}
|
|
191
307
|
chunks.push(value)
|
|
@@ -203,12 +319,14 @@ export async function enforceRequestBodyLimit(
|
|
|
203
319
|
offset += chunk.byteLength
|
|
204
320
|
}
|
|
205
321
|
|
|
322
|
+
headers.delete('transfer-encoding')
|
|
206
323
|
return {
|
|
207
324
|
ok: true,
|
|
208
325
|
request: new Request(request.url, {
|
|
209
326
|
method: request.method,
|
|
210
327
|
headers,
|
|
211
328
|
body: combined,
|
|
329
|
+
signal: request.signal,
|
|
212
330
|
}),
|
|
213
331
|
}
|
|
214
332
|
}
|
|
@@ -217,9 +335,11 @@ export function applyHstsHeader(
|
|
|
217
335
|
res: Response,
|
|
218
336
|
request: Request,
|
|
219
337
|
hstsValue: string | undefined,
|
|
220
|
-
trustProxy:
|
|
338
|
+
trustProxy: TrustProxy,
|
|
339
|
+
isDev = false,
|
|
221
340
|
): Response {
|
|
222
|
-
|
|
341
|
+
const env = nodeEnv()
|
|
342
|
+
if (hstsValue === undefined || isDev || env === 'development' || env === 'test' || !isHttpsRequest(request, trustProxy))
|
|
223
343
|
return res
|
|
224
344
|
if (res.headers.has('strict-transport-security'))
|
|
225
345
|
return res
|
|
@@ -234,40 +354,32 @@ export function applyHstsHeader(
|
|
|
234
354
|
}
|
|
235
355
|
}
|
|
236
356
|
|
|
357
|
+
/** Adds the pending cookies (when any) and the security headers the response does not set itself. */
|
|
237
358
|
export function finalizeResponse(
|
|
238
359
|
res: Response,
|
|
239
|
-
cookieStore: CookieStore,
|
|
240
|
-
|
|
360
|
+
cookieStore: CookieStore | undefined,
|
|
361
|
+
entries: readonly [string, string][],
|
|
241
362
|
): Response {
|
|
242
|
-
const
|
|
243
|
-
|
|
244
|
-
: buildSecurityHeaderEntries(securityEntries as SecurityHeadersOptions | false | undefined)
|
|
245
|
-
|
|
246
|
-
if (!cookieStore.hasChanges && entries.length === 0)
|
|
363
|
+
const hasCookies = cookieStore?.hasChanges === true
|
|
364
|
+
if (!hasCookies && entries.length === 0)
|
|
247
365
|
return res
|
|
248
366
|
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
cookieStore.applyTo(h)
|
|
254
|
-
for (let i = 0; i < entries.length; i++) {
|
|
255
|
-
const [k, v] = entries[i]!
|
|
367
|
+
const apply = (h: Headers): void => {
|
|
368
|
+
if (hasCookies)
|
|
369
|
+
cookieStore!.applyTo(h)
|
|
370
|
+
for (const [k, v] of entries) {
|
|
256
371
|
if (!h.has(k))
|
|
257
372
|
h.set(k, v)
|
|
258
373
|
}
|
|
374
|
+
}
|
|
375
|
+
// Mutate in place (no copy in Bun); a response with immutable headers (e.g. a proxied upstream fetch) is rebuilt.
|
|
376
|
+
try {
|
|
377
|
+
apply(res.headers)
|
|
259
378
|
return res
|
|
260
379
|
}
|
|
261
380
|
catch {
|
|
262
|
-
// Fallback for immutable headers (e.g. proxied upstream fetch Response)
|
|
263
381
|
const headers = new Headers(res.headers)
|
|
264
|
-
|
|
265
|
-
cookieStore.applyTo(headers)
|
|
266
|
-
for (let i = 0; i < entries.length; i++) {
|
|
267
|
-
const [k, v] = entries[i]!
|
|
268
|
-
if (!headers.has(k))
|
|
269
|
-
headers.set(k, v)
|
|
270
|
-
}
|
|
382
|
+
apply(headers)
|
|
271
383
|
return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
|
|
272
384
|
}
|
|
273
385
|
}
|