perf(studio): Studio 셸을 /studio에 들어갈 때 받는다

문제
라우트 레이아웃 표(tech-log-route-runtime.tsx)가 StudioShell을 정적으로
가져와, 공개 화면의 초기 JS에 StudioProvider·Studio 머리말·문서 server
state가 들어갔다.

고른 방법
- STUDIO 레이아웃은 lazy StudioShell을 Suspense와 ChunkRecoveryBoundary로
  감싼다. 청크를 못 받으면 라우트 청크와 같은 recoverChunk가 한 번 새로
  읽기를 정한다(chunkId `tech-log-studio-shell`).
- tests/features/tech-log/boot-graph.test.ts가 부팅 그래프(main.tsx, 그
  정적 import, 진입점이 바로 동적으로 읽는 boot·render-boot-failure)를
  빌드 없이 따라가, MOCK 소스·정적 콘텐츠·Studio 화면·HTTP Studio
  gateway가 다시 들어오지 않는지 본다. 공개 셸과 기능 입력 조립이
  그래프에 있는지도 봐서 빈 결과로 통과하지 않는다.

버린 대안
- 템플릿 소유 app-router.tsx에서 레이아웃 route에 lazy를 거는 것: 템플릿
  파일을 고치게 되고, 자식 화면 청크는 여전히 셸 뒤에 받는다.

위험·한계
- /studio 첫 진입은 셸 청크를 받은 뒤 화면 청크를 받는다(직렬 왕복 하나).
  Studio는 작성자 한 사람이 쓰는 화면이다.
- 셸을 받는 동안 LoadingSurface가 보인다.

