midwinter
Version:
A next-gen middleware engine built for the WinterCG environments.
65 lines (58 loc) • 2.75 kB
text/typescript
import { a as AnyMeta, M as MergeObjectsShallow, S as Strip } from './util-CHs1TI3T.mjs';
import { RequestHandler, Midwinter } from 'midwinter';
import { H as HttpMethodInput } from './common-nMHVn6HU.mjs';
type RequestRouter<T> = {
match: (request: Request) => T | undefined;
matchAll: (request: Request) => T[];
};
type RouteInput<T> = {
path: string;
methods: string[];
payload: T;
};
/**
* Creates a radix web router.
*
* Route matching is determined by the radix algorithm.
* Handlers associated with specific methods are prioritised over wildcard methods.
*/
declare const createRouter: <T>(initialRoutes: RouteInput<T>[]) => RequestRouter<T>;
type InferPathParams<T> = T extends `${string}:${infer P}/${infer R}` ? P | InferPathParams<R> : T extends `${string}:${infer P}` ? P : never;
declare const parsePathParams: <T extends string>(path: T) => InferPathParams<T>[];
type RoutingOpts = {
path?: string;
method?: HttpMethodInput[] | HttpMethodInput;
};
type RoutingOptsWithPath = Omit<RoutingOpts, "path"> & {
path: string;
method?: HttpMethodInput[] | HttpMethodInput;
};
type RouteHandlerList = RequestHandler<AnyMeta, Response | undefined>[];
type RouteHandlerMap = Record<string, RequestHandler<AnyMeta, Response | undefined>>;
type RouterOpts = {
onNotFound?: (request: Request) => Response;
onError?: (error: unknown) => Response;
/**
* @default false
*/
keepTrailingSlashes?: boolean;
};
interface InitRoutingReturn {
createRouter(routes: RouteHandlerList | RouteHandlerMap, opts?: RouterOpts): (request: Request) => Promise<Response>;
route<const T extends RoutingOptsWithPath>(config: T): Midwinter<{}, ConfigWithPath<T>>;
route<const T extends RoutingOpts>(config: T): Midwinter<{}, T>;
prefixed<TPrefix extends string>(prefix: TPrefix): <const T extends RoutingOptsWithPath | RoutingOpts>(config: T) => Midwinter<{}, ConfigWithPath<WithPrefix<T, TPrefix>>>;
}
type ToString<T> = T extends string ? T : "";
type WithPrefix<T extends RoutingOpts, TPrefix extends string> = Omit<T, "path"> & {
path: `${TPrefix}${ToString<T["path"]>}`;
};
type ConfigWithPath<T extends RoutingOpts> = MergeObjectsShallow<T, Strip<{
params: InferPathParams<T["path"]>[];
}, never[]>>;
type RoutingInitOpts = {
router?: typeof createRouter;
};
declare const init: (opts?: RoutingInitOpts) => InitRoutingReturn;
declare const RadixRouter: <T>(initialRoutes: RouteInput<T>[]) => RequestRouter<T>;
export { type ConfigWithPath, type InferPathParams, type InitRoutingReturn, RadixRouter, type RouteHandlerList, type RouteHandlerMap, type RouterOpts, type RoutingInitOpts, type RoutingOpts, type RoutingOptsWithPath, type WithPrefix, init, parsePathParams };