From 9c8a5f417a6e9c6213bd98ca60bc7f8c04b2b9e2 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 25 Sep 2026 22:54:40 +0900 Subject: [PATCH] fix(bootstrap): show the boot error shell when the app graph fails to evaluate (09-03) A module that threw while evaluating stopped main.tsx before boot() ran, so the static loading shell stayed up. The entry now imports the app (boot.tsx) dynamically and renders the shell on rejection; the shell reads boot messages without the feature catalog. The preload helper gets its own chunk so lazy chunks do not import the per-build entry, and the bundle budget counts the entry's dynamic imports as initial JS. Co-Authored-By: Claude Opus 5.5 --- scripts/lib/classify-vite-bundle.ts | 10 ++- src/bootstrap/boot.tsx | 59 ++++++++++++++++ src/bootstrap/main.tsx | 67 +++++-------------- src/bootstrap/render-boot-failure.tsx | 17 +++++ .../boundaries/boot-error-shell.tsx | 25 ++++--- src/presentation/i18n/boot-messages.ts | 28 ++++++++ src/presentation/i18n/catalog.ts | 17 +---- tests/component/boot-module-failure.test.tsx | 25 +++++++ tests/unit/bundle-classification.test.ts | 25 +++++++ vite.config.ts | 9 +++ 10 files changed, 203 insertions(+), 79 deletions(-) create mode 100644 src/bootstrap/boot.tsx create mode 100644 src/bootstrap/render-boot-failure.tsx create mode 100644 src/presentation/i18n/boot-messages.ts create mode 100644 tests/component/boot-module-failure.test.tsx diff --git a/scripts/lib/classify-vite-bundle.ts b/scripts/lib/classify-vite-bundle.ts index 4521b2e9..2e0660db 100644 --- a/scripts/lib/classify-vite-bundle.ts +++ b/scripts/lib/classify-vite-bundle.ts @@ -2,12 +2,15 @@ type ViteManifestEntry = Readonly<{ file: string; isEntry?: boolean; imports?: readonly string[]; + dynamicImports?: readonly string[]; }>; /** - * Static imports of an entry are part of initial JavaScript. Every remaining - * JavaScript output is governed by the lazy-chunk budget. - * + * Static imports of an entry are part of initial JavaScript, and so are the + * chunks the entry itself imports dynamically: main.tsx only imports the + * application graph that way so it can report a graph that fails to evaluate + * (09-03). Every remaining JavaScript output is governed by the lazy-chunk + * budget. */ export function classifyViteJavascript( manifest: Readonly>, @@ -31,6 +34,7 @@ export function classifyViteJavascript( } if (entry.file.endsWith(".js")) initialFiles.add(entry.file); pendingKeys.push(...(entry.imports ?? [])); + if (entry.isEntry) pendingKeys.push(...(entry.dynamicImports ?? [])); } const allJavaScript = new Set( diff --git a/src/bootstrap/boot.tsx b/src/bootstrap/boot.tsx new file mode 100644 index 00000000..1b7113b0 --- /dev/null +++ b/src/bootstrap/boot.tsx @@ -0,0 +1,59 @@ +import { createRoot } from "react-dom/client"; + +import { recordBootFailure } from "../adapters/diagnostics/index.ts"; +import { BootErrorShell } from "../presentation/boundaries/boot-error-shell.tsx"; +import { + createBootReleaseRecovery, + decideBootFailure, +} from "./boot-release-recovery.ts"; +import { createRuntimeComposition } from "./create-runtime-composition.ts"; +import { initializeColorScheme } from "./initialize-color-scheme.ts"; +import { ReleaseManifestError } from "./load-release-manifest.ts"; +import { BootConfigError } from "./load-runtime-config.ts"; +import { RuntimeApplication } from "./runtime-application.tsx"; + +/** + * The application boot. main.tsx imports this module dynamically, so a module + * in this static graph that throws while it evaluates rejects that import and + * main.tsx shows the failure (09-03). Failures after evaluation are handled + * here. + */ +const rootElement = document.getElementById("root"); + +if (!rootElement) { + throw new Error("Missing #root mount element"); +} + +const root = createRoot(rootElement); + +async function boot(): Promise { + const releaseRecovery = createBootReleaseRecovery(); + try { + const composition = await createRuntimeComposition(); + // A coherent boot clears any reload-once marker from a previous mismatch. + releaseRecovery.markCoherentBoot(); + document.documentElement.dataset.buildId = composition.release.buildId; + document.documentElement.dataset.releaseId = composition.release.releaseId; + initializeColorScheme(composition.application.preferences); + root.render(); + import.meta.hot?.dispose(() => { + void composition.dispose(); + }); + } catch (error: unknown) { + const safe = + error instanceof BootConfigError || error instanceof ReleaseManifestError + ? error.safe + : { supportReference: "boot:unknown" }; + + recordBootFailure(error, safe); + // Spec §45. A rolling-release mismatch gets exactly one fresh navigation + // (HTML is revalidated); a repeat of the same mismatch fails closed. + if (decideBootFailure(error, releaseRecovery) === "reload-once") { + window.location.reload(); + return; + } + root.render(); + } +} + +void boot(); diff --git a/src/bootstrap/main.tsx b/src/bootstrap/main.tsx index 49ff1f73..381d6ee6 100644 --- a/src/bootstrap/main.tsx +++ b/src/bootstrap/main.tsx @@ -1,54 +1,17 @@ -import { createRoot } from "react-dom/client"; - -import { recordBootFailure } from "../adapters/diagnostics/index.ts"; -import { BootErrorShell } from "../presentation/boundaries/boot-error-shell.tsx"; import "../presentation/styles/theme.css"; -import { - createBootReleaseRecovery, - decideBootFailure, -} from "./boot-release-recovery.ts"; -import { createRuntimeComposition } from "./create-runtime-composition.ts"; -import { initializeColorScheme } from "./initialize-color-scheme.ts"; -import { ReleaseManifestError } from "./load-release-manifest.ts"; -import { BootConfigError } from "./load-runtime-config.ts"; -import { RuntimeApplication } from "./runtime-application.tsx"; -const rootElement = document.getElementById("root"); - -if (!rootElement) { - throw new Error("Missing #root mount element"); -} - -const root = createRoot(rootElement); - -async function boot(): Promise { - const releaseRecovery = createBootReleaseRecovery(); - try { - const composition = await createRuntimeComposition(); - // A coherent boot clears any reload-once marker from a previous mismatch. - releaseRecovery.markCoherentBoot(); - document.documentElement.dataset.buildId = composition.release.buildId; - document.documentElement.dataset.releaseId = composition.release.releaseId; - initializeColorScheme(composition.application.preferences); - root.render(); - import.meta.hot?.dispose(() => { - void composition.dispose(); - }); - } catch (error: unknown) { - const safe = - error instanceof BootConfigError || error instanceof ReleaseManifestError - ? error.safe - : { supportReference: "boot:unknown" }; - - recordBootFailure(error, safe); - // Spec §45. A rolling-release mismatch gets exactly one fresh navigation - // (HTML is revalidated); a repeat of the same mismatch fails closed. - if (decideBootFailure(error, releaseRecovery) === "reload-once") { - window.location.reload(); - return; - } - root.render(); - } -} - -void boot(); +/** + * 09-03. The entry imports the application graph dynamically. A module in it + * that throws while it evaluates (a duplicate message key, a route or + * operation conflict) used to stop the entry before any handler ran, leaving + * the static loading shell up. Now it rejects this import and the failure is + * shown. + * + * The entry stays free of anything the application graph also imports (no + * JSX, no React): whatever it hosted, every chunk would import from it, and + * the entry's hash changes with every build id. + */ +void import("./boot.tsx").catch(async (error: unknown) => { + const { renderBootFailure } = await import("./render-boot-failure.tsx"); + renderBootFailure(error); +}); diff --git a/src/bootstrap/render-boot-failure.tsx b/src/bootstrap/render-boot-failure.tsx new file mode 100644 index 00000000..7b4e101b --- /dev/null +++ b/src/bootstrap/render-boot-failure.tsx @@ -0,0 +1,17 @@ +import { createRoot } from "react-dom/client"; + +import { recordBootFailure } from "../adapters/diagnostics/index.ts"; +import { BootErrorShell } from "../presentation/boundaries/boot-error-shell.tsx"; + +/** + * 09-03. Renders the boot failure when the application graph (boot.tsx) could + * not even be evaluated. Nothing here reaches the installed feature graph, so + * it still loads when that graph throws. + */ +export function renderBootFailure(error: unknown): void { + const safe = { supportReference: "boot:unknown" }; + recordBootFailure(error, safe); + const rootElement = document.getElementById("root"); + if (!rootElement) throw error; + createRoot(rootElement).render(); +} diff --git a/src/presentation/boundaries/boot-error-shell.tsx b/src/presentation/boundaries/boot-error-shell.tsx index d3fe5ecd..7ae7db72 100644 --- a/src/presentation/boundaries/boot-error-shell.tsx +++ b/src/presentation/boundaries/boot-error-shell.tsx @@ -1,4 +1,8 @@ -import { formatMessage } from "../i18n/index.ts"; +import { BOOT_MESSAGES } from "../i18n/boot-messages.ts"; + +// 09-03. Read from the boot messages alone, not the i18n catalog: the shell +// has to render when the installed feature graph failed to evaluate. +const MESSAGES = BOOT_MESSAGES["ko-KR"]; export type BootErrorShellProps = Readonly<{ kind?: string; @@ -19,35 +23,36 @@ export function BootErrorShell({ }: BootErrorShellProps) { return (
-

