Files
DongHyeonka c80320dfc7 chore: sync the frontend template from ebea300 to af3d8e6
Carries 359 template commits, tag v0.2.0 plus one documentation commit: the
generator-built feature index with its app, bounded-context and feature
declarations, the src/platform kernel and scale tooling, the 2026-09-24 src
review fixes, and the 2026-09-25 maturity review round with its CHANGELOG
[보안]/[계약] rows. 691 of the 824 template paths are applied, 85 of them
merged with product changes; 127 are not carried.

Product identity is unchanged: name, version 0.1.0, routes, design and the
TechLog domain.

Three decisions worth naming. TechLog stays composed directly, as the last
two syncs recorded; its directory carries a NOT_INSTALLED marker that says so,
and every installed-* composer takes the template's projection with TechLog
added on top. The reference sample is no longer installed: the template now
installs a feature only through feature-module.ts and context-routes.ts,
which load the screens this product deleted, so its three operations, six
schemas and one topic leave the registries, recorded as registry change
evidence. And AppRouter mounts the platform and TechLog routes only; the
template's bounded-context route gateway waits for a generator-installed
feature.

Required fixes: readSubject on the BFF session owner (without it every HTTP
Studio session would close as integration-failed), zod through the facade in
nine TechLog files, noUnusedLocals, and public/config.json written out to
match the local profile. Derived baselines were recomputed after reproducing
both sides' values: CI contract 101 commands / 106 references / 141
artifacts, gate shape c9adcf85; registry approval 2dc6c3a3; the runtime
config schema baseline equals the schema at 8210d48.

Verified here: types, lint, architecture, adapter inventory, CI contract,
i18n, design system, diagnostics, browser security, dev release manifest,
TechLog contract and build pass; 220 component, 155 integration, 15
contract, 418 TechLog, 43 reference-feature, 18 recipe and 46
release-coherence tests pass, and 2381 of 2383 unit tests. Reproduced at
8210d48 first and unchanged: check:registries (byte-identical),
test:runtime-schema, verify:documentation. Brought by the template and
escalated rather than suppressed: check:request-fanout on TechLog's cursor
pagination, check:remediation-ledger (fails upstream too), the shared-chunk
hash test, and the registry-dependent sample removal and second-feature
tests. Playwright suites were not run.

Full record, the five open questions and the follow-ups in
docs/operations/template-sync-2026-09-29.md.

(cherry picked from commit b2170cf265dea45dc9cc05d3c61e627e97f31cdb)
2026-11-12 08:28:54 +09:00

512 lines
17 KiB
TypeScript

