Files
tech-log-frontend/scripts/scale/collect-tsc-diagnostics.ts
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

209 lines
7.2 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { mkdir, rm, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import {
assertLinearOrBetter,
growthExponents,
} from "../../src/platform/cardinality/growth-regression.ts";
/**
* Spec §38. TypeScript scale gate.
*
* Parses `tsc --extendedDiagnostics` and measures bounded local fixtures:
* generated feature modules composed by one context, at increasing local
* cardinality. S3/S4 are never compiled; they are verified as topology.
*/
export type TscDiagnostics = Readonly<{
files: number;
lines?: number;
types: number;
symbols: number;
instantiations: number;
memoryKb?: number;
totalTimeSeconds?: number;
}>;
const FIELD_NAMES: Readonly<Record<string, keyof TscDiagnostics>> = Object.freeze({
Files: "files",
Lines: "lines",
Types: "types",
Symbols: "symbols",
Instantiations: "instantiations",
"Memory used": "memoryKb",
"Total time": "totalTimeSeconds",
});
export function parseTscExtendedDiagnostics(text: string): TscDiagnostics {
const parsed: Partial<Record<keyof TscDiagnostics, number>> = {};
for (const line of text.split(/\r?\n/u)) {
const match = /^\s*([A-Za-z][A-Za-z ]*?):\s+([\d.]+)\s*([KMs]?)\s*$/u.exec(line);
if (!match) continue;
const field = FIELD_NAMES[match[1] as string];
if (!field) continue;
const value = Number(match[2]);
if (!Number.isFinite(value)) continue;
parsed[field] = match[3] === "M" ? value * 1024 : value;
}
for (const required of ["files", "types", "symbols", "instantiations"] as const) {
if (parsed[required] === undefined) {
throw new TypeError(`tsc diagnostics missing ${required}`);
}
}
return Object.freeze(parsed) as TscDiagnostics;
}
export function runTscDiagnostics(project: string, cwd = process.cwd()): TscDiagnostics {
const tsc = resolve(cwd, "node_modules/.bin/tsc");
const result = spawnSync(tsc, ["--project", project, "--noEmit", "--extendedDiagnostics"], {
cwd,
encoding: "utf8",
maxBuffer: 16 * 1024 * 1024,
});
if (result.status !== 0) {
throw new Error(`tsc failed for ${project}: ${(result.stdout + result.stderr).slice(-2_000)}`);
}
return parseTscExtendedDiagnostics(result.stdout);
}
/**
* Generates one bounded local app: `features` feature modules, each with its
* own typed contract, composed by one generated index. The shape mirrors the
* repository's feature-module/generated-index pattern.
*/
export async function writeLocalTscFixture(
root: string,
features: number,
): Promise<string> {
await rm(root, { recursive: true, force: true });
await mkdir(join(root, "features"), { recursive: true });
const imports: string[] = [];
const members: string[] = [];
for (let index = 0; index < features; index += 1) {
const id = `feature${index}`;
await writeFile(
join(root, "features", `${id}.ts`),
`export type ${id}Input = Readonly<{ id: string; limit: number; tags?: readonly string[] }>;\n` +
`export type ${id}Output = Readonly<{ items: readonly Readonly<{ id: string; name: string }>[] }>;\n` +
`export const ${id} = Object.freeze({\n` +
` id: "${id}" as const,\n` +
` routes: Object.freeze({ ${id.toUpperCase()}_LIST: "/${id}" }),\n` +
` execute(input: ${id}Input): ${id}Output {\n` +
` return { items: [{ id: input.id, name: String(input.limit) }] };\n` +
` },\n` +
`});\n`,
);
imports.push(`import { ${id} } from "./features/${id}.ts";`);
members.push(` ${id},`);
}
await writeFile(
join(root, "index.ts"),
`${imports.join("\n")}\nexport const LOCAL_FEATURES = Object.freeze([\n${members.join("\n")}\n] as const);\n` +
`export type LocalFeatureId = (typeof LOCAL_FEATURES)[number]["id"];\n`,
);
const tsconfig = join(root, "tsconfig.json");
await writeFile(
tsconfig,
JSON.stringify(
{
compilerOptions: {
target: "ES2022",
module: "ESNext",
moduleResolution: "Bundler",
allowImportingTsExtensions: true,
strict: true,
noEmit: true,
skipLibCheck: true,
types: [],
lib: ["ES2022"],
},
include: ["index.ts", "features/*.ts"],
},
null,
2,
),
);
return tsconfig;
}
export type TscScaleReport = Readonly<{
passed: boolean;
app: TscDiagnostics;
local: readonly Readonly<{ features: number; diagnostics: TscDiagnostics }>[];
checks: readonly Readonly<{ name: string; passed: boolean; detail: string }>[];
}>;
export async function collectTscScale(
localSizes: readonly number[],
cwd = process.cwd(),
): Promise<TscScaleReport> {
const app = runTscDiagnostics("tsconfig.app.json", cwd);
const local: { features: number; diagnostics: TscDiagnostics }[] = [];
for (const features of localSizes) {
const tsconfig = await writeLocalTscFixture(
resolve(cwd, ".tmp/scale-tsc", `local-${features}`),
features,
);
local.push({ features, diagnostics: runTscDiagnostics(tsconfig, cwd) });
}
const checks: { name: string; passed: boolean; detail: string }[] = [];
for (const metric of ["types", "symbols", "instantiations"] as const) {
const series = local.map(({ features, diagnostics }) => ({
n: features,
// Library/baseline cost is constant; growth is judged on what the local
// features add on top of the smallest fixture.
cost: Math.max(1, diagnostics[metric]),
}));
try {
assertLinearOrBetter(series, { maxExponent: 1.3 });
checks.push({
name: `tsc:${metric}`,
passed: true,
detail: `exponents ${growthExponents(series).map((value) => value.toFixed(2)).join(", ")}`,
});
} catch (error) {
checks.push({
name: `tsc:${metric}`,
passed: false,
detail: error instanceof Error ? error.message : String(error),
});
}
}
return Object.freeze({
passed: checks.every((check) => check.passed),
app,
local: Object.freeze(local),
checks: Object.freeze(checks),
});
}
async function main(): Promise<void> {
const artifactArg = process.argv.find((argument) => argument.startsWith("--artifact="));
const sizesArg = process.argv.find((argument) => argument.startsWith("--local-sizes="));
const sizes = (sizesArg?.slice("--local-sizes=".length) ?? "25,100,400")
.split(",")
.map(Number)
.filter((value) => Number.isSafeInteger(value) && value > 0);
const artifact = resolve(
artifactArg?.slice("--artifact=".length) ?? "artifacts/scale/tsc-diagnostics.json",
);
const report = await collectTscScale(sizes);
await mkdir(resolve(artifact, ".."), { recursive: true });
await writeFile(
artifact,
`${JSON.stringify({ schemaVersion: 1, generatedAt: new Date().toISOString(), ...report }, null, 2)}\n`,
);
process.stdout.write(
`tsc app: files=${report.app.files} types=${report.app.types} instantiations=${report.app.instantiations}\n`,
);
for (const check of report.checks) {
process.stdout.write(`${check.passed ? "PASS" : "FAIL"} ${check.name} (${check.detail})\n`);
}
process.stdout.write(`tsc diagnostics artifact: ${artifact}\n`);
if (!report.passed) process.exitCode = 1;
}
if (import.meta.url === `file://${process.argv[1]}`) {
await main();
}