test(features): 제품 확장 타입 검사 탐침이 제품 파일을 덮어쓰지 않고 덧붙인다

문제
tests/unit/product-extension-typecheck.test.ts(1103/09-02 탐침)는 저장소
복사본의 src/contracts/product-contracts.ts와
src/bootstrap/product-composition.ts를 탐침 내용으로 통째로 바꿔 쓴다.
탐침의 composeProduct는 typecheckProbeSettings 하나만 돌려준다. 제품이
자기 capability를 product-composition.ts에서 만들고 자기 기능의 needs에
적으면, 복사본에서는 그 값이 사라져 app 프로그램이
src/bootstrap/runtime-adapters.ts에서 TS2741로 실패한다. memento와
tech-log 모두 제품 capability를 쓰므로, 동기화 직후 FE-GATE-005가 코드와
무관하게 실패한다(리뷰 실험 09-probe-downstream).

고른 방법
- 탐침은 복사본의 product-contracts.ts·product-composition.ts를 같은
  폴더의 typecheck-probe-product-contracts.ts·
  typecheck-probe-product-composition.ts로 옮긴다. 새 파일은 옮긴 모듈을
  export *로 다시 내보낸다. 그리고 런타임 설정 필드, env 행,
  composeProduct 결과와 그 capabilities를 펼친 뒤 탐침의 키·행·capability만
  더한다. 인증 프로필, credential provider, 선택 칸, session owner, 제품이
  더한 다른 export는 그대로 남는다.
- capability 타입은 저장소가 아니라 복사본의 product-capabilities.ts 끝에
  덧붙인다.
- 같은 함수로 "제품 capability를 기능에 주는 다운스트림"을 먼저 만들고 그
  위에 탐침을 올리는 케이스를 더했다(describe 1105/09-01). 다운스트림
  흉내도 덧붙이는 방식이라, 실제 다운스트림에서 이 테스트를 돌려도 그
  제품의 파일을 지우지 않는다. 이름은 예약 접두사
  typecheck-probe-downstream-*를 쓴다.
- 예약 이름 검사는 기능 폴더에 더해 context 폴더와 옮길 파일 이름도 본다.

버린 대안
- 제품 파일이 출하 상태가 아니면 탐침을 건너뛴다(리뷰의 (나)). 다운스트림
  상태의 타입 경로 확인을 잃고, 건너뛰기로 검사를 약하게 한다.
- 다운스트림 흉내를 제품 파일 전체를 새로 쓰는 방식으로 만든다. 실제
  다운스트림에서 이 테스트를 돌리면 그 제품의 capability를 지워 같은
  TS2741이 다시 난다.

위험·한계
- 제품 파일의 export 이름(composeProduct, composeProductSessionOwner,
  PRODUCT_*)에 기댄다. 템플릿이 그 이름을 import하므로 계약이다.
- credentialProviders와 인증 프로필은 Record라 빠져도 tsc가 모른다.
  펼쳐서 남기지만 테스트로 증명하지는 않는다.
- 탐침 context는 여전히 소유 앱을 template-app으로 고정한다. 앱 id를
  바꾼 제품에서는 생성기가 멈출 수 있다(리뷰 09-01의 남은 가정, 실행
  안 함). 이 커밋 범위 밖이다.
- 케이스가 하나 늘어 이 파일의 tsc 실행이 3회에서 6회가 된다. 케이스별
  제한 시간 120초는 그대로다.
- 결함이 테스트 파일 안의 탐침에 있어서, 표준 RED 구성(커밋의 테스트 +
  부모의 비테스트 파일)은 GREEN과 같다. RED는 커밋 위에 탐침을 부모처럼
  덮어쓰게 되돌리는 patch를 적용해 본다.

검증
- desktop batch에서 확인: node scripts/run-vitest.ts run
  tests/unit/product-extension-typecheck.test.ts, check:types, lint.
  RED patch를 적용하면 1105/09-01 케이스만 TS2741로 실패해야 한다.
- 이 노트북에서는 실행하지 않았다.

