Files
clean-architecture-frontend…/tests/unit/manual-code-blocks.test.ts
T
DongHyeonka 803d0f45aa fix(bootstrap): 업로드 401을 자격 증명을 붙인 주인에게 보낸다
문제: Fileserver 업로드 client가 서버 401을 AUTH_REQUIRED 실패로만
돌려준다. 세션은 authenticated로 남고 OIDC refresh도, 서버 상태 fence도
일어나지 않는다. JWT 모드(EXTERNAL_BEARER)에는 업로드에 세션 bearer를
붙일 지원 경로가 없어, 제품이 세션 owner를 붙잡아 scope fence 밖에서
부르게 된다. bootstrap은 "자격 증명 주인" 판정 순서를 attachCredentials와
reportServerUnauthenticated 두 곳에 따로 적는다. 매뉴얼 02 7절 업로드 예는
declare module로 capability를 보강해 check:types:node가 그 키를 못 본다.

고른 방법(R9-D2, R9-D13 대안):
- credentialOwner(authProfileId) 하나가 NONE·PRODUCT·SESSION을 정하고,
  V3 attachCredentials와 401 전달이 둘 다 그것을 읽는다(02-10).
- ProductCompositionContext.credentials를 더한다. V3와 같은
  attachCredentials와 같은 401 전달(onUnauthenticated)이다(추가만).
- FileserverUploadClientDependencies에 선택 onUnauthenticated를 더하고,
  client는 서버 401이면 본문과 상관없이 한 번 부른다(추가만).
- 업로드 capability 타입은 indexedDb처럼 템플릿이
  FeaturePlatformCapabilities에 opt-in 키 fileserverUpload로 선언한다.
  R9-D13 권하는 안(product-capabilities.ts가 contribution 파일에서 타입을
  가져옴)은 contribution 파일이 이미 product-capabilities.ts를 type
  import해서 그래프 순환이 된다(r9-fe 승인 2026-11-13).
- 매뉴얼 02 7절을 context.credentials를 펼치는 조각 둘로 바꾸고
  manual-code-block 표식을 단다. 시험은 제품 소유 파일 조각이 그 파일을
  통째로 바꾸게 한다.
버린 대안: 템플릿이 제품 capability를 모양으로 찾아 감싸기 — 제품이 정한
키 이름을 템플릿이 추측해야 한다.

위험·한계: 업로드 capability에 context.credentials를 펼치지 않은 제품은
그대로 401이 세션에 닿지 않는다(매뉴얼 02 7절·04에 적음). 쿠키 세션
모드 조각은 문장으로만 있고 시험 조각은 JWT 모드다.

검증: desktop, RED — 고치기 전 코드에서 새 업로드·주인 시험이 실패
(/tmp/claude-gates/r9b-pr1-red/exec_node.log). check:types·lint·
check:architecture rc=0(/tmp/claude-gates/r9b-pr1-quick). merge 단계는
PR 본문.

Refs: 1112/02-10, 1112/07-01, 1112/09-01
2026-11-13 19:02:07 +09:00

