import type { EndRoutePath, LocaleType, LocalizedPathsRecord, SegmentRoutePath, } from "../types.ts"; import { getKeys } from "../utils/getKeys.ts"; import { LocalizedEndRoute } from "./LocalizedEndRoute.ts"; import { LocalizedSegmentRoute } from "./LocalizedSegmentRoute.ts"; import { NotLocalizedEndRoute as Route } from "./NotLocalizedEndRoute.ts"; import { NotLocalizedSegmentRoute } from "./NotLocalizedSegmentRoute.ts"; import { createRoutePath, createRoutePathSegment } from "./createRoutePath.ts"; const createLocalizedPaths = < Locales extends LocaleType, Path extends EndRoutePath | SegmentRoutePath, >( localizedPathsRecord: LocalizedPathsRecord, completeLocalizedPathsRecord: LocalizedPathsRecord, segment: boolean, ): Map => { const localizedPaths = new Map(); getKeys(localizedPathsRecord).forEach((locale: Locales) => { const path = localizedPathsRecord[locale]; if (segment) { const routerPath: SegmentRoutePath = createRoutePathSegment( path, completeLocalizedPathsRecord[locale], ); localizedPaths.set(locale, routerPath as Path); } else { const routerPath: EndRoutePath = createRoutePath( path, completeLocalizedPathsRecord[locale], ); localizedPaths.set(locale, routerPath as Path); } }); return localizedPaths; }; const checkRef = (ref: RouteRef): void => { if (!ref) throw new Error(`Invalid ref: "${JSON.stringify(ref)}"`); }; export const createRoute = ( path: string, completePath: string, ref: RouteRef, ): Route => { /* istanbul ignore if */ if (process.env.NODE_ENV !== "production") { if (path.includes("(.*)")) { throw new Error("Wildcard is not supported using regexp"); } checkRef(ref); } const routePath: EndRoutePath = createRoutePath(path, completePath); return new Route(routePath, ref); }; export const createLocalizedRoute = ( localizedPathsRecord: LocalizedPathsRecord, completeLocalizedPathsRecord: LocalizedPathsRecord, ref: RouteRef, ): LocalizedEndRoute => { /* istanbul ignore if */ if (process.env.NODE_ENV !== "production") checkRef(ref); const localizedPaths = createLocalizedPaths( localizedPathsRecord, completeLocalizedPathsRecord, false, ); return new LocalizedEndRoute(localizedPaths, ref); }; export const createSegmentRoute = ( path: string, completePath: string, ): NotLocalizedSegmentRoute => { const routePath = createRoutePathSegment(path, completePath); return new NotLocalizedSegmentRoute(routePath); }; export const createLocalizedSegmentRoute = < Locales extends LocaleType, RouteRef, >( localizedPathsRecord: LocalizedPathsRecord, completeLocalizedPathsRecord: LocalizedPathsRecord, ): LocalizedSegmentRoute => { const localizedPaths = createLocalizedPaths( localizedPathsRecord, completeLocalizedPathsRecord, true, ); return new LocalizedSegmentRoute(localizedPaths); };