{formatMessage("ko-KR", "boot.failure.title")}

+

{MESSAGES["boot.failure.title"]}

-
{formatMessage("ko-KR", "boot.field.error")}
+
{MESSAGES["boot.field.error"]}
{kind}
-
{formatMessage("ko-KR", "boot.field.code")}
+
{MESSAGES["boot.field.code"]}
{code}
{buildId && ( <> -
{formatMessage("ko-KR", "boot.field.build")}
+
{MESSAGES["boot.field.build"]}
{buildId}
)} {configSchemaVersion && ( <> -
{formatMessage("ko-KR", "boot.field.configSchema")}
+
{MESSAGES["boot.field.configSchema"]}
{configSchemaVersion}
)} {releaseId && ( <> -
{formatMessage("ko-KR", "boot.field.release")}
+
{MESSAGES["boot.field.release"]}
{releaseId}
)}

- {formatMessage("ko-KR", "boot.supportReference", { - reference: supportReference, - })} + {MESSAGES["boot.supportReference"].replace( + "{reference}", + () => supportReference, + )}

); diff --git a/src/presentation/i18n/boot-messages.ts b/src/presentation/i18n/boot-messages.ts new file mode 100644 index 00000000..105449d5 --- /dev/null +++ b/src/presentation/i18n/boot-messages.ts @@ -0,0 +1,28 @@ +/** + * 09-03. The boot failure shell's words. They live apart from `catalog.ts` + * because the catalog merges every installed feature's messages: when that + * feature graph throws while it evaluates, the shell reporting it must still + * load. `catalog.ts` spreads these in, so they stay ordinary message keys. + */ +export const BOOT_MESSAGES = Object.freeze({ + "ko-KR": Object.freeze({ + "boot.failure.title": "애플리케이션을 시작할 수 없습니다.", + "boot.field.error": "오류", + "boot.field.code": "코드", + "boot.field.build": "빌드", + "boot.field.configSchema": "설정 스키마", + "boot.field.release": "릴리스", + "boot.supportReference": "지원 참조: {reference}", + } as const), + "en-US": Object.freeze({ + "boot.failure.title": "The application could not start.", + "boot.field.error": "Error", + "boot.field.code": "Code", + "boot.field.build": "Build", + "boot.field.configSchema": "Configuration schema", + "boot.field.release": "Release", + "boot.supportReference": "Support reference: {reference}", + } as const), +}); + +export type BootMessageKey = keyof (typeof BOOT_MESSAGES)["ko-KR"]; diff --git a/src/presentation/i18n/catalog.ts b/src/presentation/i18n/catalog.ts index 9bf90c7c..61bb0c16 100644 --- a/src/presentation/i18n/catalog.ts +++ b/src/presentation/i18n/catalog.ts @@ -1,4 +1,5 @@ import { INSTALLED_MESSAGE_CATALOGS } from "../../features/installed-feature-messages.ts"; +import { BOOT_MESSAGES } from "./boot-messages.ts"; const PLATFORM_KO_MESSAGES = { "common.unavailable": "요청한 문구를 표시할 수 없습니다.", @@ -143,13 +144,7 @@ const PLATFORM_KO_MESSAGES = { "error.asset_mismatch": "화면 자산 구성이 현재 릴리스와 일치하지 않습니다.", "error.render_failure": "화면을 표시하지 못했습니다.", "error.unknown_failure": "예상하지 못한 문제가 발생했습니다.", - "boot.failure.title": "애플리케이션을 시작할 수 없습니다.", - "boot.field.error": "오류", - "boot.field.code": "코드", - "boot.field.build": "빌드", - "boot.field.configSchema": "설정 스키마", - "boot.field.release": "릴리스", - "boot.supportReference": "지원 참조: {reference}", + ...BOOT_MESSAGES["ko-KR"], } as const; export const KO_MESSAGES = { @@ -301,13 +296,7 @@ const PLATFORM_EN_MESSAGES = { "error.asset_mismatch": "The page assets do not match this release.", "error.render_failure": "The page could not be displayed.", "error.unknown_failure": "An unexpected problem occurred.", - "boot.failure.title": "The application could not start.", - "boot.field.error": "Error", - "boot.field.code": "Code", - "boot.field.build": "Build", - "boot.field.configSchema": "Configuration schema", - "boot.field.release": "Release", - "boot.supportReference": "Support reference: {reference}", + ...BOOT_MESSAGES["en-US"], } as const satisfies Record; export const EN_MESSAGES = { diff --git a/tests/component/boot-module-failure.test.tsx b/tests/component/boot-module-failure.test.tsx new file mode 100644 index 00000000..d715a695 --- /dev/null +++ b/tests/component/boot-module-failure.test.tsx @@ -0,0 +1,25 @@ +// @vitest-environment jsdom + +import { screen } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; + +// 09-03. A throw while the feature graph evaluates (a duplicate message key, +// a route or operation conflict) used to stop main.tsx before boot() ran, so +// the static "loading" shell stayed up forever. +vi.mock("../../src/.generated/product-feature-index.ts", () => { + throw new TypeError("Duplicate ko-KR message key: probe.title"); +}); + +describe("boot entry (09-03)", () => { + it("shows the boot error shell when the app graph fails to evaluate", async () => { + document.body.innerHTML = + '
불러오는 중
'; + vi.spyOn(console, "error").mockImplementation(() => {}); + + await import("../../src/bootstrap/main.tsx"); + + const shell = await screen.findByRole("alert", undefined, { timeout: 5_000 }); + expect(shell).toHaveTextContent("애플리케이션을 시작할 수 없습니다."); + expect(document.querySelector("[data-boot-shell]")).toBeNull(); + }); +}); diff --git a/tests/unit/bundle-classification.test.ts b/tests/unit/bundle-classification.test.ts index c5e2e75c..bb17acf8 100644 --- a/tests/unit/bundle-classification.test.ts +++ b/tests/unit/bundle-classification.test.ts @@ -26,6 +26,31 @@ describe("Vite bundle classification", () => { }); }); + it("counts the entry's own dynamic imports as initial (09-03)", () => { + // main.tsx does nothing but import the application graph dynamically, so + // that graph is loaded on every visit; the routes it lazy-loads are not. + expect( + classifyViteJavascript({ + "index.html": { + file: "assets/entry.js", + isEntry: true, + dynamicImports: ["src/boot.tsx"], + }, + "src/boot.tsx": { + file: "assets/boot.js", + imports: ["_shared.js"], + dynamicImports: ["src/lazy.js"], + }, + "_shared.js": { file: "assets/shared.js" }, + "src/lazy.js": { file: "assets/lazy.js" }, + }), + ).toEqual({ + initialFiles: ["assets/boot.js", "assets/entry.js", "assets/shared.js"], + lazyFiles: ["assets/lazy.js"], + missingImports: [], + }); + }); + it("reports a manifest import that cannot be resolved", () => { expect( classifyViteJavascript({ diff --git a/vite.config.ts b/vite.config.ts index adee7e0e..6acd6049 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -69,6 +69,15 @@ export default defineConfig(({ mode }) => { build: { manifest: true, sourcemap: false, + rollupOptions: { + output: { + // 09-03. The entry now imports the app dynamically, so Vite's preload + // helper would land in the entry chunk and every lazy chunk would + // import the entry, whose hash changes with each build id. + manualChunks: (id: string) => + id.includes("vite/preload-helper") ? "preload-helper" : undefined, + }, + }, }, }; });