168 lines
7.3 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
import { cp, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import { linkFixtureNodeModules } from "../../scripts/lib/fixture-node-modules.ts";
import { REMOVAL_FIXTURE_COPY_TARGETS } from "../../scripts/lib/removal-fixture.ts";
import { selectRepositoryPaths } from "../../scripts/lib/repository-layout.ts";
import {
MANUAL_EXAMPLE_FEATURE_ID,
MANUAL_PROBE_FEATURE_ID,
renameFeatureText,
} from "../../scripts/lib/template-probe-features.ts";
import { childProcessTimeout } from "../helpers/child-process-timeout.ts";
/**
* 2026-11-07. The template ships no sample feature: what the generated
* feature does not show, docs/manual shows as code blocks a product copies
* into its feature folder. Each such block has `<!-- manual-code-block: <path> -->`
* above it, the path in the feature `create:feature invoice-feature
* --with-create` writes. Here a copy of the repository gets that feature, each
* block goes to its path unchanged, and the app and test typecheck programs,
* lint and the feature's tests run on it. A block that is a test runs as it
* is; what the other blocks do is checked by tests/fixtures/manual-code-blocks.
*
* 1112/08-02. The copy holds the product's own features, and a product may
* well have built `invoice-feature`. So the copy gets the reserved probe
* feature instead, and every block and check is renamed to it on the way in
* (`renameFeatureText`): paths, constants, types and words alike.
*
* 1112/09-01. A block may also be a whole product-owned file the template
* ships empty, such as the upload composition of manual 02 §7: it replaces
* that file in the copy.
*/
const MANUAL = "docs/manual";
const FEATURE_ID = MANUAL_PROBE_FEATURE_ID;
const toProbe = (text: string) => renameFeatureText(text, MANUAL_EXAMPLE_FEATURE_ID, FEATURE_ID);
const CHECKS = "tests/fixtures/manual-code-blocks";
const MARKED_BLOCK = /<!-- manual-code-block: (\S+) -->\n```tsx?\n([\s\S]*?)\n```/gu;
/** Product-owned files a block may replace whole; every other block adds a file. */
const PRODUCT_OWNED_FILES: ReadonlySet<string> = new Set([
"src/bootstrap/product-composition.ts",
"src/contracts/product-contracts.ts",
"src/features/product-capabilities.ts",
]);
async function manualDocuments(directory: string): Promise<string[]> {
const documents: string[] = [];
for (const entry of await readdir(directory, { withFileTypes: true })) {
const target = path.join(directory, entry.name);
if (entry.isDirectory()) documents.push(...(await manualDocuments(target)));
else if (entry.name.endsWith(".md")) documents.push(target);
}
return documents.sort();
}
/** Each marked block by the path it goes to. */
async function markedBlocks(): Promise<ReadonlyMap<string, string>> {
const blocks = new Map<string, string>();
for (const document of await manualDocuments(MANUAL)) {
for (const [, target = "", body = ""] of (await readFile(document, "utf8")).matchAll(MARKED_BLOCK)) {
if (blocks.has(target)) throw new Error(`${target} is marked twice in ${MANUAL}`);
blocks.set(target, `${body}\n`);
}
}
return blocks;
}
const roots: string[] = [];
afterAll(async () => {
await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true })));
});
async function copyRepository(): Promise<string> {
const root = await mkdtemp(path.join(tmpdir(), "manual-code-blocks-"));
roots.push(root);
for (const entry of REMOVAL_FIXTURE_COPY_TARGETS) {
// A removal drill runs this test in a copy that has already lost some.
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;
}
function run(root: string, command: string, args: readonly string[]) {
const result = spawnSync(command, args, { cwd: root, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
return { status: result.status, output: `${result.stdout}${result.stderr}` };
}
describe("docs/manual code blocks, pasted into a generated feature", () => {
it("marks each block with a path in the feature it is written for", async () => {
const targets = [...(await markedBlocks()).keys()].sort();
expect(targets).toEqual([
"src/bootstrap/product-composition.ts",
"src/features/invoice-feature/adapters/invoice-attachment-uploads.ts",
"src/features/invoice-feature/adapters/invoice-problem-mapping.ts",
"src/features/invoice-feature/contracts/invoice-list-search.ts",
"src/features/invoice-feature/contracts/invoice-problem-details.ts",
"src/features/invoice-feature/domain/invoice.ts",
"src/features/invoice-feature/presentation/use-invoice-failure-action.ts",
"src/features/invoice-feature/presentation/use-invoice-list-filters.ts",
"tests/features/invoice-feature/invoice-forbidden.test.tsx",
]);
});
it("typechecks, lints and does what the manual says", async () => {
const blocks = await markedBlocks();
const root = await copyRepository();
const node = process.execPath;
// The generator runs first, as `corepack pnpm create:feature` does.
const indexed = run(root, node, ["scripts/generate-product-feature-index.ts"]);
expect(indexed.status, indexed.output).toBe(0);
const created = run(root, node, ["scripts/create-feature.ts", FEATURE_ID, "--with-create"]);
expect(created.status, created.output).toBe(0);
for (const [target, block] of blocks) {
const file = path.join(root, toProbe(target));
// A block adds a file; it never stands in for one the command wrote.
expect(existsSync(file), `${target} exists before the block is pasted`).toBe(
PRODUCT_OWNED_FILES.has(target),
);
await mkdir(path.dirname(file), { recursive: true });
await writeFile(file, toProbe(block));
}
const checks = (await readdir(CHECKS)).filter((name) => name.endsWith(".check.tsx"));
expect(checks.length).toBeGreaterThan(0);
for (const check of checks) {
await writeFile(
path.join(root, "tests/features", FEATURE_ID, check.replace(/\.check\.tsx$/u, ".test.tsx")),
toProbe((await readFile(path.join(CHECKS, check), "utf8")).replaceAll("{{feature}}", MANUAL_EXAMPLE_FEATURE_ID)),
);
}
for (const program of selectRepositoryPaths("feature-typecheck")) {
const typecheck = run(root, path.resolve("node_modules/.bin/tsc"), ["--project", program]);
expect(typecheck.output, program).toBe("");
expect(typecheck.status, program).toBe(0);
}
const lint = run(root, path.resolve("node_modules/.bin/eslint"), [
`src/features/${FEATURE_ID}`,
`tests/features/${FEATURE_ID}`,
"--max-warnings=0",
]);
expect(lint.output).toBe("");
expect(lint.status).toBe(0);
const architecture = run(root, node, ["scripts/check-architecture.ts"]);
expect(architecture.status, architecture.output).toBe(0);
const tests = run(root, node, [
"scripts/run-vitest.ts",
"run",
`tests/features/${FEATURE_ID}`,
"--reporter=dot",
]);
expect(tests.status, tests.output).toBe(0);
}, childProcessTimeout(59_545));
});