@wooksjs/event-http
Version:
@wooksjs/event-http
521 lines (499 loc) • 18.4 kB
TypeScript
import * as _wooksjs_event_core from '@wooksjs/event-core';
import { TEventOptions, TEmpty, TCtxHelpers, TGenericContextStore } from '@wooksjs/event-core';
export { useEventLogger, useRouteParams } from '@wooksjs/event-core';
import * as http from 'http';
import { IncomingMessage, ServerResponse, IncomingHttpHeaders, Server } from 'http';
import { URLSearchParams } from 'url';
import { Buffer as Buffer$1 } from 'buffer';
import { TConsoleBase } from '@prostojs/logger';
import * as wooks from 'wooks';
import { TWooksHandler, TWooksOptions, WooksAdapterBase, Wooks } from 'wooks';
import { ListenOptions } from 'net';
declare const httpStatusCodes: {
100: string;
101: string;
102: string;
103: string;
200: string;
201: string;
202: string;
203: string;
204: string;
205: string;
206: string;
207: string;
208: string;
226: string;
300: string;
301: string;
302: string;
303: string;
304: string;
305: string;
306: string;
307: string;
308: string;
400: string;
401: string;
402: string;
403: string;
404: string;
405: string;
406: string;
407: string;
408: string;
409: string;
410: string;
411: string;
412: string;
413: string;
414: string;
415: string;
416: string;
417: string;
418: string;
421: string;
422: string;
423: string;
424: string;
425: string;
426: string;
428: string;
429: string;
431: string;
451: string;
500: string;
501: string;
502: string;
503: string;
504: string;
505: string;
506: string;
507: string;
508: string;
510: string;
511: string;
};
declare enum EHttpStatusCode {
Continue = 100,
SwitchingProtocols = 101,
Processing = 102,
EarlyHints = 103,
OK = 200,
Created = 201,
Accepted = 202,
NonAuthoritativeInformation = 203,
NoContent = 204,
ResetContent = 205,
PartialContent = 206,
MultiStatus = 207,
AlreadyReported = 208,
IMUsed = 226,
MultipleChoices = 300,
MovedPermanently = 301,
Found = 302,
SeeOther = 303,
NotModified = 304,
UseProxy = 305,
SwitchProxy = 306,
TemporaryRedirect = 307,
PermanentRedirect = 308,
BadRequest = 400,
Unauthorized = 401,
PaymentRequired = 402,
Forbidden = 403,
NotFound = 404,
MethodNotAllowed = 405,
NotAcceptable = 406,
ProxyAuthenticationRequired = 407,
RequestTimeout = 408,
Conflict = 409,
Gone = 410,
LengthRequired = 411,
PreconditionFailed = 412,
PayloadTooLarge = 413,
URITooLong = 414,
UnsupportedMediaType = 415,
RangeNotSatisfiable = 416,
ExpectationFailed = 417,
ImATeapot = 418,
MisdirectedRequest = 421,
UnprocessableEntity = 422,
Locked = 423,
FailedDependency = 424,
TooEarly = 425,
UpgradeRequired = 426,
PreconditionRequired = 428,
TooManyRequests = 429,
RequestHeaderFieldsTooLarge = 431,
UnavailableForLegalReasons = 451,
InternalServerError = 500,
NotImplemented = 501,
BadGateway = 502,
ServiceUnavailable = 503,
GatewayTimeout = 504,
HTTPVersionNotSupported = 505,
VariantAlsoNegotiates = 506,
InsufficientStorage = 507,
LoopDetected = 508,
NotExtended = 510,
NetworkAuthenticationRequired = 511
}
type THttpBadRequestCodes = 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451;
type THttpServerErrorCodes = 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511;
type THttpErrorCodes = THttpBadRequestCodes | THttpServerErrorCodes;
type TTimeUnit = 'ms' | 's' | 'm' | 'h' | 'd' | 'w' | 'M' | 'Y';
type TTimeSingleString = `${number}${TTimeUnit}`;
type TTimeMultiString = `${TTimeSingleString}${TTimeSingleString | ''}${TTimeSingleString | ''}${TTimeSingleString | ''}`;
declare class WooksURLSearchParams extends URLSearchParams {
toJson<T = unknown>(): T;
}
interface THttpEventData {
req: IncomingMessage;
res: ServerResponse;
}
interface THttpEvent {
type: 'HTTP';
}
interface THttpContextStore {
searchParams?: TSearchParamsCache;
cookies?: Record<string, string | null>;
setCookies?: Record<string, TSetCookieData>;
accept?: Record<string, boolean>;
authorization?: TAuthCache;
setHeader?: Record<string, string | string[]>;
request?: TRequestCache;
response?: {
responded: boolean;
};
status?: {
code: EHttpStatusCode;
};
}
interface TSetCookieData {
value: string;
attrs: TCookieAttributesInput;
}
type TCookieAttributesInput = Partial<TCookieAttributes>;
interface TCookieAttributes {
expires: Date | string | number;
maxAge: number | TTimeMultiString;
domain: string;
path: string;
secure: boolean;
httpOnly: boolean;
sameSite: boolean | 'Lax' | 'None' | 'Strict';
}
interface TAuthCache {
type: string | null;
credentials: string | null;
basicCredentials: {
username: string;
password: string;
} | null;
}
interface TRequestCache {
rawBody: Promise<Buffer>;
parsed: unknown;
forwardedIp?: string;
remoteIp?: string;
ipList?: {
remoteIp: string;
forwarded: string[];
};
contentEncodings?: string[];
isCompressed?: boolean;
maxCompressed?: number;
maxInflated?: number;
maxRatio?: number;
readTimeoutMs?: number;
}
interface TSearchParamsCache {
raw?: string;
urlSearchParams?: WooksURLSearchParams;
}
declare function useCookies(): {
rawCookies: string | undefined;
getCookie: (name: string) => string | null;
};
declare function useSetCookies(): {
setCookie: (name: string, value: string, attrs?: Partial<TCookieAttributes>) => void;
getCookie: <K2 extends string>(key2: K2) => TSetCookieData | undefined;
removeCookie: <K2 extends string>(key2: K2) => void;
clearCookies: () => void;
cookies: () => string[];
};
declare function useSetCookie(name: string): {
name: string;
type: string;
} & _wooksjs_event_core.THook<string, "value"> & _wooksjs_event_core.THook<TCookieAttributes, "attrs">;
type TCookieHook = ReturnType<typeof useSetCookie>;
declare function useAccept(): {
accept: string | undefined;
accepts: (mime: string) => unknown;
acceptsJson: () => unknown;
acceptsXml: () => unknown;
acceptsText: () => unknown;
acceptsHtml: () => unknown;
};
declare function useAuthorization(): {
authorization: string | undefined;
authType: () => string | null;
authRawCredentials: () => string | null;
isBasic: () => boolean;
isBearer: () => boolean;
basicCredentials: () => {
username: string;
password: string;
} | null;
};
interface TCacheControl {
mustRevalidate?: boolean;
noCache?: boolean | string;
noStore?: boolean;
noTransform?: boolean;
public?: boolean;
private?: boolean | string;
proxyRevalidate?: boolean;
maxAge?: number | TTimeMultiString;
sMaxage?: number | TTimeMultiString;
}
declare function renderCacheControl(data: TCacheControl): string;
declare function useSetCacheControl(): {
setExpires: (value: Date | string | number) => void;
setAge: (value: number | TTimeMultiString) => void;
setPragmaNoCache: (value?: boolean) => void;
setCacheControl: (data: TCacheControl) => void;
};
declare function useHeaders(): IncomingHttpHeaders;
declare function useSetHeaders(): {
setHeader: (name: string, value: string | number) => void;
getHeader: <K2 extends string>(key2: K2) => string | string[] | undefined;
removeHeader: <K2 extends string>(key2: K2) => void;
setContentType: (value: string) => void;
headers: () => Record<string, string | string[]>;
enableCors: (origin?: string) => void;
};
declare function useSetHeader(name: string): {
value: string | string[];
isDefined: boolean;
};
type THeaderHook = ReturnType<typeof useSetHeader>;
declare const DEFAULT_LIMITS: {
readonly maxCompressed: number;
readonly maxInflated: number;
readonly maxRatio: 100;
readonly readTimeoutMs: 10000;
};
declare function useRequest(): {
rawRequest: http.IncomingMessage;
url: string | undefined;
method: string | undefined;
headers: http.IncomingHttpHeaders;
rawBody: () => Promise<Buffer$1<ArrayBufferLike>>;
reqId: () => string;
getIp: (options?: {
trustProxy: boolean;
}) => string;
getIpList: () => {
remoteIp: string;
forwarded: string[];
};
isCompressed: () => boolean;
getMaxCompressed: () => number;
setMaxCompressed: (limit: number) => unknown;
getReadTimeoutMs: () => number;
setReadTimeoutMs: (limit: number) => unknown;
getMaxInflated: () => number;
setMaxInflated: (limit: number) => unknown;
};
interface TUseResponseOptions {
passthrough: boolean;
}
declare function useResponse(): {
rawResponse: (options?: TUseResponseOptions) => http.ServerResponse<http.IncomingMessage>;
hasResponded: () => boolean;
status: ((code?: EHttpStatusCode) => EHttpStatusCode) & _wooksjs_event_core.THook<EHttpStatusCode, "value">;
};
declare function useStatus(): {
value: EHttpStatusCode;
isDefined: boolean;
};
type TStatusHook = ReturnType<typeof useStatus>;
declare function useSearchParams(): {
rawSearchParams: () => string;
urlSearchParams: () => WooksURLSearchParams;
jsonSearchParams: () => unknown;
};
declare class BaseHttpResponseRenderer<T = unknown> implements TWooksResponseRenderer<T> {
render(response: BaseHttpResponse<T>): string | Uint8Array;
}
interface TWooksResponseRenderer<T = unknown> {
render: (response: BaseHttpResponse<T>) => string | Uint8Array;
}
declare class BaseHttpResponse<BodyType = unknown> {
protected renderer: BaseHttpResponseRenderer;
constructor(renderer?: BaseHttpResponseRenderer);
protected _status: EHttpStatusCode;
protected _body?: BodyType;
protected _headers: Record<string, string | string[]>;
get status(): EHttpStatusCode;
set status(value: EHttpStatusCode);
get body(): BodyType | undefined;
set body(value: BodyType | undefined);
setStatus(value: EHttpStatusCode): this;
setBody(value: BodyType): this;
getContentType(): string | string[];
setContentType(value: string): this;
enableCors(origin?: string): this;
setCookie(name: string, value: string, attrs?: Partial<TCookieAttributes>): this;
setCacheControl(data: TCacheControl): void;
setCookieRaw(rawValue: string): this;
header(name: string, value: string): this;
setHeader(name: string, value: string): this;
getHeader(name: string): string | string[];
protected mergeHeaders(): this;
protected mergeStatus(renderedBody: string | Uint8Array): this;
protected mergeFetchStatus(fetchStatus: number): void;
protected panic(text: string, logger: TConsoleBase): void;
respond(): Promise<unknown>;
}
declare class HttpError<T extends TWooksErrorBody = TWooksErrorBody> extends Error {
protected code: THttpErrorCodes;
protected _body: string | T;
name: string;
constructor(code?: THttpErrorCodes, _body?: string | T);
get body(): TWooksErrorBodyExt;
protected renderer?: HttpErrorRenderer;
attachRenderer(renderer: HttpErrorRenderer): void;
getRenderer(): HttpErrorRenderer | undefined;
}
interface TWooksErrorBody {
message: string;
statusCode: EHttpStatusCode;
error?: string;
}
interface TWooksErrorBodyExt extends TWooksErrorBody {
error: string;
}
declare class HttpErrorRenderer extends BaseHttpResponseRenderer<TWooksErrorBodyExt> {
protected opts?: {
version: string;
poweredBy: string;
link: string;
image: string;
} | undefined;
constructor(opts?: {
version: string;
poweredBy: string;
link: string;
image: string;
} | undefined);
protected icons: {
401: string;
403: string;
404: string;
500: string;
};
static registerFramework(opts: {
version: string;
poweredBy: string;
link: string;
image: string;
}): void;
renderHtml(response: BaseHttpResponse<TWooksErrorBodyExt>): string;
renderText(response: BaseHttpResponse<TWooksErrorBodyExt>): string;
renderJson(response: BaseHttpResponse<TWooksErrorBodyExt>): string;
render(response: BaseHttpResponse<TWooksErrorBodyExt>): string;
}
declare function createHttpContext(data: THttpEventData, options: TEventOptions): <T>(cb: (...a: any[]) => T) => T;
/**
* Wrapper on useEventContext with HTTP event types
* @returns set of hooks { getCtx, restoreCtx, clearCtx, hookStore, getStore, setStore }
*/
declare function useHttpContext<T extends TEmpty>(): TCtxHelpers<THttpContextStore & T & TGenericContextStore<THttpEventData>>;
declare function createWooksResponder(renderer?: TWooksResponseRenderer<any>, errorRenderer?: TWooksResponseRenderer<any>): {
createResponse: <T = unknown>(data: T) => BaseHttpResponse<T | TWooksErrorBodyExt> | null;
respond: (data: unknown) => Promise<unknown> | undefined;
};
interface TWooksHttpOptions {
logger?: TConsoleBase;
eventOptions?: TEventOptions;
onNotFound?: TWooksHandler;
router?: TWooksOptions['router'];
}
declare class WooksHttp extends WooksAdapterBase {
protected opts?: TWooksHttpOptions | undefined;
protected logger: TConsoleBase;
constructor(opts?: TWooksHttpOptions | undefined, wooks?: Wooks | WooksAdapterBase);
all<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): wooks.TProstoRouterPathHandle<ParamsType>;
get<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): wooks.TProstoRouterPathHandle<ParamsType>;
post<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): wooks.TProstoRouterPathHandle<ParamsType>;
put<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): wooks.TProstoRouterPathHandle<ParamsType>;
patch<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): wooks.TProstoRouterPathHandle<ParamsType>;
delete<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): wooks.TProstoRouterPathHandle<ParamsType>;
head<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): wooks.TProstoRouterPathHandle<ParamsType>;
options<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): wooks.TProstoRouterPathHandle<ParamsType>;
protected server?: Server;
/**
* Starts the http(s) server.
*
* Use this only if you rely on Wooks server.
*/
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>;
/**
* Stops the server if it was attached or passed via argument
* @param server
*/
close(server?: Server): Promise<unknown>;
/**
* Returns http(s) server that was attached to Wooks
*
* See attachServer method docs
* @returns Server
*/
getServer(): Server<typeof IncomingMessage, typeof ServerResponse> | undefined;
/**
* Attaches http(s) server instance
* to Wooks.
*
* Use it only if you want to `close` method to stop the server.
* @param server Server
*/
attachServer(server?: Server): void;
protected responder: {
createResponse: <T = unknown>(data: T) => BaseHttpResponse<T | TWooksErrorBodyExt> | null;
respond: (data: unknown) => Promise<unknown> | undefined;
};
protected respond(data: unknown): void;
/**
* Returns server callback function
* that can be passed to any node server:
* ```js
* import { createHttpApp } from '@wooksjs/event-http'
* import http from 'http'
*
* const app = createHttpApp()
* const server = http.createServer(app.getServerCb())
* server.listen(3000)
* ```
*/
getServerCb(): (req: IncomingMessage, res: ServerResponse) => void;
protected processHandlers(handlers: TWooksHandler[]): Promise<unknown>;
}
/**
* Factory for WooksHttp App
* @param opts TWooksHttpOptions
* @param wooks Wooks | WooksAdapterBase
* @returns WooksHttp
*/
declare function createHttpApp(opts?: TWooksHttpOptions, wooks?: Wooks | WooksAdapterBase): WooksHttp;
export { BaseHttpResponse, BaseHttpResponseRenderer, DEFAULT_LIMITS, EHttpStatusCode, HttpError, HttpErrorRenderer, type TAuthCache, type TCacheControl, type TCookieAttributes, type TCookieAttributesInput, type TCookieHook, type THeaderHook, type THttpContextStore, type THttpEvent, type THttpEventData, type TRequestCache, type TSearchParamsCache, type TSetCookieData, type TStatusHook, type TWooksErrorBody, type TWooksErrorBodyExt, type TWooksHttpOptions, type TWooksResponseRenderer, WooksHttp, WooksURLSearchParams, createHttpApp, createHttpContext, createWooksResponder, httpStatusCodes, renderCacheControl, useAccept, useAuthorization, useCookies, useHeaders, useHttpContext, useRequest, useResponse, useSearchParams, useSetCacheControl, useSetCookie, useSetCookies, useSetHeader, useSetHeaders, useStatus };