chore: initialize from frontend template 4dc033c
This commit is contained in:
@@ -0,0 +1,341 @@
|
||||
import {
|
||||
type ReactNode,
|
||||
Suspense,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import {
|
||||
createBrowserRouter,
|
||||
RouterProvider,
|
||||
type RouteObject,
|
||||
useLocation,
|
||||
useNavigate,
|
||||
useParams,
|
||||
useSearchParams,
|
||||
} from "react-router-dom";
|
||||
|
||||
import {
|
||||
getRoute,
|
||||
ROUTE_REGISTRY,
|
||||
} from "../../features/installed-feature-contracts.ts";
|
||||
import type { RouteDefinition } from "../../contracts/routes.ts";
|
||||
import {
|
||||
FeatureBoundary,
|
||||
RouteBoundary,
|
||||
} from "../boundaries/render-error-boundary.tsx";
|
||||
import { ChunkRecoveryBoundary } from "../boundaries/chunk-recovery-boundary.tsx";
|
||||
import { Button, PageHeader } from "../design-system/index.ts";
|
||||
import { LocaleProvider, useLocale } from "../i18n/index.ts";
|
||||
import { AppShell } from "../layouts/app-shell.tsx";
|
||||
import { useApplication } from "../providers/application-provider.tsx";
|
||||
import { SessionProvider, useSession } from "../providers/session-provider.tsx";
|
||||
import { ThemeProvider } from "../providers/theme-provider.tsx";
|
||||
import {
|
||||
createRedirectLoopGuard,
|
||||
decideRouteAccess,
|
||||
} from "./navigation-policy.ts";
|
||||
import {
|
||||
buildRouteUrl,
|
||||
parseRouteInput,
|
||||
type RouteId,
|
||||
} from "./route-codecs.ts";
|
||||
import { ROUTE_RUNTIME } from "../../features/installed-feature-runtimes.tsx";
|
||||
import type { ParsedRouteInput } from "./route-contract.ts";
|
||||
import { RouteInputProvider } from "./route-input.tsx";
|
||||
|
||||
function RouteLoadingSurface({ definition }: { definition: RouteDefinition }) {
|
||||
const { message, resolve } = useLocale();
|
||||
const title = resolve(`route.${definition.routeId}.title`);
|
||||
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>{message("route.loading")}</p>
|
||||
<span className="visually-hidden">
|
||||
{message("route.loadingNamed", { title })}
|
||||
</span>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function RouteFailureSurface({
|
||||
definition,
|
||||
}: {
|
||||
definition?: RouteDefinition;
|
||||
}) {
|
||||
const { message } = useLocale();
|
||||
return (
|
||||
<section
|
||||
className="ui-page"
|
||||
data-surface={definition?.errorSurface ?? "route-boundary"}
|
||||
>
|
||||
<PageHeader
|
||||
title={message("route.failure.title")}
|
||||
description={message("route.failure.description")}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function InvalidRouteSurface({ code }: { code: string }) {
|
||||
const { message } = useLocale();
|
||||
return (
|
||||
<section className="ui-page" data-surface="invalid-route">
|
||||
<PageHeader
|
||||
title={message("route.invalid.title")}
|
||||
description={message("route.invalid.description")}
|
||||
/>
|
||||
<p data-route-error={code}>{message("route.invalid.action")}</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function RouteLifecycle({
|
||||
definition,
|
||||
buildId,
|
||||
}: {
|
||||
definition: RouteDefinition;
|
||||
buildId: string;
|
||||
}) {
|
||||
const location = useLocation();
|
||||
const { message, resolve } = useLocale();
|
||||
const { diagnostics } = useApplication();
|
||||
useEffect(() => {
|
||||
document.title = message("route.documentTitle", {
|
||||
title: resolve(`route.${definition.routeId}.title`),
|
||||
appName: message("common.appName"),
|
||||
});
|
||||
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.
|
||||
}
|
||||
diagnostics.reportRouteChanged({
|
||||
routeId: definition.routeId,
|
||||
buildId,
|
||||
});
|
||||
}, [
|
||||
buildId,
|
||||
definition,
|
||||
diagnostics,
|
||||
location.key,
|
||||
location.pathname,
|
||||
message,
|
||||
resolve,
|
||||
]);
|
||||
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.reset();
|
||||
} else if (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 { message } = useLocale();
|
||||
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={message("route.auth.integration.title")}
|
||||
description={message("route.auth.integration.description")}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
const recovering = decision.action === "wait-for-session";
|
||||
return (
|
||||
<section className="ui-page" data-surface="authentication-required">
|
||||
<PageHeader
|
||||
title={
|
||||
recovering
|
||||
? message("route.auth.recovering.title")
|
||||
: message("route.auth.required.title")
|
||||
}
|
||||
description={
|
||||
recovering
|
||||
? message("route.auth.recovering.description")
|
||||
: message("route.auth.required.description")
|
||||
}
|
||||
/>
|
||||
<Button
|
||||
disabled={pending}
|
||||
onClick={() => void continueSession()}
|
||||
>
|
||||
{pending
|
||||
? message("common.processing")
|
||||
: recovering
|
||||
? message("action.recoverSession")
|
||||
: message("action.signIn")}
|
||||
</Button>
|
||||
{failed ? (
|
||||
<p className="ui-terminal-error" role="alert">
|
||||
{message("shell.session.actionFailed")}
|
||||
</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 = (
|
||||
<RouteInputProvider input={parsed.data}>
|
||||
<CanonicalRouteRedirect input={parsed.data} />
|
||||
<RouteLifecycle definition={definition} buildId={buildId} />
|
||||
<Suspense fallback={<RouteLoadingSurface definition={definition} />}>
|
||||
<ChunkRecoveryBoundary
|
||||
chunkId={definition.chunkId}
|
||||
recover={recovery.recoverChunk}
|
||||
>
|
||||
<runtime.Component />
|
||||
</ChunkRecoveryBoundary>
|
||||
</Suspense>
|
||||
</RouteInputProvider>
|
||||
);
|
||||
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 (
|
||||
<LocaleProvider>
|
||||
<ThemeProvider>
|
||||
<SessionProvider>
|
||||
<RouterProvider router={router} />
|
||||
</SessionProvider>
|
||||
</ThemeProvider>
|
||||
</LocaleProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { SessionState } from "../../application/ports/in/application-api.ts";
|
||||
import { getRoute } from "../../features/installed-feature-contracts.ts";
|
||||
|
||||
export type RouteAccessDecision =
|
||||
| Readonly<{ allowed: true; action: "none" }>
|
||||
| Readonly<{
|
||||
allowed: false;
|
||||
action: "wait-for-session" | "show-sign-in";
|
||||
}>;
|
||||
|
||||
export function decideRouteAccess(
|
||||
routeId: string,
|
||||
sessionState: SessionState,
|
||||
): RouteAccessDecision {
|
||||
const route = getRoute(routeId);
|
||||
if (route.access === "public") return { allowed: true, action: "none" };
|
||||
if (sessionState === "authenticated") {
|
||||
return { allowed: true, action: "none" };
|
||||
}
|
||||
if (sessionState === "recovery-pending") {
|
||||
return { allowed: false, action: "wait-for-session" };
|
||||
}
|
||||
return { allowed: false, action: "show-sign-in" };
|
||||
}
|
||||
|
||||
export function createRedirectLoopGuard(maxHops: number = 5) {
|
||||
const visitedPairs = new Set<string>();
|
||||
let hops = 0;
|
||||
|
||||
return Object.freeze({
|
||||
allow(source: string, target: string): boolean {
|
||||
const pair = `${source}->${target}`;
|
||||
if (source === target || visitedPairs.has(pair) || hops >= maxHops) {
|
||||
return false;
|
||||
}
|
||||
visitedPairs.add(pair);
|
||||
hops += 1;
|
||||
return true;
|
||||
},
|
||||
reset(): void {
|
||||
visitedPairs.clear();
|
||||
hops = 0;
|
||||
},
|
||||
get hopCount(): number {
|
||||
return hops;
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const PLATFORM_ROUTE_CODECS = {
|
||||
none: z.object({}).strict(),
|
||||
NotFoundSplat: z.object({ "*": z.string().optional() }).strict(),
|
||||
} as const;
|
||||
@@ -0,0 +1,102 @@
|
||||
import { getRoute, ROUTE_RUNTIME_CONTRACT } from "../../features/installed-feature-contracts.ts";
|
||||
import { ROUTE_CODECS } from "../../features/installed-feature-runtimes.tsx";
|
||||
import type {
|
||||
ParsedRouteInput,
|
||||
RouteId,
|
||||
RouteInputResult,
|
||||
} from "./route-contract.ts";
|
||||
|
||||
export type { ParsedRouteInput, RouteId, RouteInputResult };
|
||||
|
||||
function codecById(codecId: string) {
|
||||
const codec = ROUTE_CODECS[codecId as keyof typeof ROUTE_CODECS];
|
||||
if (!codec) throw new TypeError(`Unregistered route codec: ${codecId}`);
|
||||
return codec;
|
||||
}
|
||||
|
||||
export function parseRouteInput(
|
||||
routeId: RouteId,
|
||||
rawParams: Readonly<Record<string, string | undefined>>,
|
||||
rawSearch: URLSearchParams,
|
||||
): RouteInputResult {
|
||||
const runtime = ROUTE_RUNTIME_CONTRACT[routeId];
|
||||
const params = codecById(runtime.paramsCodec).safeParse(rawParams);
|
||||
if (!params.success) {
|
||||
return { success: false, code: "ROUTE_PARAMS_INVALID" };
|
||||
}
|
||||
const search = codecById(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 = codecById(runtime.paramsCodec).parse(input.params ?? {});
|
||||
const search = codecById(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: string,
|
||||
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,16 @@
|
||||
import { ROUTE_RUNTIME_CONTRACT } from "../../features/installed-feature-contracts.ts";
|
||||
|
||||
export type RouteId = keyof typeof ROUTE_RUNTIME_CONTRACT;
|
||||
|
||||
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";
|
||||
}>;
|
||||
@@ -0,0 +1,29 @@
|
||||
import {
|
||||
createContext,
|
||||
type ReactNode,
|
||||
useContext,
|
||||
} from "react";
|
||||
|
||||
import type { ParsedRouteInput } from "./route-contract.ts";
|
||||
|
||||
const RouteInputContext = createContext<ParsedRouteInput | null>(null);
|
||||
|
||||
export function RouteInputProvider({
|
||||
input,
|
||||
children,
|
||||
}: Readonly<{
|
||||
input: ParsedRouteInput;
|
||||
children: ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<RouteInputContext.Provider value={input}>
|
||||
{children}
|
||||
</RouteInputContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useRouteInput(): ParsedRouteInput {
|
||||
const input = useContext(RouteInputContext);
|
||||
if (!input) throw new Error("Registered route input is required");
|
||||
return input;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import {
|
||||
lazy,
|
||||
type ComponentType,
|
||||
type LazyExoticComponent,
|
||||
} from "react";
|
||||
|
||||
import { PLATFORM_ROUTE_RUNTIME_CONTRACT } from "../../contracts/route-runtime-contract.ts";
|
||||
|
||||
type RouteModule = Readonly<{ default: ComponentType }>;
|
||||
type RouteRuntime = Readonly<{
|
||||
moduleId: string;
|
||||
Component: LazyExoticComponent<ComponentType>;
|
||||
}>;
|
||||
|
||||
function runtime(
|
||||
routeId: keyof typeof PLATFORM_ROUTE_RUNTIME_CONTRACT,
|
||||
load: () => Promise<RouteModule>,
|
||||
): RouteRuntime {
|
||||
return Object.freeze({
|
||||
moduleId: PLATFORM_ROUTE_RUNTIME_CONTRACT[routeId].moduleId,
|
||||
Component: lazy(load),
|
||||
});
|
||||
}
|
||||
|
||||
export const PLATFORM_ROUTE_RUNTIME = {
|
||||
APP_HOME: runtime("APP_HOME", () => import("../pages/home-page.tsx")),
|
||||
EXAMPLES_PLATFORM: runtime(
|
||||
"EXAMPLES_PLATFORM",
|
||||
() => import("../examples/platform-overview-page.tsx"),
|
||||
),
|
||||
EXAMPLES_UI: runtime(
|
||||
"EXAMPLES_UI",
|
||||
() => import("../examples/ui-gallery-page.tsx"),
|
||||
),
|
||||
EXAMPLES_STATES: runtime(
|
||||
"EXAMPLES_STATES",
|
||||
() => import("../examples/state-gallery-page.tsx"),
|
||||
),
|
||||
EXAMPLES_AUTH: runtime(
|
||||
"EXAMPLES_AUTH",
|
||||
() => import("../examples/auth-example-page.tsx"),
|
||||
),
|
||||
NOT_FOUND: runtime(
|
||||
"NOT_FOUND",
|
||||
() => import("../pages/not-found-page.tsx"),
|
||||
),
|
||||
} satisfies Record<keyof typeof PLATFORM_ROUTE_RUNTIME_CONTRACT, RouteRuntime>;
|
||||
Reference in New Issue
Block a user