const configuredBase = import.meta.env.BASE_URL; function canonicalPathname(pathname: string): string { if (pathname === "/") return pathname; return pathname.replace(/\/+$/, "") || "/"; } /** * Prefixes application routes with Astro's configured base so the same views * work at the web root in server mode and below any directory in static mode. */ export function webPath(pathname: string, base = configuredBase): string { if (!pathname.startsWith("/")) { throw new Error(`Web paths must start with "/": ${pathname}`); } const normalizedBase = base.endsWith("/") ? base : `${base}/`; return pathname === "/" ? normalizedBase : `${normalizedBase}${pathname.slice(1)}`; } /** * Removes Astro's deployment base before matching the current navigation item. */ export function applicationPathname( pathname: string, base = configuredBase, ): string { const normalizedBase = base.endsWith("/") ? base : `${base}/`; const baseWithoutTrailingSlash = canonicalPathname(normalizedBase); if (pathname === baseWithoutTrailingSlash || pathname === normalizedBase) { return "/"; } if (normalizedBase !== "/" && pathname.startsWith(normalizedBase)) { return canonicalPathname(`/${pathname.slice(normalizedBase.length)}`); } return canonicalPathname(pathname); }