검증
- desktop CI env 빌드: 앞 커밋과 함께 초기 JS 300,869 → 232,337 B.
- boot-graph.test.ts 통과.
This commit is contained in:
DongHyeonka
2026-11-12 22:33:48 +09:00
parent 8e0ea60eac
commit 02cf5ed3f9
2 changed files with 148 additions and 3 deletions
@@ -1,17 +1,45 @@
import {
lazy,
Suspense,
type ComponentType,
type LazyExoticComponent,
type ReactNode,
} from "react";
import { Outlet } from "react-router-dom";
import { ChunkRecoveryBoundary } from "../../../presentation/boundaries/chunk-recovery-boundary.tsx";
import { LoadingSurface } from "../../../presentation/design-system/index.ts";
import { useApplicationRecovery } from "../../../presentation/providers/application-provider.tsx";
import {
TECH_LOG_ROUTE_RUNTIME_CONTRACT,
type TechLogRouteId,
} from "../contracts/tech-log-route-contract.ts";
import { PublicShell } from "./public/public-shell.tsx";
import { StudioShell } from "./studio/studio-shell.tsx";
/*
Studio 셸은 공개 화면을 읽는 사람에게 필요 없다. 정적으로 가져오면 셸이 끌고 오는
StudioProvider·Studio 머리말·문서 server state 가 모든 첫 화면의 초기 JS 에 들어갔다
(FE-GATE-012). /studio 에 들어갈 때 받는다. 라우트 청크와 같이 청크를 못 받으면
ChunkRecoveryBoundary 가 한 번 새로 읽기를 정한다.
*/
const StudioShell = lazy(async () => {
const module = await import("./studio/studio-shell.tsx");
return { default: module.StudioShell };
});
function DeferredStudioShell({ children }: Readonly<{ children: ReactNode }>) {
const recovery = useApplicationRecovery();
return (
<ChunkRecoveryBoundary
chunkId="tech-log-studio-shell"
recover={recovery.recoverChunk}
>
<Suspense fallback={<LoadingSurface />}>
<StudioShell>{children}</StudioShell>
</Suspense>
</ChunkRecoveryBoundary>
);
}
type RouteRuntime = Readonly<{
moduleId: string;
@@ -297,8 +325,8 @@ export const TECH_LOG_ROUTE_LAYOUTS: Readonly<
</PublicShell>
),
STUDIO: (
<StudioShell>
<DeferredStudioShell>
<Outlet />
</StudioShell>
</DeferredStudioShell>
),
});
+117
View File
@@ -0,0 +1,117 @@
import assert from "node:assert/strict";
import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
import { parseAsync } from "@babel/core";
import { test } from "vitest";
/**
* FE-GATE-012. 첫 화면의 초기 JS 는 진입점(main.tsx), 그 정적 import, 진입점이 바로
* 동적으로 읽는 boot·render-boot-failure 와 그 정적 import 다
* (`scripts/lib/classify-vite-bundle.ts`). 공개 화면을 읽는 사람에게 필요 없는 아래 코드가
* 정적 import 하나로 이 그래프에 다시 들어오면 번들 예산을 넘는다. 빌드 없이 여기서 먼저 잡는다.
*/
const BOOT_SEEDS = [
"src/bootstrap/main.tsx",
"src/bootstrap/boot.tsx",
"src/bootstrap/render-boot-failure.tsx",
];
const DEFERRED = [
// MOCK 소스: 런타임 문서가 MOCK 을 고른 빌드(로컬·시험)에서만 쓰인다.
"src/features/tech-log/adapters/mock/",
"src/features/tech-log/adapters/static/",
// Studio: /studio 에 들어갈 때 받는다.
"src/features/tech-log/presentation/studio/",
"src/features/tech-log/adapters/http/http-studio-gateways.ts",
"src/features/tech-log/adapters/http/http-studio-gateway.ts",
"src/features/tech-log/adapters/http/http-management-gateway.ts",
"src/features/tech-log/adapters/http/http-studio-asset-gateway.ts",
"src/features/tech-log/adapters/http/asset-upload-transport.ts",
];
type Node = Readonly<Record<string, unknown> & { type: string }>;
function isTypeOnly(statement: Node): boolean {
if (statement["importKind"] === "type" || statement["exportKind"] === "type") return true;
const specifiers = statement["specifiers"] as readonly Node[] | undefined;
if (statement.type !== "ImportDeclaration" || !specifiers || specifiers.length === 0) {
return false;
}
// `import { type A, type B } from "x"` 는 컴파일 뒤 남지 않는다(verbatimModuleSyntax 없음).
return specifiers.every((specifier) => specifier["importKind"] === "type");
}
function resolveRelative(from: string, specifier: string): string | undefined {
if (!specifier.startsWith(".")) return undefined;
const target = path.posix.normalize(path.posix.join(path.posix.dirname(from), specifier));
if (!/\.tsx?$/u.test(target)) return undefined;
assert.ok(existsSync(target), `${from} 가 없는 파일을 가져온다: ${specifier}`);
return target;
}
async function staticImports(file: string): Promise<string[]> {
const plugins: ("jsx" | ["typescript", { dts: boolean }])[] = [["typescript", { dts: false }]];
if (file.endsWith(".tsx")) plugins.push("jsx");
const tree = (await parseAsync(readFileSync(file, "utf8"), {
filename: file,
babelrc: false,
configFile: false,
sourceType: "module",
parserOpts: { plugins },
})) as unknown as { program: { body: readonly Node[] } } | null;
assert.ok(tree, `cannot parse ${file}`);
const imports: string[] = [];
for (const statement of tree.program.body) {
if (
statement.type !== "ImportDeclaration" &&
statement.type !== "ExportNamedDeclaration" &&
statement.type !== "ExportAllDeclaration"
) {
continue;
}
const source = statement["source"] as Node | null | undefined;
if (!source || isTypeOnly(statement)) continue;
const resolved = resolveRelative(file, String(source["value"]));
if (resolved) imports.push(resolved);
}
return imports;
}
async function bootGraph(): Promise<Map<string, string>> {
const importedBy = new Map<string, string>(BOOT_SEEDS.map((seed) => [seed, "(seed)"]));
const pending = [...BOOT_SEEDS];
while (pending.length > 0) {
const file = pending.pop()!;
for (const imported of await staticImports(file)) {
if (importedBy.has(imported)) continue;
importedBy.set(imported, file);
pending.push(imported);
}
}
return importedBy;
}
function chain(importedBy: ReadonlyMap<string, string>, file: string): string {
const links = [file];
let current = importedBy.get(file);
while (current && current !== "(seed)") {
links.push(current);
current = importedBy.get(current);
}
return links.join(" <- ");
}
test("공개 첫 화면의 부팅 그래프에 MOCK 소스와 Studio 코드가 없다", async () => {
const graph = await bootGraph();
// 그래프를 제대로 따라갔는지: 공개 셸과 기능 입력 조립은 부팅 때 필요하다.
assert.ok(graph.has("src/features/tech-log/presentation/public/public-shell.tsx"));
assert.ok(graph.has("src/features/tech-log/adapters/create-tech-log-feature-input.ts"));
const leaked = [...graph.keys()]
.filter((file) => DEFERRED.some((prefix) => file.startsWith(prefix)))
.sort()
.map((file) => chain(graph, file));
assert.deepEqual(leaked, [], `부팅 그래프로 들어온 지연 코드:\n${leaked.join("\n")}`);
});