문제
- 새 기능은 참조 기능을 복사해 이름을 바꾸는 방법뿐이다. 리뷰 16 실험 E
에서 이 방법은 12번 막혔다. 접두어 없는 전역 ID(NoRequest, qinv topic,
navigationOrder)는 치환으로 바뀌지 않고, 토큰 경계 없는 치환은
preference·supportReference를 깨뜨린다. 제품이 참조 기능을 지우면 복사할
원본도 없다.
고른 방법 (결정 D1·D2, 오케스트레이터 결정 2·4)
- scripts/create-feature.ts: pnpm create:feature <id> [--context <ctx>]
[--package @scope/name@x.y.z --digest sha256:… --revision <hex>].
템플릿을 이 파일 안에 두고 참조 기능을 import하지 않는다(D1).
- 뼈대: 파라미터 없는 목록 라우트 1, GET 1(SAFE, EXTERNAL_BEARER),
쿼리 1, topic 1, CollectionPage 1, ko-KR·en-US 문구. domain/ 없음.
검증은 공유 zodValidator, 링크는 route ID와 buildRouteUrl
(<base>-routes.ts). 빈 배열 응답은 공유 빈 상태로 그린다.
- 전역 ID는 모두 기능 접두어를 단다(D2): 스키마·mapper·operation·
contribution·policy·diagnostics·chunk·route·namespace·definitionId·
문구 키·telemetry kind·owner. topic은 qinv. + 무작위 26자(Crockford
base32)이고 설치된 topic과 겹치면 거부한다. navigationOrder는 설치된
최댓값 + 10.
- 패키지 인자가 없으면 결정 2의 자리표시자 상수를 import해 쓰고 경고를
출력한다. 인자가 있으면 external-contract-runtime의 신원 검사
(composeContractContributions)로 형식을 확인한다.
- 거부: kebab이 아닌 id, 기존 기능·context id(디렉터리 이름 포함),
같은 접두어를 쓰는 기존 기능, 이미 있는 <base>-context(--context 안내),
같은 라우트 루트·route ID·경로·chunk·문구 키.
- 폴더 밖은 새 context 선언과 pending a11y 기록만 쓴다. 기존 파일은
덮어쓰지 않고(wx), 쓰기나 직후 생성기 실행이 실패하면 만든 것을 지운다.
- 출력: 만든 파일, a11y 서명(FE-GATE-028), 돌릴 게이트 목록, 기준선
재승인이 필요 없다는 안내, 자리표시자 교체 방법.
- 테스트: tests/unit/create-feature.test.ts(렌더 결과만: 접두어, 샘플
토큰 없음, topic 형식·중복, 순서, 거부, 덮어쓰기·되돌리기).
생성된 기능의 테스트는 input 단위 테스트와 런타임 조립·라우터를 거치는
페이지 테스트다. MSW는 createHttpScenarioHandler(설치 계약)를 쓴다.
- 느린 드릴 test:feature-scaffold: removal-fixture로 만든 복사본(README·
CHANGELOG·docs 포함)에 기능을 만들고 커밋한 뒤 types, lint,
architecture, registries, i18n, design-system, diagnostics,
documentation, unit, component, integration, features, coverage,
check:ci, build를 돌린다. FE-GATE-020에 넣고 gates.json, 계약 기준선,
ci-workflow-generation 테스트의 개수를 맞췄다(workflow는 그대로).
- 결정 4: test:sample-removal이 기능 0개 검사 뒤 같은 복사본에서
create:feature로 기능을 만들고 같은 게이트를 scaffold- 이름으로 다시
돌린다.
- tests/release 고정 manifest가 계약 집합을 빈 배열로 고정해, EXTERNAL_
PACKAGE를 쓰는 첫 기능에서 7건이 release-mismatch로 깨졌다. 16-02가
tests/runtime-schema에 한 것처럼 설치된 집합에서 만든다.
- 버린 대안: 참조 기능 복사+토큰 치환(D1에 어긋나고 전역 ID를 놓친다),
topic을 뼈대에서 빼기(실제 기능이 같은 문제를 다시 만난다), 생성
테스트가 tests/mocks의 bootstrap·server를 쓰기(부팅 문서는 테스트 안의
fetcher가 주고, MSW는 setupServer와 http-scenarios만 쓴다).
위험·한계
- 생성기 파일이 1,408줄이다. 대부분 템플릿 문자열이다.
- context-module.ts는 생성기가 글로 읽는 선언이라 실행되지 않는다(참조
context와 같다). 나머지 생성 모듈은 생성된 테스트가 모두 실행한다
(함수 100%, 문장 100%, 페이지 분기 1개 미실행).
- --context reference-context로 참조 context에 넣으면 참조 기능의
installed-context-routing 테스트(라우트 4개 정확히 일치)가 깨진다.
드릴은 새 context를 쓴다.
- test:feature-scaffold, test:sample-removal, check:architecture는
pnpm이 필요해 worktree에서 돌리지 않았다.
- tests/unit/feature-shape-growth.test.ts는 기준 커밋에서도 1 KiB를 넘어
실패한다(이번 측정 1035·1068). 기능이 하나 더 있으면 통과한다.
검증
- RED: 생성한 기능을 넣고 돌리면 tests/release 7건 실패("expected
{ state: 'release-mismatch' } to match { state: 'booted' }"),
ci-workflow-generation 1건 실패(98 vs 99). 접두어 테스트는 템플릿의
스키마 ID를 "NoRequest"로 바꾼 변이에서 실패한다.
- GREEN(worktree에 order-feature 생성): tsc app·test·node rc=0, 전체
eslint rc=0, check-registries "11 registries PASS; compatibility=
additive"(기준선 재승인 없음), verify-documentation-readiness
PASS_SCOPED, check-i18n PASS, check-design-system·check-diagnostics·
check-adapter-inventory PASS, check-ci-contract·workflow·artifact
schema PASS, 생성 테스트 7/7, run-vitest tests/unit·component·features
238파일 통과, integration·contract·runtime-schema·platform·architecture·
release·scripts 59파일 통과(pnpm을 띄우는 2파일 제외).
- --context reference-context와 --package 변형도 tsc·registries·생성
테스트 통과. 참조 기능을 지운 복사본에서 생성 → tsc app·test, i18n,
생성 테스트·release·router 테스트 통과(결정 4 모의).
- 생성물을 지운 뒤 같은 검사 통과(feature-shape-growth 기존 실패 1건
제외), git status 깨끗.
239 lines
8.9 KiB
TypeScript
239 lines
8.9 KiB
TypeScript
import { access, mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
|
|
import { afterEach, describe, expect, it } from "vitest";
|
|
|
|
import {
|
|
CreateFeatureError,
|
|
planFeature,
|
|
randomTopicSuffix,
|
|
writeFeatureFiles,
|
|
type FeatureRequest,
|
|
type InstalledFacts,
|
|
} from "../../scripts/create-feature.ts";
|
|
import { PLACEHOLDER_CONTRACT_PACKAGE_DIGEST } from "../../src/contracts/deployment-admission.ts";
|
|
|
|
/**
|
|
* U7. What `pnpm create:feature` renders, checked without touching the
|
|
* repository. test:feature-scaffold writes a feature into a copy and runs the
|
|
* gates on it; this file covers the ids, the topic, the order and the refusals.
|
|
*/
|
|
const INSTALLED: InstalledFacts = Object.freeze({
|
|
appIds: ["template-app"],
|
|
featureIds: ["orders-feature", "drafts-feature"],
|
|
contexts: [
|
|
{ id: "orders-context", routePath: "orders/*" },
|
|
{ id: "billing-context", routePath: "billing/*" },
|
|
],
|
|
contextDirectories: ["orders-context", "billing-context"],
|
|
routes: [
|
|
{ routeId: "APP_HOME", path: "/", chunkId: "route-home", navigationOrder: 10 },
|
|
{ routeId: "ORDERS_LIST", path: "/orders", chunkId: "route-orders-list", navigationOrder: 50 },
|
|
{ routeId: "NOT_FOUND", path: "*", chunkId: "route-not-found", navigationOrder: null },
|
|
],
|
|
topics: ["qinv.0000000000000000000000000a"],
|
|
messageKeys: ["route.APP_HOME.title", "home.list.title"],
|
|
});
|
|
const TOPIC_SUFFIX = "abcdefghjkmnpqrstvwxyz0123";
|
|
|
|
function plan(request: FeatureRequest, installed: InstalledFacts = INSTALLED) {
|
|
return planFeature(request, installed, () => TOPIC_SUFFIX);
|
|
}
|
|
|
|
function rendered(request: FeatureRequest): string {
|
|
return [...plan(request).files.values()].join("\n");
|
|
}
|
|
|
|
describe("create:feature rendering", () => {
|
|
it("prefixes every global id with the feature and carries no sample token", () => {
|
|
const text = rendered({ id: "invoice-feature" });
|
|
|
|
expect(text).not.toMatch(/reference/iu);
|
|
const ids = [
|
|
...text.matchAll(
|
|
/\b(?:schemaId|inputSchemaId|operationId|mapperId|outputContractId|policyId|diagnosticsOperation|definitionId|chunkId|routeId|moduleId|loadingSurface|contributionId|owner)\s*:\s*"([^"]+)"/gu,
|
|
),
|
|
...text.matchAll(/\bzodValidator\(\s*"([^"]+)"/gu),
|
|
...text.matchAll(/defineQueryNamespaceIdentity\(\s*"([^"]+)"/gu),
|
|
...text.matchAll(/kind: "([a-z][^"]*\.[^"]*)"/gu),
|
|
...text.matchAll(/^\s+"((?:route\.)?[A-Za-z_.]+)": "/gmu),
|
|
].map((match) => match[1] ?? "");
|
|
expect(ids.length).toBeGreaterThan(30);
|
|
for (const id of ids) {
|
|
expect(id).toMatch(
|
|
/^(?:INVOICE_|Invoice|invoice[.-]|route\.INVOICE_LIST\.|route-invoice-|feature-frontend-invoice-feature$)/u,
|
|
);
|
|
}
|
|
expect(text).not.toMatch(/"NoRequest"/u);
|
|
});
|
|
|
|
it("names the route, context and topic it creates", () => {
|
|
const created = plan({ id: "invoice-feature" });
|
|
|
|
expect(created).toMatchObject({
|
|
contextId: "invoice-context",
|
|
newContext: true,
|
|
routeId: "INVOICE_LIST",
|
|
routePath: "/invoice",
|
|
topic: `qinv.${TOPIC_SUFFIX}`,
|
|
placeholder: true,
|
|
});
|
|
expect([...created.files.keys()]).toEqual(
|
|
expect.arrayContaining([
|
|
"src/contexts/invoice-context/context-module.ts",
|
|
"src/features/invoice-feature/feature-module.ts",
|
|
"tests/features/invoice-feature/invoice-feature-input.test.ts",
|
|
"tests/features/invoice-feature/invoice-list-page.test.tsx",
|
|
"artifacts/tests/a11y-manual/INVOICE_LIST.md",
|
|
]),
|
|
);
|
|
expect([...created.files.keys()].some((file) => file.includes("/domain/"))).toBe(false);
|
|
expect(created.files.get("src/contexts/invoice-context/context-module.ts")).toContain(
|
|
'CONTEXT_ROUTE_PATH = "invoice/*"',
|
|
);
|
|
expect(created.files.get("artifacts/tests/a11y-manual/INVOICE_LIST.md")).toMatch(
|
|
/^Status: pending-manual-review$/mu,
|
|
);
|
|
});
|
|
|
|
it("generates a fresh lower-case 26-character topic and refuses an installed one", () => {
|
|
const first = randomTopicSuffix();
|
|
expect(first).toMatch(/^[0-9a-hjkmnp-tv-z]{26}$/u);
|
|
expect(randomTopicSuffix()).not.toBe(first);
|
|
expect(() =>
|
|
planFeature({ id: "invoice-feature" }, INSTALLED, () => "0000000000000000000000000a"),
|
|
).toThrow(/qinv\.0000000000000000000000000a is already installed/u);
|
|
});
|
|
|
|
it("places the route after the last navigation entry", () => {
|
|
expect(rendered({ id: "invoice-feature" })).toContain("navigationOrder: 60,");
|
|
});
|
|
|
|
it("adds the route under an existing context's root", () => {
|
|
const created = plan({ id: "invoice-feature", context: "billing-context" });
|
|
|
|
expect(created).toMatchObject({ newContext: false, routePath: "/billing/invoice" });
|
|
expect([...created.files.keys()].some((file) => file.startsWith("src/contexts/"))).toBe(false);
|
|
});
|
|
|
|
it("pins the placeholder through its exported constant, or the given package", () => {
|
|
expect(rendered({ id: "invoice-feature" })).toContain(
|
|
"digest: PLACEHOLDER_CONTRACT_PACKAGE_DIGEST,",
|
|
);
|
|
const digest = `sha256:${"ab".repeat(32)}`;
|
|
const pinned = plan({
|
|
id: "invoice-feature",
|
|
contractPackage: {
|
|
packageId: "@org-contracts/invoice",
|
|
version: "1.4.2",
|
|
digest,
|
|
sourceRevision: "0a1b2c3d",
|
|
},
|
|
});
|
|
const contract = pinned.files.get(
|
|
"src/features/invoice-feature/contracts/invoice-feature-contract.ts",
|
|
);
|
|
expect(pinned.placeholder).toBe(false);
|
|
expect(contract).toContain(`digest: "${digest}",`);
|
|
expect(contract).not.toContain("PLACEHOLDER");
|
|
expect(digest).not.toBe(PLACEHOLDER_CONTRACT_PACKAGE_DIGEST);
|
|
});
|
|
});
|
|
|
|
describe("create:feature refusals", () => {
|
|
it.each(["Invoice", "invoice_feature", "-invoice", "invoice--x", "invoice-", "", "a".repeat(41)])(
|
|
"refuses the id %j",
|
|
(id) => {
|
|
expect(() => plan({ id })).toThrow(/kebab-case/u);
|
|
},
|
|
);
|
|
|
|
it.each([
|
|
[{ id: "orders-feature" }, /already a feature or context/u],
|
|
[{ id: "orders-context" }, /already a feature or context/u],
|
|
[{ id: "orders" }, /prefix its ids with "orders", which orders-feature already uses/u],
|
|
[{ id: "billing-feature" }, /pass --context billing-context/u],
|
|
[{ id: "invoice-feature", context: "orders" }, /already owns the route root orders\/\*/u],
|
|
[{ id: "invoice-feature", context: "drafts-feature" }, /is a feature id/u],
|
|
[{ id: "home-feature" }, /message keys already exist: home\.list\.title/u],
|
|
[
|
|
{
|
|
id: "invoice-feature",
|
|
contractPackage: {
|
|
packageId: "@org-contracts/invoice",
|
|
version: "1.4.2",
|
|
digest: "sha256:abc",
|
|
sourceRevision: "0a1b2c3d",
|
|
},
|
|
},
|
|
/not a pinned identity: invoice-feature: package digest/u,
|
|
],
|
|
] as const)("refuses %j", (request, reason) => {
|
|
expect(() => plan(request)).toThrow(reason);
|
|
});
|
|
|
|
it("refuses a route that collides with an installed one", () => {
|
|
expect(() =>
|
|
plan(
|
|
{ id: "invoice-feature" },
|
|
{
|
|
...INSTALLED,
|
|
routes: [
|
|
...INSTALLED.routes,
|
|
{ routeId: "LEGACY", path: "/invoice", chunkId: "route-legacy", navigationOrder: null },
|
|
],
|
|
},
|
|
),
|
|
).toThrow(/collides with installed route LEGACY/u);
|
|
});
|
|
});
|
|
|
|
describe("create:feature writing", () => {
|
|
const roots: string[] = [];
|
|
afterEach(async () => {
|
|
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
|
|
});
|
|
|
|
async function emptyRoot(): Promise<string> {
|
|
const root = await mkdtemp(path.join(tmpdir(), "create-feature-"));
|
|
roots.push(root);
|
|
return root;
|
|
}
|
|
|
|
it("refuses to overwrite and writes nothing when one target exists", async () => {
|
|
const root = await emptyRoot();
|
|
const files = plan({ id: "invoice-feature" }).files;
|
|
await mkdir(path.join(root, "artifacts/tests/a11y-manual"), { recursive: true });
|
|
await writeFile(path.join(root, "artifacts/tests/a11y-manual/INVOICE_LIST.md"), "kept\n");
|
|
|
|
await expect(writeFeatureFiles(root, files)).rejects.toThrow(
|
|
/refusing to overwrite: artifacts\/tests\/a11y-manual\/INVOICE_LIST\.md/u,
|
|
);
|
|
expect(await readdir(root)).toEqual(["artifacts"]);
|
|
});
|
|
|
|
it("refuses an existing feature directory", async () => {
|
|
const root = await emptyRoot();
|
|
await mkdir(path.join(root, "src/features/invoice-feature"), { recursive: true });
|
|
|
|
await expect(
|
|
writeFeatureFiles(root, plan({ id: "invoice-feature" }).files, [
|
|
"src/features/invoice-feature",
|
|
]),
|
|
).rejects.toThrow(CreateFeatureError);
|
|
});
|
|
|
|
it("removes what it wrote when a later write fails", async () => {
|
|
const root = await emptyRoot();
|
|
const files = new Map([
|
|
["src/features/broken/first.ts", "export {};\n"],
|
|
// A file cannot be a directory, so this write fails after the first.
|
|
["src/features/broken/first.ts/second.ts", "export {};\n"],
|
|
]);
|
|
|
|
await expect(writeFeatureFiles(root, files)).rejects.toThrow();
|
|
await expect(access(path.join(root, "src"))).rejects.toThrow();
|
|
});
|
|
});
|