Files
clean-architecture-frontend…/tests/unit/feature-shape-growth.test.ts
T
DongHyeonka 6c5818faec refactor(contracts): bearer 인증 프로필을 EXTERNAL_BEARER로 바꾼다 (1101/16-03)
문제
유일한 bearer 인증 프로필 이름이 샘플 이름 REFERENCE_EXTERNAL_BEARER다.
세션이 필요한 제품 기능은 지운 샘플의 이름을 계속 쓰거나 템플릿 소유
파일에 프로필을 더해야 한다. 샘플 제거 드릴의 잔여 검사 정규식도 이
이름을 잡지 않아 샘플을 지운 제품에 그대로 남는다. 리뷰 (2) 오류
메시지는 abf3ce5가 했고 (1) 이름 변경이 남았다.

고른 방법 (2026-11-03 결정)
- 프로필 이름을 EXTERNAL_BEARER로 바꿨다. 참조 기능의 V2 operation 3개와
  V3 descriptor 3개, external-session-adapter 주석, 테스트, VD-23 문서를
  새 이름으로 옮겼다.
- 옛 이름은 한 릴리스 동안 REST_AUTH_PROFILES에 별칭 한 줄로 남기고
  JSDoc @deprecated를 붙였다. 레지스트리는 키와 authProfileId가 같아야
  하므로 별칭은 EXTERNAL_BEARER를 펼치고 id만 옛 이름으로 둔 객체다.
  그래서 옛 이름을 적은 다운스트림 operation도 같은 transport·헤더로
  해석된다.
- scripts/scale의 PLATFORM_TOKENS에서 이 이름을 뺐다. 참조 기능에 더는
  "REFERENCE"가 든 프로필 이름이 없어 이름 바꾸기에서 보호할 것이 없다.
- 새 테스트 두 개: 별칭이 id만 빼고 EXTERNAL_BEARER와 같게 설치되는지,
  src에 옛 이름이 별칭 한 줄 외에 없는지(완료 기준).

버린 대안
- 별칭 없이 바로 바꾸기: 옛 이름을 쓰는 다운스트림 기능이 모듈 로드에서
  바로 실패한다. 공개 이름을 깨는 변경은 BREAKING 결정이 있을 때만 한다.
- 조회 시점의 이름 매핑(alias 표): resolve·executor·composition 세 곳이
  매핑을 알아야 한다. 프로필 항목 하나가 더 작다.

위험·한계
- 설치된 프로필이 셋이 된다. 같은 설정이 두 id로 있을 뿐 권한이 넓어지지
  않는다. 별칭은 다음 minor에서 지우고 CHANGELOG [계약] 행을 남긴다.
  그때 "src only on the alias line" 테스트의 기대값을 빈 목록으로 바꾼다.
- 다운스트림 문자열 id("REFERENCE_EXTERNAL_BEARER")에는 @deprecated 표시가
  보이지 않는다. CHANGELOG로 알린다.
- FE-REG-API 행 3개의 authProfileId가 바뀐다. breakingFields가 아니라
  behavior-change이므로 증거 없이 게이트를 통과한다. 기준선 재승인은 이번
  작업 묶음 끝에서 한 번에 한다.
- 초기 JS gzip(초기 청크 파일별 gzip 합) 203,818 → 203,840 B(+22 B). 별칭
  항목이 rest-profiles가 있는 초기 청크에 실린다. 참조 기능 계약은 lazy
  청크라 초기 크기에 영향이 없다.

검증
- RED(수정 전): rest-profile-contract.test.ts 새 사례 2건 실패("expected
  undefined to match object { transport: 'BEARER_HEADER', …(1) }",
  "expected [ …(9) ] to deeply equal [ Array(1) ]").
- GREEN: 같은 파일 10/10 통과. check-registries "11 registries PASS"
  (FE-REG-API authProfileId 3건 behavior-change).