Refs: 1105/09-01
This commit is contained in:
DongHyeonka
2026-11-05 22:05:52 +09:00
parent e85c8361b6
commit 397664e439
+203 -93
View File
@@ -1,6 +1,6 @@
import { spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { cp, mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
@@ -23,72 +23,131 @@ import { REMOVAL_FIXTURE_COPY_TARGETS } from "../../scripts/lib/removal-fixture.
* - a product runtime-config key with a `.default()`, which the template's
* own tests must not have to spell out.
*
* Only product-owned files and the feature's own directory are written.
* Only product-owned files, the product files kept next to them and the
* probe's own feature and context directories are written.
*
* The probe's names (`typecheck-probe-*`) are reserved for it: they are not
* the manual's example names, which a product may well use (1103 X2 #1). The
* capability type is appended to the product's own declaration, which a
* TypeScript interface merges, so a product that already declares
* capabilities keeps them.
* the manual's example names, which a product may well use (1103 X2 #1).
*
* 1105/09-01. The probe adds to the product's files and keeps everything they
* already declare and build. The capability type is appended to the
* product's own declaration, which a TypeScript interface merges. The
* product's `product-contracts.ts` and `product-composition.ts` move to
* `<name>-product-*.ts` beside themselves; the probe's files re-export them
* and add only the probe's key, env row and capability on top. Writing those
* two files from scratch dropped the capabilities a product builds for its
* own features, so in such a product the app program failed with TS2741 in
* `src/bootstrap/runtime-adapters.ts`.
*/
const PRODUCT_CAPABILITIES_FILE = "src/features/product-capabilities.ts";
const PRODUCT_CONTRACTS_FILE = "src/contracts/product-contracts.ts";
const PRODUCT_COMPOSITION_FILE = "src/bootstrap/product-composition.ts";
/** Every name one extension adds, derived from one reserved name. */
function productExtension(name: string, camelName: string, constantName: string) {
return Object.freeze({
featureId: `${name}-feature`,
contextId: `${name}-context`,
routePath: `${name}/*`,
messageKey: `${camelName}.title`,
capability: `${camelName}Settings`,
configKey: `${constantName}_PAGE_SIZE`,
keptContracts: `src/contracts/${name}-product-contracts.ts`,
keptComposition: `src/bootstrap/${name}-product-composition.ts`,
});
}
type ProductExtension = ReturnType<typeof productExtension>;
/** The probe itself. */
const PROBE = productExtension("typecheck-probe", "typecheckProbe", "TYPECHECK_PROBE");
/**
* 1105/09-01. Stands in for a downstream's own capability and the feature that
* needs it. It is added the same way, so in a downstream it lands on top of
* the downstream's real product files too.
*/
const DOWNSTREAM = productExtension(
"typecheck-probe-downstream",
"typecheckProbeDownstream",
"TYPECHECK_PROBE_DOWNSTREAM",
);
/** Appended to the product's own `product-capabilities.ts`. */
const PRODUCT_CAPABILITY_TYPES = `
function capabilityType(extension: ProductExtension): string {
return `
export interface ProductFeaturePlatformCapabilities {
readonly typecheckProbeSettings: Readonly<{ pageSize(): number }>;
readonly ${extension.capability}: Readonly<{ pageSize(): number }>;
}
`;
}
const PRODUCT_CONTRACTS = `import { z } from "./zod.ts";
/** Replaces `product-contracts.ts`; the product's own is kept beside it. */
function productContracts(extension: ProductExtension): string {
const kept = `./${path.posix.basename(extension.keptContracts)}`;
return `import {
PRODUCT_ENV_REGISTRY as KEPT_PRODUCT_ENV_REGISTRY,
PRODUCT_RUNTIME_CONFIG_FIELDS as KEPT_PRODUCT_RUNTIME_CONFIG_FIELDS,
} from "${kept}";
import { z } from "./zod.ts";
/**
* Product-owned. Filled by the 1103/09-02 typecheck fixture on top of the
* product's own file, kept as ${kept} (1105/09-01).
*/
export * from "${kept}";
/** Product-owned. Filled by the 1103/09-02 typecheck fixture. */
export const PRODUCT_RUNTIME_CONFIG_FIELDS = Object.freeze({
TYPECHECK_PROBE_PAGE_SIZE: z.int().min(1).max(100).default(20),
...KEPT_PRODUCT_RUNTIME_CONFIG_FIELDS,
${extension.configKey}: z.int().min(1).max(100).default(20),
});
export const PRODUCT_ENV_REGISTRY = Object.freeze({
TYPECHECK_PROBE_PAGE_SIZE: {
...KEPT_PRODUCT_ENV_REGISTRY,
${extension.configKey}: {
phase: "runtime",
classification: "public",
required: false,
defaultValue: "20",
},
} as const);
export const PRODUCT_REST_AUTH_PROFILES = Object.freeze({});
`;
const PRODUCT_COMPOSITION = `import type {
ProductComposition,
ProductCompositionContext,
ProductSessionOwner,
ProductSessionOwnerContext,
} from "./product-composition-contract.ts";
/** Product-owned. Filled by the 1103/09-02 typecheck fixture. */
export function composeProductSessionOwner(
context: ProductSessionOwnerContext,
): ProductSessionOwner {
return null;
}
/** Replaces `product-composition.ts`; the product's own is kept beside it. */
function productComposition(extension: ProductExtension): string {
const kept = `./${path.posix.basename(extension.keptComposition)}`;
return `import type {
ProductComposition,
ProductCompositionContext,
} from "./product-composition-contract.ts";
import { composeProduct as composeKeptProduct } from "${kept}";
/**
* Product-owned. Filled by the 1103/09-02 typecheck fixture on top of the
* product's own file, kept as ${kept} (1105/09-01).
*/
export * from "${kept}";
export function composeProduct(context: ProductCompositionContext) {
const pageSize = context.config.TYPECHECK_PROBE_PAGE_SIZE;
const product = composeKeptProduct(context);
const pageSize = context.config.${extension.configKey};
return {
...product,
capabilities: {
typecheckProbeSettings: Object.freeze({ pageSize: () => pageSize }),
...product.capabilities,
${extension.capability}: Object.freeze({ pageSize: () => pageSize }),
},
credentialProviders: {},
} satisfies ProductComposition;
}
`;
}
const FEATURE_ID = "typecheck-probe-feature";
const CONTEXT_ID = "typecheck-probe-context";
function featureModule(extension: ProductExtension): string {
return `import { defineFeatureModule } from "../feature-module.ts";
const FEATURE_MODULE = `import { defineFeatureModule } from "../feature-module.ts";
export const FEATURE_MODULE_ID = "${FEATURE_ID}";
export const FEATURE_CONTEXT_ID = "${CONTEXT_ID}";
export const FEATURE_MODULE_ID = "${extension.featureId}";
export const FEATURE_CONTEXT_ID = "${extension.contextId}";
export const FEATURE_MODULE = defineFeatureModule({
id: FEATURE_MODULE_ID,
@@ -106,54 +165,59 @@ export const FEATURE_MODULE = defineFeatureModule({
},
routes: {},
// Both locales: with the sample features removed (test:sample-removal)
// this is the only catalog the message key types come from.
// the probe's catalogs are the only ones the message key types come from.
messages: {
"ko-KR": { "typecheckProbe.title": "타입 검사 탐침" },
"en-US": { "typecheckProbe.title": "Typecheck probe" },
"ko-KR": { "${extension.messageKey}": "타입 검사 탐침" },
"en-US": { "${extension.messageKey}": "Typecheck probe" },
},
loadRuntime: async () => (await import("./feature-runtime.ts")).FEATURE_RUNTIME,
} as const);
`;
}
const FEATURE_RUNTIME = `import { defineFeatureAdapterContribution } from "../feature-adapter-contribution.ts";
function featureRuntime(extension: ProductExtension): string {
return `import { defineFeatureAdapterContribution } from "../feature-adapter-contribution.ts";
import { defineFeatureRuntime } from "../feature-module.ts";
type TypecheckProbeInput = Readonly<{ pageSize(): number }>;
declare module "../../application/ports/in/application-api.ts" {
interface ApplicationFeatureInputs {
"${FEATURE_ID}": TypecheckProbeInput;
"${extension.featureId}": TypecheckProbeInput;
}
}
export const FEATURE_RUNTIME = defineFeatureRuntime({
featureId: "${FEATURE_ID}",
featureId: "${extension.featureId}",
schemas: {},
adapters: [
defineFeatureAdapterContribution({
featureId: "${FEATURE_ID}",
needs: ["typecheckProbeSettings"] as const,
createInput: ({ typecheckProbeSettings }) =>
featureId: "${extension.featureId}",
needs: ["${extension.capability}"] as const,
createInput: ({ ${extension.capability} }) =>
Object.freeze({
featureId: "${FEATURE_ID}",
input: Object.freeze({ pageSize: () => typecheckProbeSettings.pageSize() }),
featureId: "${extension.featureId}",
input: Object.freeze({ pageSize: () => ${extension.capability}.pageSize() }),
}),
}),
],
contractContributions: [],
} as const);
`;
}
const CONTEXT_ROUTES = `import type { RouteObject } from "react-router-dom";
export const FEATURE_CONTEXT_ROUTES: readonly RouteObject[] = Object.freeze([]);
`;
const CONTEXT_MODULE = `export const CONTEXT_MODULE_ID = "${CONTEXT_ID}";
function contextModule(extension: ProductExtension): string {
return `export const CONTEXT_MODULE_ID = "${extension.contextId}";
export const CONTEXT_APP_ID = "template-app";
export const CONTEXT_ROUTE_PATH = "typecheck-probe/*";
export const CONTEXT_ROUTE_PATH = "${extension.routePath}";
export const CONTEXT_MAX_FEATURES = 1;
`;
}
const roots: string[] = [];
@@ -161,53 +225,99 @@ afterAll(async () => {
await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true })));
});
describe("1103/09-02 a product filled through its own files typechecks", () => {
it("passes the app, node and test programs", async () => {
const root = await mkdtemp(path.join(tmpdir(), "product-extension-typecheck-"));
roots.push(root);
// The repository's one copy-target list for a fixture copy. A removal
// drill runs this test in a copy that has already lost some of them
// (test:optional-recipe-removal deletes recipes/).
expect(existsSync(path.resolve("src/features", FEATURE_ID)), FEATURE_ID).toBe(false);
for (const entry of REMOVAL_FIXTURE_COPY_TARGETS) {
if (!existsSync(path.resolve(entry))) continue;
await cp(path.resolve(entry), path.join(root, entry), {
recursive: true,
filter: (source) => !source.includes(`${path.sep}.generated`),
});
}
await linkFixtureNodeModules(root);
const shipped = await readFile(path.resolve("src/features/product-capabilities.ts"), "utf8");
const files: Readonly<Record<string, string>> = {
"src/features/product-capabilities.ts": `${shipped}${PRODUCT_CAPABILITY_TYPES}`,
"src/contracts/product-contracts.ts": PRODUCT_CONTRACTS,
"src/bootstrap/product-composition.ts": PRODUCT_COMPOSITION,
[`src/contexts/${CONTEXT_ID}/context-module.ts`]: CONTEXT_MODULE,
[`src/features/${FEATURE_ID}/feature-module.ts`]: FEATURE_MODULE,
[`src/features/${FEATURE_ID}/feature-runtime.ts`]: FEATURE_RUNTIME,
[`src/features/${FEATURE_ID}/context-routes.ts`]: CONTEXT_ROUTES,
};
for (const [file, content] of Object.entries(files)) {
await mkdir(path.dirname(path.join(root, file)), { recursive: true });
await writeFile(path.join(root, file), content);
}
async function copyRepository(): Promise<string> {
const root = await mkdtemp(path.join(tmpdir(), "product-extension-typecheck-"));
roots.push(root);
// The repository's one copy-target list for a fixture copy. A removal
// drill runs this test in a copy that has already lost some of them
// (test:optional-recipe-removal deletes recipes/).
for (const entry of REMOVAL_FIXTURE_COPY_TARGETS) {
if (!existsSync(path.resolve(entry))) continue;
await cp(path.resolve(entry), path.join(root, entry), {
recursive: true,
filter: (source) => !source.includes(`${path.sep}.generated`),
});
}
await linkFixtureNodeModules(root);
return root;
}
const generated = spawnSync(
process.execPath,
[path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`],
async function writeFiles(root: string, files: Readonly<Record<string, string>>): Promise<void> {
for (const [file, content] of Object.entries(files)) {
await mkdir(path.dirname(path.join(root, file)), { recursive: true });
await writeFile(path.join(root, file), content);
}
}
/**
* Adds one capability, its runtime-config key and a feature that needs it to
* the copy, keeping whatever the copy's product files already hold.
*/
async function addProductExtension(root: string, extension: ProductExtension): Promise<void> {
// The extension's names are reserved for this file: a product that took one
// fails here, by name, instead of with a TS error in the copy.
for (const owned of [
`src/features/${extension.featureId}`,
`src/contexts/${extension.contextId}`,
extension.keptContracts,
extension.keptComposition,
]) {
expect(existsSync(path.join(root, owned)), owned).toBe(false);
}
await rename(path.join(root, PRODUCT_CONTRACTS_FILE), path.join(root, extension.keptContracts));
await rename(
path.join(root, PRODUCT_COMPOSITION_FILE),
path.join(root, extension.keptComposition),
);
const capabilities = await readFile(path.join(root, PRODUCT_CAPABILITIES_FILE), "utf8");
await writeFiles(root, {
[PRODUCT_CAPABILITIES_FILE]: `${capabilities}${capabilityType(extension)}`,
[PRODUCT_CONTRACTS_FILE]: productContracts(extension),
[PRODUCT_COMPOSITION_FILE]: productComposition(extension),
[`src/contexts/${extension.contextId}/context-module.ts`]: contextModule(extension),
[`src/features/${extension.featureId}/feature-module.ts`]: featureModule(extension),
[`src/features/${extension.featureId}/feature-runtime.ts`]: featureRuntime(extension),
[`src/features/${extension.featureId}/context-routes.ts`]: CONTEXT_ROUTES,
});
}
/** Generates the copy's indexes and runs the three programs of `check:types`. */
function expectTypecheckPasses(root: string): void {
const generated = spawnSync(
process.execPath,
[path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`],
{ encoding: "utf8" },
);
expect(generated.stderr).toBe("");
expect(generated.status).toBe(0);
for (const project of ["tsconfig.app.json", "tsconfig.node.json", "tsconfig.test.json"]) {
const typecheck = spawnSync(
path.resolve("node_modules/.bin/tsc"),
["--project", path.join(root, project)],
{ encoding: "utf8" },
);
expect(generated.stderr).toBe("");
expect(generated.status).toBe(0);
expect(typecheck.stdout + typecheck.stderr, project).toBe("");
expect(typecheck.status, project).toBe(0);
}
}
for (const project of ["tsconfig.app.json", "tsconfig.node.json", "tsconfig.test.json"]) {
const typecheck = spawnSync(
path.resolve("node_modules/.bin/tsc"),
["--project", path.join(root, project)],
{ encoding: "utf8" },
);
expect(typecheck.stdout + typecheck.stderr, project).toBe("");
expect(typecheck.status, project).toBe(0);
}
describe("1103/09-02 a product filled through its own files typechecks", () => {
it("passes the app, node and test programs", async () => {
const root = await copyRepository();
await addProductExtension(root, PROBE);
expectTypecheckPasses(root);
}, 120_000);
});
describe("1105/09-01 the probe keeps what the product's own files build", () => {
// The copy first becomes a downstream whose own product-composition.ts
// builds a capability for its own feature, as memento and tech-log do
// (CHANGELOG.md, `composeProduct(context)`). The probe must not take it away.
it("passes when a product feature needs a product capability", async () => {
const root = await copyRepository();
await addProductExtension(root, DOWNSTREAM);
await addProductExtension(root, PROBE);
expectTypecheckPasses(root);
}, 120_000);
});