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>
237 lines
9.1 KiB
TypeScript
237 lines
9.1 KiB
TypeScript
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 | string[]>;
|
|
body: string;
|
|
};
|
|
|
|
/** Metadata attached by `@Html`: optional file path and whether it is a template. */
|
|
export interface HtmlMeta {
|
|
path?: string;
|
|
template?: boolean;
|
|
}
|
|
/** Metadata attached by `@Provider`: what it provides, what it needs, and its visibility. */
|
|
export interface ProviderMeta {
|
|
provides: string;
|
|
needs: string[];
|
|
optional: boolean;
|
|
/**
|
|
* Always refused. `@Provider`'s options no longer declare `export`, so TypeScript rejects it at
|
|
* the decorator and this can only be true for a JavaScript caller. It is still recorded so that
|
|
* caller reaches `collectProviders`' boot error, which names the provider and the replacement,
|
|
* rather than having the option silently ignored.
|
|
*/
|
|
export: boolean;
|
|
}
|
|
/** Metadata attached by `@Step`: what it provides, what it needs, and its visibility. */
|
|
export interface StepMeta {
|
|
provides: string;
|
|
needs: string[];
|
|
optional: boolean;
|
|
export: boolean;
|
|
}
|
|
/** HTTP verbs supported by the route decorators. */
|
|
export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
|
|
/** Wire transport a route responds with. */
|
|
export type Transport = 'buffer' | 'sse' | 'ndjson' | 'negotiate' | 'ws';
|
|
/** Metadata attached by a route decorator to a single handler method. */
|
|
export interface RouteMeta {
|
|
method: HttpMethod;
|
|
path: string;
|
|
handlerName: string;
|
|
transport: Transport;
|
|
export: boolean;
|
|
duplicates?: 'array' | 'last';
|
|
maxBodyBytes?: number;
|
|
maxParts?: number;
|
|
}
|
|
/** Options accepted by the `@Module` decorator. */
|
|
export interface ModuleOptions {
|
|
mountpoint: string;
|
|
providers?: Ctor[];
|
|
steps?: Ctor[];
|
|
controllers?: Ctor[];
|
|
}
|
|
|
|
const K = {
|
|
provider: Symbol('gt:provider'),
|
|
step: Symbol('gt:step'),
|
|
routePrefix: Symbol('gt:routePrefix'),
|
|
routes: Symbol('gt:routes'),
|
|
module: Symbol('gt:module'),
|
|
transformer: Symbol('gt:transformer'),
|
|
html: Symbol('gt:html'),
|
|
};
|
|
|
|
/** Marks a class as a provider: a lazily-built dependency addressable by its `provides` key. */
|
|
export function Provider(opts: { provides: string; needs?: string[]; optional?: boolean }): ClassDecorator {
|
|
return (target) => {
|
|
const meta: ProviderMeta = {
|
|
provides: opts.provides,
|
|
needs: opts.needs ?? [],
|
|
optional: opts.optional ?? false,
|
|
// Read through a cast because the options type deliberately does not offer `export`: only a
|
|
// `@Step` or a route is exportable, and the option's only behaviour was to throw at boot.
|
|
// A JavaScript caller can still pass it, and recording it is what routes them to that error.
|
|
export: (opts as { export?: boolean }).export ?? false,
|
|
};
|
|
Reflect.defineMetadata(K.provider, meta, target);
|
|
};
|
|
}
|
|
|
|
/** Marks a class as a step: a per-request unit that runs in dependency order and contributes to the context. */
|
|
export function Step(opts: {
|
|
provides: string;
|
|
needs?: string[];
|
|
optional?: boolean;
|
|
export?: boolean;
|
|
}): ClassDecorator {
|
|
return (target) => {
|
|
const meta: StepMeta = {
|
|
provides: opts.provides,
|
|
needs: opts.needs ?? [],
|
|
optional: opts.optional ?? false,
|
|
export: opts.export ?? false,
|
|
};
|
|
Reflect.defineMetadata(K.step, meta, target);
|
|
};
|
|
}
|
|
|
|
/** Sets the shared path prefix for every route declared on the decorated controller. */
|
|
export function Route(prefix: string): ClassDecorator {
|
|
return (target) => {
|
|
Reflect.defineMetadata(K.routePrefix, prefix, target);
|
|
};
|
|
}
|
|
|
|
/**
|
|
* The shape every route decorator shares: a path, optional per-route overrides, and the
|
|
* `MethodDecorator` that records them against the controller.
|
|
*
|
|
* Named rather than inferred because JSR rejects an inferred type on a public symbol — an inferred
|
|
* one forces every consumer's type checker to re-derive it from the implementation instead of
|
|
* reading it from the declaration. It also gives callers a name for the shape.
|
|
*/
|
|
export type RouteDecorator = (
|
|
path: string,
|
|
opts?: { export?: boolean; duplicates?: 'array' | 'last'; maxBodyBytes?: number; maxParts?: number },
|
|
) => MethodDecorator;
|
|
|
|
function routeDecorator(method: HttpMethod, transport: Transport): RouteDecorator {
|
|
return (path, opts) => (target, propertyKey) => {
|
|
const ctor = target.constructor;
|
|
const routes = (Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? [];
|
|
routes.push({
|
|
method,
|
|
path,
|
|
handlerName: String(propertyKey),
|
|
transport,
|
|
export: opts?.export ?? false,
|
|
duplicates: opts?.duplicates,
|
|
maxBodyBytes: opts?.maxBodyBytes,
|
|
maxParts: opts?.maxParts,
|
|
});
|
|
Reflect.defineMetadata(K.routes, routes, ctor);
|
|
};
|
|
}
|
|
|
|
/** Declares a buffered `GET` route. */
|
|
export const Get: RouteDecorator = routeDecorator('GET', 'buffer');
|
|
/** Declares a buffered `HEAD` route. */
|
|
export const Head: RouteDecorator = routeDecorator('HEAD', 'buffer');
|
|
/** Declares a buffered `POST` route. */
|
|
export const Post: RouteDecorator = routeDecorator('POST', 'buffer');
|
|
/** Declares a buffered `PUT` route. */
|
|
export const Put: RouteDecorator = routeDecorator('PUT', 'buffer');
|
|
/** Declares a buffered `PATCH` route. */
|
|
export const Patch: RouteDecorator = routeDecorator('PATCH', 'buffer');
|
|
/** Declares a buffered `DELETE` route. */
|
|
export const Delete: RouteDecorator = routeDecorator('DELETE', 'buffer');
|
|
/** Declares a buffered `OPTIONS` route. */
|
|
export const Options: RouteDecorator = routeDecorator('OPTIONS', 'buffer');
|
|
/** Declares a `GET` route streamed as Server-Sent Events. */
|
|
export const Sse: RouteDecorator = routeDecorator('GET', 'sse');
|
|
/** Declares a `GET` route whose transport is content-negotiated at request time. */
|
|
export const Stream: RouteDecorator = routeDecorator('GET', 'negotiate');
|
|
/** Declares a `GET` route upgraded to a WebSocket. */
|
|
export const Ws: RouteDecorator = routeDecorator('GET', 'ws');
|
|
|
|
/** Attaches a response transformer to a handler method. */
|
|
export function Transformer(fn: TransformerFn): MethodDecorator {
|
|
return (target, propertyKey) => {
|
|
Reflect.defineMetadata(K.transformer, fn, target.constructor, String(propertyKey));
|
|
};
|
|
}
|
|
|
|
/** Marks a class as a module and records its providers, steps, controllers, and mountpoint. */
|
|
export function Module(opts: ModuleOptions): ClassDecorator {
|
|
return (target) => {
|
|
Reflect.defineMetadata(K.module, opts, target);
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Marks a buffered GET/POST handler as serving HTML. Bare `@Html` sends the handler's string return as
|
|
* `text/html`. `@Html('file.html')` serves that file (return ignored). `@Html('file.html', { template: true })`
|
|
* renders the file with the handler's returned data. Placement is validated at boot (buffered GET/POST only).
|
|
*/
|
|
export function Html(path: string, opts?: { template?: boolean }): MethodDecorator;
|
|
export function Html(target: object, propertyKey: string | symbol): void;
|
|
|
|
export function Html(a: unknown, b?: unknown): MethodDecorator | void {
|
|
if (typeof a !== 'string') {
|
|
// Bare usage: TS calls (prototype, propertyKey, descriptor?).
|
|
Reflect.defineMetadata(K.html, {}, (a as { constructor: Ctor }).constructor, String(b));
|
|
return;
|
|
}
|
|
|
|
const path = a;
|
|
const opts = b as { template?: boolean } | undefined;
|
|
|
|
return (target, propertyKey) => {
|
|
const meta: HtmlMeta = { path, template: opts?.template };
|
|
Reflect.defineMetadata(K.html, meta, (target as { constructor: Ctor }).constructor, String(propertyKey));
|
|
};
|
|
}
|
|
|
|
/** Reads the `@Html` metadata registered for a handler method, if any. */
|
|
export function getHtmlMeta(cls: Ctor, methodName: string): HtmlMeta | undefined {
|
|
return Reflect.getMetadata(K.html, cls, methodName);
|
|
}
|
|
|
|
/** Reads the `@Provider` metadata off a class, if any. */
|
|
export function getProviderMeta(cls: Ctor): ProviderMeta | undefined {
|
|
return Reflect.getMetadata(K.provider, cls);
|
|
}
|
|
|
|
/** Reads the `@Step` metadata off a class, if any. */
|
|
export function getStepMeta(cls: Ctor): StepMeta | undefined {
|
|
return Reflect.getMetadata(K.step, cls);
|
|
}
|
|
|
|
/** Reads the `@Module` metadata off a class, if any. */
|
|
export function getModuleMeta(cls: Ctor): ModuleOptions | undefined {
|
|
return Reflect.getMetadata(K.module, cls);
|
|
}
|
|
|
|
/** Reads the response transformer registered for a handler method, if any. */
|
|
export function getTransformer(cls: Ctor, methodName: string): TransformerFn | undefined {
|
|
return Reflect.getMetadata(K.transformer, cls, methodName);
|
|
}
|
|
|
|
/** Returns every route on a controller with its path resolved against the class prefix. */
|
|
export function getRoutes(cls: Ctor): RouteMeta[] {
|
|
const prefix: string = Reflect.getMetadata(K.routePrefix, cls) ?? '';
|
|
const routes: RouteMeta[] = Reflect.getMetadata(K.routes, cls) ?? [];
|
|
return routes.map((route) => ({ ...route, path: joinPath(prefix, route.path) }));
|
|
}
|
|
|
|
/** Joins two path segments with exactly one slash, collapsing any duplicates. */
|
|
export function joinPath(base: string, segment: string): string {
|
|
return `${base.replace(/\/$/, '')}/${segment.replace(/^\//, '')}`.replace(/\/+/g, '/');
|
|
}
|