feat: execute route and release recovery contracts
This commit is contained in:
@@ -5,6 +5,7 @@ import type {
|
||||
RenderFailureReport,
|
||||
} from "./ports/in/application-api.js";
|
||||
import type { ApplicationOutputPorts } from "./ports/out/application-output-ports.js";
|
||||
import { decideChunkRecovery } from "./use-cases/decide-chunk-recovery.js";
|
||||
|
||||
export type { ApplicationApi, ApplicationOutputPorts };
|
||||
|
||||
@@ -64,10 +65,54 @@ export function createApplication(
|
||||
},
|
||||
});
|
||||
|
||||
const recovery = Object.freeze({
|
||||
async recoverChunk(input: {
|
||||
chunkId: string;
|
||||
failureKind: "CHUNK_LOAD_FAILURE" | "DEPLOY_MISMATCH";
|
||||
}) {
|
||||
try {
|
||||
const current = await outputPorts.releaseInfo.getCurrent();
|
||||
const active = await outputPorts.releaseInfo.refresh();
|
||||
if (!active.routeChunks[input.chunkId]) {
|
||||
return {
|
||||
action: "support" as const,
|
||||
reason: "active-chunk-unknown",
|
||||
};
|
||||
}
|
||||
const decision = decideChunkRecovery({
|
||||
failureKind: input.failureKind,
|
||||
manifestLoaded: true,
|
||||
currentBuildId: current.buildId,
|
||||
currentReleaseId: current.releaseId,
|
||||
activeBuildId: active.buildId,
|
||||
activeReleaseId: active.releaseId,
|
||||
storage: outputPorts.preferences,
|
||||
});
|
||||
if (decision.action === "reload-once") {
|
||||
try {
|
||||
outputPorts.navigation.reload();
|
||||
} catch {
|
||||
return {
|
||||
action: "support" as const,
|
||||
reason: "reload-failed",
|
||||
};
|
||||
}
|
||||
}
|
||||
return decision;
|
||||
} catch {
|
||||
return {
|
||||
action: "support" as const,
|
||||
reason: "manifest-unavailable",
|
||||
};
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return Object.freeze({
|
||||
session,
|
||||
preferences,
|
||||
diagnostics,
|
||||
runtime,
|
||||
recovery,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -38,4 +38,13 @@ export type ApplicationApi = Readonly<{
|
||||
runtime: Readonly<{
|
||||
getReleaseSummary(): Promise<ReleaseSummary>;
|
||||
}>;
|
||||
recovery: Readonly<{
|
||||
recoverChunk(input: Readonly<{
|
||||
chunkId: string;
|
||||
failureKind: "CHUNK_LOAD_FAILURE" | "DEPLOY_MISMATCH";
|
||||
}>): Promise<
|
||||
| Readonly<{ action: "reload-once"; releasePair: string }>
|
||||
| Readonly<{ action: "support"; reason: string }>
|
||||
>;
|
||||
}>;
|
||||
}>;
|
||||
|
||||
@@ -15,4 +15,5 @@ export type ApplicationOutputPorts = Readonly<{
|
||||
preferences: StoragePort;
|
||||
diagnostics: TelemetryPort;
|
||||
releaseInfo: ReleaseInfoPort;
|
||||
navigation: Readonly<{ reload(): void }>;
|
||||
}>;
|
||||
|
||||
@@ -9,7 +9,16 @@
|
||||
* apiContractVersion: string,
|
||||
* assetManifestHash: string,
|
||||
* releaseId: string,
|
||||
* builtAt?: string
|
||||
* builtAt?: string,
|
||||
* routeChunks: Record<string, string>
|
||||
* }>,
|
||||
* refresh(): Promise<{
|
||||
* buildId: string,
|
||||
* configSchemaVersion: string,
|
||||
* apiContractVersion: string,
|
||||
* assetManifestHash: string,
|
||||
* releaseId: string,
|
||||
* routeChunks: Record<string, string>
|
||||
* }>
|
||||
* }} ReleaseInfoPort
|
||||
*/
|
||||
|
||||
@@ -1,13 +1,21 @@
|
||||
const RECOVERABLE_KINDS = new Set(["CHUNK_LOAD_FAILURE", "DEPLOY_MISMATCH"]);
|
||||
|
||||
/**
|
||||
* @typedef {{action: "reload-once", releasePair: string} |
|
||||
* {action: "support", reason: string}} ChunkRecoveryDecision
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {{
|
||||
* failureKind: string,
|
||||
* manifestLoaded: boolean,
|
||||
* currentBuildId: string,
|
||||
* currentReleaseId: string,
|
||||
* activeBuildId: string,
|
||||
* activeReleaseId: string,
|
||||
* storage: import("../ports/storage-port.js").StoragePort
|
||||
* }} input
|
||||
* @returns {ChunkRecoveryDecision}
|
||||
*/
|
||||
export function decideChunkRecovery(input) {
|
||||
if (!RECOVERABLE_KINDS.has(input.failureKind)) {
|
||||
@@ -16,13 +24,21 @@ export function decideChunkRecovery(input) {
|
||||
if (!input.manifestLoaded) {
|
||||
return { action: "support", reason: "manifest-unavailable" };
|
||||
}
|
||||
if (input.activeReleaseId === input.currentBuildId) {
|
||||
if (
|
||||
input.activeBuildId === input.currentBuildId &&
|
||||
input.activeReleaseId === input.currentReleaseId
|
||||
) {
|
||||
return { action: "support", reason: "same-release" };
|
||||
}
|
||||
|
||||
const releasePair = `${input.currentBuildId}->${input.activeReleaseId}`;
|
||||
const releasePair =
|
||||
`${input.currentBuildId}/${input.currentReleaseId}` +
|
||||
`->${input.activeBuildId}/${input.activeReleaseId}`;
|
||||
const guard = input.storage.read("CHUNK_RELOAD_GUARD");
|
||||
if (!guard.ok || guard.value === releasePair) {
|
||||
if (!guard.ok) {
|
||||
return { action: "support", reason: "guard-read-failed" };
|
||||
}
|
||||
if (guard.value === releasePair) {
|
||||
return { action: "support", reason: "reload-already-attempted" };
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const version = z.string().regex(/^\d+(?:\.\d+){0,2}$/);
|
||||
const releaseManifestSchema = z
|
||||
export const releaseManifestSchema = z
|
||||
.object({
|
||||
schemaVersion: z.literal(1),
|
||||
appVersion: z.string().min(1),
|
||||
@@ -12,6 +12,7 @@ const releaseManifestSchema = z
|
||||
assetManifestHash: z.string().min(1),
|
||||
releaseId: z.string().min(1),
|
||||
builtAt: z.string().min(1),
|
||||
routeChunks: z.record(z.string().min(1), z.string().min(1)),
|
||||
})
|
||||
.strict();
|
||||
|
||||
@@ -20,7 +21,14 @@ export class ReleaseManifestError extends Error {
|
||||
constructor(code, safe) {
|
||||
super("Release manifest could not be loaded");
|
||||
this.name = "ReleaseManifestError";
|
||||
this.kind = "RELEASE_MANIFEST_FAILURE";
|
||||
this.kind =
|
||||
{
|
||||
MANIFEST_BUILD_MISMATCH: "BUILD_MISMATCH",
|
||||
MANIFEST_CONFIG_SCHEMA_MISMATCH: "CONFIG_MISMATCH",
|
||||
MANIFEST_API_CONTRACT_MISMATCH: "API_CONTRACT_MISMATCH",
|
||||
MANIFEST_RELEASE_MISMATCH: "RELEASE_MISMATCH",
|
||||
MANIFEST_ASSET_MISMATCH: "ASSET_MISMATCH",
|
||||
}[code] ?? "RELEASE_MANIFEST_FAILURE";
|
||||
this.code = code;
|
||||
this.safe = Object.freeze({
|
||||
kind: this.kind,
|
||||
@@ -33,75 +41,98 @@ export class ReleaseManifestError extends Error {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Awaited<ReturnType<typeof import("./load-runtime-config.js").loadRuntimeConfig>>} runtime
|
||||
* @param {{fetcher?: typeof fetch}} [options]
|
||||
* Fetches and validates the active manifest without imposing the current
|
||||
* build tuple. Chunk recovery uses this no-store view to detect a new release.
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {{
|
||||
* fetcher?: typeof fetch,
|
||||
* buildId: string,
|
||||
* releaseId?: string
|
||||
* }} options
|
||||
*/
|
||||
export async function loadReleaseManifest(runtime, options = {}) {
|
||||
export async function fetchReleaseManifest(url, options) {
|
||||
const fetcher = options.fetcher ?? fetch;
|
||||
let response;
|
||||
try {
|
||||
response = await fetcher(runtime.config.RELEASE_MANIFEST_URL, {
|
||||
response = await fetcher(url, {
|
||||
cache: "no-store",
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
} catch {
|
||||
throw new ReleaseManifestError("MANIFEST_FETCH_FAILED", {
|
||||
buildId: runtime.build.buildId,
|
||||
releaseId: runtime.config.RELEASE_ID,
|
||||
});
|
||||
throw new ReleaseManifestError("MANIFEST_FETCH_FAILED", options);
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new ReleaseManifestError("MANIFEST_HTTP_FAILED", {
|
||||
buildId: runtime.build.buildId,
|
||||
releaseId: runtime.config.RELEASE_ID,
|
||||
});
|
||||
throw new ReleaseManifestError("MANIFEST_HTTP_FAILED", options);
|
||||
}
|
||||
|
||||
let raw;
|
||||
try {
|
||||
raw = await response.json();
|
||||
} catch {
|
||||
throw new ReleaseManifestError("MANIFEST_JSON_INVALID", {
|
||||
buildId: runtime.build.buildId,
|
||||
releaseId: runtime.config.RELEASE_ID,
|
||||
});
|
||||
throw new ReleaseManifestError("MANIFEST_JSON_INVALID", options);
|
||||
}
|
||||
const parsed = releaseManifestSchema.safeParse(raw);
|
||||
if (!parsed.success) {
|
||||
throw new ReleaseManifestError("MANIFEST_SCHEMA_INVALID", {
|
||||
throw new ReleaseManifestError("MANIFEST_SCHEMA_INVALID", options);
|
||||
}
|
||||
return Object.freeze(structuredClone(parsed.data));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Awaited<ReturnType<typeof import("./load-runtime-config.js").loadRuntimeConfig>>} runtime
|
||||
* @param {{fetcher?: typeof fetch, expectedAssetManifestHash?: string}} [options]
|
||||
*/
|
||||
export async function loadReleaseManifest(runtime, options = {}) {
|
||||
const manifest = await fetchReleaseManifest(
|
||||
runtime.config.RELEASE_MANIFEST_URL,
|
||||
{
|
||||
fetcher: options.fetcher,
|
||||
buildId: runtime.build.buildId,
|
||||
releaseId: runtime.config.RELEASE_ID,
|
||||
});
|
||||
},
|
||||
);
|
||||
let mismatchCode = null;
|
||||
if (manifest.buildId !== runtime.build.buildId) {
|
||||
mismatchCode = "MANIFEST_BUILD_MISMATCH";
|
||||
}
|
||||
|
||||
const manifest = parsed.data;
|
||||
const mismatches = [];
|
||||
if (manifest.buildId !== runtime.build.buildId) mismatches.push("buildId");
|
||||
if (
|
||||
!mismatchCode &&
|
||||
runtime.config.BUILD_ID &&
|
||||
manifest.buildId !== runtime.config.BUILD_ID
|
||||
) {
|
||||
mismatches.push("runtimeBuildId");
|
||||
mismatchCode = "MANIFEST_BUILD_MISMATCH";
|
||||
}
|
||||
if (
|
||||
!mismatchCode &&
|
||||
manifest.configSchemaVersion !== runtime.config.CONFIG_SCHEMA_VERSION
|
||||
) {
|
||||
mismatches.push("configSchemaVersion");
|
||||
}
|
||||
if (manifest.apiContractVersion !== runtime.config.API_CONTRACT_VERSION) {
|
||||
mismatches.push("apiContractVersion");
|
||||
mismatchCode = "MANIFEST_CONFIG_SCHEMA_MISMATCH";
|
||||
}
|
||||
if (
|
||||
!mismatchCode &&
|
||||
manifest.apiContractVersion !== runtime.config.API_CONTRACT_VERSION
|
||||
) {
|
||||
mismatchCode = "MANIFEST_API_CONTRACT_MISMATCH";
|
||||
}
|
||||
if (
|
||||
!mismatchCode &&
|
||||
runtime.config.RELEASE_ID &&
|
||||
manifest.releaseId !== runtime.config.RELEASE_ID
|
||||
) {
|
||||
mismatches.push("releaseId");
|
||||
mismatchCode = "MANIFEST_RELEASE_MISMATCH";
|
||||
}
|
||||
if (mismatches.length > 0) {
|
||||
throw new ReleaseManifestError("MANIFEST_RUNTIME_MISMATCH", {
|
||||
if (
|
||||
!mismatchCode &&
|
||||
options.expectedAssetManifestHash &&
|
||||
manifest.assetManifestHash !== options.expectedAssetManifestHash
|
||||
) {
|
||||
mismatchCode = "MANIFEST_ASSET_MISMATCH";
|
||||
}
|
||||
if (mismatchCode) {
|
||||
throw new ReleaseManifestError(mismatchCode, {
|
||||
buildId: runtime.build.buildId,
|
||||
releaseId: runtime.config.RELEASE_ID,
|
||||
});
|
||||
}
|
||||
return Object.freeze(structuredClone(manifest));
|
||||
return manifest;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
} from "../adapters/query-cache/tanstack-query-cache.js";
|
||||
import { createBrowserStorageAdapter } from "../adapters/storage/browser-storage-adapter.js";
|
||||
import { createTelemetryAdapter } from "../adapters/telemetry/best-effort-telemetry.js";
|
||||
import { fetchReleaseManifest } from "./load-release-manifest.js";
|
||||
|
||||
/**
|
||||
* @param {Record<string, unknown>} host
|
||||
@@ -97,6 +98,23 @@ export async function createRuntimeAdapters(context) {
|
||||
async getCurrent() {
|
||||
return structuredClone(context.release);
|
||||
},
|
||||
async refresh() {
|
||||
return fetchReleaseManifest(config.RELEASE_MANIFEST_URL, {
|
||||
fetcher: context.fetcher,
|
||||
buildId: context.release.buildId,
|
||||
releaseId: context.release.releaseId,
|
||||
});
|
||||
},
|
||||
});
|
||||
const navigation = Object.freeze({
|
||||
reload() {
|
||||
const location =
|
||||
/** @type {{reload?: () => void} | undefined} */ (host.location);
|
||||
if (typeof location?.reload !== "function") {
|
||||
throw new Error("Browser reload is unavailable");
|
||||
}
|
||||
location.reload();
|
||||
},
|
||||
});
|
||||
|
||||
return Object.freeze({
|
||||
@@ -105,6 +123,7 @@ export async function createRuntimeAdapters(context) {
|
||||
preferences: storage,
|
||||
diagnostics: telemetry,
|
||||
releaseInfo,
|
||||
navigation,
|
||||
}),
|
||||
infrastructure: Object.freeze({
|
||||
queryClient,
|
||||
|
||||
@@ -111,6 +111,41 @@ export const ERROR_REGISTRY = Object.freeze({
|
||||
"reload-once",
|
||||
"release.mismatch.detected",
|
||||
),
|
||||
BUILD_MISMATCH: row(
|
||||
"BUILD_MISMATCH",
|
||||
false,
|
||||
"error",
|
||||
"reload-once",
|
||||
"release.mismatch.detected",
|
||||
),
|
||||
CONFIG_MISMATCH: row(
|
||||
"CONFIG_MISMATCH",
|
||||
false,
|
||||
"error",
|
||||
"contact-support",
|
||||
"app.boot.failed",
|
||||
),
|
||||
API_CONTRACT_MISMATCH: row(
|
||||
"API_CONTRACT_MISMATCH",
|
||||
false,
|
||||
"error",
|
||||
"contact-support",
|
||||
"app.boot.failed",
|
||||
),
|
||||
RELEASE_MISMATCH: row(
|
||||
"RELEASE_MISMATCH",
|
||||
false,
|
||||
"error",
|
||||
"reload-once",
|
||||
"release.mismatch.detected",
|
||||
),
|
||||
ASSET_MISMATCH: row(
|
||||
"ASSET_MISMATCH",
|
||||
false,
|
||||
"error",
|
||||
"reload-once",
|
||||
"release.mismatch.detected",
|
||||
),
|
||||
STORAGE_UNAVAILABLE: row(
|
||||
"STORAGE_UNAVAILABLE",
|
||||
false,
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* @typedef {"none" | "NotFoundSplat" | "SampleResourceListQuery"} RouteCodecId
|
||||
*/
|
||||
|
||||
/** @param {Readonly<{routeId: string, moduleId: string, paramsCodec: RouteCodecId, searchCodec: RouteCodecId}>} value */
|
||||
const runtime = (value) => Object.freeze(value);
|
||||
|
||||
export const ROUTE_RUNTIME_CONTRACT = Object.freeze({
|
||||
APP_HOME: runtime({
|
||||
routeId: "APP_HOME",
|
||||
moduleId: "home-page",
|
||||
paramsCodec: "none",
|
||||
searchCodec: "none",
|
||||
}),
|
||||
EXAMPLES_UI: runtime({
|
||||
routeId: "EXAMPLES_UI",
|
||||
moduleId: "ui-gallery-page",
|
||||
paramsCodec: "none",
|
||||
searchCodec: "none",
|
||||
}),
|
||||
EXAMPLES_STATES: runtime({
|
||||
routeId: "EXAMPLES_STATES",
|
||||
moduleId: "state-gallery-page",
|
||||
paramsCodec: "none",
|
||||
searchCodec: "none",
|
||||
}),
|
||||
EXAMPLES_AUTH: runtime({
|
||||
routeId: "EXAMPLES_AUTH",
|
||||
moduleId: "auth-example-page",
|
||||
paramsCodec: "none",
|
||||
searchCodec: "none",
|
||||
}),
|
||||
SAMPLE_RESOURCE_LIST: runtime({
|
||||
routeId: "SAMPLE_RESOURCE_LIST",
|
||||
moduleId: "sample-contract-page",
|
||||
paramsCodec: "none",
|
||||
searchCodec: "SampleResourceListQuery",
|
||||
}),
|
||||
NOT_FOUND: runtime({
|
||||
routeId: "NOT_FOUND",
|
||||
moduleId: "not-found-page",
|
||||
paramsCodec: "NotFoundSplat",
|
||||
searchCodec: "none",
|
||||
}),
|
||||
});
|
||||
@@ -86,7 +86,7 @@ export const ROUTE_REGISTRY = Object.freeze({
|
||||
NOT_FOUND: route({
|
||||
routeId: "NOT_FOUND",
|
||||
path: "*",
|
||||
paramsSchema: null,
|
||||
paramsSchema: "NotFoundSplat",
|
||||
searchSchema: null,
|
||||
access: "public",
|
||||
loadingSurface: "none",
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import {
|
||||
Component,
|
||||
type ErrorInfo,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
|
||||
type RecoveryResult =
|
||||
| Readonly<{ action: "reload-once"; releasePair: string }>
|
||||
| Readonly<{ action: "support"; reason: string }>;
|
||||
|
||||
type Props = Readonly<{
|
||||
children: ReactNode;
|
||||
chunkId: string;
|
||||
recover(input: Readonly<{
|
||||
chunkId: string;
|
||||
failureKind: "CHUNK_LOAD_FAILURE";
|
||||
}>): Promise<RecoveryResult>;
|
||||
}>;
|
||||
|
||||
type State = Readonly<{
|
||||
error: unknown | null;
|
||||
recovery: "idle" | "checking" | "reload-requested" | "support";
|
||||
reason?: string;
|
||||
}>;
|
||||
|
||||
export function isChunkLoadFailure(error: unknown): boolean {
|
||||
if (!(error instanceof Error)) return false;
|
||||
const value = `${error.name} ${error.message}`.toLowerCase();
|
||||
return (
|
||||
value.includes("chunkloaderror") ||
|
||||
value.includes("loading chunk") ||
|
||||
value.includes("dynamically imported module") ||
|
||||
value.includes("failed to fetch module script")
|
||||
);
|
||||
}
|
||||
|
||||
export class ChunkRecoveryBoundary extends Component<Props, State> {
|
||||
state: State = { error: null, recovery: "idle" };
|
||||
|
||||
static getDerivedStateFromError(error: unknown): State {
|
||||
return { error, recovery: "checking" };
|
||||
}
|
||||
|
||||
componentDidCatch(error: unknown, _info: ErrorInfo) {
|
||||
if (!isChunkLoadFailure(error)) return;
|
||||
void this.props
|
||||
.recover({
|
||||
chunkId: this.props.chunkId,
|
||||
failureKind: "CHUNK_LOAD_FAILURE",
|
||||
})
|
||||
.then((result) => {
|
||||
this.setState({
|
||||
error,
|
||||
recovery:
|
||||
result.action === "reload-once"
|
||||
? "reload-requested"
|
||||
: "support",
|
||||
...(result.action === "support" ? { reason: result.reason } : {}),
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
this.setState({
|
||||
error,
|
||||
recovery: "support",
|
||||
reason: "recovery-controller-failed",
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
render() {
|
||||
const { error, recovery, reason } = this.state;
|
||||
if (error && !isChunkLoadFailure(error)) throw error;
|
||||
if (error && recovery === "checking") {
|
||||
return (
|
||||
<section className="ui-page" aria-live="polite" aria-busy="true">
|
||||
새 릴리스 정보를 확인하고 있습니다.
|
||||
</section>
|
||||
);
|
||||
}
|
||||
if (error && recovery === "reload-requested") {
|
||||
return (
|
||||
<section className="ui-page" aria-live="polite">
|
||||
새 버전으로 한 번만 전환합니다.
|
||||
</section>
|
||||
);
|
||||
}
|
||||
if (error && recovery === "support") {
|
||||
return (
|
||||
<section className="ui-page" role="alert" data-recovery-reason={reason}>
|
||||
<h1>화면 자산을 복구하지 못했습니다.</h1>
|
||||
<p>문제가 계속되면 배포 상태와 지원 참조 정보를 확인해 주세요.</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { Component } from "react";
|
||||
* boundaryName: string,
|
||||
* routeId: string,
|
||||
* buildId: string,
|
||||
* resetKey?: string,
|
||||
* onRenderFailure?: (report: import("../../application/ports/in/application-api.js").RenderFailureReport) => void,
|
||||
* fallback?: React.ReactNode
|
||||
* }} RenderBoundaryProps
|
||||
@@ -37,6 +38,16 @@ export class RenderErrorBoundary extends Component {
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {RenderBoundaryProps} previous */
|
||||
componentDidUpdate(previous) {
|
||||
if (
|
||||
this.state.hasError &&
|
||||
previous.resetKey !== this.props.resetKey
|
||||
) {
|
||||
this.setState({ hasError: false });
|
||||
}
|
||||
}
|
||||
|
||||
reset = () => {
|
||||
this.setState({ hasError: false });
|
||||
};
|
||||
|
||||
@@ -8,6 +8,11 @@ const ERROR_MESSAGES = Object.freeze({
|
||||
"error.rate_limited": "요청이 많습니다. 잠시 후 다시 시도해 주세요.",
|
||||
"error.server_failure": "요청을 완료하지 못했습니다.",
|
||||
"error.chunk_load_failure": "새 화면 파일을 불러오지 못했습니다.",
|
||||
"error.build_mismatch": "현재 화면과 활성 빌드가 일치하지 않습니다.",
|
||||
"error.config_mismatch": "런타임 설정 버전이 현재 화면과 일치하지 않습니다.",
|
||||
"error.api_contract_mismatch": "API 계약 버전이 현재 화면과 일치하지 않습니다.",
|
||||
"error.release_mismatch": "현재 화면과 활성 릴리스가 일치하지 않습니다.",
|
||||
"error.asset_mismatch": "화면 자산 구성이 현재 릴리스와 일치하지 않습니다.",
|
||||
"error.render_failure": "화면을 표시하지 못했습니다.",
|
||||
"error.unknown_failure": "예상하지 못한 문제가 발생했습니다.",
|
||||
});
|
||||
|
||||
@@ -11,7 +11,6 @@ export function PageHeader({ title, description, eyebrow }) {
|
||||
const headingRef = useRef(/** @type {HTMLHeadingElement | null} */ (null));
|
||||
|
||||
useEffect(() => {
|
||||
document.title = `${title} · Frontend Skeleton`;
|
||||
headingRef.current?.focus();
|
||||
}, [title]);
|
||||
|
||||
|
||||
@@ -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