Files
clean-architecture-frontend…/vite.config.ts
DongHyeonka f4d5761a2a fix(test-run): 실행마다 빌드·Playwright 출력 폴더를 따로 쓴다
문제: 빌드는 `dist`, `.generated/frontend-runtime`, `artifacts/release`·
`artifacts/quality`에 고정으로 쓰고, 다섯 Playwright 설정은 결과·report·
JUnit을 `artifacts/tests/<이름>/`에 고정으로 쓴다. 한 checkout에서 두
번째 e2e 실행이 시작하면 빌드 1단계가 첫 실행의 preview가 서빙 중인
`dist`를 지우고, Playwright가 `outputDir`을 비워 첫 실행의 trace를 지운다.
증거 파일도 늦게 끝난 쪽 것으로 섞인다(1105/12-04).

고른 방법: 변수 두 개로 나눈다(`scripts/lib/run-isolation.ts`).
- `TEST_RUN_ID`: Playwright 설정이 읽는다. 값이 있으면 그 실행의 결과·
  report·JUnit과 서빙할 빌드를 `.tmp/runs/<id>/` 아래 같은 상대 경로에
  둔다. 없으면 지금 경로 그대로라 게이트, CI upload, 증거 검사가 읽는
  곳이 바뀌지 않는다.
- `RUN_OUTPUT_ROOT`: 설정이 web server에만 넘긴다. 빌드 단계 전부
  (`build-frontend`, contract set, runtime config, SW asset 목록, SW 빌드,
  build manifest)와 `vite.config.ts`가 읽어 `dist`·생성 모듈·증거·Vite
  캐시를 그 아래에 쓴다. preview는 `--outDir`로 같은 `dist`를 서빙한다.
빌드 코드는 `TEST_RUN_ID`를 읽지 않는다. e2e worker가 저장소 복사본을
빌드할 때(fixture-builds, service-worker-builds) runner 환경을 물려받는데,
그 빌드는 복사본 자기 `dist`에 써야 하기 때문이다.
두 루트는 `.` 또는 `.tmp/` 아래만 받는다. git, Tailwind 소스 스캔(report
안 문자열이 CSS에 들어가지 않게), Vite watcher, vitest, 저장소 복사
helper가 모두 `.tmp`를 건너뛴다. service-worker-builds의 복사 제외 목록에
`.tmp`를 더했다(fixture-builds와 같아짐). build manifest의 경로는 빌드가
쓴 폴더 기준 상대 경로로 둔다.
`vite.config.ts`가 새로 가져오는 `scripts/lib/run-isolation.ts`는 저장소
일부를 임시 루트에 복사해 빌드하는 두 목록(초기 JS 측정
`scripts/scale/measure-feature-shape-growth.ts`,
`tests/unit/product-feature-selection-build.test.ts`)에도 더한다.
Storybook은 run ID가 있으면 `build:storybook`의 두 단계를 다른 `-o`로
돌린다. 같은 단계인지는 단위 테스트가 package script와 대조한다.
버린 대안: 운영 증거 경로(54개 스크립트, `config/ci/gates.json`)까지 run
ID로 옮기기. 게이트와 workflow upload가 고정 경로를 읽으므로 이번 범위
밖이다(아래 한계). 실행마다 저장소를 임시 폴더로 복사하기: 매번 수십
MB 복사와 node_modules 링크가 들고, 개발자가 보는 결과 위치가 사라진다.

위험·한계: 포트는 아직 고정이라 이 커밋만으로는 두 실행이 함께 돌지
못한다(다음 커밋). `ci:gate`와 증거 검사(`check:test-evidence`,
`verify:browser-capability-evidence`)는 기본 경로만 읽는다. run ID를 준
채 게이트를 돌리면 증거가 기본 경로에 새로 생기지 않아 게이트가 "not
freshly produced"로 실패한다(통과로 새지 않는다). Storybook 내부 캐시
(`node_modules/.cache`)는 여전히 공유한다. capability 설정
(`playwright.capabilities.config.ts`)은 test:browser-file-storage-removal이
capability와 함께 지운다. 설정 테스트는 그 파일이 있을 때만 그 설정을 읽고,
경로를 변수로 두어 타입 검사가 그 파일을 요구하지 않는다.

