@cslug/http 0.0.0-stage → 0.2.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 CHANGED
@@ -1,3 +1,7 @@
1
- # Temporary Holding Version
1
+ # @cslug/http
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Routing, middleware, `HttpContext`, request validation, responses, RFC 9457 errors, sessions, CSRF, form errors
4
+ with old input, throttling, locale detection and graceful shutdown, on `Bun.serve`.
5
+
6
+ Part of [cslug](https://github.com/cslugts/cslug). Docs: [docs/README.md](docs/README.md), [docs/api.md](docs/api.md),
7
+ guides [05](../../guides/05-routing-and-middleware.md), [06](../../guides/06-controllers.md).
package/docs/README.md ADDED
@@ -0,0 +1,24 @@
1
+ # @cslug/http
2
+
3
+ Routing, controllers, request validation, responses, error rendering, sessions, CSRF, form errors with old
4
+ input, throttling and locale detection, on `Bun.serve`.
5
+
6
+ ```ts
7
+ // routes/web.ts
8
+ export default defineRoutes((r) => {
9
+ r.group({ prefix: '/:locale', as: 'public' }, (r) => {
10
+ r.get('/circuits/:slug', [CircuitController, 'show']).name('circuits.show')
11
+ })
12
+ r.resource('operators', OperatorController).only(['index', 'show'])
13
+ r.group({ domain: 'api.albastr.com', prefix: '/v1' }, (r) => { … })
14
+ })
15
+
16
+ // a controller action
17
+ async store({ request }: HttpContext) {
18
+ const data = await request.validate(StoreTripRequestValidator) // typed; 422 on failure
19
+ return created(await this.trips.open(data))
20
+ }
21
+ ```
22
+
23
+ - Full reference: [api.md](./api.md)
24
+ - Guides: [05 Routing & middleware](../../../guides/05-routing-and-middleware.md), [06 Controllers](../../../guides/06-controllers.md), [07 Validation](../../../guides/07-validation.md)
package/docs/api.md ADDED
@@ -0,0 +1,100 @@
1
+ # @cslug/http: API
2
+
3
+ ## Routes
4
+
5
+ `defineRoutes((r) => { … })`, loaded by `HttpProvider` from `routes/web.ts` (web group) and `routes/api.ts`
6
+ (api group); `router.load(fn, group)` for more.
7
+
8
+ | | |
9
+ |---|---|
10
+ | `r.get/post/put/patch/delete/options(path, action)` | `action`: `[Controller, 'method']`, a single-action class (`handle`), or a closure |
11
+ | `.name(n)`, `.middleware(...m)`, `.where('param', /re/)` | |
12
+ | `r.group({ prefix, domain, middleware, as, ...meta }, fn)` | Nested groups accumulate prefix, middleware and name prefix; `domain` may contain `:params` |
13
+ | `r.resource('operators', Ctl).only([...]) / .except([...])` | index, create, store, show, edit, update (PATCH), destroy; nested `'operators.documents'` |
14
+
15
+ Matching: routes with a domain first; static segments beat parameters beat wildcards; trailing slash ignored;
16
+ parameters URL-decoded; `HEAD` → `GET` without a body; a known path with another method → **405** with `Allow`.
17
+
18
+ ## URLs
19
+
20
+ `route(name, params?, { absolute?, query?, signed?, expiresIn? })`: unknown params become the query string; a route
21
+ on another domain is absolute; `signed` adds an HMAC (APP_KEY) checked by the `signed()` middleware;
22
+ `urlFor(router, appUrl, key, …)` and `verifySignedUrl(url, key)` for code without an app context.
23
+
24
+ ## `HttpContext`
25
+
26
+ `request`, `params`, `response` (`header()`, `cookie()`, `status`), `app`, `scope`, `requestId`, `signal`, `log`,
27
+ `locale`, `routeName`, `resolve(token)`. Packages augment it (`declare module '@cslug/http' { interface HttpContext { … } }`).
28
+
29
+ `HttpRequest`: `method`, `path`, `url`, `headers`, `header()`, `ip()` (X-Forwarded-For only from
30
+ `http.trustedProxies`, `'loopback'` allowed), `query()`, `queryAll()`, `body()` (JSON; forms with `a[b]`/`a[]`
31
+ keys; files), `raw()` (bytes, for signatures), `input()`, `file()`, `wantsJson()`, `isJson`, `isForm`,
32
+ `validate(schema | Validator | ValidatorClass | StandardSchema, { from? })`. Query and form input is coerced to the
33
+ schema: numbers, checkboxes, single → array, `''` → undefined for optional fields. Validator classes are built by
34
+ the container (DI).
35
+
36
+ ## Responses
37
+
38
+ Return a `Response`, a `Responsable` (`toResponse(ctx)`), an object/array (JSON: bigint → string, Date → ISO,
39
+ `toJSON()`), a string (`text/plain`), or `null`/`undefined` (204). Helpers: `json`, `created`, `accepted`,
40
+ `noContent`, `download(content, filename, type?)`, `stream(asyncIterable)`, `sse(asyncIterable)`,
41
+ `redirect().route(name, params) / .to(url) / .away(url) / .back(fallback) / .intended(fallback) / .with(key, value)`
42
+ (303 after non-GET; `.with()` and `.intended()` need the session).
43
+
44
+ ## Errors (`ExceptionHandler`)
45
+
46
+ `ValidationError` → 422 with translated `errors`; `AppError` subclasses → their status, `code`, `params`; anything
47
+ else → 500, logged with the stack, **no detail in production** (detail + short stack otherwise). API clients get
48
+ `application/problem+json` (`type`, `title`, `status`, `code`, `requestId`, …); browsers a minimal HTML page.
49
+ Extend with `handler.render(fn)` (first match wins) and `handler.report(fn)` (5xx).
50
+
51
+ ## Middleware (`@cslug/http/middleware`)
52
+
53
+ `securityHeaders({ hsts?, csp?, frameOptions? })` (global by default), `bodyLimit(size)` (global `1mb`; also
54
+ enforced on bytes read), `timeout(duration)` (503, aborts `ctx.signal`), `signed()`, `cors({ origins, … })`.
55
+ Function middleware `(ctx, next) => Response`, or a class with `handle(ctx, next)` built by the container.
56
+
57
+ ## Kernel
58
+
59
+ `HttpKernel.handle(request)` (no port: used by tests), `listen({ port?, hostname? })`, `stop(timeoutMs)` (waits for
60
+ in-flight requests, then closes the rest), `health('live' | 'ready')` (runs checks tagged `HEALTH_CHECKS`, e.g.
61
+ the database's). One log line per request: method, path, status, ms, route, requestId.
62
+
63
+ ## `HttpProvider`
64
+
65
+ Config `http`: `port`, `host`, `shutdownTimeout`, `bodyLimit`, `trustedProxies`, `cors` (api group),
66
+ `groups.{web,api}`, `middleware`, `problemBase`, `health`.
67
+
68
+ ## Sessions, CSRF, forms (web group)
69
+
70
+ `routes/web.ts` routes get `session()` and `csrf()`.
71
+
72
+ | | |
73
+ |---|---|
74
+ | `session(options?)` | Loads the session from its cookie (`config('session')`: `cookie` (`cslug_session`), `lifetime` (`14d`), `sameSite`, `domain`), saves what changed, sends an HttpOnly cookie (Secure in production). Errors are rendered inside it so flashes are saved |
75
+ | `ctx.session` | `get`, `put`, `has`, `forget`, `pull`, `flash`, `reflash`, `flashed()`, `errors()`, `old(key?)`, `token()`, `verifyToken()`, `regenerate()` (on login), `invalidate()` (on logout). Without the middleware, using it throws an explanation; `ctx.session.available` is false then |
76
+ | `csrf({ except? })` | 419 for POST/PUT/PATCH/DELETE without the session token (`_token` form field or `X-CSRF-Token` header) |
77
+ | form errors | A `ValidationError` on a non-JSON, non-GET request with a session → **303 back** (Referer) with `_errors` (translated) and `_old` (input without passwords, tokens, files) flashed |
78
+ | method spoofing | A form POST with `_method=PUT/PATCH/DELETE` is routed as that method |
79
+ | `redirect().with(k, v)` / `.intended(fallback)` | Flash / go to `session('url.intended')` |
80
+ | `request.cookie(name)` | |
81
+
82
+ ## Throttle and locale
83
+
84
+ | | |
85
+ |---|---|
86
+ | `throttle('5/min', key?)` | Through the `RateLimiter` (memory, or Redis). Key: route + (user, else IP), or your function. `X-RateLimit-Limit/Remaining`; over → 429 with `Retry-After` |
87
+ | `locale()` | `:locale` param → `locale` cookie → `Accept-Language` (weighted, region stripped) → default; only `config('i18n.locales')`. Sets `ctx.locale` and the ambient locale (`t()`) |
88
+
89
+ ## Static files
90
+
91
+ GET/HEAD requests that match no route are served from `public/` (`config('http.public')`: a folder name, or
92
+ `false`). Dotfiles and paths escaping the folder are refused. Hashed build files (`name-1a2b3c4d.js`) get
93
+ `Cache-Control: public, max-age=31536000, immutable`; others revalidate with `Last-Modified` / 304.
94
+
95
+ ## Commands
96
+
97
+ | | |
98
+ |---|---|
99
+ | `cslug serve [--port] [--host] [--reuse-port] [--with-worker] [--with-scheduler]` | The HTTP server; SIGTERM drains in-flight requests. `--with-worker` / `--with-scheduler` also run `queue:work` / `schedule:work` in this process (one-process deployment, guide 21); they are found by signature, so http does not import the queue, and missing commands are an error |
100
+ | `cslug routes [filter] [--json]` | The routes, with names and middleware |
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "@cslug/http",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Router, middleware, HttpContext, sessions, CSRF, error rendering on Bun.serve.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/cslugts/cslug.git",
10
+ "directory": "packages/http"
11
+ },
12
+ "homepage": "https://github.com/cslugts/cslug/tree/main/packages/http",
13
+ "keywords": [
14
+ "cslug",
15
+ "bun",
16
+ "framework"
17
+ ],
18
+ "exports": {
19
+ ".": "./src/index.ts",
20
+ "./middleware": "./src/middleware/index.ts"
21
+ },
22
+ "files": [
23
+ "src",
24
+ "docs",
25
+ "stubs",
26
+ "README.md"
27
+ ],
28
+ "engines": {
29
+ "bun": ">=1.3.14"
30
+ },
31
+ "peerDependencies": {
32
+ "@cslug/core": "0.2.0",
33
+ "@cslug/validation": "0.2.0"
34
+ }
35
+ }
package/src/body.ts ADDED
@@ -0,0 +1,72 @@
1
+ import {
2
+ ArraySchema,
3
+ BooleanSchema,
4
+ DefaultSchema,
5
+ NullableSchema,
6
+ NumberSchema,
7
+ ObjectSchema,
8
+ OptionalSchema,
9
+ type Schema,
10
+ } from '@cslug/validation'
11
+
12
+ /** Form keys with brackets → nested objects: `budget[amount]=1` → `{ budget: { amount: '1' } }`; `tags[]=a`. */
13
+ export function nestKeys(entries: Iterable<[string, unknown]>): Record<string, unknown> {
14
+ const out: Record<string, unknown> = {}
15
+ for (const [key, value] of entries) {
16
+ const path = key.replace(/\]/g, '').split('[')
17
+ let node: Record<string, unknown> = out
18
+ path.forEach((part, i) => {
19
+ const last = i === path.length - 1
20
+ const nextIsArray = path[i + 1] === ''
21
+ if (part === '') return
22
+ if (last || (i === path.length - 2 && nextIsArray)) {
23
+ if (nextIsArray) {
24
+ const list = Array.isArray(node[part]) ? (node[part] as unknown[]) : []
25
+ list.push(value)
26
+ node[part] = list
27
+ } else if (part in node && !Array.isArray(node[part]) && typeof node[part] !== 'object') {
28
+ node[part] = [node[part], value] // a repeated key becomes a list
29
+ } else node[part] = value
30
+ return
31
+ }
32
+ node[part] ??= {}
33
+ node = node[part] as Record<string, unknown>
34
+ })
35
+ }
36
+ return out
37
+ }
38
+
39
+ const unwrap = (s: Schema): Schema => {
40
+ let current: Schema = s
41
+ for (;;) {
42
+ if (current instanceof OptionalSchema || current instanceof NullableSchema || current instanceof DefaultSchema)
43
+ current = current.inner as Schema
44
+ else return current
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Strings from query strings and HTML forms → what the schema expects: numbers, booleans (checkboxes), single
50
+ * values → arrays, and empty strings → undefined for optional fields (an empty input means "not given").
51
+ */
52
+ export function coerceForm(schema: Schema, value: unknown): unknown {
53
+ const target = unwrap(schema)
54
+ const optional = target !== schema
55
+ if (value === '' && optional) return undefined
56
+ if (target instanceof ObjectSchema && value && typeof value === 'object' && !Array.isArray(value)) {
57
+ const out: Record<string, unknown> = { ...(value as Record<string, unknown>) }
58
+ for (const [k, s] of Object.entries(target.shape as Record<string, Schema>)) out[k] = coerceForm(s, out[k])
59
+ return out
60
+ }
61
+ if (target instanceof ArraySchema) {
62
+ if (value === undefined || value === '') return optional ? undefined : []
63
+ return (Array.isArray(value) ? value : [value]).map((v) => coerceForm(target.element as Schema, v))
64
+ }
65
+ if (typeof value !== 'string') return value
66
+ if (target instanceof NumberSchema && /^-?\d+(\.\d+)?$/.test(value.trim())) return Number(value)
67
+ if (target instanceof BooleanSchema) {
68
+ if (['1', 'on', 'true', 'yes'].includes(value.toLowerCase())) return true
69
+ if (['0', 'off', 'false', 'no'].includes(value.toLowerCase())) return false
70
+ }
71
+ return value
72
+ }
@@ -0,0 +1,132 @@
1
+ import { join } from 'node:path'
2
+ import { arg, COMMANDS, Command, type CommandClass, flag, names, parseArgs } from '@cslug/core'
3
+ import { HttpKernel } from './kernel'
4
+ import { Router } from './router'
5
+
6
+ const STUBS = join(import.meta.dir, '../stubs')
7
+
8
+ /** `cslug serve`: the HTTP server; SIGTERM drains in-flight requests (`http.shutdownTimeout`), then exits. */
9
+ export class ServeCommand extends Command {
10
+ static signature = 'serve'
11
+ static description = 'Start the HTTP server'
12
+ static longRunning = true
13
+ static args = {
14
+ port: flag.number().optional().describe('Port (default: config http.port, PORT, or 3000)'),
15
+ host: flag.string().optional().describe('Interface to bind (default: all)'),
16
+ reusePort: flag.boolean().describe('Share the port between several processes (cslug start with web instances > 1)'),
17
+ withWorker: flag.boolean().describe('Also run queue:work in this process (needs @cslug/queue)'),
18
+ withScheduler: flag.boolean().describe('Also run schedule:work in this process (needs ScheduleProvider)'),
19
+ }
20
+
21
+ async handle({ port, host, reusePort, withWorker, withScheduler }: Command.Args<typeof ServeCommand>) {
22
+ // http does not import the queue: the other roles run through their own commands, found by signature
23
+ const roles = [withWorker && 'queue:work', withScheduler && 'schedule:work'].filter((r): r is string => !!r)
24
+ const found = this.app.taggedTokens(COMMANDS) as CommandClass[]
25
+ for (const signature of roles) {
26
+ if (!found.some((c) => c.signature === signature)) {
27
+ this.error(
28
+ `--with-${signature === 'queue:work' ? 'worker' : 'scheduler'}: no ${signature} command (is its provider listed?)`,
29
+ )
30
+ return 1
31
+ }
32
+ }
33
+ const envPort = process.env.PORT ? Number(process.env.PORT) : undefined
34
+ const server = this.app.resolve(HttpKernel).listen({ port: port ?? envPort, hostname: host, reusePort })
35
+ this.log.info('http.listening', { url: server.url.toString() })
36
+ if (process.stdout.isTTY) this.info(`Listening on ${server.url}`)
37
+ for (const signature of roles) {
38
+ const cmd = found.find((c) => c.signature === signature) as CommandClass
39
+ const instance = this.app.createScope().build(cmd as never) as { handle(args: unknown): unknown }
40
+ await instance.handle(parseArgs(cmd.args ?? {}, []))
41
+ }
42
+ return 0
43
+ }
44
+ }
45
+
46
+ /** `cslug routes`: every route with its name and middleware. */
47
+ export class RoutesCommand extends Command {
48
+ static signature = 'routes'
49
+ static description = 'List the routes'
50
+ static args = {
51
+ json: flag.boolean(),
52
+ filter: arg.string().optional().describe('Only paths or names containing this'),
53
+ }
54
+
55
+ handle({ json, filter }: Command.Args<typeof RoutesCommand>) {
56
+ const rows = this.app
57
+ .resolve(Router)
58
+ .routes.filter((r) => !filter || r.path.includes(filter) || r.name?.includes(filter))
59
+ .map((r) => ({
60
+ method: r.method,
61
+ path: `${r.domain ? `//${r.domain}` : ''}${r.path}`,
62
+ name: r.name ?? '',
63
+ action: actionName(r.action),
64
+ middleware: r.middleware.map((m) => (typeof m === 'function' ? m.name || 'fn' : String(m))).join(', '),
65
+ }))
66
+ if (json) this.line(JSON.stringify(rows))
67
+ else this.table(rows)
68
+ }
69
+ }
70
+
71
+ const actionName = (action: unknown): string => {
72
+ if (Array.isArray(action)) return `${(action[0] as { name?: string })?.name}.${String(action[1])}`
73
+ return typeof action === 'function' ? action.name || 'closure' : 'closure'
74
+ }
75
+
76
+ const makeArgs = { name: arg.string().describe('Name, optionally in a folder: admin/Claim'), force: flag.boolean() }
77
+
78
+ /** `cslug make:controller Claim [--resource]` → app/controllers/claim-controller.ts. */
79
+ export class MakeControllerCommand extends Command {
80
+ static signature = 'make:controller'
81
+ static description = 'Create a controller (--resource for the REST actions)'
82
+ static boot = false
83
+ static args = { ...makeArgs, resource: flag.boolean().describe('index, show, create, store, edit, update, destroy') }
84
+
85
+ handle({ name, force, resource }: Command.Args<typeof MakeControllerCommand>) {
86
+ const n = names(name, 'controller')
87
+ const ok = this.generate(
88
+ STUBS,
89
+ resource ? 'controller.resource.stub' : 'controller.stub',
90
+ `app/controllers/${n.file}.ts`,
91
+ { ...n, plural: `${n.kebab}s` },
92
+ force,
93
+ )
94
+ if (ok)
95
+ this.line(
96
+ ` route: r.${resource ? `resource('${n.kebab}s', ${n.class})` : `get('/${n.kebab}s', [${n.class}, 'index'])`}`,
97
+ )
98
+ return ok ? 0 : 1
99
+ }
100
+ }
101
+
102
+ /** `cslug make:validator StoreClaim` → app/validators/store-claim-validator.ts. */
103
+ export class MakeValidatorCommand extends Command {
104
+ static signature = 'make:validator'
105
+ static description = 'Create a request validator'
106
+ static boot = false
107
+ static args = makeArgs
108
+ handle({ name, force }: Command.Args<typeof MakeValidatorCommand>) {
109
+ const n = names(name, 'validator')
110
+ return this.generate(STUBS, 'validator.stub', `app/validators/${n.file}.ts`, n, force) ? 0 : 1
111
+ }
112
+ }
113
+
114
+ /** `cslug make:middleware EnsureOperator` → app/middleware/ensure-operator-middleware.ts. */
115
+ export class MakeMiddlewareCommand extends Command {
116
+ static signature = 'make:middleware'
117
+ static description = 'Create a middleware class'
118
+ static boot = false
119
+ static args = makeArgs
120
+ handle({ name, force }: Command.Args<typeof MakeMiddlewareCommand>) {
121
+ const n = names(name, 'middleware')
122
+ return this.generate(STUBS, 'middleware.stub', `app/middleware/${n.file}.ts`, n, force) ? 0 : 1
123
+ }
124
+ }
125
+
126
+ export const httpCommands = [
127
+ ServeCommand,
128
+ RoutesCommand,
129
+ MakeControllerCommand,
130
+ MakeValidatorCommand,
131
+ MakeMiddlewareCommand,
132
+ ]
package/src/context.ts ADDED
@@ -0,0 +1,232 @@
1
+ import { type Application, BadRequestError, type Container, type Logger, type Resolved, type Token } from '@cslug/core'
2
+ import { type Output, type Schema, type Validatable, Validator, validate } from '@cslug/validation'
3
+ import { coerceForm, nestKeys } from './body'
4
+ import type { Session } from './session'
5
+
6
+ type ValidatorClass = abstract new (...args: never[]) => Validator
7
+ /** What `request.validate()` accepts: a schema, a Validator instance or class, a Standard Schema. */
8
+ export type Validated<T> = T extends ValidatorClass ? Output<InstanceType<T>> : Output<T>
9
+
10
+ /** The incoming request, with parsed input. Body bytes are read once and cached. */
11
+ export class HttpRequest {
12
+ private bytes?: Promise<Uint8Array<ArrayBuffer>>
13
+ /** Maximum body size in bytes (set by the `bodyLimit` middleware), enforced on the bytes actually read. */
14
+ maxBodyBytes?: number
15
+ private parsed?: Promise<Record<string, unknown>>
16
+ readonly url: URL
17
+
18
+ constructor(
19
+ readonly raw_: Request,
20
+ private readonly scope: Container,
21
+ readonly ip_: string | undefined,
22
+ ) {
23
+ this.url = new URL(raw_.url)
24
+ }
25
+
26
+ get method(): string {
27
+ return this.raw_.method
28
+ }
29
+ get path(): string {
30
+ return this.url.pathname
31
+ }
32
+ get headers(): Headers {
33
+ return this.raw_.headers
34
+ }
35
+ header(name: string): string | undefined {
36
+ return this.raw_.headers.get(name) ?? undefined
37
+ }
38
+ /** Client IP (from the socket; `X-Forwarded-For` only behind trusted proxies, handled by the kernel). */
39
+ ip(): string | undefined {
40
+ return this.ip_
41
+ }
42
+
43
+ private cookieJar?: Map<string, string>
44
+ /** A cookie sent by the client. */
45
+ cookie(name: string): string | undefined {
46
+ if (!this.cookieJar) {
47
+ this.cookieJar = new Map()
48
+ for (const part of (this.header('cookie') ?? '').split(';')) {
49
+ const i = part.indexOf('=')
50
+ if (i > 0) {
51
+ try {
52
+ this.cookieJar.set(part.slice(0, i).trim(), decodeURIComponent(part.slice(i + 1).trim()))
53
+ } catch {}
54
+ }
55
+ }
56
+ }
57
+ return this.cookieJar.get(name)
58
+ }
59
+
60
+ /** One query parameter. */
61
+ query(key: string): string | undefined {
62
+ return this.url.searchParams.get(key) ?? undefined
63
+ }
64
+ /** All query parameters, with `a[b]` nesting. */
65
+ queryAll(): Record<string, unknown> {
66
+ return nestKeys(this.url.searchParams.entries())
67
+ }
68
+
69
+ /** The body as bytes (for webhook signatures). */
70
+ raw(): Promise<Uint8Array<ArrayBuffer>> {
71
+ this.bytes ??= this.raw_.arrayBuffer().then((b) => {
72
+ if (this.maxBodyBytes !== undefined && b.byteLength > this.maxBodyBytes) {
73
+ throw Object.assign(new BadRequestError('http.payload_too_large', 'The request body is too large.'), {
74
+ status: 413,
75
+ })
76
+ }
77
+ return new Uint8Array(b)
78
+ })
79
+ return this.bytes
80
+ }
81
+
82
+ get contentType(): string {
83
+ return (this.header('content-type') ?? '').split(';')[0]?.trim().toLowerCase() ?? ''
84
+ }
85
+ get isJson(): boolean {
86
+ return this.contentType === 'application/json' || this.contentType.endsWith('+json')
87
+ }
88
+ get isForm(): boolean {
89
+ return this.contentType === 'application/x-www-form-urlencoded' || this.contentType === 'multipart/form-data'
90
+ }
91
+
92
+ /** The client prefers JSON (an API call or `fetch` from an island) over an HTML page. */
93
+ wantsJson(): boolean {
94
+ const accept = this.header('accept') ?? ''
95
+ return (
96
+ this.isJson ||
97
+ accept.includes('application/json') ||
98
+ (!accept.includes('text/html') && this.header('x-requested-with') === 'XMLHttpRequest')
99
+ )
100
+ }
101
+
102
+ /** The parsed body: JSON, or a form (nested keys, files as File). GET/HEAD → the query string. */
103
+ body(): Promise<Record<string, unknown>> {
104
+ this.parsed ??= this.parse().then((b) => {
105
+ this.parsedBody = b
106
+ return b
107
+ })
108
+ return this.parsed
109
+ }
110
+
111
+ /** The parsed body once it has been read (sync access for error renderers); undefined before. */
112
+ parsedBody?: Record<string, unknown>
113
+
114
+ private async parse(): Promise<Record<string, unknown>> {
115
+ if (this.method === 'GET' || this.method === 'HEAD') return this.queryAll()
116
+ const bytes = await this.raw()
117
+ if (!bytes.length) return {}
118
+ if (this.isJson) {
119
+ try {
120
+ const value = JSON.parse(new TextDecoder().decode(bytes))
121
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : { value }
122
+ } catch {
123
+ throw new BadRequestError('http.invalid_json', 'The request body is not valid JSON.')
124
+ }
125
+ }
126
+ if (this.isForm) {
127
+ const form = await new Request(this.raw_.url, {
128
+ method: 'POST',
129
+ headers: this.raw_.headers,
130
+ body: bytes,
131
+ }).formData()
132
+ return nestKeys(form.entries())
133
+ }
134
+ return {}
135
+ }
136
+
137
+ /** One input value (body for POST/PUT/PATCH/DELETE, query for GET). Prefer `validate()` for writes. */
138
+ async input(key: string): Promise<unknown> {
139
+ return (await this.body())[key]
140
+ }
141
+
142
+ /** A file from a multipart body. */
143
+ async file(key: string): Promise<File | undefined> {
144
+ const v = (await this.body())[key]
145
+ return v instanceof File ? v : undefined
146
+ }
147
+
148
+ /**
149
+ * Validate the input and return it typed: `await request.validate(StoreTripRequestValidator)`.
150
+ * GET reads the query string; other methods the body. Form and query strings are coerced to the schema
151
+ * (numbers, checkboxes, arrays, empty → undefined). Throws `ValidationError` (422).
152
+ */
153
+ async validate<T extends Validatable | ValidatorClass>(
154
+ target: T,
155
+ options: { from?: 'body' | 'query' } = {},
156
+ ): Promise<Validated<T>> {
157
+ const instance =
158
+ typeof target === 'function'
159
+ ? (this.scope.resolve(target as unknown as Token<Validator>) as Validator)
160
+ : (target as Validatable)
161
+ const fromQuery =
162
+ options.from === 'query' || (options.from === undefined && (this.method === 'GET' || this.method === 'HEAD'))
163
+ let input: unknown = fromQuery ? this.queryAll() : await this.body()
164
+ const schema = instance instanceof Validator ? instance.schema : instance
165
+ if ((fromQuery || this.isForm) && isCslugSchema(schema)) input = coerceForm(schema, input)
166
+ return (await validate(instance, input)) as Validated<T>
167
+ }
168
+ }
169
+
170
+ const isCslugSchema = (s: unknown): s is Schema => typeof s === 'object' && s !== null && '_def' in s && '_run' in s
171
+
172
+ /** Outgoing response details set by the handler (cookies, extra headers). */
173
+ export class ResponseBuilder {
174
+ readonly headers = new Headers()
175
+ status?: number
176
+
177
+ header(name: string, value: string): this {
178
+ this.headers.set(name, value)
179
+ return this
180
+ }
181
+ /** `Set-Cookie`, defaults: HttpOnly, Secure (in production), SameSite=Lax, Path=/. */
182
+ cookie(
183
+ name: string,
184
+ value: string,
185
+ options: {
186
+ maxAge?: number
187
+ httpOnly?: boolean
188
+ secure?: boolean
189
+ sameSite?: 'lax' | 'strict' | 'none'
190
+ path?: string
191
+ domain?: string
192
+ } = {},
193
+ ): this {
194
+ const parts = [
195
+ `${name}=${encodeURIComponent(value)}`,
196
+ `Path=${options.path ?? '/'}`,
197
+ `SameSite=${options.sameSite ?? 'Lax'}`,
198
+ ]
199
+ if (options.httpOnly !== false) parts.push('HttpOnly')
200
+ if (options.secure ?? process.env.APP_ENV === 'production') parts.push('Secure')
201
+ if (options.maxAge !== undefined) parts.push(`Max-Age=${options.maxAge}`)
202
+ if (options.domain) parts.push(`Domain=${options.domain}`)
203
+ this.headers.append('set-cookie', parts.join('; '))
204
+ return this
205
+ }
206
+ }
207
+
208
+ /**
209
+ * What a handler receives. Packages add fields with module augmentation
210
+ * (`declare module '@cslug/http' { interface HttpContext { auth: Auth } }`).
211
+ */
212
+ export interface HttpContext {
213
+ readonly request: HttpRequest
214
+ /** Route parameters (path and domain), URL-decoded strings. */
215
+ readonly params: Record<string, string>
216
+ readonly response: ResponseBuilder
217
+ readonly app: Application
218
+ readonly scope: Container
219
+ readonly requestId: string
220
+ /** Aborted when the client disconnects or a `timeout()` middleware fires. */
221
+ readonly signal: AbortSignal
222
+ /** Logger bound to this request. */
223
+ readonly log: Logger
224
+ /** The current locale (set by the locale middleware; the default locale otherwise). */
225
+ locale: string
226
+ /** The session (needs the `session()` middleware, which routes/web.ts has). */
227
+ session: Session
228
+ /** Name of the matched route. */
229
+ readonly routeName?: string
230
+ /** Resolve from the request scope. */
231
+ resolve<K extends Token>(token: K): Resolved<K>
232
+ }