import type { EndRoute } from "../routes/interfaces.ts"; import type { LocaleType, RouteMap, Routes } from "../types.ts"; import type { RouteMatch } from "./findMatch.ts"; import { findMatch } from "./findMatch.ts"; export interface Router { get: (key: string) => EndRoute; find: ( path: string, locale?: Locales, ) => RouteMatch | null; toLocalizedPath: (locale: Locales, key: string, args?: any) => string; toPath: (key: string, args?: any) => string; } export function createRouter( routes: Routes, routeMap: RouteMap, ): Router { const getRequiredRoute = (routeKey: string): EndRoute => { const route = routeMap.get(routeKey); if (!route) throw new Error(`No route named "${routeKey}"`); return route; }; return { get: getRequiredRoute, find: ( path: string, locale?: Locales, ): RouteMatch | null => findMatch(path, routes, locale), toPath: (key: string, args?: Record): string => getRequiredRoute(key).getPath().toPath(args), toLocalizedPath: ( locale: Locales, key: string, args?: Record, ): string => getRequiredRoute(key).getPath(locale).toPath(args), }; }