검증: desktop batch에서 확인.
node scripts/run-vitest.ts run tests/unit/run-isolation.test.ts tests/unit/playwright-run-isolation.test.ts tests/unit/run-output-root-build.test.ts
node scripts/run-vitest.ts run tests/unit/feature-shape-growth.test.ts tests/unit/product-feature-selection-build.test.ts
corepack pnpm test:browser-file-storage-removal

Refs: 1105/12-04
2026-11-06 02:11:17 +09:00

287 lines
12 KiB
TypeScript

import { existsSync } from "node:fs";
import { createRequire } from "node:module";
import path from "node:path";
import { defineConfig, loadEnv } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";
import { runOutputRoot } from "./scripts/lib/run-isolation.ts";
import { viteModuleInventoryPlugin } from "./scripts/lib/vite-module-inventory.ts";
import { ENV_REGISTRY } from "./src/contracts/env.ts";
/**
* 13-06. Every VITE_* value Vite loads (shell or `.env*`) is public once
* something bundles it, so a value the build does not declare is refused
* rather than carried along.
*/
function assertDeclaredBuildVariables(mode: string): void {
const undeclared = Object.keys(loadEnv(mode, process.cwd(), "VITE_"))
.filter((name) => !Object.hasOwn(ENV_REGISTRY, name))
.sort();
if (undeclared.length > 0) {
throw new Error(
`Undeclared VITE_* build variables: ${undeclared.join(", ")}. ` +
"Declare them in ENV_REGISTRY (src/contracts/env.ts) or unset them; " +
"VITE_ values are published to the browser.",
);
}
}
/**
* §6.1. One sub-path, declared once.
*
* `VITE_ROUTER_BASE_PATH` already drives the router and the Service Worker
* scope. Vite's asset `base` was left at its default, so a build served from
* `/app/` emitted root-absolute asset URLs and loaded nothing: the three
* consumers of the same setting disagreed. They are read from one value here so
* a sub-path deployment is coherent or fails at build time.
*/
function routerBasePath(environment: NodeJS.ProcessEnv): string {
const declared = environment["VITE_ROUTER_BASE_PATH"];
if (declared === undefined || declared === "") return "/";
if (!declared.startsWith("/") || !declared.endsWith("/")) {
throw new Error(
`VITE_ROUTER_BASE_PATH must start and end with "/"; received ${declared}`,
);
}
return declared;
}
/**
* 13-07. The runtime document ships inside dist, which is served under the
* base path. An explicit root-relative URL outside it would 404 at boot.
*/
function assertRuntimeConfigUnderBase(
environment: NodeJS.ProcessEnv,
base: string,
): void {
const declared = environment["VITE_RUNTIME_CONFIG_URL"];
if (declared?.startsWith("/") && !declared.startsWith(base)) {
throw new Error(
`VITE_RUNTIME_CONFIG_URL ${declared} is outside VITE_ROUTER_BASE_PATH ${base}`,
);
}
}
type ModuleGraph = Readonly<{
getModuleInfo(id: string): Readonly<{
importedIds: readonly string[];
dynamicallyImportedIds: readonly string[];
}> | null;
}>;
function staticClosure(
graph: ModuleGraph,
roots: readonly string[],
within: (id: string) => boolean = () => true,
): Set<string> {
const reached = new Set<string>();
const pending = [...roots];
for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
if (reached.has(next) || !within(next)) continue;
reached.add(next);
pending.push(...(graph.getModuleInfo(next)?.importedIds ?? []));
}
return reached;
}
/**
* 15-01. Two chunk groups that keep moving the feature runtime halves out of
* the initial JavaScript from costing more than it saves.
*
* - `feature-declarations`: every installed feature's declaration, the static
* graph under src/features/ that the generated feature index reaches
* (feature-module.ts, its route contract and messages). A declaration is
* shared by the boot graph and its own feature's lazy runtime and pages,
* and rolldown otherwise gives each such set of importers a chunk of its
* own: one more initial file per feature, which doubled what a feature
* added to the initial JavaScript.
* - `feature-platform`: the boot modules the runtime halves also import (HTTP
* executor, contract runtime, zod). Left to rolldown they split into one
* initial chunk per set of importers; the per-file gzip overhead and the
* compression lost across files cost more than the runtime code removed.
* Modules that the boot-failure screen needs are left out, so
* render-boot-failure.tsx never depends on this chunk: it must still render
* when a module of the application graph throws while evaluating (09-03).
*
* Both only regroup modules the boot already loads; nothing lazy becomes
* initial. If feature-declarations comes out empty, the per-feature bound in
* tests/unit/feature-shape-growth.test.ts fails. feature-platform only moves
* the platform total (about 2 KB at 15-01), which the bundle budget
* (FE-GATE-012) checks.
*/
function createFeatureChunkGroups(root: string) {
const at = (file: string) => path.join(root, file);
const featuresRoot = `${at("src/features")}${path.sep}`;
let groups: ReadonlyMap<string, string> | undefined;
const classify = (graph: ModuleGraph): ReadonlyMap<string, string> => {
const index = graph.getModuleInfo(at("src/.generated/product-feature-index.ts"));
const declarations = staticClosure(graph, index?.importedIds ?? [], (id) =>
id.startsWith(featuresRoot),
);
const runtimes = staticClosure(
graph,
[...declarations].flatMap((id) => graph.getModuleInfo(id)?.dynamicallyImportedIds ?? []),
);
const boot = staticClosure(graph, [at("src/bootstrap/boot.tsx")]);
const bootFailure = staticClosure(graph, [at("src/bootstrap/render-boot-failure.tsx")]);
const result = new Map<string, string>();
for (const id of declarations) result.set(id, "feature-declarations");
for (const id of runtimes) {
if (boot.has(id) && !bootFailure.has(id) && !declarations.has(id)) {
result.set(id, "feature-platform");
}
}
return result;
};
return (id: string, graph: ModuleGraph): string | null => {
groups ??= classify(graph);
return groups.get(id) ?? null;
};
}
/**
* 1103/15-07. react-router publishes its production build under
* dist/production, but its exports map points every condition at
* dist/development. A production bundle carried the router's development
* warnings (ENABLE_DEV_WARNINGS): 604 gzip bytes of initial JavaScript at
* 15-07 and warnings in the production console. A build resolves the two
* entries react-router-dom imports to the production files next to the
* development entry. If an upgrade moves them, the build stops here rather
* than silently shipping the development build again;
* tests/unit/build-environment-bundle.test.ts checks the bundle. Remove this
* when the package exports a production condition.
*/
function reactRouterProductionAliases(root: string) {
const projectRequire = createRequire(path.join(root, "package.json"));
const routerRequire = createRequire(projectRequire.resolve("react-router-dom"));
const production = path.join(path.dirname(routerRequire.resolve("react-router")), "..", "production");
const aliases = [
{ find: /^react-router$/u, replacement: path.join(production, "index.mjs") },
{ find: /^react-router\/dom$/u, replacement: path.join(production, "dom-export.mjs") },
];
const missing = aliases.filter(({ replacement }) => !existsSync(replacement));
if (missing.length > 0) {
throw new Error(
`react-router production build not found: ${missing.map(({ replacement }) => replacement).join(", ")}`,
);
}
return aliases;
}
/**
* 1105/12-04. A run with its own output folder (`RUN_OUTPUT_ROOT`, which a
* Playwright config sets for its web server under `TEST_RUN_ID`) builds into
* `<root>/dist` and keeps Vite's dependency cache in `<root>/.vite`, so two
* builds or dev servers in one checkout do not empty or rewrite each other's
* files. Unset, nothing is set here and Vite's defaults (`dist`,
* `node_modules/.vite`) apply as before; Storybook, which loads this file,
* keeps its own.
*/
function runOutputOverrides(
environment: NodeJS.ProcessEnv,
): Readonly<{ cacheDir: string; outDir: string }> | null {
const root = runOutputRoot(environment);
return root === "."
? null
: { cacheDir: path.posix.join(root, ".vite"), outDir: path.posix.join(root, "dist") };
}
export default defineConfig(({ command, mode }) => {
assertDeclaredBuildVariables(mode);
const base = routerBasePath(process.env);
assertRuntimeConfigUnderBase(process.env, base);
const runOutput = runOutputOverrides(process.env);
return {
base,
...(runOutput ? { cacheDir: runOutput.cacheDir } : {}),
plugins: [react(), tailwindcss(), viteModuleInventoryPlugin()],
// Development keeps the router's warnings.
resolve: command === "build" ? { alias: reactRouterProductionAliases(process.cwd()) } : {},
server: {
watch: {
// Test and build output, never app source. Playwright writes trace
// resources (.html) under artifacts/ while a dev-server test runs;
// watched, each one made Vite reload every open page.
ignored: ["**/artifacts/**", "**/dist/**", "**/.tmp/**"],
},
},
build: {
...(runOutput ? { outDir: runOutput.outDir } : {}),
manifest: true,
sourcemap: false,
rolldownOptions: {
/**
* 1101/08-08. The design-system modules have no top-level effects:
* they declare components, icons and token lists. Declared so, a
* primitive file none of whose exports a chunk uses is dropped from
* it, instead of riding the initial chunk because the app shell
* imports the index that re-exports it. The bundler drops an import
* kept only for its effect along with its module, so these files hold
* no such import; tests/unit/design-system-initial-chunk.test.ts
* checks both. Stylesheets load from bootstrap/main.tsx.
*
* Trade: at 08-08 the initial JavaScript fell by 2,718 gzip bytes
* and the initial chunks rose from 16 to 25. The entry preloads them
* in parallel, so over HTTP/2 they add no round trip. Over HTTP/1.1
* they queue for six connections; 1101/14.4 measured that cost and
* why the chunks stay split ("초기 청크 수와 HTTP/1.1" in
* docs/operations/performance-evidence.md).
*/
treeshake: {
moduleSideEffects: [
{
test: /[\\/]src[\\/]presentation[\\/]design-system[\\/].+\.tsx?$/,
sideEffects: false,
},
],
},
output: {
codeSplitting: {
groups: [
// 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.
{ name: "preload-helper", test: /vite[\\/]preload-helper/ },
// 1103/15-06. react-dom and scheduler (about 56 KB gzip) shared
// the boot-failure chunk with the build id, so a release that
// only changed the build id renamed half of the initial
// JavaScript (99,785 of 201,857 B) and returning visitors
// downloaded it again. In a chunk of their own they keep their
// name: the same change renames 44,297 B (boot, entry and the
// boot-failure screen, which hold or import the build id).
// The boot-failure screen still needs no module of the
// application graph (09-03): this chunk is a library leaf.
{
name: "react-dom",
test: /[\\/]node_modules[\\/](?:\.pnpm[\\/][^\\/]+[\\/]node_modules[\\/])?(?:react-dom|scheduler)[\\/]/,
includeDependenciesRecursively: false,
},
// 1101/07-03. Every feature's schemas and runtime half import
// the shared zod adapter. Alone it becomes a chunk of its own
// once two features share it, and every route and runtime
// import then preloads one more file (about 50 gzip bytes of
// initial JavaScript for the second feature). Those imports
// already preload schema-registry.ts, so the adapter rides
// that lazy chunk. Both modules stay off the boot graph.
{
name: "schema-registry",
test: /[\\/]src[\\/]contracts[\\/](?:schema-registry|zod-validator)\.ts$/,
includeDependenciesRecursively: false,
},
{
name: createFeatureChunkGroups(process.cwd()),
// The boot-failure screen's modules stay out of
// feature-platform even when a grouped module imports them.
includeDependenciesRecursively: false,
},
],
},
},
},
},
};
});