- 회귀: tests/{unit,integration,features,contract,runtime-schema}
  207 파일 2,366건 통과(pnpm·corepack을 띄우는 6개 제외:
  http-scenario-evidence, ci-workflow-generation, lab-performance,
  fixture-node-modules, deployment-admission, security-followup-archive).
  tsc app·test·node rc=0, 바꾼 파일 eslint rc=0. vite build 성공.
- 미실행: check:architecture, test:sample-removal(pnpm 필요), e2e.

Refs: docs/reviews/2026-11-01-maturity-review/16-structure-patterns.md
2026-11-03 00:55:33 +09:00

177 lines
7.0 KiB
TypeScript

import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import {
FEATURE_SHAPE_BASELINE_PATH,
FEATURE_SHAPE_CEILINGS_PATH,
measureInitialJavascriptGzipBytes,
renameReferenceFeature,
} from "../../scripts/scale/measure-feature-shape-growth.ts";
import { APP_MAX_CONTEXTS } from "../../src/apps/template-app/app-module.ts";
import { CONTEXT_MAX_FEATURES } from "../../src/contexts/reference-context/context-module.ts";
/**
* 11-04 (D-18). The scale evidence used to come from stub features that only
* differ by name, so the cost of one app growing towards its declared ceiling
* (20 contexts x 200 features) was never measured. The committed baseline is a
* measurement with copies of the real reference feature.
*/
const context = { id: "shape-context-0", routeRoot: "shape-0" } as const;
type Run = Readonly<{
addedFeatures: number;
routes: number;
tsc: Readonly<{ passed: boolean; instantiations: number; wallMs: number }>;
build: Readonly<{
wallMs: number;
initialJavascriptGzipBytes: number;
lazyJavascriptFiles: number;
}>;
loadBefore: readonly number[];
}>;
describe("feature-shape growth measurement (11-04)", () => {
it("renames every feature-owned identifier of a reference copy", () => {
const source = [
'featureId: "reference-feature"',
'path: "/examples/reference-resources/:id"',
"REFERENCE_RESOURCE_LIST",
"ReferenceResourcePage",
'contextId: "reference-context"',
'topic: "qinv.01k10f7m3w9p6r2c8v5n4x"',
"NoRequest",
].join("\n");
const renamed = renameReferenceFeature(source, "s007", context);
expect(renamed).not.toMatch(/reference/iu);
expect(renamed).toContain('featureId: "s007-feature"');
expect(renamed).toContain('path: "/shape-0/s007-resources/:id"');
expect(renamed).toContain("S007_RESOURCE_LIST");
expect(renamed).toContain("S007ResourcePage");
expect(renamed).toContain('contextId: "shape-context-0"');
expect(renamed).toContain('topic: "qinv.shape.s007"');
expect(renamed).toContain("S007NoRequest");
});
// 1101/07-04 made assembly refuse a TEMPLATE_FIXTURE contribution outside
// the reference feature, so every copy must pin an EXTERNAL_PACKAGE the way
// a product feature does.
it("turns the copied fixture source into an external package", () => {
const source = [
" source: Object.freeze({",
' kind: "TEMPLATE_FIXTURE" as const,',
' fixtureId: "REFERENCE_FEATURE_V1" as const,',
" revision: 1 as const,",
" }),",
" contractPackages: Object.freeze([]),",
].join("\n");
const renamed = renameReferenceFeature(source, "s007", context);
expect(renamed).not.toContain("TEMPLATE_FIXTURE");
expect(renamed).toContain('kind: "EXTERNAL_PACKAGE" as const');
expect(renamed.match(/packageId: "@feature-shape\/s007"/gu)).toHaveLength(2);
expect(renamed).not.toContain("contractPackages: Object.freeze([])");
});
it("keeps platform-owned names that only contain the word", () => {
const source =
"REFERENCE_FEATURE_V1 supportReference";
expect(renameReferenceFeature(source, "s001", context)).toBe(source);
});
it("commits a baseline measured at 25 and 100 real-shape features, twice each", async () => {
const baseline = JSON.parse(
await readFile(FEATURE_SHAPE_BASELINE_PATH, "utf8"),
) as Readonly<{
environment: Readonly<Record<string, unknown>>;
source: unknown;
runs: readonly Run[];
}>;
expect(baseline.environment).toMatchObject({
cpuModel: expect.any(String),
logicalCpus: expect.any(Number),
});
// 11-05 (2026-09-29). Without the commit it measured, nobody can tell
// whether the baseline still describes the code or compare a new run.
expect(baseline.source).toEqual({
commit: expect.stringMatching(/^[0-9a-f]{40}$/u),
modifiedPaths: expect.any(Array),
});
const bySize = (size: number) =>
baseline.runs.filter((run) => run.addedFeatures === size);
const [origin] = bySize(0);
expect(origin?.tsc.passed).toBe(true);
for (const size of [25, 100]) {
const runs = bySize(size);
// A failed typecheck is the result and is not repeated.
expect(runs.length).toBeGreaterThanOrEqual(runs[0]?.tsc.passed ? 2 : 1);
for (const run of runs) {
// Every copy contributes the reference feature's own routes.
expect((run.routes - origin!.routes) % size).toBe(0);
expect(run.routes).toBeGreaterThan(origin!.routes);
expect(run.build.lazyJavascriptFiles).toBeGreaterThan(
origin!.build.lazyJavascriptFiles,
);
expect(run.loadBefore).toHaveLength(3);
}
// Compiler counts are deterministic; only times vary with the host.
expect(new Set(runs.map((run) => run.tsc.instantiations)).size).toBe(1);
}
});
/**
* 15-01. The initial budget (config/performance/budgets.json) is a fixed
* 200 KiB for the whole app, so what one installed feature adds to the
* initial chunk decides how many features fit. Before 15-01 every feature's
* contracts, schemas, mappers, HTTP gateway and API loaded at boot: +3,922 B
* per copy, and the first added feature exceeded the budget. Only what the
* shell needs before a feature route is entered may load at boot (route
* table, navigation and page messages, invalidation identities: 741 B when
* 15-01 landed); the rest loads with the feature's routes. The bound also
* fails if the feature-declarations chunk group in vite.config.ts stops
* matching.
*/
it("adds at most 1 KiB of initial JavaScript per reference-shaped feature (15-01)", async () => {
const withoutCopies = await measureInitialJavascriptGzipBytes(0);
const withOneCopy = await measureInitialJavascriptGzipBytes(1);
expect(withOneCopy - withoutCopies).toBeLessThanOrEqual(1_024);
}, 120_000);
it("states in the committed rationale what the ceilings rest on", async () => {
// The rationale lives next to the baseline, not in a review document: the
// history documents may be deleted after copying (README.md).
const rationale = JSON.parse(
await readFile(FEATURE_SHAPE_CEILINGS_PATH, "utf8"),
) as Readonly<{
baseline: string;
ceilings: Readonly<{ contextMaxFeatures: number; appMaxContexts: number }>;
axes: readonly Readonly<Record<string, string>>[];
}>;
expect(rationale.baseline).toBe(FEATURE_SHAPE_BASELINE_PATH);
expect(rationale.ceilings).toEqual({
contextMaxFeatures: CONTEXT_MAX_FEATURES,
appMaxContexts: APP_MAX_CONTEXTS,
});
expect(rationale.axes.map((row) => row.axis)).toEqual(
expect.arrayContaining([
"Typecheck of one app",
"Production build",
"Initial JavaScript",
"Lazy JavaScript",
"Routes",
]),
);
for (const row of rationale.axes) {
for (const column of ["axis", "verified", "condition", "notVerified"])
expect(row[column], `${row.axis}.${column}`).toMatch(/\S/u);
}
});
});