// @vitest-environment jsdom
import { act, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, expectTypeOf, it, vi } from "vitest";
import { z } from "zod";
import {
createMemoryRouter,
matchRoutes,
Outlet,
RouterProvider,
} from "react-router-dom";
import { createExternalAuthSessionAdapter } from "../../src/adapters/auth/external-session-adapter.ts";
import { createAnonymousSessionAdapter } from "../../src/adapters/auth/external-session-adapter.ts";
import type { ApplicationOutputPorts } from "../../src/application/create-application.ts";
import { createTechLogFeatureInstalledInput } from "../../src/features/tech-log/adapters/create-tech-log-feature-input.ts";
import { MOCK_STUDIO_INSTALL_CONTEXT } from "../helpers/studio-install-context.ts";
import { TECH_LOG_FEATURE_ID } from "../../src/features/tech-log/application/tech-log-feature-input.ts";
import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx";
import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx";
import { renderWithQueryProviders } from "../helpers/query-providers.tsx";
import {
AppRouter,
createGroupedRouteObjects,
} from "../../src/presentation/routes/app-router.tsx";
import { createTestApplication } from "../helpers/create-test-application.ts";
import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts";
import {
ROUTE_CODECS,
ROUTE_RUNTIME,
} from "../../src/features/installed-feature-runtimes.tsx";
import { LocaleProvider } from "../../src/presentation/i18n/index.ts";
import { SessionProvider } from "../../src/presentation/providers/session-provider.tsx";
import { ThemeProvider } from "../../src/presentation/providers/theme-provider.tsx";
import { useRouteInput } from "../../src/presentation/routes/route-input.tsx";
function StudioFallbackFixture() {
const input = useRouteInput();
return <h1>{String(input.params["*"])}</h1>;
}
const reviewFixtureCodecs = Object.freeze({
ReviewFixtureParams: z
.object({ reviewId: z.string().min(1) })
.strict(),
ReviewFixtureSearch: z
.object({
filter: z.preprocess(
(value) => (Array.isArray(value) ? value[0] : value),
z.string().trim().min(1).optional(),
),
})
.strip(),
});
const groupedFixtureCodecs = Object.freeze({
none: ROUTE_CODECS.none,
NotFoundSplat: ROUTE_CODECS.NotFoundSplat,
});
const reviewFixtureRegistry = Object.freeze({
REVIEW_FIXTURE: Object.freeze({
...ROUTE_REGISTRY.TECH_LOG_HOME,
routeId: "REVIEW_FIXTURE",
path: "/review/:reviewId",
paramsSchema: "ReviewFixtureParams",
searchSchema: "ReviewFixtureSearch",
}),
});
function ReviewRouteFixture() {
const input = useRouteInput<"REVIEW_FIXTURE">();
expectTypeOf(input.routeId).toEqualTypeOf<"REVIEW_FIXTURE">();
return (
<section>
<h1>{input.routeId}</h1>
<p data-testid="review-param">{String(input.params.reviewId)}</p>
<p data-testid="review-search">{JSON.stringify(input.search)}</p>
</section>
);
}
const reviewFixtureRuntime = Object.freeze({
REVIEW_FIXTURE: Object.freeze({
moduleId: "review-fixture",
Component: ReviewRouteFixture,
}),
});
function compileTimeGroupedRouteContract() {
// @ts-expect-error A grouped route composition must provide its codec registry.
createGroupedRouteObjects(
reviewFixtureRegistry,
reviewFixtureRuntime,
{ PUBLIC: <Outlet />, STUDIO: <Outlet /> },
"type-test-build",
);
return createGroupedRouteObjects(
reviewFixtureRegistry,
reviewFixtureRuntime,
{ PUBLIC: <Outlet />, STUDIO: <Outlet /> },
"type-test-build",
reviewFixtureCodecs,
);
}
void compileTimeGroupedRouteContract;
/**
* Studio routes are `session-required`, so a Studio assertion needs a session
* that says so — with the anonymous adapter the router correctly renders the
* sign-in surface instead of the page, which is what the gate is for.
*/
function createSignedInSessionAdapter() {
return createExternalAuthSessionAdapter({
readState: () => "authenticated" as const,
subscribe: () => () => {},
beginSignIn: async () => {},
signOut: async () => {},
attachCredential: async () => ({ headers: {} }),
recoverSession: async () => "restored" as const,
notifyUnauthenticated: () => {},
// Template sync (af3d8e6): the external owner must name its subject.
readSubject: () => "router-test-subject",
});
}
function renderRouter(
session = createAnonymousSessionAdapter(),
diagnostics: ApplicationOutputPorts["diagnostics"] = { record: () => {} },
) {
const techLog = createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT);
return render(
renderWithQueryProviders(
<ApplicationProvider
application={createTestApplication({
session,
diagnostics,
featureInputs: { [TECH_LOG_FEATURE_ID]: techLog.input },
})}
>
<PreferenceProviders>
<AppRouter />
</PreferenceProviders>
</ApplicationProvider>,
),
);
}
/** A back/forward style navigation that leaves focus where the user left it. */
function navigateByHistory(url: string) {
act(() => {
window.history.pushState({}, "", url);
window.dispatchEvent(new PopStateEvent("popstate"));
});
}
function routeChangeReports(record: ReturnType<typeof vi.fn>) {
return record.mock.calls.filter(
([event]) => (event as { eventId: string }).eventId === "route.changed",
).length;
}
describe("generic application router", () => {
it("renders and canonicalizes an isolated non-installed route codec contract", async () => {
expect(ROUTE_REGISTRY).not.toHaveProperty("REVIEW_FIXTURE");
expect(ROUTE_CODECS).not.toHaveProperty("ReviewFixtureParams");
expect(ROUTE_CODECS).not.toHaveProperty("ReviewFixtureSearch");
const routes = createGroupedRouteObjects(
reviewFixtureRegistry,
reviewFixtureRuntime,
{ PUBLIC: <Outlet />, STUDIO: <Outlet /> },
"test-build",
reviewFixtureCodecs,
);
const router = createMemoryRouter(routes, {
initialEntries: [
"/review/non-empty?filter=%20first%20&filter=second&unknown=drop",
],
});
render(
renderWithQueryProviders(
<ApplicationProvider application={createTestApplication()}>
<LocaleProvider>
<ThemeProvider>
<SessionProvider>
<RouterProvider router={router} />
</SessionProvider>
</ThemeProvider>
</LocaleProvider>
</ApplicationProvider>,
),
);
expect(
await screen.findByRole("heading", { name: "REVIEW_FIXTURE" }),
).toBeVisible();
expect(screen.getByTestId("review-param")).toHaveTextContent("non-empty");
expect(screen.getByTestId("review-search")).toHaveTextContent(
'{"filter":"first"}',
);
await waitFor(() =>
expect(router.state.location).toMatchObject({
pathname: "/review/non-empty",
search: "?filter=first",
}),
);
});
it("assembles generic Public and Studio parents with Studio catch-all precedence", () => {
const registry = {
TECH_LOG_HOME: ROUTE_REGISTRY.TECH_LOG_HOME,
STUDIO_FIXTURE: {
...ROUTE_REGISTRY.NOT_FOUND,
routeId: "STUDIO_FIXTURE",
path: "/studio/*",
layoutGroup: "STUDIO" as const,
},
NOT_FOUND: ROUTE_REGISTRY.NOT_FOUND,
};
const runtime = {
TECH_LOG_HOME: ROUTE_RUNTIME.TECH_LOG_HOME,
STUDIO_FIXTURE: ROUTE_RUNTIME.NOT_FOUND,
NOT_FOUND: ROUTE_RUNTIME.NOT_FOUND,
};
const routes = createGroupedRouteObjects(
registry,
runtime,
{
PUBLIC: <div data-layout="public" />,
STUDIO: <div data-layout="studio" />,
},
"test-build",
groupedFixtureCodecs,
);
expect(routes.map((route) => route.id)).toEqual([
"STUDIO_LAYOUT",
"PUBLIC_LAYOUT",
]);
expect(
matchRoutes(routes, "/studio/unknown")?.map((match) => match.route.id),
).toEqual(["STUDIO_LAYOUT", "STUDIO_FIXTURE"]);
expect(
matchRoutes(routes, "/publicly-unknown")?.map((match) => match.route.id),
).toEqual(["PUBLIC_LAYOUT", "NOT_FOUND"]);
const installedRoutes = createGroupedRouteObjects(
ROUTE_REGISTRY,
ROUTE_RUNTIME,
{
PUBLIC: <div data-layout="public" />,
STUDIO: <div data-layout="studio" />,
},
"test-build",
groupedFixtureCodecs,
);
expect(installedRoutes[1]?.children?.at(-1)?.id).toBe("NOT_FOUND");
});
it("rejects a grouped registry whose leaf runtime is missing", () => {
expect(() =>
createGroupedRouteObjects(
ROUTE_REGISTRY,
{},
{
PUBLIC: <div data-layout="public" />,
STUDIO: <div data-layout="studio" />,
},
"test-build",
groupedFixtureCodecs,
),
).toThrow("Missing route runtime: TECH_LOG_HOME");
});
it("renders a non-installed Studio wildcard leaf without rewriting its URL", async () => {
const routes = createGroupedRouteObjects(
{
STUDIO_FIXTURE: {
...ROUTE_REGISTRY.NOT_FOUND,
routeId: "STUDIO_FIXTURE",
path: "/studio/*",
layoutGroup: "STUDIO",
},
},
{
STUDIO_FIXTURE: {
moduleId: "studio-fixture",
Component: StudioFallbackFixture,
},
},
{
PUBLIC: <Outlet />,
STUDIO: (
<section data-testid="studio-layout">
<Outlet />
</section>
),
},
"test-build",
groupedFixtureCodecs,
);
const router = createMemoryRouter(routes, {
initialEntries: ["/studio/unknown/path"],
});
render(
renderWithQueryProviders(
<ApplicationProvider application={createTestApplication()}>
<LocaleProvider>
<ThemeProvider>
<SessionProvider>
<RouterProvider router={router} />
</SessionProvider>
</ThemeProvider>
</LocaleProvider>
</ApplicationProvider>,
),
);
expect(await screen.findByTestId("studio-layout")).toBeVisible();
expect(
await screen.findByRole("heading", { name: "unknown/path" }),
).toBeVisible();
expect(router.state.location.pathname).toBe("/studio/unknown/path");
});
it("applies authorization from a non-installed route definition", async () => {
const routes = createGroupedRouteObjects(
{
PROTECTED_FIXTURE: {
...ROUTE_REGISTRY.TECH_LOG_HOME,
routeId: "PROTECTED_FIXTURE",
path: "/private-fixture",
access: "session-required",
searchSchema: null,
},
},
{
PROTECTED_FIXTURE: {
moduleId: "protected-fixture",
Component: StudioFallbackFixture,
},
},
{
PUBLIC: <Outlet />,
STUDIO: <Outlet />,
},
"test-build",
groupedFixtureCodecs,
);
const router = createMemoryRouter(routes, {
initialEntries: ["/private-fixture"],
});
render(
renderWithQueryProviders(
<ApplicationProvider application={createTestApplication()}>
<LocaleProvider>
<ThemeProvider>
<SessionProvider>
<RouterProvider router={router} />
</SessionProvider>
</ThemeProvider>
</LocaleProvider>
</ApplicationProvider>,
),
);
/*
문구가 아니라 동작을 묻는다. 「세션이 필요합니다.」라는 옛 제목을 그대로 적어 두었더니
그 말이 바뀐 뒤로 이 검사는 계속 빨간 채로 지나갔다 — 잡아야 할 것(보호된 라우트가
로그인 관문으로 떨어진다)은 멀쩡한데 검사만 낡은 상태였다. 관문임을 말하는 것은
`data-surface` 이고, 그 값은 계약이다.
*/
const gate = await screen.findByRole("heading", { level: 1 });
expect(gate).toBeVisible();
expect(gate.closest("[data-surface]")).toHaveAttribute(
"data-surface",
"authentication-required",
);
});
it("renders the installed TechLog home in the Public layout", async () => {
const user = userEvent.setup();
window.history.pushState({}, "", "/");
renderRouter();
expect(
await screen.findByRole("heading", { name: "TechLog", level: 1 }),
).toBeVisible();
expect(screen.getByRole("navigation", { name: "주요 탐색" })).toBeVisible();
await user.click(
within(screen.getByRole("navigation", { name: "주요 탐색" })).getByRole(
"link",
{ name: "프로젝트" },
),
);
expect(
await screen.findByRole("heading", { name: "프로젝트", level: 1 }),
).toBeVisible();
expect(window.location.pathname).toBe("/projects");
});
it("keeps the unreachable client-side Public fallback inside its accessible shell", async () => {
window.history.pushState({}, "", "/missing");
renderRouter();
expect(
await screen.findByRole("heading", { name: "페이지를 찾을 수 없습니다." }),
).toBeVisible();
expect(screen.getByRole("navigation", { name: "주요 탐색" })).toBeVisible();
expect(screen.queryByText("Not Found", { exact: true })).not.toBeInTheDocument();
});
it("keeps a signed-out visitor out of the Studio layout entirely", async () => {
window.history.pushState({}, "", "/studio");
renderRouter();
// Not merely "no data": the Studio surface itself must not mount. Every
// TechLog route used to register as `access: "public"`, so a signed-out
// visitor who typed /studio got the shell, the navigation, and the page —
// and the page then issued Studio API calls.
await screen.findByRole("heading", { name: /세션|로그인/ });
expect(
screen.queryByRole("heading", { name: "작업 흐름" }),
).not.toBeInTheDocument();
expect(
screen.queryByRole("navigation", { name: "Studio 주 탐색" }),
).not.toBeInTheDocument();
});
it("keeps Studio routes inside the persistent Studio layout", async () => {
window.history.pushState({}, "", "/studio");
renderRouter(createSignedInSessionAdapter());
expect(
await screen.findByRole("heading", { name: "작업 흐름" }),
).toBeVisible();
expect(screen.getByRole("navigation", { name: "Studio 주 탐색" })).toBeVisible();
expect(screen.getByRole("link", { name: "공개 사이트 보기" })).toHaveAttribute(
"href",
"/",
);
});
it("gives the Studio wildcard precedence over the Public not-found route", async () => {
window.history.pushState({}, "", "/studio/missing");
renderRouter(createSignedInSessionAdapter());
expect(
await screen.findByRole("heading", {
name: "Studio 화면을 찾을 수 없습니다",
}),
).toBeVisible();
expect(screen.getByRole("navigation", { name: "Studio 주 탐색" })).toBeVisible();
expect(window.location.pathname).toBe("/studio/missing");
});
// Template sync (af3d8e6). The template pins these two router behaviours on
// its example screens; this product deleted those, so they are pinned on
// TechLog routes instead.
it("ignores unknown query parameters on a route without search and keeps the URL", async () => {
// D-16: `?utm_source=` or an OAuth callback parameter is not an invalid
// address. The `none` codec drops it from the parsed input only.
window.history.pushState({}, "", "/projects?utm_source=mail#top");
const { container } = renderRouter();
expect(
await screen.findByRole(
"heading",
{ name: "프로젝트", level: 1 },
{ timeout: 5000 },
),
).toBeVisible();
expect(container.querySelector('[data-surface="invalid-route"]')).toBeNull();
expect(`${window.location.pathname}${window.location.search}`).toBe(
"/projects?utm_source=mail",
);
});
it("runs the route lifecycle on the authentication-required surface", async () => {
// Title and route telemetry belong to every answer a route gives, not only
// to the page it renders once allowed.
const record = vi.fn();
window.history.pushState({}, "", "/");
const { container } = renderRouter(createAnonymousSessionAdapter(), {
record,
});
await screen.findByRole("heading", { name: "TechLog", level: 1 });
navigateByHistory("/studio");
await waitFor(
() =>
expect(
container.querySelector('[data-surface="authentication-required"]'),
).not.toBeNull(),
{ timeout: 5000 },
);
expect(routeChangeReports(record)).toBeGreaterThan(1);
expect(record).toHaveBeenCalledWith(
expect.objectContaining({
eventId: "route.changed",
context: expect.objectContaining({ route_id: "TECH_LOG_STUDIO_HOME" }),
}),
);
});
});