import { BaseRoute, ErrorHandlerContext, ServeHandlerInfo } from "./types.ts"; type HandlerContext = T & ServeHandlerInfo; export type Handler = ( req: Request, ctx: HandlerContext, ) => Response | Promise; export type FinalHandler = ( req: Request, ctx: HandlerContext, params: Record, route?: InternalRoute, ) => { destination: DestinationKind; handler: () => Response | Promise; }; export type ErrorHandler = ( req: Request, ctx: HandlerContext, err: unknown, ) => Response | Promise; type UnknownMethodHandler = ( req: Request, ctx: HandlerContext, knownMethods: KnownMethod[], ) => Response | Promise; export type MatchHandler = ( req: Request, ctx: HandlerContext, match: Record, ) => Response | Promise; // deno-lint-ignore ban-types export interface Routes { [key: string]: { baseRoute: BaseRoute; methods: { [K in KnownMethod | "default"]?: MatchHandler; }; }; } export type DestinationKind = "internal" | "static" | "route" | "notFound"; // deno-lint-ignore ban-types export type InternalRoute = { baseRoute: BaseRoute; pattern: URLPattern; methods: { [K in KnownMethod]?: MatchHandler }; default?: MatchHandler; destination: DestinationKind; }; export interface RouterOptions { internalRoutes: Routes; staticRoutes: Routes; routes: Routes; otherHandler: Handler; errorHandler: ErrorHandler; unknownMethodHandler?: UnknownMethodHandler; } export type KnownMethod = typeof knownMethods[number]; export const knownMethods = [ "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", ] as const; export function defaultOtherHandler(_req: Request): Response { return new Response(null, { status: 404, }); } export function defaultErrorHandler( _req: Request, _ctx: ErrorHandlerContext, err: unknown, ): Response { console.error(err); return new Response(null, { status: 500, }); } export function defaultUnknownMethodHandler( _req: Request, _ctx: HandlerContext, knownMethods: KnownMethod[], ): Response { return new Response(null, { status: 405, headers: { Accept: knownMethods.join(", "), }, }); } function processRoutes( processedRoutes: InternalRoute[], routes: Routes, destination: DestinationKind, ) { for (const [path, def] of Object.entries(routes)) { const entry: InternalRoute = { baseRoute: def.baseRoute, pattern: new URLPattern({ pathname: path }), methods: {}, default: undefined, destination, }; for (const [method, handler] of Object.entries(def.methods)) { if (method === "default") { entry.default = handler; } else if (knownMethods.includes(method as KnownMethod)) { entry.methods[method as KnownMethod] = handler; } } processedRoutes.push(entry); } } export function getParamsAndRoute( { internalRoutes, staticRoutes, routes, }: RouterOptions, ): ( url: string, ) => { route: InternalRoute | undefined; params: Record } { const processedRoutes: InternalRoute[] = []; processRoutes(processedRoutes, internalRoutes, "internal"); processRoutes(processedRoutes, staticRoutes, "static"); processRoutes(processedRoutes, routes, "route"); return (url: string) => { for (const route of processedRoutes) { const res = route.pattern.exec(url); if (res !== null) { const groups: Record = {}; const matched = res?.pathname.groups; for (const key in matched) { const value = matched[key]; if (value !== undefined) { groups[key] = decodeURIComponent(value); } } return { route: route, params: groups }; } } return { route: undefined, params: {}, }; }; } export function router( { otherHandler, unknownMethodHandler, }: RouterOptions, ): FinalHandler { unknownMethodHandler ??= defaultUnknownMethodHandler; return (req, ctx, groups, route) => { if (route) { const res = route.pattern.exec(req.url); if (res !== null) { // If not overridden, HEAD requests should be handled as GET requests but without the body. if (req.method === "HEAD" && !route.methods["HEAD"]) { req = new Request(req.url, { method: "GET", headers: req.headers }); } for (const [method, handler] of Object.entries(route.methods)) { if (req.method === method) { return { destination: route.destination, handler: () => handler(req, ctx, groups), }; } } if (route.default) { return { destination: route.destination, handler: () => route.default!(req, ctx, groups), }; } else { return { destination: route.destination, handler: () => unknownMethodHandler!( req, ctx, Object.keys(route.methods) as KnownMethod[], ), }; } } } return { destination: "notFound", handler: () => otherHandler!(req, ctx), }; }; }