Files
DongHyeonka 7679ce6592 revert: #55 되돌림(411c9338)을 되돌려 그룹 C 검사기 변경을 다시 넣는다
This reverts commit 411c9338c6.

문제: #55(b4895894)가 main run 376의 FE-GATE-030(browser file/storage
제거 드릴)을 깨서 411c9338(#64)로 통째로 되돌렸다. #55의 검사기 진단과
시험 빈틈 고침 12커밋이 main에 없다.

고른 방법: 되돌림을 되돌려 #55를 그대로 다시 넣고, 드릴을 깬 원인은
다음 커밋에서 따로 고친다. 리뷰어가 이 커밋이 #55와 같은지 트리로 볼 수
있다. 이 커밋의 트리는 b4895894 트리에 그 뒤 main에 들어온 #63·#65만
더한 것이다(git diff b4895894 <이 커밋>: docs/ledger 두 파일,
cross-context-invalidation adapter 한 파일과 시험 두 파일).
버린 대안: #55 커밋 12개 cherry-pick. 71606ff1 merge의 충돌 해소분을
다시 풀어야 하고 결과 트리를 b4895894와 대조하기 어렵다.

위험·한계: 이 커밋만으로는 main 단계의 FE-GATE-030이 run 376처럼
실패한다(같은 트리 내용). PR 단계 게이트는 돈다.

검증: 다음 커밋 본문에 적는다. 그 커밋의 새 단언을 이 커밋의 검사기에
돌리면 실패한다(RED).

Refs: #55, #64
2026-11-19 16:32:00 +09:00

238 lines
8.2 KiB
TypeScript

import { createHash } from "node:crypto";
import { lstat, readFile, realpath } from "node:fs/promises";
import path from "node:path";
import type { BuildManifestArtifact } from "../../src/contracts/release-artifacts.ts";
import { moduleInventoryArtifactSchema } from "../contracts/release-artifacts.ts";
type VerifyBuildManifestOutputsDependencies = Readonly<{
repositoryRoot?: string;
readBytes?: (target: string) => Promise<Buffer>;
realpathPath?: (target: string) => Promise<string>;
assertRegularFile?: (target: string) => Promise<void>;
assertDirectory?: (target: string) => Promise<void>;
}>;
export const CANONICAL_VITE_MANIFEST_PATH = "dist/.vite/manifest.json";
function isSafeRelativePath(value: string): boolean {
return (
value.length > 0 &&
!path.posix.isAbsolute(value) &&
!path.win32.isAbsolute(value) &&
!value.includes("\\") &&
!value.includes("\0") &&
path.posix.normalize(value) === value &&
value !== ".." &&
!value.startsWith("../")
);
}
function isWithinRoot(root: string, target: string): boolean {
const relative = path.relative(root, target);
return (
relative === "" ||
(relative !== ".." &&
!relative.startsWith(`..${path.sep}`) &&
!path.isAbsolute(relative))
);
}
function belongsToApprovedRoot(value: string, approvedRoot: string): boolean {
return value.startsWith(`${approvedRoot}/`);
}
async function defaultAssertRegularFile(target: string): Promise<void> {
const metadata = await lstat(target);
if (!metadata.isFile() || metadata.isSymbolicLink()) {
throw new TypeError("not a regular file");
}
}
async function defaultAssertDirectory(target: string): Promise<void> {
const metadata = await lstat(target);
if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
throw new TypeError("not a directory");
}
}
export async function verifyBuildManifestOutputs(
manifest: BuildManifestArtifact,
dependencies: VerifyBuildManifestOutputsDependencies = {},
): Promise<string[]> {
const repositoryRoot = path.resolve(dependencies.repositoryRoot ?? process.cwd());
const readBytes = dependencies.readBytes ?? readFile;
const realpathPath = dependencies.realpathPath ?? realpath;
const assertRegularFile = dependencies.assertRegularFile ?? defaultAssertRegularFile;
const assertDirectory = dependencies.assertDirectory ?? defaultAssertDirectory;
const mismatches: string[] = [];
const resolvedRoot = await realpathPath(repositoryRoot);
const approvedRoots = new Map<string, Promise<string | null>>();
function resolveApprovedRoot(relativeRoot: string): Promise<string | null> {
const existing = approvedRoots.get(relativeRoot);
if (existing) return existing;
const pending = (async () => {
const absoluteRoot = path.resolve(repositoryRoot, relativeRoot);
try {
await assertDirectory(absoluteRoot);
const resolvedApprovedRoot = await realpathPath(absoluteRoot);
return isWithinRoot(resolvedRoot, resolvedApprovedRoot)
? resolvedApprovedRoot
: null;
} catch {
return null;
}
})();
approvedRoots.set(relativeRoot, pending);
return pending;
}
async function confinedPath(
label: string,
relativePath: string,
kind: "file" | "directory",
approvedRoot?: string,
): Promise<string | null> {
if (
!isSafeRelativePath(relativePath) ||
(approvedRoot !== undefined &&
!belongsToApprovedRoot(relativePath, approvedRoot))
) {
mismatches.push(`buildManifest:${label}:path`);
return null;
}
const absolutePath = path.resolve(repositoryRoot, relativePath);
if (!isWithinRoot(repositoryRoot, absolutePath)) {
mismatches.push(`buildManifest:${label}:path`);
return null;
}
try {
if (kind === "file") await assertRegularFile(absolutePath);
else await assertDirectory(absolutePath);
const resolvedPath = await realpathPath(absolutePath);
const resolvedApprovedRoot = approvedRoot
? await resolveApprovedRoot(approvedRoot)
: resolvedRoot;
if (
resolvedApprovedRoot === null ||
!isWithinRoot(resolvedRoot, resolvedPath) ||
!isWithinRoot(resolvedApprovedRoot, resolvedPath)
) {
mismatches.push(`buildManifest:${label}:path`);
return null;
}
return absolutePath;
} catch {
mismatches.push(`buildManifest:${label}:missing`);
return null;
}
}
if (manifest.outputs.directory !== "dist") {
mismatches.push("buildManifest:directory:path");
} else {
await confinedPath("directory", manifest.outputs.directory, "directory");
}
if (manifest.outputs.viteManifest !== CANONICAL_VITE_MANIFEST_PATH) {
mismatches.push("buildManifest:viteManifest:path");
} else {
await confinedPath(
"viteManifest",
manifest.outputs.viteManifest,
"file",
"dist",
);
}
await confinedPath(
"runtimeConfigSchema",
manifest.outputs.runtimeConfigSchema,
"file",
"dist",
);
for (const [chunkId, chunkPath] of Object.entries(manifest.outputs.routeChunks)) {
if (!isSafeRelativePath(chunkPath)) {
mismatches.push(`buildManifest:routeChunk:${chunkId}:path`);
continue;
}
await confinedPath(
`routeChunk:${chunkId}`,
path.posix.join(manifest.outputs.directory, chunkPath),
"file",
"dist",
);
}
const moduleInventoryPath = await confinedPath(
"moduleInventory",
manifest.outputs.moduleInventory,
"file",
"artifacts/quality",
);
if (moduleInventoryPath) {
try {
const bytes = await readBytes(moduleInventoryPath);
const digest = createHash("sha256").update(bytes).digest("hex");
if (digest !== manifest.moduleInventoryHash) {
mismatches.push("buildManifest:moduleInventoryHash");
}
try {
moduleInventoryArtifactSchema.parse(JSON.parse(bytes.toString("utf8")));
} catch {
mismatches.push("buildManifest:moduleInventory:invalid");
}
} catch {
mismatches.push("buildManifest:moduleInventory:missing");
}
}
return mismatches;
}
/**
* 0929/13-03. The built chunk of a route's lazy page, for the build manifest
* and the two release checks that compare its `routeChunks`. A route runtime's
* `moduleId` is the file name of the page it imports
* (`src/presentation/routes/route-runtime.tsx`, a generated feature's
* `<id>-route-runtime.ts`), so the chunk is the dynamic entry whose source
* file — the Vite manifest key — has that name. The chunk's own `name` used to
* be matched instead, so a chunk-naming change in vite.config.ts stopped the
* build with a reason-less `Missing built route chunk`.
*/
export type RouteChunkLookup = Readonly<{ file: string }> | Readonly<{ error: string }>;
const SOURCE_EXTENSION = /\.(?:tsx|ts|jsx|js)$/u;
export function findRouteChunk(
manifest: Readonly<Record<string, unknown>>,
routeId: string,
moduleId: string | undefined,
): RouteChunkLookup {
if (moduleId === undefined) {
return { error: `Missing built route chunk: ${routeId} has no route runtime contract (ROUTE_RUNTIME_CONTRACT)` };
}
const matches: { source: string; file: string }[] = [];
for (const [key, entry] of Object.entries(manifest)) {
if (!isManifestRecord(entry) || entry["isDynamicEntry"] !== true || typeof entry["file"] !== "string") continue;
const source = typeof entry["src"] === "string" ? entry["src"] : key;
if (path.posix.basename(source).replace(SOURCE_EXTENSION, "") === moduleId) {
matches.push({ source, file: entry["file"] });
}
}
if (matches.length === 1) return { file: matches[0]!.file };
if (matches.length === 0) {
return {
error:
`Missing built route chunk: ${routeId}: no lazily imported module in the Vite manifest has the source ` +
`file ${moduleId}.tsx (or .ts). A route runtime's moduleId must be the file name of the page it imports.`,
};
}
return {
error:
`Ambiguous built route chunk: ${routeId}: the lazily imported modules ` +
`${matches.map(({ source }) => source).join(", ")} are all named ${moduleId}.`,
};
}
function isManifestRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}