feat: execute route and release recovery contracts
This commit is contained in:
@@ -1,260 +0,0 @@
|
||||
import { lazy, Suspense, useState } from "react";
|
||||
import {
|
||||
BrowserRouter,
|
||||
Route,
|
||||
Routes,
|
||||
useLocation,
|
||||
} from "react-router-dom";
|
||||
|
||||
import { getRoute, routePath } from "../../contracts/routes.js";
|
||||
import { RouteBoundary } from "../boundaries/render-error-boundary.jsx";
|
||||
import { AppShell } from "../layouts/app-shell.jsx";
|
||||
import { PageHeader } from "../components/page-header.jsx";
|
||||
import { useApplication } from "../providers/application-provider.js";
|
||||
import { SessionProvider, useSession } from "../providers/session-provider.jsx";
|
||||
import { ThemeProvider } from "../providers/theme-provider.jsx";
|
||||
import { decideRouteAccess } from "./navigation-policy.js";
|
||||
|
||||
const HomePage = lazy(() => import("../pages/home-page.jsx"));
|
||||
const UiGalleryPage = lazy(() => import("../examples/ui-gallery-page.jsx"));
|
||||
const StateGalleryPage = lazy(
|
||||
() => import("../examples/state-gallery-page.jsx"),
|
||||
);
|
||||
const AuthExamplePage = lazy(
|
||||
() => import("../examples/auth-example-page.jsx"),
|
||||
);
|
||||
const SampleContractPage = lazy(
|
||||
() => import("../pages/sample-contract-page.jsx"),
|
||||
);
|
||||
const NotFoundPage = lazy(() => import("../pages/not-found-page.jsx"));
|
||||
|
||||
/** @param {{ routeId: string }} props */
|
||||
function RouteLoadingSurface({ routeId }) {
|
||||
const definition = getRoute(routeId);
|
||||
return (
|
||||
<section className="ui-page route-loading" aria-live="polite" aria-busy="true">
|
||||
<div className="ui-skeleton" aria-hidden="true" />
|
||||
<p>화면을 준비하고 있습니다.</p>
|
||||
<span className="visually-hidden">{definition.title} 로딩 중</span>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function RouteFailureSurface() {
|
||||
return (
|
||||
<section className="ui-page">
|
||||
<PageHeader
|
||||
title="화면을 표시하지 못했습니다."
|
||||
description="잠시 후 페이지를 새로고침해 주세요. 문제가 계속되면 운영 지원 참조 정보를 확인하세요."
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{
|
||||
* routeId: string,
|
||||
* buildId: string,
|
||||
* children: React.ReactNode
|
||||
* }} props
|
||||
*/
|
||||
function RouteSurface({ routeId, buildId, children }) {
|
||||
const { diagnostics } = useApplication();
|
||||
return (
|
||||
<RouteBoundary
|
||||
routeId={routeId}
|
||||
buildId={buildId}
|
||||
onRenderFailure={diagnostics.reportRenderFailure}
|
||||
fallback={<RouteFailureSurface />}
|
||||
>
|
||||
<Suspense fallback={<RouteLoadingSurface routeId={routeId} />}>
|
||||
{children}
|
||||
</Suspense>
|
||||
</RouteBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{
|
||||
* routeId: string,
|
||||
* children: React.ReactNode
|
||||
* }} props
|
||||
*/
|
||||
function ProtectedRoute({ routeId, children }) {
|
||||
const location = useLocation();
|
||||
const { sessionState, beginSignIn, recover } = useSession();
|
||||
const [pending, setPending] = useState(false);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const decision = decideRouteAccess(routeId, sessionState);
|
||||
|
||||
async function continueSession() {
|
||||
setPending(true);
|
||||
setFailed(false);
|
||||
try {
|
||||
if (decision.action === "wait-for-session") {
|
||||
await recover();
|
||||
} else {
|
||||
await beginSignIn(
|
||||
`${location.pathname}${location.search}${location.hash}`,
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
setFailed(true);
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (decision.allowed) return children;
|
||||
|
||||
if (sessionState === "integration-failed") {
|
||||
return (
|
||||
<section className="ui-page">
|
||||
<PageHeader
|
||||
title="로그인 연동이 필요합니다."
|
||||
description="외부 인증 소유자가 런타임에 연결되면 이 보호 라우트를 사용할 수 있습니다."
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const recovering = decision.action === "wait-for-session";
|
||||
return (
|
||||
<section className="ui-page">
|
||||
<PageHeader
|
||||
title={recovering ? "세션을 복구하고 있습니다." : "세션이 필요합니다."}
|
||||
description={
|
||||
recovering
|
||||
? "기존 세션 확인을 계속하려면 복구를 실행하세요."
|
||||
: "이 화면은 인증 연동 지점을 확인하기 위한 보호 라우트입니다."
|
||||
}
|
||||
/>
|
||||
<div>
|
||||
<button
|
||||
className="ui-button"
|
||||
type="button"
|
||||
disabled={pending}
|
||||
onClick={() => void continueSession()}
|
||||
>
|
||||
{pending
|
||||
? "처리 중…"
|
||||
: recovering
|
||||
? "세션 복구"
|
||||
: "로그인 시작"}
|
||||
</button>
|
||||
</div>
|
||||
{failed ? (
|
||||
<p className="ui-terminal-error" role="alert">
|
||||
세션 작업을 완료하지 못했습니다.
|
||||
</p>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{
|
||||
* routeId: string,
|
||||
* buildId: string,
|
||||
* children: React.ReactNode
|
||||
* }} props
|
||||
*/
|
||||
function PublicRoute({ routeId, buildId, children }) {
|
||||
return (
|
||||
<RouteSurface routeId={routeId} buildId={buildId}>
|
||||
{children}
|
||||
</RouteSurface>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{
|
||||
* basename?: string,
|
||||
* buildId?: string
|
||||
* }} props
|
||||
*/
|
||||
export function AppRouter({
|
||||
basename = "/",
|
||||
buildId = "local-build",
|
||||
}) {
|
||||
return (
|
||||
<BrowserRouter basename={basename}>
|
||||
<ThemeProvider>
|
||||
<SessionProvider>
|
||||
<Routes>
|
||||
<Route element={<AppShell />}>
|
||||
<Route
|
||||
index
|
||||
element={
|
||||
<PublicRoute
|
||||
routeId="APP_HOME"
|
||||
buildId={buildId}
|
||||
>
|
||||
<HomePage />
|
||||
</PublicRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path={routePath("EXAMPLES_UI")}
|
||||
element={
|
||||
<PublicRoute
|
||||
routeId="EXAMPLES_UI"
|
||||
buildId={buildId}
|
||||
>
|
||||
<UiGalleryPage />
|
||||
</PublicRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path={routePath("EXAMPLES_STATES")}
|
||||
element={
|
||||
<PublicRoute
|
||||
routeId="EXAMPLES_STATES"
|
||||
buildId={buildId}
|
||||
>
|
||||
<StateGalleryPage />
|
||||
</PublicRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path={routePath("EXAMPLES_AUTH")}
|
||||
element={
|
||||
<PublicRoute
|
||||
routeId="EXAMPLES_AUTH"
|
||||
buildId={buildId}
|
||||
>
|
||||
<AuthExamplePage />
|
||||
</PublicRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path={routePath("SAMPLE_RESOURCE_LIST")}
|
||||
element={
|
||||
<RouteSurface
|
||||
routeId="SAMPLE_RESOURCE_LIST"
|
||||
buildId={buildId}
|
||||
>
|
||||
<ProtectedRoute routeId="SAMPLE_RESOURCE_LIST">
|
||||
<SampleContractPage />
|
||||
</ProtectedRoute>
|
||||
</RouteSurface>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path={routePath("NOT_FOUND")}
|
||||
element={
|
||||
<PublicRoute
|
||||
routeId="NOT_FOUND"
|
||||
buildId={buildId}
|
||||
>
|
||||
<NotFoundPage />
|
||||
</PublicRoute>
|
||||
}
|
||||
/>
|
||||
</Route>
|
||||
</Routes>
|
||||
</SessionProvider>
|
||||
</ThemeProvider>
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
import {
|
||||
createContext,
|
||||
type ReactNode,
|
||||
Suspense,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import {
|
||||
createBrowserRouter,
|
||||
RouterProvider,
|
||||
type RouteObject,
|
||||
useLocation,
|
||||
useNavigate,
|
||||
useParams,
|
||||
useSearchParams,
|
||||
} from "react-router-dom";
|
||||
|
||||
import {
|
||||
getRoute,
|
||||
ROUTE_REGISTRY,
|
||||
type RouteDefinition,
|
||||
} from "../../contracts/routes.js";
|
||||
import {
|
||||
FeatureBoundary,
|
||||
RouteBoundary,
|
||||
} from "../boundaries/render-error-boundary.jsx";
|
||||
import { ChunkRecoveryBoundary } from "../boundaries/chunk-recovery-boundary.js";
|
||||
import { PageHeader } from "../components/page-header.jsx";
|
||||
import { AppShell } from "../layouts/app-shell.jsx";
|
||||
import { useApplication } from "../providers/application-provider.js";
|
||||
import { SessionProvider, useSession } from "../providers/session-provider.jsx";
|
||||
import { ThemeProvider } from "../providers/theme-provider.jsx";
|
||||
import {
|
||||
createRedirectLoopGuard,
|
||||
decideRouteAccess,
|
||||
} from "./navigation-policy.js";
|
||||
import {
|
||||
buildRouteUrl,
|
||||
parseRouteInput,
|
||||
type ParsedRouteInput,
|
||||
type RouteId,
|
||||
} from "./route-codecs.js";
|
||||
import { ROUTE_RUNTIME } from "./route-runtime.js";
|
||||
|
||||
const RouteInputContext = createContext<ParsedRouteInput | null>(null);
|
||||
|
||||
export function useRouteInput(): ParsedRouteInput {
|
||||
const input = useContext(RouteInputContext);
|
||||
if (!input) throw new Error("Registered route input is required");
|
||||
return input;
|
||||
}
|
||||
|
||||
function RouteLoadingSurface({ definition }: { definition: RouteDefinition }) {
|
||||
return (
|
||||
<section
|
||||
className="ui-page route-loading"
|
||||
aria-live="polite"
|
||||
aria-busy="true"
|
||||
data-surface={definition.loadingSurface}
|
||||
>
|
||||
<div className="ui-skeleton" aria-hidden="true" />
|
||||
<p>화면을 준비하고 있습니다.</p>
|
||||
<span className="visually-hidden">{definition.title} 로딩 중</span>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function RouteFailureSurface({
|
||||
definition,
|
||||
}: {
|
||||
definition?: RouteDefinition;
|
||||
}) {
|
||||
return (
|
||||
<section
|
||||
className="ui-page"
|
||||
data-surface={definition?.errorSurface ?? "route-boundary"}
|
||||
>
|
||||
<PageHeader
|
||||
title="화면을 표시하지 못했습니다."
|
||||
description="잠시 후 다시 시도해 주세요. 문제가 계속되면 운영 지원 참조 정보를 확인하세요."
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function InvalidRouteSurface({ code }: { code: string }) {
|
||||
return (
|
||||
<section className="ui-page" data-surface="invalid-route">
|
||||
<PageHeader
|
||||
title="올바르지 않은 주소입니다."
|
||||
description="주소의 경로 또는 검색 조건을 확인해 주세요."
|
||||
/>
|
||||
<p data-route-error={code}>안전한 탐색 링크를 사용해 주세요.</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function RouteLifecycle({ definition }: { definition: RouteDefinition }) {
|
||||
const location = useLocation();
|
||||
useEffect(() => {
|
||||
document.title = `${definition.title} · Frontend Skeleton`;
|
||||
const main = document.getElementById("main-content");
|
||||
main?.focus({ preventScroll: true });
|
||||
try {
|
||||
if (!navigator.userAgent.toLowerCase().includes("jsdom")) {
|
||||
window.scrollTo({ top: 0, left: 0, behavior: "auto" });
|
||||
}
|
||||
} catch {
|
||||
// Non-browser test hosts may not implement scrolling.
|
||||
}
|
||||
}, [definition, location.key, location.pathname]);
|
||||
return null;
|
||||
}
|
||||
|
||||
function CanonicalRouteRedirect({
|
||||
input,
|
||||
}: {
|
||||
input: ParsedRouteInput;
|
||||
}) {
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const guard = useRef(createRedirectLoopGuard(3));
|
||||
useEffect(() => {
|
||||
if (input.routeId === "NOT_FOUND") return;
|
||||
const source = `${location.pathname}${location.search}`;
|
||||
const target = buildRouteUrl(input.routeId, {
|
||||
params: input.params,
|
||||
search: input.search,
|
||||
});
|
||||
if (source !== target && guard.current.allow(source, target)) {
|
||||
void navigate(target, { replace: true });
|
||||
}
|
||||
}, [input, location.pathname, location.search, navigate]);
|
||||
return null;
|
||||
}
|
||||
|
||||
function ProtectedRoute({
|
||||
routeId,
|
||||
children,
|
||||
}: {
|
||||
routeId: RouteId;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const location = useLocation();
|
||||
const { sessionState, beginSignIn, recover } = useSession();
|
||||
const [pending, setPending] = useState(false);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const decision = decideRouteAccess(routeId, sessionState);
|
||||
|
||||
async function continueSession() {
|
||||
setPending(true);
|
||||
setFailed(false);
|
||||
try {
|
||||
if (decision.action === "wait-for-session") {
|
||||
await recover();
|
||||
} else {
|
||||
await beginSignIn(
|
||||
`${location.pathname}${location.search}${location.hash}`,
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
setFailed(true);
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (decision.allowed) return children;
|
||||
if (sessionState === "integration-failed") {
|
||||
return (
|
||||
<section className="ui-page" data-surface="auth-integration-required">
|
||||
<PageHeader
|
||||
title="로그인 연동이 필요합니다."
|
||||
description="외부 인증 소유자가 연결되면 이 보호 라우트를 사용할 수 있습니다."
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
const recovering = decision.action === "wait-for-session";
|
||||
return (
|
||||
<section className="ui-page" data-surface="authentication-required">
|
||||
<PageHeader
|
||||
title={recovering ? "세션을 복구하고 있습니다." : "세션이 필요합니다."}
|
||||
description={
|
||||
recovering
|
||||
? "기존 세션 확인을 계속하려면 복구를 실행하세요."
|
||||
: "이 화면은 인증 연동 지점을 확인하기 위한 보호 라우트입니다."
|
||||
}
|
||||
/>
|
||||
<button
|
||||
className="ui-button"
|
||||
type="button"
|
||||
disabled={pending}
|
||||
onClick={() => void continueSession()}
|
||||
>
|
||||
{pending ? "처리 중…" : recovering ? "세션 복구" : "로그인 시작"}
|
||||
</button>
|
||||
{failed ? (
|
||||
<p className="ui-terminal-error" role="alert">
|
||||
세션 작업을 완료하지 못했습니다.
|
||||
</p>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function RegisteredRoute({
|
||||
routeId,
|
||||
buildId,
|
||||
}: {
|
||||
routeId: RouteId;
|
||||
buildId: string;
|
||||
}) {
|
||||
const definition = getRoute(routeId);
|
||||
const runtime = ROUTE_RUNTIME[routeId];
|
||||
const params = useParams();
|
||||
const [search] = useSearchParams();
|
||||
const location = useLocation();
|
||||
const { diagnostics, recovery } = useApplication();
|
||||
const parsed = parseRouteInput(routeId, params, search);
|
||||
if (!parsed.success) return <InvalidRouteSurface code={parsed.code} />;
|
||||
|
||||
const content = (
|
||||
<RouteInputContext.Provider value={parsed.data}>
|
||||
<CanonicalRouteRedirect input={parsed.data} />
|
||||
<RouteLifecycle definition={definition} />
|
||||
<Suspense fallback={<RouteLoadingSurface definition={definition} />}>
|
||||
<ChunkRecoveryBoundary
|
||||
chunkId={definition.chunkId}
|
||||
recover={recovery.recoverChunk}
|
||||
>
|
||||
<runtime.Component />
|
||||
</ChunkRecoveryBoundary>
|
||||
</Suspense>
|
||||
</RouteInputContext.Provider>
|
||||
);
|
||||
const protectedContent =
|
||||
definition.access === "public" ? (
|
||||
content
|
||||
) : (
|
||||
<ProtectedRoute routeId={routeId}>{content}</ProtectedRoute>
|
||||
);
|
||||
const boundaryProps = {
|
||||
routeId,
|
||||
buildId,
|
||||
resetKey: `${location.pathname}${location.search}`,
|
||||
onRenderFailure: diagnostics.reportRenderFailure,
|
||||
fallback: <RouteFailureSurface definition={definition} />,
|
||||
children: protectedContent,
|
||||
};
|
||||
return definition.errorSurface === "feature-boundary" ? (
|
||||
<FeatureBoundary {...boundaryProps} />
|
||||
) : (
|
||||
<RouteBoundary {...boundaryProps} />
|
||||
);
|
||||
}
|
||||
|
||||
function createRegisteredRoutes(buildId: string): RouteObject[] {
|
||||
const children = Object.values(ROUTE_REGISTRY).map((definition) => {
|
||||
const routeId = definition.routeId as RouteId;
|
||||
if (definition.path === "/") {
|
||||
return {
|
||||
id: routeId,
|
||||
index: true,
|
||||
element: <RegisteredRoute routeId={routeId} buildId={buildId} />,
|
||||
};
|
||||
}
|
||||
return {
|
||||
id: routeId,
|
||||
path:
|
||||
definition.path === "*"
|
||||
? "*"
|
||||
: definition.path.replace(/^\//, ""),
|
||||
element: <RegisteredRoute routeId={routeId} buildId={buildId} />,
|
||||
};
|
||||
});
|
||||
return [
|
||||
{
|
||||
id: "APP_SHELL",
|
||||
path: "/",
|
||||
element: <AppShell />,
|
||||
errorElement: <RouteFailureSurface />,
|
||||
children,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export function AppRouter({
|
||||
basename = "/",
|
||||
buildId = "local-build",
|
||||
}: Readonly<{ basename?: string; buildId?: string }>) {
|
||||
const router = useMemo(
|
||||
() =>
|
||||
createBrowserRouter(createRegisteredRoutes(buildId), {
|
||||
basename,
|
||||
}),
|
||||
[basename, buildId],
|
||||
);
|
||||
return (
|
||||
<ThemeProvider>
|
||||
<SessionProvider>
|
||||
<RouterProvider router={router} />
|
||||
</SessionProvider>
|
||||
</ThemeProvider>
|
||||
);
|
||||
}
|
||||
@@ -16,8 +16,10 @@ export function decideRouteAccess(routeId, sessionState) {
|
||||
return { allowed: false, action: "show-sign-in" };
|
||||
}
|
||||
|
||||
export function createRedirectLoopGuard() {
|
||||
/** @param {number} [maxHops] */
|
||||
export function createRedirectLoopGuard(maxHops = 5) {
|
||||
const visitedPairs = new Set();
|
||||
let hops = 0;
|
||||
|
||||
return Object.freeze({
|
||||
/**
|
||||
@@ -26,12 +28,23 @@ export function createRedirectLoopGuard() {
|
||||
*/
|
||||
allow(source, target) {
|
||||
const pair = `${source}->${target}`;
|
||||
if (source === target || visitedPairs.has(pair)) return false;
|
||||
if (
|
||||
source === target ||
|
||||
visitedPairs.has(pair) ||
|
||||
hops >= maxHops
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
visitedPairs.add(pair);
|
||||
hops += 1;
|
||||
return true;
|
||||
},
|
||||
reset() {
|
||||
visitedPairs.clear();
|
||||
hops = 0;
|
||||
},
|
||||
get hopCount() {
|
||||
return hops;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { getRoute } from "../../contracts/routes.js";
|
||||
import { ROUTE_RUNTIME_CONTRACT } from "../../contracts/route-runtime-contract.js";
|
||||
|
||||
export type RouteId = keyof typeof ROUTE_RUNTIME_CONTRACT;
|
||||
|
||||
const emptyCodec = z.object({}).strict();
|
||||
const notFoundSplatCodec = z.object({ "*": z.string().optional() }).strict();
|
||||
const sampleResourceListQuery = z
|
||||
.object({
|
||||
cursor: z.string().min(1).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(100).default(20),
|
||||
tags: z
|
||||
.preprocess(
|
||||
(value) =>
|
||||
value === undefined
|
||||
? undefined
|
||||
: Array.isArray(value)
|
||||
? value
|
||||
: [value],
|
||||
z.array(z.string().trim().min(1)),
|
||||
)
|
||||
.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const codecs = {
|
||||
none: emptyCodec,
|
||||
NotFoundSplat: notFoundSplatCodec,
|
||||
SampleResourceListQuery: sampleResourceListQuery,
|
||||
} as const;
|
||||
|
||||
export type ParsedRouteInput = Readonly<{
|
||||
routeId: RouteId;
|
||||
params: Readonly<Record<string, unknown>>;
|
||||
search: Readonly<Record<string, unknown>>;
|
||||
}>;
|
||||
|
||||
export type RouteInputResult =
|
||||
| Readonly<{ success: true; data: ParsedRouteInput }>
|
||||
| Readonly<{
|
||||
success: false;
|
||||
code: "ROUTE_PARAMS_INVALID" | "ROUTE_SEARCH_INVALID";
|
||||
}>;
|
||||
|
||||
export function parseRouteInput(
|
||||
routeId: RouteId,
|
||||
rawParams: Readonly<Record<string, string | undefined>>,
|
||||
rawSearch: URLSearchParams,
|
||||
): RouteInputResult {
|
||||
const runtime = ROUTE_RUNTIME_CONTRACT[routeId];
|
||||
const params = codecs[runtime.paramsCodec].safeParse(rawParams);
|
||||
if (!params.success) {
|
||||
return { success: false, code: "ROUTE_PARAMS_INVALID" };
|
||||
}
|
||||
const search = codecs[runtime.searchCodec].safeParse(
|
||||
searchRecord(rawSearch),
|
||||
);
|
||||
if (!search.success) {
|
||||
return { success: false, code: "ROUTE_SEARCH_INVALID" };
|
||||
}
|
||||
const parsedParams: Record<string, unknown> = { ...params.data };
|
||||
const parsedSearch: Record<string, unknown> = { ...search.data };
|
||||
return {
|
||||
success: true,
|
||||
data: Object.freeze({
|
||||
routeId,
|
||||
params: Object.freeze(parsedParams),
|
||||
search: Object.freeze(parsedSearch),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildRouteUrl(
|
||||
routeId: RouteId,
|
||||
input: Readonly<{
|
||||
params?: Readonly<Record<string, unknown>>;
|
||||
search?: Readonly<Record<string, unknown>>;
|
||||
}> = {},
|
||||
): string {
|
||||
const definition = getRoute(routeId);
|
||||
if (definition.path === "*") {
|
||||
throw new TypeError("The not-found route cannot build a canonical URL");
|
||||
}
|
||||
const runtime = ROUTE_RUNTIME_CONTRACT[routeId];
|
||||
const params = codecs[runtime.paramsCodec].parse(input.params ?? {});
|
||||
const search = codecs[runtime.searchCodec].parse(input.search ?? {});
|
||||
const parsedParams: Record<string, unknown> = { ...params };
|
||||
const parsedSearch: Record<string, unknown> = { ...search };
|
||||
let path = definition.path;
|
||||
path = path.replace(
|
||||
/:([A-Za-z][A-Za-z0-9_]*)|\{([A-Za-z][A-Za-z0-9_]*)\}/g,
|
||||
(_token, colonName: string | undefined, braceName: string | undefined) => {
|
||||
const name = colonName ?? braceName ?? "";
|
||||
const value = parsedParams[name];
|
||||
if (typeof value !== "string" && typeof value !== "number") {
|
||||
throw new TypeError(`Missing route path parameter: ${name}`);
|
||||
}
|
||||
return encodeURIComponent(String(value));
|
||||
},
|
||||
);
|
||||
const query = new URLSearchParams();
|
||||
for (const key of Object.keys(parsedSearch).sort((left, right) =>
|
||||
left.localeCompare(right),
|
||||
)) {
|
||||
const value = parsedSearch[key];
|
||||
if (value === undefined || value === null) continue;
|
||||
for (const item of Array.isArray(value) ? value : [value]) {
|
||||
query.append(key, String(item));
|
||||
}
|
||||
}
|
||||
const serialized = query.toString();
|
||||
return serialized ? `${path}?${serialized}` : path;
|
||||
}
|
||||
|
||||
function searchRecord(
|
||||
search: URLSearchParams,
|
||||
): Readonly<Record<string, string | readonly string[]>> {
|
||||
const result: Record<string, string | readonly string[]> = {};
|
||||
for (const key of [...new Set(search.keys())].sort((left, right) =>
|
||||
left.localeCompare(right),
|
||||
)) {
|
||||
const values = search.getAll(key);
|
||||
result[key] = values.length === 1 ? values[0] : values;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import {
|
||||
lazy,
|
||||
type ComponentType,
|
||||
type LazyExoticComponent,
|
||||
} from "react";
|
||||
|
||||
import { ROUTE_RUNTIME_CONTRACT } from "../../contracts/route-runtime-contract.js";
|
||||
import type { RouteId } from "./route-codecs.js";
|
||||
|
||||
type RouteModule = Readonly<{ default: ComponentType }>;
|
||||
type RouteRuntime = Readonly<{
|
||||
moduleId: string;
|
||||
Component: LazyExoticComponent<ComponentType>;
|
||||
}>;
|
||||
|
||||
function runtime(
|
||||
routeId: RouteId,
|
||||
load: () => Promise<RouteModule>,
|
||||
): RouteRuntime {
|
||||
return Object.freeze({
|
||||
moduleId: ROUTE_RUNTIME_CONTRACT[routeId].moduleId,
|
||||
Component: lazy(load),
|
||||
});
|
||||
}
|
||||
|
||||
export const ROUTE_RUNTIME = {
|
||||
APP_HOME: runtime("APP_HOME", () => import("../pages/home-page.jsx")),
|
||||
EXAMPLES_UI: runtime(
|
||||
"EXAMPLES_UI",
|
||||
() => import("../examples/ui-gallery-page.jsx"),
|
||||
),
|
||||
EXAMPLES_STATES: runtime(
|
||||
"EXAMPLES_STATES",
|
||||
() => import("../examples/state-gallery-page.jsx"),
|
||||
),
|
||||
EXAMPLES_AUTH: runtime(
|
||||
"EXAMPLES_AUTH",
|
||||
() => import("../examples/auth-example-page.jsx"),
|
||||
),
|
||||
SAMPLE_RESOURCE_LIST: runtime(
|
||||
"SAMPLE_RESOURCE_LIST",
|
||||
() => import("../pages/sample-contract-page.jsx"),
|
||||
),
|
||||
NOT_FOUND: runtime(
|
||||
"NOT_FOUND",
|
||||
() => import("../pages/not-found-page.jsx"),
|
||||
),
|
||||
} satisfies Record<RouteId, RouteRuntime>;
|
||||
Reference in New Issue
Block a user