앞 커밋(1112/01-01) 뒤 확인 리뷰가 완료 기준의 남은 셋과 결함 둘을 찾았다. - 생성 작성 페이지에 마운트 표시(useRef)와 저장 뒤 이동이 남았다. 저장이 끝나면 페이지가 폼보다 먼저, 폼이 pending인 동안 상세로 옮겼다. 다시 마운트한 폼에서 재전송이 성공하면 사용자가 돌아와 입력한, 보낸 적 없는 값을 이탈 확인 없이 버렸다(1112/01-02 영향). - 폼이 재전송 결과로 결과 불명을 다시 판정했다(resendLeftUnknown). 코디네이터와 401에서 갈린다. 코디네이터는 결과 불명을 쥐고 폼은 다시 로그인으로 가는데, FormSaveFeedback이 결과 불명을 먼저 그려 다시 로그인 안내를 가렸다(D-2 위반). - 지난 세 결함(1105/08-02·08-04, 1106/08-02)의 시험이 생성 페이지 시험에만 있었다. 고른 방법: useAppForm에 onSaved를 더한다(추가만). 폼이 결과를 보이고 pending을 끈 뒤, 마운트된 동안만 부른다. confirmUnknownEffect(then)도 마운트된 동안만 then을 부른다. resendUnknownEffect의 then 인자와 FormSaveFeedback의 onResent는 지운다(앞 커밋에서 생겨 아직 내보낸 적이 없다). 재전송 뒤 결과 불명인지는 코디네이터의 새 holdsUnknownEffect로 묻는다. mutation 없이 쓰는 폼(이미 생성한 페이지)은 물을 곳이 없어 같은 거절 표(isRefusedOnEveryAttempt)로 본다. FormSaveFeedback은 다시 로그인 실패를 결과 불명보다 먼저 그린다. 생성 페이지는 mutation.submit을 그대로 넘기고 onSaved와 onConfirmed에서 옮기기만 한다. VD-04 머리 칸에 넣었던 문장은 보완 절로 옮긴다(머리 칸의 백틱 낱말을 문서 검사가 경로로 본다). 페이지가 FormSaveFeedback을 늘 넘기므로, 할 말이 없는 피드백 칸은 자리를 차지하지 않는다(templates.css, 빈 칸이 그리드 간격을 한 줄 더했다). 위험·한계: 저장 뒤 이동이 폼이 결과를 그린 뒤로 한 번 늦어진다. 다시 마운트한 폼에 보내지 않은 값이 있으면 이동이 이탈 확인을 띄운다(의도). 검증: form-foundation 새 시험 일곱과 create-feature 생성 페이지 시험 (RED·GREEN, 막기·다른 저장·충돌 안내 변이 셋), 생성 기능 e2e의 피드백 칸 간격 시험은 desktop에서 돌려 PR 본문에 적는다. Refs: 1112/01-01, 1112/01-02, 1105/08-02, 1105/08-04, 1106/08-02, 1112/04-02
584 lines
24 KiB
TypeScript
584 lines
24 KiB
TypeScript
import { access, mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
import { pathToFileURL } from "node:url";
|
|
|
|
import { afterEach, describe, expect, it } from "vitest";
|
|
|
|
import {
|
|
CreateFeatureError,
|
|
parseRequest,
|
|
planFeature,
|
|
randomTopicSuffix,
|
|
writeFeatureFiles,
|
|
type FeatureRequest,
|
|
type InstalledFacts,
|
|
} from "../../scripts/create-feature.ts";
|
|
import { createFileSystemDeclarationSource } from "../../scripts/generate-product-feature-index.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",
|
|
"docs/accessibility/route-reviews/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("docs/accessibility/route-reviews/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);
|
|
});
|
|
|
|
// 1101 README 14.3. test:feature-scaffold runs the gateway test this renders.
|
|
it("reads the paired backend's Envelope and tests it with the backend's own bodies", () => {
|
|
const { files } = plan({ id: "invoice-feature" });
|
|
const contracts = "src/features/invoice-feature/contracts";
|
|
|
|
expect(files.get(`${contracts}/invoice-contract-contribution.ts`)).toContain(
|
|
'responseEnvelope: "ENVELOPE_V1" as const,',
|
|
);
|
|
expect(files.get(`${contracts}/invoice-schemas.ts`)).toMatch(
|
|
/invoiceProblemSchema = z\s*\.object\(\{\s*code: z\.string\(\)\.regex/u,
|
|
);
|
|
expect(
|
|
files.get("tests/features/invoice-feature/invoice-http-gateway.test.ts"),
|
|
).toContain('success: true, data: [{ id: "item-1", name: "First item" }]');
|
|
});
|
|
|
|
// 1103/03-07. The paired backend's new-feature.sh maps /<plural> (its
|
|
// camel-case name plus s, es or ies); the frontend's list reads the same
|
|
// resource path. The backend's api-base-path belongs in API_BASE_URL.
|
|
it.each([
|
|
["invoice-feature", "/invoices"],
|
|
["purchase-order-feature", "/purchaseOrders"],
|
|
["batch-feature", "/batches"],
|
|
["box-feature", "/boxes"],
|
|
["company-feature", "/companies"],
|
|
["day-feature", "/days"],
|
|
["status-feature", "/statuses"],
|
|
])("lists %s at the backend scaffold's resource path %s", (id, apiPath) => {
|
|
const base = id.slice(0, -"-feature".length);
|
|
const contribution = plan({ id }).files.get(
|
|
`src/features/${id}/contracts/${base}-contract-contribution.ts`,
|
|
);
|
|
|
|
expect(contribution).toContain(`const API_PATH = "${apiPath}";`);
|
|
});
|
|
|
|
// 1103/03-02. A page list's meta.page.total counts every page.
|
|
it("shows the total the backend counted, not the length of the first page", () => {
|
|
const { files } = plan({ id: "invoice-feature" });
|
|
|
|
expect(files.get("src/features/invoice-feature/contracts/invoice-mapper.ts")).toContain(
|
|
"total: page?.total ?? items.length",
|
|
);
|
|
expect(
|
|
files.get("src/features/invoice-feature/presentation/invoice-list-page.tsx"),
|
|
).toContain('message("invoice.list.resultCount", { count: query.data.total })');
|
|
});
|
|
});
|
|
|
|
/**
|
|
* 1103/09-06, 03-07. `--with-create` adds the paired backend scaffold's other
|
|
* two endpoints (POST /<plural>, GET /<plural>/{id}) with a detail page, a
|
|
* create form and the unknown-result handling. test:feature-scaffold and
|
|
* test:sample-removal generate it and run the gates on it.
|
|
*/
|
|
describe("create:feature --with-create", () => {
|
|
const contributionOf = (files: ReadonlyMap<string, string>) =>
|
|
files.get("src/features/invoice-feature/contracts/invoice-contract-contribution.ts") ?? "";
|
|
|
|
it("prefixes every id of the slice and adds its routes, pages and tests", () => {
|
|
const created = plan({ id: "invoice-feature", write: "NEVER" });
|
|
const text = [...created.files.values()].join("\n");
|
|
|
|
// No sample id. (`supportReference` is a platform prop.) Written so this
|
|
// file holds no sample id itself, which test:sample-removal looks for.
|
|
expect(text).not.toMatch(/REFERENCE_|ReferenceResource|reference-(?:feature|context)/u);
|
|
const ids = [
|
|
...text.matchAll(
|
|
/\b(?:schemaId|operationId|policyId|diagnosticsOperation|definitionId|chunkId|routeId|moduleId|loadingSurface|contributionId)\s*:\s*"([^"]+)"/gu,
|
|
),
|
|
...text.matchAll(/\bzodValidator\(\s*"([^"]+)"/gu),
|
|
...text.matchAll(/kind: "([a-z][^"]*\.[^"]*)"/gu),
|
|
...text.matchAll(/^\s+"((?:route\.)?[A-Za-z_.]+)": "/gmu),
|
|
].map((match) => match[1] ?? "");
|
|
expect(ids.length).toBeGreaterThan(50);
|
|
for (const id of ids) {
|
|
expect(id).toMatch(
|
|
/^(?:INVOICE_|Invoice|invoice[.-]|route\.INVOICE_(?:LIST|DETAIL|CREATE)\.|route-invoice-)/u,
|
|
);
|
|
}
|
|
expect([...created.files.keys()]).toEqual(
|
|
expect.arrayContaining([
|
|
"src/features/invoice-feature/presentation/invoice-detail-page.tsx",
|
|
"src/features/invoice-feature/presentation/invoice-create-page.tsx",
|
|
"src/features/invoice-feature/presentation/invoice-form.ts",
|
|
"src/features/invoice-feature/presentation/invoice-route-codecs.ts",
|
|
"src/features/invoice-feature/presentation/use-invoice-item.ts",
|
|
"src/features/invoice-feature/presentation/use-invoice-create.ts",
|
|
"tests/features/invoice-feature/invoice-create-page.test.tsx",
|
|
"docs/accessibility/route-reviews/INVOICE_DETAIL.md",
|
|
"docs/accessibility/route-reviews/INVOICE_CREATE.md",
|
|
]),
|
|
);
|
|
expect(created.routes).toEqual([
|
|
{ routeId: "INVOICE_LIST", path: "/invoice" },
|
|
{ routeId: "INVOICE_DETAIL", path: "/invoice/items/:invoiceId" },
|
|
{ routeId: "INVOICE_CREATE", path: "/invoice/new" },
|
|
]);
|
|
});
|
|
|
|
// 1103/16-01. Every generated operation declares the Envelope.
|
|
it("declares the Envelope on every operation it writes", () => {
|
|
const contribution = contributionOf(plan({ id: "invoice-feature", write: "NEVER" }).files);
|
|
|
|
expect(contribution.match(/operationId: "INVOICE_[A-Z_]+",/gu)).toHaveLength(3);
|
|
expect(contribution.match(/responseEnvelope: "ENVELOPE_V1" as const,/gu)).toHaveLength(3);
|
|
expect(contribution).toContain("pathTemplate: `${API_PATH}/{id}`,");
|
|
});
|
|
|
|
// 1103/03-07. new-feature.sh generates a NOT_IDEMPOTENT create: the backend
|
|
// ignores a key, so a same-key resend would create a second item.
|
|
it("matches the backend scaffold's NOT_IDEMPOTENT create with a NEVER command", () => {
|
|
const contribution = contributionOf(plan({ id: "invoice-feature", write: "NEVER" }).files);
|
|
|
|
expect(contribution).toContain('retrySemantics: "NEVER" as const,');
|
|
expect(contribution).toContain("retryBudget: 0 as const,");
|
|
expect(contribution).not.toContain("IDEMPOTENCY_REPLAY");
|
|
expect(contribution).toContain("acceptedStatuses: Object.freeze([201]),");
|
|
// 1103/03-01. The backend checks the name before its transaction.
|
|
expect(contribution).toContain('refusedBeforeWrite: Object.freeze(["INVOICE_INVALID"]),');
|
|
});
|
|
|
|
// 1105/08-04. Like the reference form: while a save this page did not
|
|
// start holds the coordinator, the save is off and the feedback says a
|
|
// save is running, instead of a save button that does nothing.
|
|
it("keeps the create's save off and says so while another save of it runs", () => {
|
|
const page =
|
|
plan({ id: "invoice-feature", write: "NEVER" }).files.get(
|
|
"src/features/invoice-feature/presentation/invoice-create-page.tsx",
|
|
) ?? "";
|
|
|
|
expect(page).toContain(
|
|
'const otherSaveRunning = mutation.state.indicator === "mutation-pending" && !form.pending;',
|
|
);
|
|
expect(page).toContain("disabled={effectUnknown || otherSaveRunning}");
|
|
expect(page).toContain('otherSaveRunning && form.result !== "effect-unknown" ? (');
|
|
expect(page).toContain("<AsyncSurface state={mutation.state} />");
|
|
});
|
|
|
|
// 1105/08-02. Confirming an unknown create used to leave an emptied form
|
|
// that said nothing. It opens the list, which shows whether the item is
|
|
// there, and the generated page test walks that path.
|
|
it.each(["NEVER", "KEYED"] as const)(
|
|
"opens the list after the user confirms an unknown %s create",
|
|
(write) => {
|
|
const { files } = plan({ id: "invoice-feature", write });
|
|
|
|
expect(
|
|
files.get("src/features/invoice-feature/presentation/invoice-create-page.tsx"),
|
|
).toContain('void navigate(invoiceRouteUrl("INVOICE_LIST"));');
|
|
expect(
|
|
files.get("tests/features/invoice-feature/invoice-create-page.test.tsx"),
|
|
).toContain('it("opens the list after the user confirms a create whose response was lost"');
|
|
},
|
|
);
|
|
|
|
// 1106/08-02. A save that ended after the user left the form took them to
|
|
// the item anyway. The page opens the item or the list only while it is
|
|
// still mounted, and the generated page test walks that path.
|
|
it.each(["NEVER", "KEYED"] as const)(
|
|
"does not open the item when the user left during a %s create",
|
|
(write) => {
|
|
const { files } = plan({ id: "invoice-feature", write });
|
|
const page =
|
|
files.get("src/features/invoice-feature/presentation/invoice-create-page.tsx") ?? "";
|
|
|
|
expect(page).toContain("if (outcome?.ok && mounted.current) {");
|
|
expect(page).toContain(
|
|
'if (mounted.current) void navigate(invoiceRouteUrl("INVOICE_LIST"));',
|
|
);
|
|
expect(
|
|
files.get("tests/features/invoice-feature/invoice-create-page.test.tsx"),
|
|
).toContain('it("stays on the list the user went to while the create was saving"');
|
|
},
|
|
);
|
|
|
|
// 1103/16-07. A backend create made KEYED (IdempotencyExecutor) takes these.
|
|
it("writes the KEYED values for a backend create made KEYED", () => {
|
|
const { files } = plan({ id: "invoice-feature", write: "KEYED" });
|
|
const contribution = contributionOf(files);
|
|
|
|
expect(contribution).toContain('retrySemantics: "KEYED" as const,');
|
|
expect(contribution).toContain('mode: "IDEMPOTENCY_REPLAY" as const,');
|
|
expect(contribution).toContain('operationIdentityField: "idempotencyKey",');
|
|
expect(contribution).toContain("retryBudget: 1 as const,");
|
|
expect(
|
|
files.get("tests/features/invoice-feature/invoice-create-page.test.tsx"),
|
|
).toContain('posts[1]!.headers.get("idempotency-key")');
|
|
expect(
|
|
files.get("src/features/invoice-feature/presentation/use-invoice-create.ts"),
|
|
).toContain("...commandMutationIdentity(INVOICE_CREATE_ITEM_CONTRACT),");
|
|
});
|
|
|
|
it("refuses a slice route that collides with an installed one", () => {
|
|
expect(() =>
|
|
plan(
|
|
{ id: "invoice-feature", write: "NEVER" },
|
|
{
|
|
...INSTALLED,
|
|
routes: [
|
|
...INSTALLED.routes,
|
|
{ routeId: "LEGACY", path: "/invoice/new", chunkId: "route-legacy", navigationOrder: null },
|
|
],
|
|
},
|
|
),
|
|
).toThrow(/route INVOICE_CREATE .* collides with installed route LEGACY/u);
|
|
});
|
|
|
|
it("takes --with-create and --keyed, and --keyed only with --with-create", () => {
|
|
expect(parseRequest(["invoice-feature", "--with-create"])).toMatchObject({
|
|
write: "NEVER",
|
|
});
|
|
expect(parseRequest(["invoice-feature", "--with-create", "--keyed"])).toMatchObject({
|
|
write: "KEYED",
|
|
});
|
|
expect(parseRequest(["invoice-feature"]).write).toBeUndefined();
|
|
expect(() => parseRequest(["invoice-feature", "--keyed"])).toThrow(
|
|
/--keyed needs --with-create/u,
|
|
);
|
|
});
|
|
});
|
|
|
|
/**
|
|
* X1 (2026-11-04). The generated context declaration is executed, not only
|
|
* read as text: the generator's declaration source reads it from disk, and an
|
|
* app module built from its exported route root accepts every route the
|
|
* feature declares (the check the router relies on, 09-06).
|
|
*/
|
|
describe("create:feature context declaration", () => {
|
|
const roots: string[] = [];
|
|
afterEach(async () => {
|
|
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
|
|
});
|
|
|
|
async function appFor(
|
|
contextId: string,
|
|
routePath: string,
|
|
maxFeatures: number,
|
|
routes: readonly Readonly<{ routeId: string; path: string }>[],
|
|
) {
|
|
const { defineBoundedContextModule } = await import(
|
|
"../../src/contexts/bounded-context-module.ts"
|
|
);
|
|
const { defineDeployableAppModule } = await import("../../src/apps/deployable-app-module.ts");
|
|
return defineDeployableAppModule({
|
|
id: "template-app",
|
|
budget: { maxContexts: 20 },
|
|
contexts: [
|
|
defineBoundedContextModule({
|
|
id: contextId,
|
|
budget: { maxFeatures },
|
|
features: [
|
|
{
|
|
id: "invoice-feature",
|
|
contracts: {
|
|
routes: Object.fromEntries(routes.map((route) => [route.routeId, route])),
|
|
},
|
|
} as never,
|
|
],
|
|
route: { path: routePath, loadRoutes: async () => [] },
|
|
}),
|
|
],
|
|
});
|
|
}
|
|
|
|
it.each([undefined, "NEVER"] as const)(
|
|
"writes a context module the generator reads and whose root holds the routes (write %s)",
|
|
async (write) => {
|
|
const root = await mkdtemp(path.join(tmpdir(), "create-feature-context-"));
|
|
roots.push(root);
|
|
const created = plan({ id: "invoice-feature", write });
|
|
await mkdir(path.join(root, "src/apps/template-app"), { recursive: true });
|
|
await writeFile(
|
|
path.join(root, "src/apps/template-app/app-module.ts"),
|
|
'export const APP_MODULE_ID = "template-app";\nexport const APP_MAX_CONTEXTS = 20;\n',
|
|
);
|
|
await writeFeatureFiles(root, created.files);
|
|
|
|
const source = await createFileSystemDeclarationSource(root);
|
|
expect(source.contextsOf("template-app")).toEqual([
|
|
{ id: "invoice-context", appId: "template-app", routePath: "invoice/*", maxFeatures: 20 },
|
|
]);
|
|
expect(source.featuresOf("invoice-context").map((feature) => feature.id)).toEqual([
|
|
"invoice-feature",
|
|
]);
|
|
const declared = (await import(
|
|
pathToFileURL(path.join(root, "src/contexts/invoice-context/context-module.ts")).href
|
|
)) as Record<string, unknown>;
|
|
expect(declared).toMatchObject({
|
|
CONTEXT_MODULE_ID: "invoice-context",
|
|
CONTEXT_APP_ID: "template-app",
|
|
CONTEXT_ROUTE_PATH: "invoice/*",
|
|
});
|
|
|
|
const app = await appFor(
|
|
String(declared["CONTEXT_MODULE_ID"]),
|
|
String(declared["CONTEXT_ROUTE_PATH"]),
|
|
Number(declared["CONTEXT_MAX_FEATURES"]),
|
|
created.routes,
|
|
);
|
|
expect(app.contexts.map((context) => context.id)).toEqual(["invoice-context"]);
|
|
},
|
|
);
|
|
|
|
it("puts the routes under an existing context's root", async () => {
|
|
const created = plan({ id: "invoice-feature", context: "billing-context", write: "NEVER" });
|
|
|
|
expect(created.routes.map((route) => route.path)).toEqual([
|
|
"/billing/invoice",
|
|
"/billing/invoice/items/:invoiceId",
|
|
"/billing/invoice/new",
|
|
]);
|
|
await expect(appFor("billing-context", "billing/*", 20, created.routes)).resolves.toBeDefined();
|
|
});
|
|
});
|
|
|
|
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, "docs/accessibility/route-reviews"), { recursive: true });
|
|
await writeFile(path.join(root, "docs/accessibility/route-reviews/INVOICE_LIST.md"), "kept\n");
|
|
|
|
await expect(writeFeatureFiles(root, files)).rejects.toThrow(
|
|
/refusing to overwrite: docs\/accessibility\/route-reviews\/INVOICE_LIST\.md/u,
|
|
);
|
|
expect(await readdir(root)).toEqual(["docs"]);
|
|
});
|
|
|
|
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();
|
|
});
|
|
});
|
|
|
|
// 1112/01-01. The generated create page leaves the rules of a save through
|
|
// its mutation to the platform form: it gives useAppForm the mutation and
|
|
// draws FormSaveFeedback, so a platform fix to those rules reaches it.
|
|
describe("generated create page", () => {
|
|
it("hands the save rules to the platform form", () => {
|
|
const { files } = plan({ id: "invoice-feature", write: "KEYED" });
|
|
const page = files.get("src/features/invoice-feature/presentation/invoice-create-page.tsx") ?? "";
|
|
|
|
expect(page).toContain(" mutation,\n");
|
|
expect(page).toContain("<FormSaveFeedback");
|
|
expect(page).not.toContain("mutation.state.indicator");
|
|
expect(page).not.toContain("reconcileUnknownEffect");
|
|
});
|
|
|
|
// R-01 완료 기준 (round9 confirm review). Opening what was saved only while
|
|
// the page is open is the form's rule too (onSaved), not a mount flag the
|
|
// page keeps, and the page calls no resend or settle of its own.
|
|
it("keeps no save rule of its own", () => {
|
|
const { files } = plan({ id: "invoice-feature", write: "KEYED" });
|
|
const page = files.get("src/features/invoice-feature/presentation/invoice-create-page.tsx") ?? "";
|
|
|
|
expect(page).toContain("onSaved:");
|
|
expect(page).not.toMatch(/useRef|useEffect|mounted/u);
|
|
expect(page).not.toMatch(/resendUnknown|settleApplied|onResent/u);
|
|
});
|
|
});
|