@kayjs/kay 1.106.0 → 1.108.0
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/README.md +2 -2
- package/dist/eslint.js +477 -204
- package/editors/zed/extension.toml +2 -2
- package/llms/action-protection.md +1 -1
- package/llms/actions-from-islands.md +1 -1
- package/llms/actions-refused-fields.md +22 -0
- package/llms/actions.md +2 -22
- package/llms/browser-only.md +1 -1
- package/llms/compiler-api.md +1 -1
- package/llms/component-libraries.md +1 -1
- package/llms/components.md +1 -1
- package/llms/deprecated-lints.md +2 -4
- package/llms/island-and-form-lints.md +1 -0
- package/llms/islands.md +11 -2
- package/llms/project-new-and-add.md +1 -1
- package/llms/project.md +2 -2
- package/llms/schemas.md +6 -4
- package/llms/upgrading.md +25 -1
- package/llms/whats-new-archive.md +36 -1
- package/llms/whats-new.md +18 -35
- package/llms.txt +1 -1
- package/package.json +15 -6
- package/src/build/client.ts +23 -26
- package/src/build/entry-files.ts +19 -0
- package/src/build/icon-slots.ts +140 -0
- package/src/build/lazy-components.ts +130 -0
- package/src/build/lazy-manifest.ts +56 -0
- package/src/build/lazy-stubs.ts +31 -0
- package/src/build/libraries.ts +24 -2
- package/src/build/plugin.ts +13 -1
- package/src/build/runtime-chunk.ts +3 -3
- package/src/build/source-files.ts +8 -3
- package/src/build/transform.ts +17 -7
- package/src/build/variants.ts +97 -5
- package/src/check/action-options.ts +56 -0
- package/src/check/project.ts +4 -4
- package/src/check/renamed-packages.ts +3 -63
- package/src/check/schema-json.ts +226 -0
- package/src/check/shadow-types.ts +15 -27
- package/src/compiler/codegen.ts +7 -17
- package/src/compiler/dead-code.ts +22 -0
- package/src/compiler/deprecated-lints-1-105.ts +41 -0
- package/src/compiler/deprecated-lints-1-106.ts +1 -1
- package/src/compiler/deprecated-lints-1-107.ts +14 -0
- package/src/compiler/deprecated-lints.ts +8 -65
- package/src/compiler/dom-property.ts +23 -0
- package/src/compiler/dom.ts +15 -15
- package/src/compiler/import-edits.ts +15 -0
- package/src/compiler/index.ts +8 -3
- package/src/compiler/island-declaration.ts +15 -0
- package/src/compiler/kay-exports.ts +1 -0
- package/src/compiler/lazy-imports.ts +357 -0
- package/src/compiler/parser.ts +2 -2
- package/src/compiler/route-lints.ts +2 -0
- package/src/compiler/schema-lints.ts +13 -0
- package/src/compiler/script-server.ts +6 -3
- package/src/content/validate.ts +1 -1
- package/src/new.ts +6 -2
- package/src/package-names.ts +1 -1
- package/src/runtime/action-call.ts +39 -327
- package/src/runtime/action-run.ts +357 -0
- package/src/runtime/action.ts +47 -4
- package/src/runtime/client.ts +10 -0
- package/src/runtime/dom-lazy.ts +276 -0
- package/src/runtime/field-errors.ts +58 -0
- package/src/runtime/field-refusal.ts +179 -0
- package/src/runtime/form.ts +3 -2
- package/src/runtime/html.ts +6 -1
- package/src/runtime/index.ts +2 -0
- package/src/runtime/island.server.ts +36 -2
- package/src/runtime/schema-record.ts +2 -1
- package/src/runtime/schema.client.ts +104 -14
- package/src/runtime/schema.ts +9 -2
- package/src/runtime/standard-schema.ts +32 -0
- package/src/runtime/validate-run.client.ts +179 -0
- package/src/runtime/validate.client.ts +11 -0
- package/src/runtime/validate.ts +4 -137
- package/src/server/actions.ts +48 -43
- package/src/server/answer.ts +102 -0
- package/src/server/api-input.ts +166 -0
- package/src/server/api.ts +12 -44
- package/src/server/app-stages.ts +15 -8
- package/src/server/app.ts +5 -2
- package/src/server/client.ts +2 -0
- package/src/server/dev.ts +7 -9
- package/src/server/file-limit.ts +7 -1
- package/src/server/forms.ts +1 -1
- package/src/server/host-allowlist.ts +7 -7
- package/src/server/index.ts +2 -0
- package/src/server/kay-routes.ts +221 -0
- package/src/server/kay-server.ts +228 -0
- package/src/server/kept-exports.ts +1 -0
- package/src/server/library.ts +0 -2
- package/src/server/mcp.ts +1 -1
- package/src/server/openapi.ts +12 -3
- package/src/server/phases.ts +249 -0
- package/src/server/protection.ts +6 -6
- package/src/server/proxy-key.ts +8 -8
- package/src/server/query.ts +4 -25
- package/src/server/receive.ts +43 -0
- package/src/server/render-document.ts +13 -3
- package/src/server/request-context.ts +137 -0
- package/src/server/schema-check.ts +1 -1
- package/src/server/socket.ts +19 -47
- package/src/server/stream.ts +1 -1
- package/src/server/validate.ts +346 -0
- package/src/test/mount.ts +6 -2
- package/types/build/client.d.ts +3 -2
- package/types/build/client.d.ts.map +1 -1
- package/types/build/entry-files.d.ts +4 -0
- package/types/build/entry-files.d.ts.map +1 -0
- package/types/build/icon-slots.d.ts +7 -0
- package/types/build/icon-slots.d.ts.map +1 -0
- package/types/build/lazy-components.d.ts +6 -0
- package/types/build/lazy-components.d.ts.map +1 -0
- package/types/build/lazy-manifest.d.ts +19 -0
- package/types/build/lazy-manifest.d.ts.map +1 -0
- package/types/build/lazy-stubs.d.ts +5 -0
- package/types/build/lazy-stubs.d.ts.map +1 -0
- package/types/build/libraries.d.ts +2 -0
- package/types/build/libraries.d.ts.map +1 -1
- package/types/build/plugin.d.ts +2 -0
- package/types/build/plugin.d.ts.map +1 -1
- package/types/build/source-files.d.ts.map +1 -1
- package/types/build/transform.d.ts +3 -1
- package/types/build/transform.d.ts.map +1 -1
- package/types/build/variants.d.ts.map +1 -1
- package/types/check/action-options.d.ts +3 -0
- package/types/check/action-options.d.ts.map +1 -0
- package/types/check/renamed-packages.d.ts +0 -3
- package/types/check/renamed-packages.d.ts.map +1 -1
- package/types/check/schema-json.d.ts +3 -0
- package/types/check/schema-json.d.ts.map +1 -0
- package/types/check/shadow-types.d.ts.map +1 -1
- package/types/compiler/codegen.d.ts +2 -0
- package/types/compiler/codegen.d.ts.map +1 -1
- package/types/compiler/dead-code.d.ts +9 -0
- package/types/compiler/dead-code.d.ts.map +1 -0
- package/types/compiler/deprecated-lints-1-105.d.ts +39 -0
- package/types/compiler/deprecated-lints-1-105.d.ts.map +1 -0
- package/types/compiler/deprecated-lints-1-106.d.ts +1 -1
- package/types/compiler/deprecated-lints-1-106.d.ts.map +1 -1
- package/types/compiler/deprecated-lints-1-107.d.ts +12 -0
- package/types/compiler/deprecated-lints-1-107.d.ts.map +1 -0
- package/types/compiler/deprecated-lints.d.ts +36 -53
- package/types/compiler/deprecated-lints.d.ts.map +1 -1
- package/types/compiler/dom-property.d.ts +9 -0
- package/types/compiler/dom-property.d.ts.map +1 -0
- package/types/compiler/dom.d.ts +1 -0
- package/types/compiler/dom.d.ts.map +1 -1
- package/types/compiler/import-edits.d.ts +1 -0
- package/types/compiler/import-edits.d.ts.map +1 -1
- package/types/compiler/index.d.ts +2 -0
- package/types/compiler/index.d.ts.map +1 -1
- package/types/compiler/island-declaration.d.ts +5 -0
- package/types/compiler/island-declaration.d.ts.map +1 -1
- package/types/compiler/kay-exports.d.ts.map +1 -1
- package/types/compiler/lazy-imports.d.ts +33 -0
- package/types/compiler/lazy-imports.d.ts.map +1 -0
- package/types/compiler/lints.d.ts +44 -53
- package/types/compiler/lints.d.ts.map +1 -1
- package/types/compiler/route-lints.d.ts +8 -0
- package/types/compiler/route-lints.d.ts.map +1 -1
- package/types/compiler/schema-lints.d.ts +11 -0
- package/types/compiler/schema-lints.d.ts.map +1 -0
- package/types/compiler/script-server.d.ts.map +1 -1
- package/types/new.d.ts +1 -0
- package/types/new.d.ts.map +1 -1
- package/types/runtime/action-call.d.ts.map +1 -1
- package/types/runtime/action-run.d.ts +23 -0
- package/types/runtime/action-run.d.ts.map +1 -0
- package/types/runtime/action.d.ts +26 -1
- package/types/runtime/action.d.ts.map +1 -1
- package/types/runtime/client.d.ts.map +1 -1
- package/types/runtime/dom-lazy.d.ts +6 -0
- package/types/runtime/dom-lazy.d.ts.map +1 -0
- package/types/runtime/field-errors.d.ts +4 -0
- package/types/runtime/field-errors.d.ts.map +1 -0
- package/types/runtime/field-refusal.d.ts +37 -0
- package/types/runtime/field-refusal.d.ts.map +1 -0
- package/types/runtime/form.d.ts +1 -1
- package/types/runtime/form.d.ts.map +1 -1
- package/types/runtime/html.d.ts.map +1 -1
- package/types/runtime/index.d.ts +2 -0
- package/types/runtime/index.d.ts.map +1 -1
- package/types/runtime/island.server.d.ts +2 -0
- package/types/runtime/island.server.d.ts.map +1 -1
- package/types/runtime/schema-record.d.ts.map +1 -1
- package/types/runtime/schema.client.d.ts.map +1 -1
- package/types/runtime/schema.d.ts +6 -1
- package/types/runtime/schema.d.ts.map +1 -1
- package/types/runtime/standard-schema.d.ts +37 -0
- package/types/runtime/standard-schema.d.ts.map +1 -0
- package/types/runtime/validate-run.client.d.ts +4 -0
- package/types/runtime/validate-run.client.d.ts.map +1 -0
- package/types/runtime/validate.client.d.ts +4 -0
- package/types/runtime/validate.client.d.ts.map +1 -0
- package/types/runtime/validate.d.ts +1 -21
- package/types/runtime/validate.d.ts.map +1 -1
- package/types/server/actions.d.ts.map +1 -1
- package/types/server/answer.d.ts +6 -0
- package/types/server/answer.d.ts.map +1 -0
- package/types/server/api-input.d.ts +19 -0
- package/types/server/api-input.d.ts.map +1 -0
- package/types/server/api.d.ts.map +1 -1
- package/types/server/app-stages.d.ts +4 -1
- package/types/server/app-stages.d.ts.map +1 -1
- package/types/server/app.d.ts +2 -0
- package/types/server/app.d.ts.map +1 -1
- package/types/server/client.d.ts +1 -0
- package/types/server/client.d.ts.map +1 -1
- package/types/server/dev.d.ts +1 -1
- package/types/server/dev.d.ts.map +1 -1
- package/types/server/file-limit.d.ts.map +1 -1
- package/types/server/host-allowlist.d.ts +3 -3
- package/types/server/host-allowlist.d.ts.map +1 -1
- package/types/server/index.d.ts +2 -0
- package/types/server/index.d.ts.map +1 -1
- package/types/server/kay-routes.d.ts +47 -0
- package/types/server/kay-routes.d.ts.map +1 -0
- package/types/server/kay-server.d.ts +25 -0
- package/types/server/kay-server.d.ts.map +1 -0
- package/types/server/kept-exports.d.ts.map +1 -1
- package/types/server/library.d.ts +0 -1
- package/types/server/library.d.ts.map +1 -1
- package/types/server/openapi.d.ts.map +1 -1
- package/types/server/phases.d.ts +36 -0
- package/types/server/phases.d.ts.map +1 -0
- package/types/server/protection.d.ts +3 -2
- package/types/server/protection.d.ts.map +1 -1
- package/types/server/proxy-key.d.ts +3 -3
- package/types/server/proxy-key.d.ts.map +1 -1
- package/types/server/query.d.ts.map +1 -1
- package/types/server/receive.d.ts +9 -0
- package/types/server/receive.d.ts.map +1 -0
- package/types/server/render-document.d.ts.map +1 -1
- package/types/server/request-context.d.ts +29 -0
- package/types/server/request-context.d.ts.map +1 -0
- package/types/server/schema-check.d.ts +1 -0
- package/types/server/schema-check.d.ts.map +1 -1
- package/types/server/socket.d.ts +3 -5
- package/types/server/socket.d.ts.map +1 -1
- package/types/server/validate.d.ts +26 -0
- package/types/server/validate.d.ts.map +1 -0
- package/types/test/mount.d.ts.map +1 -1
- package/src/check/schema-type.ts +0 -9
- package/src/compiler/deprecated-script-fence.ts +0 -26
- package/src/server/field-errors.ts +0 -136
- package/types/check/schema-type.d.ts +0 -3
- package/types/check/schema-type.d.ts.map +0 -1
- package/types/compiler/deprecated-script-fence.d.ts +0 -3
- package/types/compiler/deprecated-script-fence.d.ts.map +0 -1
- package/types/server/field-errors.d.ts +0 -6
- package/types/server/field-errors.d.ts.map +0 -1
package/src/server/openapi.ts
CHANGED
|
@@ -7,7 +7,9 @@ import type { ServedPaths } from './served-paths'
|
|
|
7
7
|
import { posix } from 'node:path'
|
|
8
8
|
import { NON_ROOT_TRAILING_SLASH } from '../runtime/base'
|
|
9
9
|
import { escape } from '../runtime/escape'
|
|
10
|
+
import { jsonSchemaOf } from '../runtime/standard-schema'
|
|
10
11
|
import { inLocale, passGuards } from './actions'
|
|
12
|
+
import { declaredInputs } from './api-input'
|
|
11
13
|
import { API_PREFIX, KAY_PREFIX, openApiPaths, referenced } from './api-modules'
|
|
12
14
|
import { sharedContext } from './render'
|
|
13
15
|
import { apiRoutePath } from './routes'
|
|
@@ -208,7 +210,7 @@ export function openApiDocument(modules: MountedApi[], options: { title: string,
|
|
|
208
210
|
for (const module of modules) {
|
|
209
211
|
for (const route of module.instance.routes) {
|
|
210
212
|
const method = route.method.toUpperCase()
|
|
211
|
-
const hooks = route.hooks as Record<string, unknown> & { detail?: { summary?: string, description?: string, tags?: string[], deprecated?: boolean, hide?: boolean, operationId?: string, tool?: boolean | string | ActionTool } }
|
|
213
|
+
const hooks = { ...route.hooks as object, ...Object.fromEntries(Object.entries(declaredInputs(route.hooks)).map(([input, schema]) => [input, described(schema)])) } as Record<string, unknown> & { detail?: { summary?: string, description?: string, tags?: string[], deprecated?: boolean, hide?: boolean, operationId?: string, tool?: boolean | string | ActionTool } }
|
|
212
214
|
|
|
213
215
|
if ((!METHODS.has(method) && method !== 'ALL') || hooks.detail?.hide === true)
|
|
214
216
|
continue
|
|
@@ -361,7 +363,7 @@ function withRefusal(answers: Record<string, Schema>, hooks: Record<string, unkn
|
|
|
361
363
|
|
|
362
364
|
// A schema under the type it goes as: raw bytes as such, text as text, anything else as `fallback`.
|
|
363
365
|
function content(schema: unknown, fallback: string): Record<string, { schema: unknown }> {
|
|
364
|
-
const plain = schemaOf(schema) as Schema
|
|
366
|
+
const plain = schemaOf(described(schema)) as Schema
|
|
365
367
|
let type = fallback
|
|
366
368
|
|
|
367
369
|
if (plain.format === 'binary')
|
|
@@ -372,7 +374,14 @@ function content(schema: unknown, fallback: string): Record<string, { schema: un
|
|
|
372
374
|
return { [type]: { schema: plain } }
|
|
373
375
|
}
|
|
374
376
|
|
|
375
|
-
|
|
377
|
+
// What a schema describes as JSON Schema: itself, or what a Standard Schema validator says of its input, none for one that cannot.
|
|
378
|
+
function described(schema: unknown): unknown {
|
|
379
|
+
return typeof schema === 'object' && schema !== null ? jsonSchemaOf(schema) ?? {} : schema
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function holdsFile(given: unknown): boolean {
|
|
383
|
+
const schema = described(given)
|
|
384
|
+
|
|
376
385
|
if (typeof schema !== 'object' || schema === null)
|
|
377
386
|
return false
|
|
378
387
|
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import type { LocaleState } from '../runtime/locale-state'
|
|
2
|
+
import type { RouteRecord } from './kay-routes'
|
|
3
|
+
import type { Received, ReceiveServer, ReceiveStep } from './receive'
|
|
4
|
+
import { runInLocale } from '../runtime/locale-state'
|
|
5
|
+
import { kayLog } from '../runtime/log'
|
|
6
|
+
import { answer } from './answer'
|
|
7
|
+
import { answeringRequest } from './log'
|
|
8
|
+
import { runReceive } from './receive'
|
|
9
|
+
import { inContext, RequestContext } from './request-context'
|
|
10
|
+
import { Denied, NotFound, Redirect } from './signals'
|
|
11
|
+
import { SERVER_SPAN, traced } from './trace'
|
|
12
|
+
|
|
13
|
+
type Outcome = Response | undefined | void
|
|
14
|
+
|
|
15
|
+
// A step of `limit`, `admit` or `input`: it answers with a Response to end the request there, or returns nothing.
|
|
16
|
+
export type Step = (context: RequestContext) => Outcome | Promise<Outcome>
|
|
17
|
+
|
|
18
|
+
// A step of `respond`, which takes the Response and gives the one that goes on; the order is the order of the list.
|
|
19
|
+
export type RespondStep = (context: RequestContext, response: Response) => Response | Promise<Response>
|
|
20
|
+
|
|
21
|
+
// A step of `after`, run once the answer is made.
|
|
22
|
+
export type AfterStep = (context: RequestContext, response: Response) => void | Promise<void>
|
|
23
|
+
|
|
24
|
+
// A step of `error`, which answers a failure with a Response or leaves it to the next, kay's own last.
|
|
25
|
+
export type ErrorStep = (context: RequestContext, error: unknown) => Outcome | Promise<Outcome>
|
|
26
|
+
|
|
27
|
+
// What runs in each phase, in this order for every kind of route: `receive`, `limit`, `admit`, `input`, `handle`, `answer`, `respond`, `after`, with `error` taking over a failure of any of them. Each list holds what extensions and kay add, in the order they are added.
|
|
28
|
+
export interface Phases {
|
|
29
|
+
receive: ReceiveStep[]
|
|
30
|
+
limit: Step[]
|
|
31
|
+
admit: Step[]
|
|
32
|
+
input: Step[]
|
|
33
|
+
respond: RespondStep[]
|
|
34
|
+
after: AfterStep[]
|
|
35
|
+
error: ErrorStep[]
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function emptyPhases(): Phases {
|
|
39
|
+
return { receive: [], limit: [], admit: [], input: [], respond: [], after: [], error: [] }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface PipelineOptions {
|
|
43
|
+
// Whether an unexpected failure's message goes in the 500 answer, as `kay dev` shows it.
|
|
44
|
+
dev?: boolean | undefined
|
|
45
|
+
// The locale a request is answered in, so the handler, the log lines and the stream it opens read it.
|
|
46
|
+
locale?: ((context: RequestContext) => LocaleState | undefined) | undefined
|
|
47
|
+
// Where an unexpected failure is reported, the route's own bug.
|
|
48
|
+
report?: ((error: unknown, request: Request) => void) | undefined
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function text(status: number, body: string): Response {
|
|
52
|
+
return new Response(body, { status, headers: { 'content-type': 'text/plain; charset=utf-8' } })
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// What a handler wrote to `set`, folded into the answer: its headers go on where the answer has none of that name, a cookie added to the others.
|
|
56
|
+
function folded(response: Response, context: RequestContext): Response {
|
|
57
|
+
const written = context.written
|
|
58
|
+
|
|
59
|
+
if (written === undefined || [...written.headers].length === 0)
|
|
60
|
+
return response
|
|
61
|
+
|
|
62
|
+
const headers = new Headers(response.headers)
|
|
63
|
+
|
|
64
|
+
for (const [name, value] of written.headers) {
|
|
65
|
+
if (name === 'set-cookie')
|
|
66
|
+
headers.append(name, value)
|
|
67
|
+
else if (!headers.has(name))
|
|
68
|
+
headers.set(name, value)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return new Response(response.body, { status: response.status, statusText: response.statusText, headers })
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// A body that goes unread under `HEAD`, the headers as the GET would send them.
|
|
75
|
+
function headOf(response: Response): Response {
|
|
76
|
+
return new Response(null, { status: response.status, statusText: response.statusText, headers: response.headers })
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// The phases around a request, the same for every route kind, so a record kay serves and the Elysia app behind it as a fallback are answered the same way.
|
|
80
|
+
export class Pipeline {
|
|
81
|
+
readonly phases: Phases
|
|
82
|
+
readonly #options: PipelineOptions
|
|
83
|
+
// The requests `receive` ran for, so it runs once however many times a request is handed on, as it is to the fallback app which still has its own bridge to it.
|
|
84
|
+
readonly #received = new WeakSet<Request>()
|
|
85
|
+
|
|
86
|
+
constructor(phases: Phases = emptyPhases(), options: PipelineOptions = {}) {
|
|
87
|
+
this.phases = phases
|
|
88
|
+
this.#options = options
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// `receive`: the request to go on with, or the answer. A request already received is returned as it is.
|
|
92
|
+
receive(request: Request, server: ReceiveServer): Received {
|
|
93
|
+
if (this.#received.has(request))
|
|
94
|
+
return request
|
|
95
|
+
|
|
96
|
+
this.#received.add(request)
|
|
97
|
+
|
|
98
|
+
const received = runReceive(this.phases.receive, request, server)
|
|
99
|
+
|
|
100
|
+
if (received instanceof Request)
|
|
101
|
+
this.#received.add(received)
|
|
102
|
+
|
|
103
|
+
return received
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Whether a phase has a step: with none, a static Response can go to `Bun.serve` as it is, as nothing is left to apply to it.
|
|
107
|
+
get empty(): boolean {
|
|
108
|
+
const { phases } = this
|
|
109
|
+
|
|
110
|
+
return phases.receive.length === 0 && phases.respond.length === 0 && phases.after.length === 0 && phases.limit.length === 0 && phases.admit.length === 0
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Answers a request for a record, from `limit` to `after`.
|
|
114
|
+
async serve(record: RouteRecord, params: Record<string, string> | undefined, request: Request): Promise<Response> {
|
|
115
|
+
const context = new RequestContext(request, record, params)
|
|
116
|
+
|
|
117
|
+
return this.#inScope(context, async () => {
|
|
118
|
+
let response: Response
|
|
119
|
+
|
|
120
|
+
try {
|
|
121
|
+
response = await this.#handle(context, record)
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
response = await this.#fail(context, error)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return this.#finish(context, response)
|
|
128
|
+
})
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Runs `respond` and `after` over an answer made before any record was reached: a refusal of `receive`, or the fallback app's.
|
|
132
|
+
async settle(request: Request, response: Response): Promise<Response> {
|
|
133
|
+
// The fallback app's answer, as it is, when no step is left to run over it: Bun leaves a HEAD answer's body out itself, with the length the body gave. An upgraded socket has no answer to run them over.
|
|
134
|
+
if ((this.phases.respond.length === 0 && this.phases.after.length === 0) || response === undefined)
|
|
135
|
+
return response
|
|
136
|
+
|
|
137
|
+
const context = new RequestContext(request, undefined, {})
|
|
138
|
+
|
|
139
|
+
return this.#inScope(context, async () => this.#finish(context, response))
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Answers a failure that came before any record was reached, through the same chain as a handler's.
|
|
143
|
+
async failed(request: Request, error: unknown): Promise<Response> {
|
|
144
|
+
const context = new RequestContext(request, undefined, {})
|
|
145
|
+
|
|
146
|
+
return this.#inScope(context, async () => this.#finish(context, await this.#fail(context, error)))
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async #inScope<T>(context: RequestContext, run: () => Promise<T>): Promise<T> {
|
|
150
|
+
const { request } = context
|
|
151
|
+
|
|
152
|
+
return inContext(context, async () => answeringRequest(request, async () => {
|
|
153
|
+
const inside = async () => traced(() => `${request.method} ${context.route?.path ?? context.url.pathname}`, () => ({ kind: SERVER_SPAN }), run, request)
|
|
154
|
+
const state = this.#options.locale?.(context)
|
|
155
|
+
|
|
156
|
+
return state === undefined ? inside() : runInLocale(state, inside)
|
|
157
|
+
}))
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async #handle(context: RequestContext, record: RouteRecord): Promise<Response> {
|
|
161
|
+
const refused = await this.#run(this.phases.limit, context) ?? await this.#run(this.phases.admit, context) ?? this.#malformed(context) ?? await this.#run(this.phases.input, context)
|
|
162
|
+
|
|
163
|
+
return refused !== undefined ? refused : answer(await record.handle!(context), context)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// A param that does not decode refuses the path as a client's mistake, in `input` after the guards, which read nothing of it.
|
|
167
|
+
#malformed(context: RequestContext): Response | undefined {
|
|
168
|
+
return context.malformed ? text(400, 'Bad Request: the path holds an escape that does not decode\n') : undefined
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async #run(steps: readonly Step[], context: RequestContext): Promise<Response | undefined> {
|
|
172
|
+
for (const step of steps) {
|
|
173
|
+
const result = await step(context)
|
|
174
|
+
|
|
175
|
+
if (result instanceof Response)
|
|
176
|
+
return result
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return undefined
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// One chain: the steps of `error`, then kay's own kinds of failure, so what an app or an extension answers wins over the default and a message never leaks unless `dev` says so.
|
|
183
|
+
async #fail(context: RequestContext, error: unknown): Promise<Response> {
|
|
184
|
+
try {
|
|
185
|
+
for (const step of this.phases.error) {
|
|
186
|
+
const result = await step(context, error)
|
|
187
|
+
|
|
188
|
+
if (result instanceof Response)
|
|
189
|
+
return result
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
catch (thrown) {
|
|
193
|
+
error = thrown
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (error instanceof Redirect)
|
|
197
|
+
return new Response(null, { status: error.status, headers: { location: error.location } })
|
|
198
|
+
|
|
199
|
+
if (error instanceof NotFound)
|
|
200
|
+
return text(404, 'Not Found\n')
|
|
201
|
+
|
|
202
|
+
if (error instanceof Denied)
|
|
203
|
+
return text(error.status, `${error.message}\n`)
|
|
204
|
+
|
|
205
|
+
this.#report(error, context.request)
|
|
206
|
+
|
|
207
|
+
return text(500, this.#options.dev === true && error instanceof Error ? `${error.message}\n` : 'Internal Server Error\n')
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
#report(error: unknown, request: Request): void {
|
|
211
|
+
if (this.#options.report === undefined)
|
|
212
|
+
kayLog('error', `${request.method} ${new URL(request.url).pathname} failed`, error)
|
|
213
|
+
else
|
|
214
|
+
this.#options.report(error, request)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// `respond` in its order, then the `HEAD` body dropped, then `after` on a later turn, once the answer has gone.
|
|
218
|
+
async #finish(context: RequestContext, answered: Response): Promise<Response> {
|
|
219
|
+
let response = folded(answered, context)
|
|
220
|
+
|
|
221
|
+
try {
|
|
222
|
+
for (const step of this.phases.respond)
|
|
223
|
+
response = await step(context, response)
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
response = text(500, 'Internal Server Error\n')
|
|
227
|
+
this.#report(error, context.request)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
if (context.request.method === 'HEAD' && response.body !== null)
|
|
231
|
+
response = headOf(response)
|
|
232
|
+
|
|
233
|
+
if (this.phases.after.length > 0)
|
|
234
|
+
setImmediate(() => void this.#after(context, response))
|
|
235
|
+
|
|
236
|
+
return response
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async #after(context: RequestContext, response: Response): Promise<void> {
|
|
240
|
+
for (const step of this.phases.after) {
|
|
241
|
+
try {
|
|
242
|
+
await step(context, response)
|
|
243
|
+
}
|
|
244
|
+
catch (error) {
|
|
245
|
+
this.#report(error, context.request)
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
package/src/server/protection.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import type { Server } from 'bun'
|
|
2
|
-
import type {
|
|
2
|
+
import type { TSchema } from 'elysia'
|
|
3
3
|
import type { BlockList } from 'node:net'
|
|
4
4
|
import type { ProxyConfig } from '../config'
|
|
5
5
|
import type { ActionRateLimit, RateKey, RateKeyContext, RateLimit, RateStore, RateWindow, ServerAction } from '../runtime/action'
|
|
6
6
|
import type { Duration } from '../runtime/duration'
|
|
7
|
+
import type { ReceiveStep } from './receive'
|
|
7
8
|
import type { RequestRecord } from './request-record'
|
|
8
9
|
import { linkSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
|
9
10
|
import process from 'node:process'
|
|
@@ -903,11 +904,10 @@ export function checkProxy(setting: ProxyConfig | number | boolean | undefined):
|
|
|
903
904
|
|
|
904
905
|
// Records the app's proxy settings on each request it gets, for `clientAddress` to read them wherever it is called from.
|
|
905
906
|
// In production a `proxy` left out is one proxy in front, read from private addresses only: a server there is behind one far more often than it faces visitors, and `false` says it is not.
|
|
906
|
-
export function trustProxy(
|
|
907
|
+
export function trustProxy(setting: ProxyConfig | number | boolean | undefined): ReceiveStep {
|
|
907
908
|
const proxy = checkProxy(setting) ?? (setting === undefined && process.env.NODE_ENV === 'production' ? INFERRED_PROXY : undefined)
|
|
908
|
-
const off = setting === false
|
|
909
909
|
|
|
910
|
-
|
|
910
|
+
return (request, server) => {
|
|
911
911
|
const record = requestRecord(request)
|
|
912
912
|
|
|
913
913
|
record.proxy = proxy
|
|
@@ -915,8 +915,8 @@ export function trustProxy(app: Elysia, setting: ProxyConfig | number | boolean
|
|
|
915
915
|
if (server)
|
|
916
916
|
record.server = server
|
|
917
917
|
|
|
918
|
-
record.proxyOff =
|
|
919
|
-
}
|
|
918
|
+
record.proxyOff = setting === false ? true : undefined
|
|
919
|
+
}
|
|
920
920
|
}
|
|
921
921
|
|
|
922
922
|
// The socket's address, unless it is a proxy on this machine or network the app's `proxy` setting trusts: then the client's address as that proxy passed it on.
|
package/src/server/proxy-key.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { Elysia } from 'elysia'
|
|
2
1
|
import type { ProxyConfig } from '../config'
|
|
2
|
+
import type { ReceiveStep } from './receive'
|
|
3
3
|
import type { Secret } from './secret'
|
|
4
4
|
import process from 'node:process'
|
|
5
5
|
import { KayError } from '../compiler/errors'
|
|
@@ -34,11 +34,11 @@ function isOpen(path: string, open: readonly string[]): boolean {
|
|
|
34
34
|
// Refuses with 403 every request that does not carry the proxy's shared key in the header `proxy.key` names, so a process or a container reaching the port directly skips nothing the proxy does.
|
|
35
35
|
// The `endpoint` is the MCP endpoint while `mcp.token` guards it: a POST to it carries its own credential, the bearer, and so skips the check.
|
|
36
36
|
// Off under `kay dev`, in a static export, and outside production while no key is given (a warning says so, except in a test run); a production server with `key` and no key to compare with does not boot.
|
|
37
|
-
export function requireProxyKey(
|
|
37
|
+
export function requireProxyKey(proxy: ProxyConfig | undefined, options: { root: string, dev: boolean, exported: boolean, base: string, health: string | undefined, metrics?: (() => readonly string[]) | undefined, endpoint?: (() => readonly string[]) | undefined, logRefused?: ((request: Request, status: number) => void) | undefined, security?: Record<string, string> | undefined }): ReceiveStep | undefined {
|
|
38
38
|
const header = proxy?.key?.header
|
|
39
39
|
|
|
40
40
|
if (header === undefined || options.dev || options.exported)
|
|
41
|
-
return
|
|
41
|
+
return undefined
|
|
42
42
|
|
|
43
43
|
const secret = proxyKeyValue(proxy?.key?.secret, options.root)
|
|
44
44
|
|
|
@@ -50,7 +50,7 @@ export function requireProxyKey(app: Elysia, proxy: ProxyConfig | undefined, opt
|
|
|
50
50
|
if (process.env.NODE_ENV !== 'test')
|
|
51
51
|
kayLog('warn', `proxy.key is set but ${source} gives none, so requests are not checked for the ${header} header; a production server would not boot`)
|
|
52
52
|
|
|
53
|
-
return
|
|
53
|
+
return undefined
|
|
54
54
|
}
|
|
55
55
|
|
|
56
56
|
throw new KayError('config-invalid', `kay: proxy.key names the header ${header}, which carries a key read from ${source}, and it gives no non-empty one`)
|
|
@@ -58,22 +58,22 @@ export function requireProxyKey(app: Elysia, proxy: ProxyConfig | undefined, opt
|
|
|
58
58
|
|
|
59
59
|
const open = [...(proxy?.open ?? []).map(entry => entry.length > 1 && entry.endsWith('/') ? entry.slice(0, -1) : entry), ...options.health === undefined ? [] : [options.health]]
|
|
60
60
|
|
|
61
|
-
|
|
61
|
+
return (request) => {
|
|
62
62
|
const path = routerPath(pathOf(request.url), options.base)
|
|
63
63
|
const metrics = options.metrics?.() ?? []
|
|
64
64
|
|
|
65
65
|
// The metrics route answers by its own rule, so a collector on the private network needs no key.
|
|
66
66
|
if (isInternal(request) || isOpen(path, open) || metrics.some(at => path === at || path === `${at}/`) || (request.method === 'POST' && options.endpoint?.().some(at => path === at || path === `${at}/`) === true))
|
|
67
|
-
return
|
|
67
|
+
return undefined
|
|
68
68
|
|
|
69
69
|
const given = request.headers.get(header)
|
|
70
70
|
|
|
71
71
|
if (given !== null && sameText(given, secret))
|
|
72
|
-
return
|
|
72
|
+
return undefined
|
|
73
73
|
|
|
74
74
|
// This hook runs before the request id and request log hooks, which a response made here skips.
|
|
75
75
|
options.logRefused?.(request, 403)
|
|
76
76
|
|
|
77
77
|
return new Response('Forbidden\n', { status: 403, headers: { ...options.security, 'content-type': 'text/plain; charset=utf-8', [requestIdHeader()]: requestId(request) } })
|
|
78
|
-
}
|
|
78
|
+
}
|
|
79
79
|
}
|
package/src/server/query.ts
CHANGED
|
@@ -3,11 +3,9 @@ import type { ParamRule, QueryRules } from '../runtime/query-param'
|
|
|
3
3
|
import { relative } from 'node:path'
|
|
4
4
|
import process from 'node:process'
|
|
5
5
|
import { ARRIVAL_PARAM } from '../runtime/arrival'
|
|
6
|
-
import { formInput } from '../runtime/form'
|
|
7
|
-
import { errorText } from './field-errors'
|
|
8
6
|
import { pageSetting } from './page-settings'
|
|
9
|
-
import { compiledCheck, fieldOf, refusals, summaryOf } from './schema-check'
|
|
10
7
|
import { Denied } from './signals'
|
|
8
|
+
import { isRefusal, messagesOf, validateNow } from './validate'
|
|
11
9
|
|
|
12
10
|
export type ReadFields = { value: Record<string, unknown> } | { refused: Map<string, string> }
|
|
13
11
|
|
|
@@ -149,30 +147,11 @@ export function readQueryLeniently(schema: unknown, url: URL): Readonly<Record<s
|
|
|
149
147
|
}
|
|
150
148
|
|
|
151
149
|
// Text read the way a form's fields are, a top-level field left out taking its schema's default, then checked and decoded: the value, or a message per field refused.
|
|
152
|
-
// `form` is
|
|
150
|
+
// `form` is the difference between a query and the environment: a GET form leaves an unticked checkbox out of its query, while nothing leaves a variable out of the environment on purpose, nor pads it with spaces by mistake.
|
|
153
151
|
export function readFields(schema: TSchema, input: Record<string, unknown>, form = true): ReadFields {
|
|
154
|
-
const
|
|
155
|
-
const required = (schema as { required?: string[] }).required ?? []
|
|
156
|
-
|
|
157
|
-
for (const [name, field] of Object.entries((schema as ObjectSchema).properties ?? {})) {
|
|
158
|
-
// A blank list is the empty one, as `persisted.query` writes it, never one blank item; a blank optional field with a default is left out, so the default fills in. Only here: an action's body goes through `formInput` alone.
|
|
159
|
-
if (form && filled[name] === '' && (field as { type?: unknown }).type === 'array')
|
|
160
|
-
filled[name] = []
|
|
161
|
-
else if (form && filled[name] === '' && field.default !== undefined && !required.includes(name))
|
|
162
|
-
delete filled[name]
|
|
163
|
-
|
|
164
|
-
if (filled[name] === undefined && field.default !== undefined)
|
|
165
|
-
filled[name] = structuredClone(field.default)
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
const value = formInput(schema, filled, form) as Record<string, unknown>
|
|
169
|
-
const check = compiledCheck(schema)
|
|
170
|
-
|
|
171
|
-
// Decoding turns what a schema reads from text, such as an `s.Date()`, into the value its type says.
|
|
172
|
-
if (check.Check(value))
|
|
173
|
-
return { value: check.Decode<Record<string, unknown>>(value) }
|
|
152
|
+
const result = validateNow<Record<string, unknown>>(schema, input, { source: form ? 'query' : 'env' })
|
|
174
153
|
|
|
175
|
-
return { refused:
|
|
154
|
+
return isRefusal(result) ? { refused: new Map(Object.entries(messagesOf(result.errors))) } : { value: result.value }
|
|
176
155
|
}
|
|
177
156
|
|
|
178
157
|
// The rules of a page's `query` schema, which its islands' `queryParam` reads its params by: a param the rules cannot tell the type of reads as its text.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { Server } from 'bun'
|
|
2
|
+
import type { Elysia } from 'elysia'
|
|
3
|
+
|
|
4
|
+
// What a `receive` step is given: the server the request came through, none under `app.handle()`.
|
|
5
|
+
export type ReceiveServer = Server<unknown> | null | undefined
|
|
6
|
+
|
|
7
|
+
// A step of the `receive` phase, which runs before routing: it answers with a Response, hands on a Request to go on with (a rewrite), or returns nothing to let the request through.
|
|
8
|
+
export type ReceiveStep = (request: Request, server: ReceiveServer) => Request | Response | undefined | void
|
|
9
|
+
|
|
10
|
+
// What `receive` ends with: the answer, or the request every later phase and the router see.
|
|
11
|
+
export type Received = Request | Response
|
|
12
|
+
|
|
13
|
+
// The steps run in turn; the first to answer ends it, and one that hands on another request leaves the later steps to read that one.
|
|
14
|
+
export function runReceive(steps: readonly ReceiveStep[], request: Request, server: ReceiveServer): Received {
|
|
15
|
+
let current = request
|
|
16
|
+
|
|
17
|
+
for (const step of steps) {
|
|
18
|
+
const result = step(current, server)
|
|
19
|
+
|
|
20
|
+
if (result instanceof Response)
|
|
21
|
+
return result
|
|
22
|
+
|
|
23
|
+
if (result instanceof Request)
|
|
24
|
+
current = result
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
return current
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function receiving(steps: readonly (ReceiveStep | undefined)[]): (request: Request, server: ReceiveServer) => Received {
|
|
31
|
+
const given = steps.filter(step => step !== undefined)
|
|
32
|
+
|
|
33
|
+
return (request, server) => runReceive(given, request, server)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// `receive` as the Elysia hook the app still routes through while its routes are not on kay's table: the hook runs before Elysia routes, and a Response it returns is the answer.
|
|
37
|
+
export function bridgeReceive(app: Elysia, receive: (request: Request, server: ReceiveServer) => Received): void {
|
|
38
|
+
app.onRequest(({ request, server }) => {
|
|
39
|
+
const received = receive(request, server)
|
|
40
|
+
|
|
41
|
+
return received instanceof Response ? received : undefined
|
|
42
|
+
})
|
|
43
|
+
}
|
|
@@ -255,11 +255,11 @@ function navigationScripts(client: ClientBuild): string {
|
|
|
255
255
|
// A page without islands needs no hydration script, only the entry swapping pages.
|
|
256
256
|
// `saving` is set where a page drops island-only preloads for a visitor saving data. The chunks of the islands hydrating at once, `immediate`, that page keeps: they are marked `data-load`, which the dropping no longer matches.
|
|
257
257
|
// One also needed by an island that waits for that visitor, `waiting`, is marked `data-wait` too, where the code waiting for the viewport is preloaded for that visitor even though no link was dropped.
|
|
258
|
-
function islandScripts(client: ClientBuild, islands: Set<string>, streamed: boolean, hydration: boolean, lazy: boolean, saving?: { immediate: Set<string>, waiting: Set<string> }): string {
|
|
258
|
+
function islandScripts(client: ClientBuild, islands: Set<string>, streamed: boolean, hydration: boolean, lazy: boolean, drawn: Set<string>, saving?: { immediate: Set<string>, waiting: Set<string> }): string {
|
|
259
259
|
const immediate = saving?.immediate
|
|
260
260
|
const waiting = saving?.waiting
|
|
261
261
|
|
|
262
|
-
return islandScriptsOf(client, `${streamed}\n${hydration}\n${lazy}\n${[...islands].sort().join('\n')}\n\0${immediate === undefined ? '-' : [...immediate].sort().join('\n')}\n\0${waiting === undefined ? '-' : [...waiting].sort().join('\n')}`, () => {
|
|
262
|
+
return islandScriptsOf(client, `${streamed}\n${hydration}\n${lazy}\n${[...islands].sort().join('\n')}\n\0${[...drawn].sort().join('\n')}\n\0${immediate === undefined ? '-' : [...immediate].sort().join('\n')}\n\0${waiting === undefined ? '-' : [...waiting].sort().join('\n')}`, () => {
|
|
263
263
|
const chunks = new Set(client.entryImports)
|
|
264
264
|
|
|
265
265
|
// Waiting for an island to be visible or idle, or a deferred server island to near the viewport, needs its own chunk, which the entry would ask for only once it ran.
|
|
@@ -283,6 +283,16 @@ function islandScripts(client: ClientBuild, islands: Set<string>, streamed: bool
|
|
|
283
283
|
}
|
|
284
284
|
}
|
|
285
285
|
|
|
286
|
+
// The components an island draws at first paint that its own chunk loads lazily: loaded before it hydrates, as the island's own code is.
|
|
287
|
+
for (const key of drawn) {
|
|
288
|
+
for (const chunk of client.lazies?.[key] ?? []) {
|
|
289
|
+
chunks.add(chunk)
|
|
290
|
+
|
|
291
|
+
if (immediate !== undefined)
|
|
292
|
+
now.add(chunk)
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
286
296
|
return `${[...chunks].map(chunk => `<link rel="modulepreload" href="${chunk}"${now.has(chunk) ? ` data-load${waits.has(chunk) ? ' data-wait' : ''}` : ''}>`).join('')}${hydration ? hydrationScript : ''}${streamed ? '' : `<script type="module" src="${client.entry}"></script>`}`
|
|
287
297
|
})
|
|
288
298
|
}
|
|
@@ -495,7 +505,7 @@ function documentOf(files: string[], modules: PageModule[], data: Record<string,
|
|
|
495
505
|
// A production page only posting forms loads navigation alone; a streamed one, or a prerendered one holding a server island, may still render islands or forms per request, which the islands' entry runs.
|
|
496
506
|
const navigates = posts && !hasIslands && !follows && !defers && !streamed && (scan?.modes.length ?? 0) === 0 && client.navEntry !== undefined
|
|
497
507
|
const checked = posts ? formsScript(forms, options.dev) : ''
|
|
498
|
-
const scripts = shipsEntry ? (navigates ? navigationScripts(client) : islandScripts(client, islands.eager, streamed, hasIslands, islands.lazy > 0 || defers, options.islandPreloads === undefined ? undefined : islands)) + checked + workScript(forms, options.prerendering === true) : ''
|
|
508
|
+
const scripts = shipsEntry ? (navigates ? navigationScripts(client) : islandScripts(client, islands.eager, streamed, hasIslands, islands.lazy > 0 || defers, islands.lazies, options.islandPreloads === undefined ? undefined : islands)) + checked + workScript(forms, options.prerendering === true) : ''
|
|
499
509
|
const state = localeState()
|
|
500
510
|
// Without `i18n` the page may say its own language; with it, the locale decides.
|
|
501
511
|
const lang = (state === undefined || state.implicit ? head.lang : undefined) ?? state?.locale ?? options.lang ?? DEFAULT_LANG
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import type { RouteRecord } from './kay-routes'
|
|
2
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
3
|
+
import { requestCookies } from './cookies'
|
|
4
|
+
import { requestUrl } from './request-url'
|
|
5
|
+
import { Denied } from './signals'
|
|
6
|
+
|
|
7
|
+
// What a handler writes to the answer: the status and the headers, folded into the Response once, at the end. It is apart from `headers`, which reads the request.
|
|
8
|
+
export interface ResponseSet {
|
|
9
|
+
status: number | undefined
|
|
10
|
+
headers: Headers
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
type Params = Record<string, string>
|
|
14
|
+
type Fields = Record<string, string | string[]>
|
|
15
|
+
|
|
16
|
+
function addField(fields: Record<string, unknown>, key: string, value: unknown): void {
|
|
17
|
+
const held = fields[key]
|
|
18
|
+
|
|
19
|
+
if (held === undefined)
|
|
20
|
+
fields[key] = value
|
|
21
|
+
else
|
|
22
|
+
fields[key] = Array.isArray(held) ? [...held, value] : [held, value]
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// The query as an object, a name given twice holding both values; a name such as `__proto__` is a key like any other.
|
|
26
|
+
function queryOf(url: URL): Fields {
|
|
27
|
+
const fields: Fields = Object.create(null) as Fields
|
|
28
|
+
|
|
29
|
+
for (const [key, value] of url.searchParams)
|
|
30
|
+
addField(fields, key, value)
|
|
31
|
+
|
|
32
|
+
return fields
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// What the body holds as its type says: JSON parsed, a form read into fields (a file kept as a File), text as it is, any other body as bytes, and none as undefined.
|
|
36
|
+
async function readBody(request: Request): Promise<unknown> {
|
|
37
|
+
if (request.body === null)
|
|
38
|
+
return undefined
|
|
39
|
+
|
|
40
|
+
const type = request.headers.get('content-type') ?? ''
|
|
41
|
+
|
|
42
|
+
if (type.startsWith('application/json') || type.includes('+json')) {
|
|
43
|
+
try {
|
|
44
|
+
return await request.json()
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
throw new Denied(400, 'The body is not valid JSON')
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (type.startsWith('application/x-www-form-urlencoded') || type.startsWith('multipart/form-data')) {
|
|
52
|
+
const fields: Record<string, unknown> = Object.create(null) as Record<string, unknown>
|
|
53
|
+
|
|
54
|
+
try {
|
|
55
|
+
for (const [key, value] of (await request.formData()).entries())
|
|
56
|
+
addField(fields, key, value)
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
throw new Denied(400, 'The body is not a valid form')
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return fields
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return type.startsWith('text/') ? request.text() : request.arrayBuffer()
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// The one context of a request kay answers from its table, whatever the route kind: what it reads of the request is parsed on first read, once.
|
|
69
|
+
export class RequestContext {
|
|
70
|
+
readonly request: Request
|
|
71
|
+
// The route's params, decoded once from the path, empty while `malformed`.
|
|
72
|
+
readonly params: Params
|
|
73
|
+
// Whether a param held an escape that does not decode, which the `input` phase refuses with a 400.
|
|
74
|
+
readonly malformed: boolean
|
|
75
|
+
readonly locale: string | undefined
|
|
76
|
+
readonly route: RouteRecord | undefined
|
|
77
|
+
// What the phases before the handler hand on, such as a plugin's or a guard's values.
|
|
78
|
+
readonly locals: Record<string, unknown> = Object.create(null) as Record<string, unknown>
|
|
79
|
+
#query: Fields | undefined
|
|
80
|
+
#body: Promise<unknown> | undefined
|
|
81
|
+
#set: ResponseSet | undefined
|
|
82
|
+
|
|
83
|
+
constructor(request: Request, route: RouteRecord | undefined, params: Params | undefined, locale?: string) {
|
|
84
|
+
this.request = request
|
|
85
|
+
this.route = route
|
|
86
|
+
this.malformed = params === undefined
|
|
87
|
+
this.params = params ?? {}
|
|
88
|
+
this.locale = locale ?? route?.locale
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
get url(): URL {
|
|
92
|
+
return requestUrl(this.request)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
get method(): string {
|
|
96
|
+
return this.request.method
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// The request's headers; the answer's are written through `set`.
|
|
100
|
+
get headers(): Headers {
|
|
101
|
+
return this.request.headers
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
get query(): Fields {
|
|
105
|
+
return this.#query ??= queryOf(this.url)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
get cookies(): Pick<Bun.CookieMap, 'get' | 'has'> {
|
|
109
|
+
return requestCookies(this.request)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// The parsed body, a promise as reading it waits for the bytes; a malformed one refuses with a 400 when it is read.
|
|
113
|
+
get body(): Promise<unknown> {
|
|
114
|
+
return this.#body ??= readBody(this.request)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// Made when the handler first writes to it, so a route that sets nothing allocates nothing.
|
|
118
|
+
get set(): ResponseSet {
|
|
119
|
+
return this.#set ??= { status: undefined, headers: new Headers() }
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// The answer's status and headers a handler set, if it set any.
|
|
123
|
+
get written(): ResponseSet | undefined {
|
|
124
|
+
return this.#set
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const scopes = new AsyncLocalStorage<RequestContext>()
|
|
129
|
+
|
|
130
|
+
// The context of the request kay is answering in this async context, a handler running after a macrotask included.
|
|
131
|
+
export function requestContext(): RequestContext | undefined {
|
|
132
|
+
return scopes.getStore()
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function inContext<T>(context: RequestContext, run: () => T): T {
|
|
136
|
+
return scopes.run(context, run)
|
|
137
|
+
}
|
|
@@ -40,7 +40,7 @@ export function refusals(check: TypeCheck<TSchema>, value: unknown, keyOf: (poin
|
|
|
40
40
|
}
|
|
41
41
|
|
|
42
42
|
// A block of a `blocks()` list that fails is reported by the fields of its own type, as the union of all the types would only say the item is not valid; a block naming no declared type keeps the union's error.
|
|
43
|
-
function* withoutBlockUnions(issues: Iterable<ValueError>): Generator<ValueError> {
|
|
43
|
+
export function* withoutBlockUnions(issues: Iterable<ValueError>): Generator<ValueError> {
|
|
44
44
|
for (const issue of issues) {
|
|
45
45
|
const own = variantOf(issue)
|
|
46
46
|
|