UNPKG

@moostjs/event-http

Version:
471 lines (462 loc) 17.6 kB
import * as moost from 'moost'; import { TInterceptorPriority, TOvertakeFn, TInterceptorDef, TClassConstructor, TMoostAdapter, Moost, TConsoleBase, TMoostAdapterOptions } from 'moost'; import * as _wooksjs_event_http from '@wooksjs/event-http'; import { TCookieAttributes as TCookieAttributes$1, TCookieAttributesInput, WooksHttp, TWooksHttpOptions } from '@wooksjs/event-http'; export { HttpError, TCacheControl, TCookieAttributesInput, TSetCookieData, httpKind, useHttpContext } from '@wooksjs/event-http'; import { IncomingMessage, ServerResponse } from 'http'; import { ListenOptions } from 'net'; /** Bearer token transport configuration for auth guards. */ interface TAuthTransportBearer { format?: string; description?: string; } /** Basic auth transport configuration for auth guards. */ interface TAuthTransportBasic { description?: string; } /** API key transport configuration specifying location (header, query, or cookie). */ interface TAuthTransportApiKey { name: string; in: 'header' | 'query' | 'cookie'; description?: string; } /** Cookie-based auth transport configuration. */ interface TAuthTransportCookie { name: string; description?: string; } /** Declares which auth credential transports a guard accepts. */ interface TAuthTransportDeclaration { bearer?: TAuthTransportBearer; basic?: TAuthTransportBasic; apiKey?: TAuthTransportApiKey; cookie?: TAuthTransportCookie; } /** Type-narrowed credential values extracted from declared transports. */ type TAuthTransportValues<T extends TAuthTransportDeclaration> = { [K in keyof T & keyof TAuthTransportDeclaration]: K extends 'basic' ? { username: string; password: string; } : string; }; /** Extracts auth credentials from the current request based on transport declarations. Throws 401 if none found. */ declare function extractTransports<T extends TAuthTransportDeclaration>(declaration: T): TAuthTransportValues<T>; /** Auth guard def returned by defineAuthGuard — carries transport declarations. */ interface TAuthGuardDef extends TInterceptorDef { __authTransports: TAuthTransportDeclaration; } /** Auth guard class extending AuthGuard — carries transport declarations as static property. */ type TAuthGuardClass = TClassConstructor<AuthGuard> & { transports: TAuthTransportDeclaration; priority: TInterceptorPriority; }; /** Accepted handler for Authenticate — either a functional or class-based auth guard. */ type TAuthGuardHandler = TAuthGuardDef | TAuthGuardClass; /** * Creates a functional auth guard interceptor. * Extracts credentials from declared transports and passes them to the handler. * Return a value from the handler to short-circuit with that response. */ declare function defineAuthGuard<T extends TAuthTransportDeclaration>(transports: T, handler: (transports: TAuthTransportValues<T>) => unknown | Promise<unknown>): TAuthGuardDef; /** * Abstract base class for class-based auth guards. * Extend this class, set `static transports`, and implement `handle()`. */ declare abstract class AuthGuard<T extends TAuthTransportDeclaration = TAuthTransportDeclaration> { static transports: TAuthTransportDeclaration; static priority: TInterceptorPriority; abstract handle(transports: TAuthTransportValues<T>): unknown | Promise<unknown>; __intercept(reply: TOvertakeFn): Promise<undefined> | undefined; } /** * Registers an auth guard as an interceptor and stores its transport * declarations in metadata for swagger auto-discovery. * * Accepts either a functional guard from `defineAuthGuard()` or a * class-based guard extending `AuthGuard`. */ declare function Authenticate(handler: TAuthGuardHandler): ClassDecorator & MethodDecorator; /** Base decorator for registering an HTTP route handler with an explicit method. */ declare function HttpMethod(method: '*' | 'GET' | 'PUT' | 'POST' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS' | 'UPGRADE', path?: string): MethodDecorator; /** Register a catch-all route handler matching any HTTP method. */ declare const All: (path?: string) => MethodDecorator; /** Register a GET route handler. */ declare const Get: (path?: string) => MethodDecorator; /** Register a POST route handler. */ declare const Post: (path?: string) => MethodDecorator; /** Register a PUT route handler. */ declare const Put: (path?: string) => MethodDecorator; /** Register a DELETE route handler. */ declare const Delete: (path?: string) => MethodDecorator; /** Register a PATCH route handler. */ declare const Patch: (path?: string) => MethodDecorator; /** * Register an UPGRADE route handler for WebSocket upgrade requests. * * Use together with `WooksWs` (injected via DI) to complete the handshake: * ```ts * @Upgrade('/ws') * handleUpgrade(ws: WooksWs) { * return ws.upgrade() * } * ``` */ declare const Upgrade: (path?: string) => MethodDecorator; /** * Ref to the Response Status * @decorator * @paramType TStatusRef */ declare const StatusRef: () => ParameterDecorator & PropertyDecorator; /** * Ref to the Response Header * @decorator * @param name - header name * @paramType THeaderRef */ declare const HeaderRef: (name: string) => ParameterDecorator & PropertyDecorator; /** * Ref to the Response Cookie * @decorator * @param name - cookie name * @paramType TCookieRef */ declare const CookieRef: (name: string) => ParameterDecorator & PropertyDecorator; /** * Ref to the Response Cookie Attributes * @decorator * @param name - cookie name * @paramType TCookieAttributes */ declare const CookieAttrsRef: (name: string) => ParameterDecorator & PropertyDecorator; /** * Parse Authorisation Header * @decorator * @param name - define what to take from the Auth header * @paramType string */ declare function Authorization(name: 'username' | 'password' | 'bearer' | 'raw' | 'type'): ParameterDecorator & PropertyDecorator; /** * Get Request Header Value * @decorator * @param name - header name * @paramType string */ declare function Header(name: string): ParameterDecorator & PropertyDecorator; /** * Get Request Cookie Value * @decorator * @param name - cookie name * @paramType string */ declare function Cookie(name: string): ParameterDecorator & PropertyDecorator; /** * Get Query Item value or the whole parsed Query as an object * @decorator * @param name - query item name (optional) * @paramType string | object */ declare function Query(name?: string): ParameterDecorator; /** * Get Requested URL * @decorator * @paramType string */ declare function Url(): ParameterDecorator & PropertyDecorator; /** * Get Requested HTTP Method * @decorator * @paramType string */ declare function Method(): ParameterDecorator & PropertyDecorator; /** * Get Raw Request Instance * @decorator * @paramType IncomingMessage */ declare function Req(): ParameterDecorator & PropertyDecorator; /** * Get Raw Response Instance * @decorator * @param opts (optional) { passthrough: boolean } * @paramType ServerResponse */ declare function Res(opts?: { passthrough: boolean; }): ParameterDecorator & PropertyDecorator; /** * Get Request Unique Identificator (UUID) * @decorator * @paramType string */ declare function ReqId(): ParameterDecorator & PropertyDecorator; /** * Get Request IP Address * @decorator * @paramType string */ declare function Ip(opts?: { trustProxy: boolean; }): ParameterDecorator & PropertyDecorator; /** * Get Request IP Address list * @decorator * @paramType string[] */ declare function IpList(): ParameterDecorator & PropertyDecorator; /** * Get Parsed Request Body * @decorator * @paramType object | string | unknown */ declare function Body(): MethodDecorator & ClassDecorator & ParameterDecorator & PropertyDecorator; /** * Get Raw Request Body Buffer * @decorator * @paramType Promise<Buffer> */ declare function RawBody(): ParameterDecorator & PropertyDecorator; /** Reactive ref for reading/writing the response status code. */ interface TStatusRef { value: number; } /** Reactive ref for reading/writing a response header value. */ interface THeaderRef { value: string | string[] | undefined; } /** Partial cookie attributes (all optional). */ type TCookieAttributes = Partial<TCookieAttributes$1>; /** Reactive ref for reading/writing a response cookie. */ interface TCookieRef { value: string; attrs?: TCookieAttributes; } declare const setHeaderInterceptor: (name: string, value: string, opts?: { force?: boolean; status?: number; when?: "always" | "error" | "ok"; }) => TInterceptorDef; /** * Set Header for Request Handler * * ```ts * import { Get, SetHeader } from '@moostjs/event-http'; * import { Controller } from 'moost'; * * @Controller() * export class ExampleController { * @Get('test') * // setting header for request handler * @SetHeader('x-server', 'my-server') * testHandler() { * return '...' * } * } * ``` * * ```ts * import { Get, SetHeader } from '@moostjs/event-http'; * import { Controller } from 'moost'; * * @Controller() * export class ExampleController { * @Get('test') * // setting header only if status = 400 * @SetHeader('content-type', 'text/plain', { status: 400 }) * testHandler() { * return '...' * } * } * ``` * * @param name name of header * @param value value for header * @param options options { status?: number, force?: boolean } */ declare function SetHeader(...args: Parameters<typeof setHeaderInterceptor>): ClassDecorator & MethodDecorator; declare const setCookieInterceptor: (name: string, value: string, attrs?: TCookieAttributesInput) => TInterceptorDef; /** * Set Cookie for Request Handler * ```ts * import { Get, SetCookie } from '@moostjs/event-http'; * import { Controller } from 'moost'; * * @Controller() * export class ExampleController { * @Get('test') * // setting 'my-cookie' = 'value' with maxAge of 10 minutes * @SetCookie('my-cookie', 'value', { maxAge: '10m' }) * testHandler() { * return '...' * } * } * ``` * * @param name name of cookie * @param value value for cookie * @param attrs cookie attributes */ declare function SetCookie(...args: Parameters<typeof setCookieInterceptor>): ClassDecorator & MethodDecorator; declare const setStatusInterceptor: (code: number, opts?: { force?: boolean; }) => TInterceptorDef; /** * Set Response Status for Request Handler * * ```ts * import { Get, SetStatus } from '@moostjs/event-http'; * import { Controller } from 'moost'; * * @Controller() * export class ExampleController { * @Get('test') * @SetStatus(201) * testHandler() { * return '...' * } * } * ``` * @param code number * @param opts optional { force?: boolean } */ declare function SetStatus(...args: Parameters<typeof setStatusInterceptor>): ClassDecorator & MethodDecorator; /** * Creates an interceptor that sets the maximum allowed inflated body size in bytes. * * @param n - Maximum body size in bytes after decompression. * @returns Interceptor def to enforce the limit. */ declare const globalBodySizeLimit: (n: number) => moost.TInterceptorDef; /** * Creates an interceptor that sets the maximum allowed compressed body size in bytes. * * @param n - Maximum body size in bytes before decompression. * @returns Interceptor def to enforce the limit. */ declare const globalCompressedBodySizeLimit: (n: number) => moost.TInterceptorDef; /** * Creates an interceptor that sets the timeout for reading the request body. * * @param n - Timeout in milliseconds. * @returns Interceptor def to enforce the timeout. */ declare const globalBodyReadTimeoutMs: (n: number) => moost.TInterceptorDef; /** * Decorator to limit the maximum inflated body size for the request. Default: 10 MB * * @param n - Maximum body size in bytes after decompression. */ declare const BodySizeLimit: (n: number) => ClassDecorator & MethodDecorator; /** * Decorator to limit the maximum compressed body size for the request. Default: 1 MB * * @param n - Maximum body size in bytes before decompression. */ declare const CompressedBodySizeLimit: (n: number) => ClassDecorator & MethodDecorator; /** * Decorator to set a timeout (in milliseconds) for reading the request body. Default: 10 s * * @param n - Timeout duration in milliseconds. */ declare const BodyReadTimeoutMs: (n: number) => ClassDecorator & MethodDecorator; type TPathBuilder<ParamsType = Record<string, string | string[]>> = (params?: ParamsType) => string; /** Handler metadata for HTTP events, carrying the HTTP method and route path. */ interface THttpHandlerMeta { method: string; path: string; } /** * ## Moost HTTP Adapter * * Moost Adapter for HTTP events * * ```ts * │ // HTTP server example * │ import { MoostHttp, Get } from '@moostjs/event-http' * │ import { Moost, Param } from 'moost' * │ * │ class MyServer extends Moost { * │ @Get('test/:name') * │ test(@Param('name') name: string) { * │ return { message: `Hello ${name}!` } * │ } * │ } * │ * │ const app = new MyServer() * │ const http = new MoostHttp() * │ app.adapter(http).listen(3000, () => { * │ app.getLogger('MyApp').log('Up on port 3000') * │ }) * │ app.init() * ``` */ declare class MoostHttp implements TMoostAdapter<THttpHandlerMeta> { readonly name = "http"; protected httpApp: WooksHttp; constructor(httpApp?: WooksHttp | TWooksHttpOptions); getHttpApp(): WooksHttp; getServerCb(onNoMatch?: (req: IncomingMessage, res: ServerResponse) => void): (req: IncomingMessage, res: ServerResponse) => void; /** * Programmatic route invocation using the Web Standard fetch API. * Goes through the full Moost pipeline: DI scoping, interceptors, * argument resolution, pipes, validation, and handler execution. * * When called from within an existing HTTP context (e.g. during SSR), * identity headers (authorization, cookie) are automatically forwarded. */ fetch(request: Request): Promise<Response | null>; /** * Convenience wrapper for programmatic route invocation. * Accepts a URL string (relative paths auto-prefixed with `http://localhost`), * URL object, or Request, plus optional `RequestInit`. * * Returns `null` when no route matches the request. */ request(input: string | URL | Request, init?: RequestInit): Promise<Response | null>; /** * Runs `fn` inside an HTTP event context seeded from a real `(req, res)` pair, * without route dispatch. Nested `fetch()`/`request()` calls made during `fn` * see this context as their caller, so `forwardHeaders` and parent `Set-Cookie` * propagation apply. Never writes to `res` — apply buffered response state * (e.g. `response.getSetCookieStrings()`) yourself. */ withHttpContext<T>(req: IncomingMessage, res: ServerResponse, fn: () => T): Promise<{ result: Awaited<T>; response: _wooksjs_event_http.HttpResponse; }>; listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): Promise<void>; listen(port?: number, hostname?: string, listeningListener?: () => void): Promise<void>; listen(port?: number, backlog?: number, listeningListener?: () => void): Promise<void>; listen(port?: number, listeningListener?: () => void): Promise<void>; listen(path: string, backlog?: number, listeningListener?: () => void): Promise<void>; listen(path: string, listeningListener?: () => void): Promise<void>; listen(options: ListenOptions, listeningListener?: () => void): Promise<void>; listen(handle: any, backlog?: number, listeningListener?: () => void): Promise<void>; listen(handle: any, listeningListener?: () => void): Promise<void>; readonly pathBuilders: Record<string, { GET?: TPathBuilder; PUT?: TPathBuilder; PATCH?: TPathBuilder; POST?: TPathBuilder; DELETE?: TPathBuilder; }>; onNotFound(): Promise<unknown>; protected moost?: Moost; onInit(moost: Moost): void; getProvideRegistry(): moost.TProvideRegistry; getLogger(): TConsoleBase; bindHandler<T extends object = object>(opts: TMoostAdapterOptions<THttpHandlerMeta, T>): void; } /** * Patches `globalThis.fetch` so that requests to local paths (starting with `/`) * are routed through `MoostHttp` in-process instead of making a network request. * Falls back to the original `fetch` when no Moost route matches. * * Useful for SSR scenarios where server-side code needs to call its own API endpoints * without the overhead of a TCP round-trip. * * @returns A teardown function that restores the original `globalThis.fetch`. */ declare function enableLocalFetch(http: MoostHttp): () => void; export { All, AuthGuard, Authenticate, Authorization, Body, BodyReadTimeoutMs, BodySizeLimit, CompressedBodySizeLimit, Cookie, CookieAttrsRef, CookieRef, Delete, Get, Header, HeaderRef, HttpMethod, Ip, IpList, Method, MoostHttp, Patch, Post, Put, Query, RawBody, Req, ReqId, Res, SetCookie, SetHeader, SetStatus, StatusRef, Upgrade, Url, defineAuthGuard, enableLocalFetch, extractTransports, globalBodyReadTimeoutMs, globalBodySizeLimit, globalCompressedBodySizeLimit }; export type { TAuthGuardClass, TAuthGuardDef, TAuthGuardHandler, TAuthTransportApiKey, TAuthTransportBasic, TAuthTransportBearer, TAuthTransportCookie, TAuthTransportDeclaration, TAuthTransportValues, TCookieAttributes, TCookieRef, THeaderRef, THttpHandlerMeta, TStatusRef };