feat(http)!: cookie decorators, setCookie, and string | string[] response headers (CARD-14, #113)
Reading a cookie meant parsing the Cookie header by hand, and a response
could not carry more than one Set-Cookie: response header values were
Record<string, string>, and the fetch adapters would have stringified an
array into one broken "a,b" cookie anyway.
- @cookie('name') / @cookies() sit next to @header/@headers as a new
'cookies' arg source. The header is parsed on first use per request and
cached on the context, so a route without a cookie argument never parses
it. RFC 6265: first value wins, %-sequences decoded, malformed pairs
skipped (never a 400), undecodable values kept raw. Several cookie lines
are joined with "; ". The map has no prototype. @needs('cookies') reads
the same map, and 'cookies' joins the seed-key allow-list.
- setCookie(name, value, options) serialises one Set-Cookie value with
HttpOnly, SameSite=Lax, Path=/ and Secure by default (D10), and throws,
naming the field, on anything that could inject a header or that browsers
reject (sameSite none / partitioned without secure).
- Response header values widen to string | string[] (D11) across
TransformerFn, ErrorResponse, HttpError(Like).headers, ResponseShape and
the neutral outcome. Node writes a set-cookie array as one line per
element and joins every other array with ", " before writeHead; the
fetch adapters build a Headers and append each set-cookie element.
mergeInjectedHeaders keeps arrays by reference and joins a vary array
before merging it.
- OpenAPI maps a cookie argument to an in: cookie parameter.
BREAKING CHANGE: code that reads a header value from TransformerFn,
ErrorResponse, HttpError or ResponseShape as a string must handle string[].
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
24 files changed
+781
-34
No files matched your search
+11
-1
@@ -883,7 +883,17 @@ function assertNeedsSatisfiable(
|
||||
...providerNodes.flatMap((node) => node.provides),
|
||||
...stepNodes.flatMap((node) => node.provides),
|
||||
]);
|
||||
const allowed = new Set<string>([...producedKeys, 'req', 'params', 'query', 'body', 'headers', 'inbound', 'abort']);
|
||||
const allowed = new Set<string>([
|
||||
...producedKeys,
|
||||
'req',
|
||||
'params',
|
||||
'query',
|
||||
'body',
|
||||
'headers',
|
||||
'cookies',
|
||||
'inbound',
|
||||
'abort',
|
||||
]);
|
||||
|
||||
for (const plan of routePlans) {
|
||||
for (const need of plan.needs) {
|
||||
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
// src/cookies.ts — request cookie parsing and `Set-Cookie` serialisation (RFC 6265), dependency-free.
|
||||
|
||||
/**
|
||||
* Options for {@link setCookie}. Every attribute is optional; the defaults are the safe ones
|
||||
* (`httpOnly: true`, `sameSite: 'lax'`, `path: '/'`, `secure: true`).
|
||||
*/
|
||||
export interface CookieOptions {
|
||||
/** `Max-Age` in seconds. An integer; `0` or a negative value tells the browser to drop the cookie. */
|
||||
maxAge?: number;
|
||||
/** `Expires`, written as an HTTP date. `maxAge` wins in browsers when both are set. */
|
||||
expires?: Date;
|
||||
/** `Path`. Default `'/'`. */
|
||||
path?: string;
|
||||
/** `Domain`. Omitted by default, which scopes the cookie to the exact host that set it. */
|
||||
domain?: string;
|
||||
/**
|
||||
* `Secure`. Default `true`: Chrome, Edge and Firefox accept a `Secure` cookie on
|
||||
* `http://localhost`. Safari, a LAN IP or a plain-HTTP dev hostname do not — pass `false` there
|
||||
* (for example `secure: !isDev`).
|
||||
*/
|
||||
secure?: boolean;
|
||||
/** `HttpOnly`. Default `true`, so page scripts cannot read the cookie. */
|
||||
httpOnly?: boolean;
|
||||
/** `SameSite`. Default `'lax'`. `'none'` requires `secure`. */
|
||||
sameSite?: 'strict' | 'lax' | 'none';
|
||||
/** `Partitioned` (CHIPS). Requires `secure`. */
|
||||
partitioned?: boolean;
|
||||
}
|
||||
|
||||
/** RFC 6265 §4.1.1 cookie-name: an RFC 7230 token. */
|
||||
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
||||
/** What a cookie value may not contain: CR, LF, `;`, `,`, whitespace and every control character. */
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const BAD_VALUE = /[\u0000- ;,\u007f]/;
|
||||
/**
|
||||
* What an attribute value may not contain. CR/LF is the header-injection case the card names; `;`
|
||||
* and the other control characters are refused too, because a `;` inside `Path` would start a new
|
||||
* attribute and change what the cookie means without breaking the header.
|
||||
*/
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const BAD_ATTRIBUTE = /[\u0000-\u001f;\u007f]/;
|
||||
|
||||
const SAME_SITE = { strict: 'Strict', lax: 'Lax', none: 'None' } as const;
|
||||
|
||||
/**
|
||||
* Serialises one `Set-Cookie` header value.
|
||||
*
|
||||
* Throws, naming the field, rather than producing a header that would split or reshape the
|
||||
* response: a name outside the RFC 6265 token set, a value carrying CR, LF, `;`, `,`, whitespace or a
|
||||
* control character, an attribute carrying CR/LF, `;` or a control character, a non-integer
|
||||
* `maxAge`, an invalid `expires`, and `sameSite: 'none'` or `partitioned` without `secure`.
|
||||
*
|
||||
* The value is written as given. Encode it yourself (`encodeURIComponent`) if it can hold any of the
|
||||
* refused characters; the cookie decorators decode `%`-sequences on the way back in.
|
||||
*
|
||||
* Several cookies on one response go in an array: `headers: { 'set-cookie': [a, b] }`, and each
|
||||
* element is sent as its own `Set-Cookie` line on every adapter.
|
||||
*
|
||||
* @example
|
||||
* setCookie('session', id, { maxAge: 3600 })
|
||||
* // 'session=<id>; Max-Age=3600; Path=/; Secure; HttpOnly; SameSite=Lax'
|
||||
*/
|
||||
export function setCookie(name: string, value: string, options: CookieOptions = {}): string {
|
||||
if (typeof name !== 'string' || !TOKEN.test(name))
|
||||
throw new TypeError(`setCookie: name ${JSON.stringify(name)} is not a valid cookie name (RFC 6265 token)`);
|
||||
|
||||
if (typeof value !== 'string' || BAD_VALUE.test(value))
|
||||
throw new TypeError(
|
||||
`setCookie: value for '${name}' contains a character a cookie value cannot carry (CR, LF, ';', ',', whitespace or a control character)`,
|
||||
);
|
||||
|
||||
const secure = options.secure ?? true;
|
||||
const sameSite = options.sameSite ?? 'lax';
|
||||
const parts = [`${name}=${value}`];
|
||||
|
||||
if (options.maxAge !== undefined) {
|
||||
if (!Number.isInteger(options.maxAge)) throw new TypeError(`setCookie: maxAge for '${name}' must be an integer`);
|
||||
parts.push(`Max-Age=${options.maxAge}`);
|
||||
}
|
||||
|
||||
if (options.expires !== undefined) {
|
||||
if (!(options.expires instanceof Date) || Number.isNaN(options.expires.getTime()))
|
||||
throw new TypeError(`setCookie: expires for '${name}' must be a valid Date`);
|
||||
parts.push(`Expires=${options.expires.toUTCString()}`);
|
||||
}
|
||||
|
||||
if (options.domain !== undefined) parts.push(`Domain=${attribute(name, 'domain', options.domain)}`);
|
||||
parts.push(`Path=${attribute(name, 'path', options.path ?? '/')}`);
|
||||
if (secure) parts.push('Secure');
|
||||
if (options.httpOnly ?? true) parts.push('HttpOnly');
|
||||
|
||||
if (!Object.prototype.hasOwnProperty.call(SAME_SITE, sameSite))
|
||||
throw new TypeError(`setCookie: sameSite for '${name}' must be 'strict', 'lax' or 'none'`);
|
||||
|
||||
if (sameSite === 'none' && !secure)
|
||||
throw new TypeError(`setCookie: sameSite 'none' for '${name}' requires secure (browsers reject it otherwise)`);
|
||||
parts.push(`SameSite=${SAME_SITE[sameSite]}`);
|
||||
|
||||
if (options.partitioned) {
|
||||
if (!secure) throw new TypeError(`setCookie: partitioned for '${name}' requires secure`);
|
||||
parts.push('Partitioned');
|
||||
}
|
||||
|
||||
return parts.join('; ');
|
||||
}
|
||||
|
||||
function attribute(name: string, field: string, value: string): string {
|
||||
if (typeof value !== 'string' || value === '' || BAD_ATTRIBUTE.test(value))
|
||||
throw new TypeError(
|
||||
`setCookie: ${field} for '${name}' must be a non-empty string without CR, LF, ';' or control characters`,
|
||||
);
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a request `Cookie` header into a name → value map (RFC 6265 §5.2 / §4.2).
|
||||
*
|
||||
* - The first value wins for a repeated name — the browser sends the most specific cookie first.
|
||||
* - `%`-sequences are decoded; a value that fails to decode is kept raw rather than rejected.
|
||||
* - A malformed pair (no `=`, or an empty name) is skipped. A broken cookie never becomes a 400:
|
||||
* the header is client state the server did not choose and the request may not even need it.
|
||||
* - Several `cookie` lines (HTTP/2, some proxies) arrive as an array and are joined with `; `.
|
||||
*
|
||||
* The map has no prototype, so a cookie named `__proto__` or `constructor` is just a key.
|
||||
*/
|
||||
export function parseCookies(header: string | string[] | undefined): Record<string, string> {
|
||||
const out: Record<string, string> = Object.create(null);
|
||||
if (header === undefined) return out;
|
||||
const raw = Array.isArray(header) ? header.join('; ') : header;
|
||||
|
||||
for (const pair of raw.split(';')) {
|
||||
const eq = pair.indexOf('=');
|
||||
if (eq === -1) continue;
|
||||
const key = pair.slice(0, eq).trim();
|
||||
if (key === '' || key in out) continue;
|
||||
out[key] = decode(pair.slice(eq + 1).trim());
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
function decode(value: string): string {
|
||||
if (!value.includes('%')) return value;
|
||||
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -8,7 +8,7 @@ import type { MatchedRoute, HttpOptions } from './types';
|
||||
|
||||
/** A ready-to-send error response produced while acquiring the request body. */
|
||||
export interface BodyFailure {
|
||||
fail: { status: number; headers: Record<string, string>; body: string };
|
||||
fail: { status: number; headers: Record<string, string | string[]>; body: string };
|
||||
}
|
||||
|
||||
/** A value, or a promise of one. Readers that have nothing to await return the value directly. */
|
||||
|
||||
+3
-3
@@ -85,10 +85,10 @@ export function correlateRequest(headers: Record<string, string | string[] | und
|
||||
|
||||
/** The neutral shape of a response: a fully buffered body, or a stream to pipe frame-by-frame. */
|
||||
export type NeutralOutcome =
|
||||
| { kind: 'buffered'; status: number; headers: Record<string, string>; body: string | Buffer }
|
||||
| { kind: 'buffered'; status: number; headers: Record<string, string | string[]>; body: string | Buffer }
|
||||
| {
|
||||
kind: 'stream';
|
||||
headers: Record<string, string>;
|
||||
headers: Record<string, string | string[]>;
|
||||
stream: AsyncIterable<unknown>;
|
||||
encoder: StreamEncoder;
|
||||
/** The matched route's pattern, for naming the stream lifecycle events. */
|
||||
@@ -126,7 +126,7 @@ function errorOutcome(
|
||||
req: NeutralRequest,
|
||||
injected: Record<string, string>,
|
||||
opts: HttpOptions | undefined,
|
||||
headers: Record<string, string> = {},
|
||||
headers: Record<string, string | string[]> = {},
|
||||
): HandleResult {
|
||||
const rendered = renderError(error, req, opts?.onError, opts?.logger);
|
||||
return {
|
||||
|
||||
+46
-1
@@ -19,7 +19,10 @@ export function mergeInjectedHeaders(
|
||||
const lowerKey = key.toLowerCase();
|
||||
|
||||
if (lowerKey === 'vary') {
|
||||
handlerVary = handlerHeaders[key];
|
||||
// A header value may be an array (D11). `mergeVary` splits on commas, so joining first keeps
|
||||
// every token a handler listed instead of stringifying the array by accident.
|
||||
const value = handlerHeaders[key];
|
||||
handlerVary = Array.isArray(value) ? value.join(', ') : value;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -40,3 +43,45 @@ export function mergeInjectedHeaders(
|
||||
else if (handlerVary !== undefined) merged['vary'] = handlerVary;
|
||||
return merged;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares merged headers for Node's `writeHead`, which writes one header line per array element
|
||||
* for *any* header. That is right for `set-cookie`, the one header whose values cannot be
|
||||
* comma-joined (an `Expires` date carries a comma), and wrong for every other: RFC 9110 §5.3 makes a
|
||||
* list header's repeated lines equivalent to one comma-joined line, and joining keeps all four
|
||||
* adapters sending the same bytes. So every other array is joined with `, ` here, before
|
||||
* `writeHead`. Returns the input untouched when it holds no array, which is nearly every response.
|
||||
*/
|
||||
export function joinListHeaders<T extends Record<string, unknown>>(headers: T): T {
|
||||
let out: Record<string, unknown> | undefined;
|
||||
|
||||
for (const key of Object.keys(headers)) {
|
||||
const value = headers[key];
|
||||
if (!Array.isArray(value) || key.toLowerCase() === 'set-cookie') continue;
|
||||
out ??= { ...headers };
|
||||
out[key] = value.join(', ');
|
||||
}
|
||||
|
||||
return (out as T | undefined) ?? headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a web `Headers` from merged headers. A plain record cannot be handed to `new Response`:
|
||||
* the Fetch spec stringifies an array value to `a,b`, which for `set-cookie` is one broken cookie.
|
||||
* `set-cookie` elements are appended one by one, so each reaches the client as its own line;
|
||||
* every other array is joined with `, `, exactly as {@link joinListHeaders} does for Node.
|
||||
*/
|
||||
export function toWebHeaders(headers: Record<string, unknown>): Headers {
|
||||
const out = new Headers();
|
||||
|
||||
for (const key of Object.keys(headers)) {
|
||||
const value = headers[key];
|
||||
if (value === undefined) continue;
|
||||
|
||||
if (!Array.isArray(value)) out.set(key, String(value));
|
||||
else if (key.toLowerCase() === 'set-cookie') for (const cookie of value) out.append(key, String(cookie));
|
||||
else out.set(key, value.join(', '));
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
+2
-2
@@ -6,7 +6,7 @@ import type { Bus } from '../bus';
|
||||
import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
|
||||
import { pipeStream } from './stream';
|
||||
import { attachWs } from './ws';
|
||||
import { mergeInjectedHeaders } from './headers';
|
||||
import { mergeInjectedHeaders, joinListHeaders } from './headers';
|
||||
import {
|
||||
handle,
|
||||
correlateRequest,
|
||||
@@ -286,7 +286,7 @@ function patchResponseHeaders(res: http.ServerResponse, injected: Record<string,
|
||||
|
||||
(res as any).writeHead = (status: number, arg2?: any, arg3?: any) => {
|
||||
const handlerHeaders = (typeof arg2 === 'string' ? arg3 : arg2) as Record<string, any> | undefined;
|
||||
const merged = mergeInjectedHeaders(handlerHeaders, injected);
|
||||
const merged = joinListHeaders(mergeInjectedHeaders(handlerHeaders, injected));
|
||||
return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged);
|
||||
};
|
||||
}
|
||||
+11
-9
@@ -10,7 +10,7 @@ import {
|
||||
type HandleResult,
|
||||
type Preflight,
|
||||
} from './core';
|
||||
import { mergeInjectedHeaders } from './headers';
|
||||
import { mergeInjectedHeaders, toWebHeaders } from './headers';
|
||||
import { peerOf, trustedProxyClient } from './peer';
|
||||
import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body';
|
||||
import { HttpError } from '../signals';
|
||||
@@ -204,7 +204,7 @@ export function toBodyInit(body: string | Buffer): ResponseBody {
|
||||
|
||||
/** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */
|
||||
function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correlation = {}): Response {
|
||||
const headers = mergeInjectedHeaders(result.outcome.headers, result.injected) as Record<string, string>;
|
||||
const headers = toWebHeaders(mergeInjectedHeaders(result.outcome.headers, result.injected));
|
||||
|
||||
if (result.outcome.kind === 'stream') {
|
||||
const body = asReadableStream(
|
||||
@@ -274,12 +274,14 @@ export function buildFetch(routes: RouteTable, opts: HttpOptions | undefined) {
|
||||
|
||||
return new Response(JSON.stringify({ error: 'Service Unavailable' }), {
|
||||
status: 503,
|
||||
headers: mergeInjectedHeaders(
|
||||
{
|
||||
'content-type': 'application/json',
|
||||
'retry-after': '1',
|
||||
},
|
||||
injected,
|
||||
headers: toWebHeaders(
|
||||
mergeInjectedHeaders(
|
||||
{
|
||||
'content-type': 'application/json',
|
||||
'retry-after': '1',
|
||||
},
|
||||
injected,
|
||||
),
|
||||
),
|
||||
});
|
||||
}
|
||||
@@ -323,7 +325,7 @@ export function buildFetch(routes: RouteTable, opts: HttpOptions | undefined) {
|
||||
if ('preflight' in result) {
|
||||
return new Response(null, {
|
||||
status: 204,
|
||||
headers: mergeInjectedHeaders(result.preflight, injected),
|
||||
headers: toWebHeaders(mergeInjectedHeaders(result.preflight, injected)),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+5
-1
@@ -78,9 +78,13 @@ export { flow, Flow } from './flow';
|
||||
export type { StepFn, CompiledFlow } from './flow';
|
||||
|
||||
// Parameter decorators
|
||||
export { needs, ctx, param, query, body, headers, header, inbound, abort } from './params';
|
||||
export { needs, ctx, param, query, body, headers, header, cookies, cookie, inbound, abort } from './params';
|
||||
export type { Query, Headers, Context, ArgSpec, ArgDecorator } from './params';
|
||||
|
||||
// Cookies
|
||||
export { setCookie, parseCookies } from './cookies';
|
||||
export type { CookieOptions } from './cookies';
|
||||
|
||||
// Observability
|
||||
export { createDefaultLogger, logRequests, withConsoleFallback } from './logger';
|
||||
export type { Logger, LogLevel, LogFields } from './logger';
|
||||
|
||||
+5
-1
@@ -3,7 +3,11 @@ import 'reflect-metadata';
|
||||
/** Any class constructor. Kept `any` because decorators must accept every target shape. */
|
||||
export type Ctor = new (...args: any[]) => any;
|
||||
/** Serializes a handler's return value into an HTTP response envelope. */
|
||||
export type TransformerFn = (value: unknown) => { status?: number; headers?: Record<string, string>; body: string };
|
||||
export type TransformerFn = (value: unknown) => {
|
||||
status?: number;
|
||||
headers?: Record<string, string | string[]>;
|
||||
body: string;
|
||||
};
|
||||
|
||||
/** Metadata attached by `@Html`: optional file path and whether it is a template. */
|
||||
export interface HtmlMeta {
|
||||
|
||||
+11
-4
@@ -26,7 +26,7 @@ export interface OpenApiDoc {
|
||||
|
||||
type Parameter = {
|
||||
name: string;
|
||||
in: 'path' | 'query' | 'header';
|
||||
in: 'path' | 'query' | 'header' | 'cookie';
|
||||
required: boolean;
|
||||
schema: { type: 'string'; pattern?: string };
|
||||
};
|
||||
@@ -57,13 +57,20 @@ function pathParams(pattern: string): Parameter[] {
|
||||
});
|
||||
}
|
||||
|
||||
/** Query and header parameters declared by the handler's `@query` / `@headers` / `@header` argument decorators. */
|
||||
/** Where each argument source sits in an OpenAPI parameter list; sources absent here are not parameters. */
|
||||
const ARG_LOCATION: Partial<Record<ArgSpec['source'], Parameter['in']>> = {
|
||||
query: 'query',
|
||||
headers: 'header',
|
||||
cookies: 'cookie',
|
||||
};
|
||||
|
||||
/** Query, header and cookie parameters declared by `@query` / `@headers` / `@header` / `@cookies` / `@cookie`. */
|
||||
function argParams(args: ArgSpec[]): Parameter[] {
|
||||
const params: Parameter[] = [];
|
||||
|
||||
for (const arg of args) {
|
||||
if (arg.source !== 'query' && arg.source !== 'headers') continue;
|
||||
const location = arg.source === 'query' ? 'query' : 'header';
|
||||
const location = ARG_LOCATION[arg.source];
|
||||
if (!location) continue;
|
||||
const names = arg.keys ?? (arg.key ? [arg.key] : []);
|
||||
for (const name of names) params.push({ name, in: location, required: false, schema: { type: 'string' } });
|
||||
}
|
||||
|
||||
+27
-3
@@ -2,6 +2,7 @@ import 'reflect-metadata';
|
||||
import type { Ctor } from './metadata';
|
||||
import { isStandardSchema, type StandardSchemaV1 } from './standard-schema';
|
||||
import { ValidationError } from './signals';
|
||||
import { parseCookies } from './cookies';
|
||||
|
||||
/** Parsed URL query string as flat key/value pairs. */
|
||||
export type Query = Record<string, string>;
|
||||
@@ -10,7 +11,7 @@ export type Headers = Record<string, string | string[] | undefined>;
|
||||
/** Per-request bag that accumulates values produced by steps and providers. */
|
||||
export type Context = Record<string, unknown>;
|
||||
|
||||
type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'inbound' | 'abort';
|
||||
type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'cookies' | 'inbound' | 'abort';
|
||||
/** Describes how a single handler parameter is sourced and (optionally) validated. */
|
||||
export interface ArgSpec {
|
||||
index: number;
|
||||
@@ -71,6 +72,14 @@ export const body: ArgDecorator = envelope('body');
|
||||
export const headers: ArgDecorator = envelope('headers');
|
||||
/** Inject a single request header by name (singular alias of {@link headers}); accepts a schema to validate it. */
|
||||
export const header: ArgDecorator = envelope('headers');
|
||||
/**
|
||||
* Inject request cookies, parsed from the `Cookie` header: no arg for the whole map (`{}` when the
|
||||
* request has none), a key to pick one, an array to pick several. Accepts a schema to validate.
|
||||
* First value wins for a repeated name, `%`-sequences are decoded, malformed pairs are skipped.
|
||||
*/
|
||||
export const cookies: ArgDecorator = envelope('cookies');
|
||||
/** Inject a single request cookie by name (singular alias of {@link cookies}); `undefined` when absent. */
|
||||
export const cookie: ArgDecorator = envelope('cookies');
|
||||
|
||||
/** Inject a value produced upstream by a step or provider, addressed by key. */
|
||||
export function needs(key: string): ParameterDecorator {
|
||||
@@ -126,10 +135,11 @@ export async function resolveArgs(specs: ArgSpec[], context: Context): Promise<u
|
||||
|
||||
function resolveOne(spec: ArgSpec, context: Context): unknown {
|
||||
if (spec.source === 'ctx') return context;
|
||||
if (spec.source === 'needs') return context[spec.key as string];
|
||||
// `cookies` is a seed token like `headers`, but parsed on demand rather than seeded on every request.
|
||||
if (spec.source === 'needs') return spec.key === 'cookies' ? cookiesOf(context) : context[spec.key as string];
|
||||
if (spec.source === 'inbound') return context.inbound;
|
||||
if (spec.source === 'abort') return context.abort;
|
||||
const bag = context[spec.source];
|
||||
const bag = spec.source === 'cookies' ? cookiesOf(context) : context[spec.source];
|
||||
if (typeof bag !== 'object' || bag === null) return bag; // can't pick from a non-object; return as-is
|
||||
const values = bag as Record<string, unknown>;
|
||||
|
||||
@@ -142,3 +152,17 @@ function resolveOne(spec: ArgSpec, context: Context): unknown {
|
||||
if (spec.key !== undefined) return values[spec.key];
|
||||
return values;
|
||||
}
|
||||
|
||||
/**
|
||||
* The request's cookie map, parsed on first use and cached on the context, so a route that never
|
||||
* declares a cookie argument never parses the header and one that declares several parses it once.
|
||||
* Serves `@cookie`, `@cookies` and `@needs('cookies')` alike.
|
||||
*/
|
||||
function cookiesOf(context: Context): unknown {
|
||||
if (context.cookies === undefined) {
|
||||
const headers = context.headers as Headers | undefined;
|
||||
context.cookies = parseCookies(headers?.cookie);
|
||||
}
|
||||
|
||||
return context.cookies;
|
||||
}
|
||||
+2
-1
@@ -14,7 +14,8 @@ export interface PipelineStep {
|
||||
/** A fully materialized HTTP response produced by a transformer. */
|
||||
export interface ResponseShape {
|
||||
status: number;
|
||||
headers: Record<string, string>;
|
||||
/** A value may be an array: `set-cookie` arrays are sent one line per element, others joined with `, `. */
|
||||
headers: Record<string, string | string[]>;
|
||||
body: string;
|
||||
}
|
||||
/** A streaming response; the async iterable is written to the socket and bypasses the transformer. */
|
||||
|
||||
+2
-2
@@ -20,7 +20,7 @@ export interface HttpErrorLike {
|
||||
status: number;
|
||||
message: string;
|
||||
body?: unknown;
|
||||
headers?: Record<string, string>;
|
||||
headers?: Record<string, string | string[]>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -35,7 +35,7 @@ export class HttpError extends Error {
|
||||
readonly status: number,
|
||||
message?: string,
|
||||
readonly body?: unknown,
|
||||
readonly headers?: Record<string, string>,
|
||||
readonly headers?: Record<string, string | string[]>,
|
||||
) {
|
||||
super(message ?? `HTTP ${status}`);
|
||||
this.name = new.target.name;
|
||||
|
||||
+2
-1
@@ -6,7 +6,8 @@ import type { Logger } from './logger';
|
||||
/** A ready-to-send HTTP response. */
|
||||
export interface ErrorResponse {
|
||||
status: number;
|
||||
headers: Record<string, string>;
|
||||
/** A value may be an array: `set-cookie` arrays are sent one line per element, others joined with `, `. */
|
||||
headers: Record<string, string | string[]>;
|
||||
body: string;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user