Files
clean-architecture-frontend…/scripts/create-feature-write-slice.ts
DongHyeonka 116cbf3d06 fix(scaffold): 저장 중에 떠난 사용자를 생성 작성 폼이 상세로 옮기지 않는다
문제: 생성기 템플릿의 작성 폼은 저장을 기다린 뒤 openSaved에서 상세로
navigate한다. 그 사이 화면이 남아 있는지 보지 않는다. 저장 중에는 이탈 확인이
꺼져 있어 사용자는 목록이나 다른 기능으로 갈 수 있다. 저장이 끝나면 언마운트된
화면의 navigate가 앱을 그 항목의 상세로 옮긴다(데이터 라우터의 navigate는
언마운트 뒤에도 동작한다, 리뷰 probe 08-R7). 다시 돌아온 작성 폼에 입력이
있으면 이유 없는 이탈 확인 창이 뜬다. 참조 폼은 저장 뒤 이동하지 않아 생성기에만
있다.

고른 방법: 생성 페이지가 마운트 여부를 ref로 들고(useEffect에서 true, 정리에서
false), 저장 뒤 상세 이동과 "변경됨으로 확인" 뒤 목록 이동을 마운트된 동안만
한다. 생성 페이지 테스트에 한 행을 더했다: 저장을 붙잡아 둔 채 breadcrumb으로
목록에 가고, 저장을 끝내면 목록이 새 항목을 보이고(목록 무효화) 1초 안에 상세
heading이 오지 않으며 목록 heading이 남는다. 생성기 단위 테스트가 두 조건과 그
행을 NEVER·KEYED 모두에서 본다. 매뉴얼 reference/create-feature.md에 적었다.
버린 대안: 현재 위치가 작성 라우트인지 보기(다시 돌아온 새 인스턴스가 있으면
옛 인스턴스의 이동도 통과한다), 이동 대신 결과를 남겨 보이기(1106/08-01 (2)처럼;
완료 기준은 이동만 요구해 이번에는 넣지 않았다).

위험·한계: 떠난 뒤 끝난 저장은 다시 돌아온 작성 폼에 결과를 보이지 않는다(참조
폼의 목록 안내는 생성기에 없다). 생성 페이지 테스트의 새 행은 녹색일 때 1초를
기다린다(상세가 오지 않음을 보는 음성 확인). repo 안에 생성 결과 파일은 없다
(src/features/.generated 없음). 이미 생성한 기능에는 반영되지 않는다.

검증: desktop batch에서 확인. node scripts/run-vitest.ts run
tests/unit/create-feature.test.ts, corepack pnpm test:feature-scaffold
(FE-GATE-020, 생성 기능 드릴 NEVER·KEYED)

Refs: 1106/08-02
2026-11-06 05:36:06 +09:00

1155 lines
41 KiB
TypeScript

/**
* 1103/09-06, 03-07. The `--with-create` slice of `pnpm create:feature`: the
* paired backend scaffold's other two endpoints
* (clean-architecture-backend-template scripts/new-feature.sh,
* `__Feature__Controller.java.tmpl`): `POST /<plural>` answers 201 with the
* new item in the Envelope, `GET /<plural>/{id}` reads one. With them come a
* detail page, a create form with the unknown-result handling, and tests that
* answer with the backend's own bodies. The base templates in
* `create-feature.ts` call into this file where the slice adds to one of
* their files; the files only the slice has are rendered here whole.
*
* The backend generates a NOT_IDEMPOTENT create, which reads no
* Idempotency-Key, so the default command is NEVER: no key, no resend.
* `--keyed` is for a backend create made KEYED with its IdempotencyExecutor
* (its docs/manual/05-idempotency.md). Like the rest of the command, nothing
* here imports a sample feature.
*
* 1105/16-02. The backend scaffold facts copied here (name limit, error
* codes, 201 and the endpoints, the check order behind refusedBeforeWrite)
* and the path rule in create-feature.ts are listed with their backend
* files in config/contracts/backend-contract-pin.json `scaffoldSources`;
* `check:backend-contract-drift` says when one of those files changes.
*/
export type WriteSemantics = "NEVER" | "KEYED";
export type SliceRoute = Readonly<{
routeId: string;
path: string;
chunkId: string;
moduleId: string;
loadingSurface: string;
}>;
export type WriteSlice = Readonly<{
semantics: WriteSemantics;
/** The detail route's path parameter. */
idParam: string;
detail: SliceRoute;
create: SliceRoute;
getOperationId: string;
createOperationId: string;
/** The backend scaffold's `__FEATURE___INVALID` (400) and `_NOT_FOUND` (404). */
invalidCode: string;
notFoundCode: string;
}>;
type SliceNames = Readonly<{
id: string;
base: string;
upper: string;
pascal: string;
camel: string;
title: string;
}>;
type SliceShape = Readonly<{
names: SliceNames;
routeId: string;
apiPath: string;
write: WriteSlice;
}>;
/** The backend aggregate's `NAME_MAX_LENGTH`; its create refuses a longer name. */
const BACKEND_NAME_MAX_LENGTH = 100;
export function planWriteSlice(
names: SliceNames,
listPath: string,
semantics: WriteSemantics,
): WriteSlice {
const { base, camel, upper } = names;
const route = (suffix: string, path: string): SliceRoute =>
Object.freeze({
routeId: `${upper}_${suffix.toUpperCase()}`,
path,
chunkId: `route-${base}-${suffix}`,
moduleId: `${base}-${suffix}-page`,
loadingSurface: `${base}-${suffix}`,
});
return Object.freeze({
semantics,
idParam: `${camel}Id`,
// `items/` keeps the detail apart from the static `new` (01 6단계).
detail: route("detail", `${listPath}/items/:${camel}Id`),
create: route("create", `${listPath}/new`),
getOperationId: `${upper}_GET_ITEM`,
createOperationId: `${upper}_CREATE_ITEM`,
invalidCode: `${upper}_INVALID`,
notFoundCode: `${upper}_NOT_FOUND`,
});
}
export function writeSliceMessageKeys(names: SliceNames, slice: WriteSlice): string[] {
const { camel } = names;
return [
...[slice.detail.routeId, slice.create.routeId].flatMap((routeId) => [
`route.${routeId}.navigation`,
`route.${routeId}.title`,
]),
`${camel}.list.create`,
`${camel}.detail.titlePending`,
`${camel}.detail.itemId`,
`${camel}.form.title`,
`${camel}.form.name`,
`${camel}.form.save`,
`${camel}.form.saving`,
];
}
/** Route titles, ko-KR then en-US. The contract's `title` repeats ko-KR. */
export function writeSliceRouteTitles(names: SliceNames) {
const { title } = names;
return Object.freeze({
detail: Object.freeze({ ko: `${title} 상세`, en: `${title} detail` }),
create: Object.freeze({ ko: `${title} 만들기`, en: `New ${title}` }),
});
}
// ---------------------------------------------------------------------------
// Fragments the base templates insert.
export function renderWriteRoutes({ names, write }: SliceShape): string {
const titles = writeSliceRouteTitles(names);
const entry = (route: SliceRoute, paramsSchema: string, title: string) => ` ${route.routeId}: Object.freeze({
routeId: "${route.routeId}",
path: "${route.path}",
paramsSchema: ${paramsSchema},
searchSchema: null,
access: "session-required",
loadingSurface: "${route.loadingSurface}",
errorSurface: "feature-boundary",
chunkId: "${route.chunkId}",
title: "${title}",
navigationLabel: null,
navigationOrder: null,
}),
`;
return (
entry(write.detail, `"${names.pascal}Params"`, titles.detail.ko) +
entry(write.create, "null", titles.create.ko)
);
}
export function renderWriteRouteRuntimeContracts({ names, write }: SliceShape): string {
const entry = (route: SliceRoute, paramsCodec: string) => ` ${route.routeId}: Object.freeze({
routeId: "${route.routeId}",
moduleId: "${route.moduleId}",
paramsCodec: "${paramsCodec}",
searchCodec: "none",
}),
`;
return entry(write.detail, `${names.pascal}Params`) + entry(write.create, "none");
}
export function renderWriteSchemas({ names, write }: SliceShape): string {
const { camel, pascal, upper } = names;
return `
/** The backend aggregate's \`NAME_MAX_LENGTH\`. The request and the form share it. */
export const ${upper}_NAME_MAX_LENGTH = ${BACKEND_NAME_MAX_LENGTH};
/**
* The detail route's params and the GET's input. The backend reads the id as
* a canonical UUID and answers another text with 400 BAD_PARAMETER.
*/
export const ${camel}ParamsSchema = z
.object({
${write.idParam}: z.string().trim().min(1).max(120),
})
.strict();
export type ${pascal}Params = z.output<typeof ${camel}ParamsSchema>;
/**
* The backend's \`Create__Feature__HttpRequest\`. It has no bean validation:
* the aggregate refuses a blank or longer name with 400 ${write.invalidCode}.
*/
export const ${camel}CreateCommandSchema = z
.object({
name: z.string().min(1).max(${upper}_NAME_MAX_LENGTH),
})
.strict();
export type ${pascal}CreateRequest = z.output<typeof ${camel}CreateCommandSchema>;
`;
}
export function renderWriteValidators({ names }: SliceShape): string {
const { camel, pascal } = names;
return ` ${pascal}Params: zodValidator("${pascal}Params", ${camel}ParamsSchema),
${pascal}ItemPayload: zodValidator("${pascal}ItemPayload", ${camel}ItemDtoSchema),
${pascal}CreateCommand: zodValidator("${pascal}CreateCommand", ${camel}CreateCommandSchema),
`;
}
export function renderWriteMapper({ names }: SliceShape): string {
const { pascal } = names;
return `
export function map${pascal}Item(
dto: ${pascal}ItemDto,
): BoundaryMappingResult<${pascal}ItemView> {
return mappingSuccess(toView(dto));
}
`;
}
export function renderWriteSchemaRows({ names }: SliceShape): string {
const { pascal } = names;
const row = (
schemaId: string,
boundary: string,
direction: string,
unknownFieldPolicy: string,
) => ` ${schemaId}: Object.freeze({
schemaId: "${schemaId}",
boundary: "${boundary}",
owner: OWNER,
runtime: "zod",
schemaVersion: 1,
direction: "${direction}",
unknownFieldPolicy: "${unknownFieldPolicy}",
}),
`;
return (
row(`${pascal}Params`, "route-params", "REQUEST", "REJECT_UNKNOWN") +
row(`${pascal}ItemPayload`, "api-response", "RESPONSE", "STRIP_UNKNOWN") +
row(`${pascal}CreateCommand`, "api-request", "REQUEST", "REJECT_UNKNOWN")
);
}
export function renderWriteDescriptors({ names, write }: SliceShape): string {
const { base, pascal, upper } = names;
const keyed = write.semantics === "KEYED";
const semantics = keyed
? ` // The backend create runs behind its IdempotencyExecutor
// (http-contract.md §2): the same key replays, never applies twice.
retrySemantics: "KEYED" as const,`
: ` // new-feature.sh generates a NOT_IDEMPOTENT create: the backend reads no
// Idempotency-Key and a second request creates a second item. Make the
// backend create KEYED (its docs/manual/05-idempotency.md) before this.
retrySemantics: "NEVER" as const,`;
const recovery = keyed
? ` // The intent's key, which the executor sends as Idempotency-Key. Recorded
// in FE-REG-API; the executor does not read it.
commandRecovery: Object.freeze({
mode: "IDEMPOTENCY_REPLAY" as const,
operationIdentityField: "idempotencyKey",
}),`
: ` commandRecovery: null,`;
const budget = keyed
? ` // One automatic resend, with the same key, after 503
// IDEMPOTENCY_UNAVAILABLE (refused before the work ran). The app's
// MAX_RETRY_ATTEMPTS caps it too. A lost response is never resent on its
// own: the form offers the same-key resend.
retryBudget: 1 as const,`
: ` retryBudget: 0 as const,`;
return `
/**
* The paired backend's \`GET /<plural>/{id}\`: the item in the Envelope, or
* 404 ${write.notFoundCode}.
*/
export const ${write.getOperationId}_CONTRACT = Object.freeze({
contract: Object.freeze({
operationId: "${write.getOperationId}",
method: "GET" as const,
pathTemplate: \`\${API_PATH}/{id}\`,
inputValidator: ${upper}_VALIDATORS.${pascal}Params,
outputValidator: ${upper}_VALIDATORS.${pascal}ItemPayload,
problemValidator: ${upper}_VALIDATORS.${pascal}Problem,
acceptedStatuses: Object.freeze([200]),
emptyBodyStatuses: Object.freeze([]),
retrySemantics: "SAFE" as const,
requestBody: "NONE" as const,
responseBody: "REQUIRED_JSON" as const,
responseEnvelope: "ENVELOPE_V1" as const,
commandRecovery: null,
commandEffect: null,
projectRequest(input: ${pascal}Params) {
return Object.freeze({
pathValues: Object.freeze({ id: input.${write.idParam} }),
queryEntries: Object.freeze([]),
body: null,
});
},
}),
frontend: Object.freeze({
policyId: "${upper}_GET_V1",
requestByteLimit: 0,
responseByteLimit: 32_768,
totalDeadlineMs: 10_000,
retryBudget: 2 as const,
authProfileId: "EXTERNAL_BEARER",
diagnosticsOperation: "${base}.detail",
}),
}) satisfies InstalledHttpContract<${pascal}Params, ${pascal}ItemDto, ${pascal}Problem>;
/**
* 1103/03-01. Whether a failed create applied. The executor's backend table
* decides 400, 409, 422 and the backend's own 5xx answers; \`classifyProblem\`
* gets every other status.
*/
const ${upper}_CREATE_EFFECT: CommandEffectDescriptor<${pascal}Problem> = Object.freeze({
successEffect: "APPLIED_CONFIRMED" as const,
classifyProblem: () => "MAYBE_APPLIED" as const,
// The backend refuses these before the use case runs: 401 in the security
// filter chain, 403 at the use case's @RequiresPermission proxy, 429 in the
// rate-limit interceptor. Recheck if the use case asks AuthorizationPort
// after it writes.
classifyStatus: () => "NOT_APPLIED" as const,
// Create<Feature>UseCase checks the name before its transaction. List a
// code here only when the endpoint raises it before any write.
refusedBeforeWrite: Object.freeze(["${write.invalidCode}"]),
});
/** The paired backend's \`POST /<plural>\`: 201 with the new item in the Envelope. */
export const ${write.createOperationId}_CONTRACT = Object.freeze({
contract: Object.freeze({
operationId: "${write.createOperationId}",
method: "POST" as const,
pathTemplate: API_PATH,
inputValidator: ${upper}_VALIDATORS.${pascal}CreateCommand,
outputValidator: ${upper}_VALIDATORS.${pascal}ItemPayload,
problemValidator: ${upper}_VALIDATORS.${pascal}Problem,
acceptedStatuses: Object.freeze([201]),
emptyBodyStatuses: Object.freeze([]),
${semantics}
requestBody: "JSON" as const,
responseBody: "REQUIRED_JSON" as const,
responseEnvelope: "ENVELOPE_V1" as const,
${recovery}
commandEffect: ${upper}_CREATE_EFFECT,
projectRequest(input: ${pascal}CreateRequest) {
return Object.freeze({
pathValues: Object.freeze({}),
queryEntries: Object.freeze([]),
body: Object.freeze({ name: input.name }),
});
},
}),
frontend: Object.freeze({
policyId: "${upper}_CREATE_V1",
requestByteLimit: 4_096,
responseByteLimit: 32_768,
totalDeadlineMs: 10_000,
${budget}
authProfileId: "EXTERNAL_BEARER",
diagnosticsOperation: "${base}.create",
}),
}) satisfies InstalledHttpContract<${pascal}CreateRequest, ${pascal}ItemDto, ${pascal}Problem>;
`;
}
export function renderWriteMessages({ names, write }: SliceShape, locale: "ko" | "en"): string {
const { camel } = names;
const titles = writeSliceRouteTitles(names);
const copy =
locale === "ko"
? {
create: "새 항목 만들기",
titlePending: `${names.title} 항목`,
itemId: "ID",
formTitle: titles.create.ko,
name: "이름",
save: "저장",
saving: "저장 중…",
}
: {
create: "Create item",
titlePending: `${names.title} item`,
itemId: "ID",
formTitle: titles.create.en,
name: "Name",
save: "Save",
saving: "Saving…",
};
return ` "route.${write.detail.routeId}.navigation": "${titles.detail[locale]}",
"route.${write.detail.routeId}.title": "${titles.detail[locale]}",
"route.${write.create.routeId}.navigation": "${titles.create[locale]}",
"route.${write.create.routeId}.title": "${titles.create[locale]}",
"${camel}.list.create": "${copy.create}",
"${camel}.detail.titlePending": "${copy.titlePending}",
"${camel}.detail.itemId": "${copy.itemId}",
"${camel}.form.title": "${copy.formTitle}",
"${camel}.form.name": "${copy.name}",
"${camel}.form.save": "${copy.save}",
"${camel}.form.saving": "${copy.saving}",
`;
}
export function renderWriteGatewayOperations({ names, write }: SliceShape): string {
const { pascal } = names;
return ` ${write.getOperationId}: define${pascal}HttpOperation({
contract: ${write.getOperationId}_CONTRACT,
routeId: "${write.detail.routeId}",
mapSuccess: map${pascal}Item,
}),
${write.createOperationId}: define${pascal}HttpOperation({
contract: ${write.createOperationId}_CONTRACT,
routeId: "${write.create.routeId}",
mapSuccess: map${pascal}Item,
// The scaffold aggregate has one rule, on the name: show the backend's
// refusal on that field. Map each field the aggregate grows.
mapProblem: (problem) =>
problem.code === "${write.invalidCode}"
? Object.freeze({
kind: "VALIDATION_REJECTED" as const,
code: problem.code,
validationIssues: Object.freeze([Object.freeze({ path: "name", code: "INVALID" })]),
})
: undefined,
}),
`;
}
export function renderWriteGatewayMethods({ write }: SliceShape): string {
return ` get(${write.idParam}, context) {
return http.execute("${write.getOperationId}", Object.freeze({ ${write.idParam} }), context);
},
create(command, context) {
return http.execute("${write.createOperationId}", command, context);
},
`;
}
// ---------------------------------------------------------------------------
// Files only the slice has.
export function renderRouteCodecs({ names }: SliceShape): string {
const { base, camel, pascal, upper } = names;
return `import { ${camel}ParamsSchema } from "../contracts/${base}-schemas.ts";
/**
* The route codecs, keyed by the codec ids \`routeRuntimeContracts\` names.
* They load with the context routes (\`context-routes.ts\` puts them on each
* handle), not with the declaration in the initial chunk.
*/
export const ${upper}_ROUTE_CODECS = {
${pascal}Params: ${camel}ParamsSchema,
} as const;
`;
}
export function renderUseItem({ names }: SliceShape): string {
const { base, pascal, upper } = names;
return `import { bindQuery, type QueryResultMeasure } from "../../../contracts/server-state.ts";
import { useApplicationQuery } from "../../../presentation/adapters/query/application-query.ts";
import { useServerStateScope } from "../../../presentation/adapters/query/server-state-scope-provider.tsx";
import { useApplicationFeature } from "../../../presentation/providers/application-provider.tsx";
import {
${upper}_FEATURE_ID,
${upper}_ITEM_QUERY_NAMESPACE,
} from "../contracts/${base}-feature-contract.ts";
import type { ${pascal}ItemView } from "../contracts/${base}-mapper.ts";
const UTF8 = new TextEncoder();
function measureItem(item: ${pascal}ItemView): QueryResultMeasure {
return {
itemCount: 1,
estimatedBytes: UTF8.encode(item.itemId).byteLength + UTF8.encode(item.name).byteLength + 16,
};
}
/** One item. A save of this feature invalidates its namespace, so a new item shows. */
export function use${pascal}Item(itemId: string) {
const input = useApplicationFeature(${upper}_FEATURE_ID);
const scope = useServerStateScope();
return useApplicationQuery(
bindQuery(
{
definitionId: "${base}-item-detail-v1",
definitionVersion: 1,
namespace: ${upper}_ITEM_QUERY_NAMESPACE,
profileId: "DETAIL_STANDARD",
measureResult: measureItem,
execute: (selected: string, { signal }) => input.getItem(selected, { signal }),
},
itemId,
scope,
),
);
}
`;
}
export function renderUseCreate({ names, write }: SliceShape): string {
const { base, pascal, upper } = names;
return `import {
commandMutationIdentity,
type BoundMutation,
} from "../../../contracts/server-state.ts";
import { useApplicationMutation } from "../../../presentation/adapters/query/application-query.ts";
import { useServerStateScope } from "../../../presentation/adapters/query/server-state-scope-provider.tsx";
import { useApplicationFeature } from "../../../presentation/providers/application-provider.tsx";
import type { ${pascal}CreateCommand } from "../application/${base}-feature-api.ts";
import { ${write.createOperationId}_CONTRACT } from "../contracts/${base}-contract-contribution.ts";
import {
${upper}_FEATURE_ID,
${upper}_ITEM_INVALIDATION_TOPIC,
} from "../contracts/${base}-feature-contract.ts";
import type { ${pascal}ItemView } from "../contracts/${base}-mapper.ts";
/**
* 1103/16-05. The operation id and whether the intent carries an
* idempotency key are the descriptor's. A second save while one runs is
* refused, and a saved item invalidates the list and the detail.
*/
const ${upper}_CREATE_MUTATION_POLICY = Object.freeze({
definitionId: "${base}-create-v1",
definitionVersion: 1,
...commandMutationIdentity(${write.createOperationId}_CONTRACT),
duplicatePolicy: "REJECT_WHILE_ACTIVE" as const,
invalidate: Object.freeze([${upper}_ITEM_INVALIDATION_TOPIC]),
});
export function use${pascal}Create() {
const input = useApplicationFeature(${upper}_FEATURE_ID);
const scope = useServerStateScope();
const mutation: BoundMutation<${pascal}CreateCommand, ${pascal}ItemView> = Object.freeze({
...${upper}_CREATE_MUTATION_POLICY,
scope,
execute: input.createItem,
});
return useApplicationMutation(mutation);
}
`;
}
export function renderForm({ names }: SliceShape): string {
const { base, camel, pascal, upper } = names;
return `import { z } from "../../../contracts/zod.ts";
import type { ${pascal}CreateCommand } from "../application/${base}-feature-api.ts";
import { ${upper}_NAME_MAX_LENGTH } from "../contracts/${base}-schemas.ts";
/** What the user types. The length comes from the request schema's constant. */
export const ${camel}FormSchema = z
.object({
name: z.string().trim().min(1).max(${upper}_NAME_MAX_LENGTH),
})
.strict();
export type ${pascal}FormValues = z.infer<typeof ${camel}FormSchema>;
export const ${upper}_FORM_DEFAULTS: ${pascal}FormValues = Object.freeze({ name: "" });
export function to${pascal}CreateCommand(values: ${pascal}FormValues): ${pascal}CreateCommand {
return Object.freeze({ name: values.name });
}
`;
}
export function renderDetailPage({ names, routeId }: SliceShape): string {
const { base, camel, pascal } = names;
return `import { Link } from "react-router-dom";
import {
AsyncSurface,
DetailPage,
} from "../../../presentation/design-system/index.ts";
import { useLocale } from "../../../presentation/i18n/index.ts";
import { ${camel}RouteUrl, use${pascal}ItemId } from "./${base}-routes.ts";
import { use${pascal}Item } from "./use-${base}-item.ts";
/** The heading stays while the item loads or fails, so the page always has an h1. */
export default function ${pascal}DetailPage() {
const { message } = useLocale();
const itemId = use${pascal}ItemId();
const query = use${pascal}Item(itemId);
const item = query.data;
return (
<DetailPage
key={itemId}
breadcrumb={<Link to={${camel}RouteUrl("${routeId}")}>{message("${camel}.list.title")}</Link>}
heading={{ title: item?.name ?? message("${camel}.detail.titlePending") }}
metadata={
item ? (
<dl>
<dt>{message("${camel}.detail.itemId")}</dt>
<dd>{item.itemId}</dd>
</dl>
) : null
}
feedback={<AsyncSurface state={query.state} onRetry={query.retry} />}
/>
);
}
`;
}
export function renderCreatePage({ names, routeId, write }: SliceShape): string {
const { base, camel, pascal, upper } = names;
return `import { useCallback, useEffect, useRef } from "react";
import { Link, useNavigate } from "react-router-dom";
import type { Result } from "../../../contracts/result.ts";
import {
AsyncSurface,
Button,
DirtyNavigationDialog,
ErrorSummary,
Form,
FormActions,
FormFailureStatus,
FormField,
FormPage,
useAppForm,
useDirtyNavigationGuard,
} from "../../../presentation/design-system/index.ts";
import { useLocale } from "../../../presentation/i18n/index.ts";
import type { ${pascal}CreateCommand } from "../application/${base}-feature-api.ts";
import type { ${pascal}ItemView } from "../contracts/${base}-mapper.ts";
import {
${upper}_FORM_DEFAULTS,
${camel}FormSchema,
to${pascal}CreateCommand,
type ${pascal}FormValues,
} from "./${base}-form.ts";
import { ${camel}RouteUrl } from "./${base}-routes.ts";
import { use${pascal}Create } from "./use-${base}-create.ts";
/**
* The create form. A saved item opens its detail page, unless the user left
* this page while it saved. The backend's refusal
* of the name (400 ${write.invalidCode}, refused before the write) shows on
* the field and the form saves again. A save whose result is unknown (the
* response was lost) keeps the form: the user checks, or, for a KEYED
* command, resends the same request with the same key. Confirming it was
* applied opens the list, which shows whether the item is there.
*/
export default function ${pascal}CreatePage() {
const navigate = useNavigate();
const { message } = useLocale();
const fieldLabels = {
name: message("${camel}.form.name"),
} satisfies Record<keyof ${pascal}FormValues, string>;
const mutation = use${pascal}Create();
// A save outlives this page when the user leaves while it runs. Ending
// then, it does not take them to its item or the list (1106/08-02).
const mounted = useRef(false);
useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, []);
const openSaved = useCallback(
(outcome: Result<${pascal}ItemView> | null) => {
if (outcome?.ok && mounted.current) {
void navigate(
${camel}RouteUrl("${write.detail.routeId}", {
params: { ${write.idParam}: outcome.value.itemId },
}),
);
}
return outcome;
},
[navigate],
);
const submit = useCallback(
async (command: ${pascal}CreateCommand) => {
const outcome = await mutation.submit(command);
openSaved(outcome);
return outcome;
},
[mutation, openSaved],
);
const form = useAppForm({
schema: ${camel}FormSchema,
defaultValues: ${upper}_FORM_DEFAULTS,
allowedServerFields: ["name"],
mapToCommand: to${pascal}CreateCommand,
submit,
});
const effectUnknown = mutation.state.indicator === "mutation-effect-unknown";
const blocked = effectUnknown || mutation.state.indicator === "mutation-pending";
// A save this form did not start holds the coordinator (one left running
// when the user came back, or the check behind "confirm applied"): the save
// is off and the feedback says a save is running (1105/08-04).
const otherSaveRunning = mutation.state.indicator === "mutation-pending" && !form.pending;
const guard = useDirtyNavigationGuard(form.dirty && !form.pending);
return (
<Form
id={form.formId}
pending={form.pending}
onSubmit={(event) => {
if (blocked) {
event.preventDefault();
return;
}
void form.submitForm(event);
}}
>
<FormPage
feedbackId={form.feedbackId}
breadcrumb={<Link to={${camel}RouteUrl("${routeId}")}>{message("${camel}.list.title")}</Link>}
heading={{ title: message("${camel}.form.title") }}
errorSummary={
<ErrorSummary
fieldErrors={form.fieldErrors}
formErrors={form.formErrors}
fieldLabels={fieldLabels}
fieldId={form.fieldId}
onFocusField={form.focusField}
/>
}
fields={
<FormField {...form.field("name")} label={fieldLabels.name} autoComplete="off" required />
}
formActions={
<FormActions sticky>
{/* Busy, not disabled, while saving: a disabled button drops
keyboard focus (1103/08-02). */}
<Button
type="submit"
pending={form.pending}
pendingLabel={message("${camel}.form.saving")}
disabled={effectUnknown || otherSaveRunning}
>
{message("${camel}.form.save")}
</Button>
</FormActions>
}
feedback={
form.failure ? (
<FormFailureStatus
failure={form.failure}
onAction={form.result === "retry-later" ? () => void form.submitForm() : undefined}
/>
) : effectUnknown ? (
<AsyncSurface
state={mutation.state}
supportReference={form.supportReference}
// The list shows whether the item is there; the form alone
// would show nothing but an emptied input (1105/08-02).
onReconcileUnknownEffect={(resolution) => {
void mutation.reconcileUnknownEffect(resolution).then(() => {
form.settleApplied();
if (mounted.current) void navigate(${camel}RouteUrl("${routeId}"));
});
}}
// Drawn only for a request with a key (a KEYED command).
onResendUnknownEffect={() => {
void form.resendUnknown(async () => openSaved(await mutation.resendUnknownEffect()));
}}
/>
) : otherSaveRunning && form.result !== "effect-unknown" ? (
<AsyncSurface state={mutation.state} />
) : null
}
guard={<DirtyNavigationDialog guard={guard} />}
/>
</Form>
);
}
`;
}
export function renderCreatePageTest({ names, apiPath, write }: SliceShape): string {
const { base, camel, upper } = names;
const keyed = write.semantics === "KEYED";
const unknownTest = keyed
? ` // KEYED: the key is kept, and the resend carries it, so the backend's
// IdempotencyExecutor replays the first request instead of applying twice.
it("resends a create whose response was lost with the same key", async () => {
const posts = answerCreate(() => HttpResponse.error());
const user = await openForm();
await user.type(await nameField(), "First item");
await user.click(saveButton());
expect(await screen.findByText(KO_MESSAGES["async.mutationEffectUnknown"])).toBeVisible();
expect(saveButton()).toBeDisabled();
answerCreate(() => created(), posts);
answerItem();
await user.click(screen.getByRole("button", { name: KO_MESSAGES["action.resendMutation"] }));
expect(await screen.findByRole("heading", { level: 1, name: "First item" })).toBeVisible();
expect(posts).toHaveLength(2);
expect(posts[0]!.headers.get("idempotency-key")).toMatch(/^[\\x21-\\x7e]+$/u);
expect(posts[1]!.headers.get("idempotency-key")).toBe(posts[0]!.headers.get("idempotency-key"));
});`
: ` // NEVER: the backend scaffold's create reads no key, so a resend would be a
// second, unprotected create. The form keeps the unknown result and offers
// no resend; the user checks the list.
it("keeps a create whose response was lost unknown and offers no resend", async () => {
const posts = answerCreate(() => HttpResponse.error());
const user = await openForm();
await user.type(await nameField(), "First item");
await user.click(saveButton());
expect(await screen.findByText(KO_MESSAGES["async.mutationEffectUnknown"])).toBeVisible();
expect(
screen.queryByRole("button", { name: KO_MESSAGES["action.resendMutation"] }),
).toBeNull();
expect(saveButton()).toBeDisabled();
expect(posts).toHaveLength(1);
expect(posts[0]!.headers.get("idempotency-key")).toBeNull();
});`;
return `// @vitest-environment jsdom
import { screen, waitFor, within } from "@testing-library/react";
import { http, HttpResponse, type JsonBodyType } from "msw";
import { setupServer } from "msw/node";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import { ${upper}_MESSAGE_CATALOGS } from "../../../src/features/${names.id}/contracts/${base}-message-catalog.ts";
import { ${camel}RouteUrl } from "../../../src/features/${names.id}/presentation/${base}-routes.ts";
import { KO_MESSAGES } from "../../../src/presentation/i18n/catalog.ts";
import { API, openSignedIn } from "./${base}-test-app.tsx";
const MESSAGES = ${upper}_MESSAGE_CATALOGS["ko-KR"];
const ITEM_ID = "0b6f2c1e-5d4a-4f3b-9c2d-1a2b3c4d5e6f";
const META = { requestId: "req-1", traceId: "0af7651916cd43dd8448eb211c80319c" };
const api = setupServer();
beforeAll(() => api.listen({ onUnhandledRequest: "error" }));
afterEach(() => api.resetHandlers());
afterAll(() => api.close());
/**
* The paired backend's answers, written out (new-feature.sh's controller and
* http-contract.md §1), not taken from the shared scenarios: a descriptor
* that stops reading this wire fails here.
*/
function created() {
return HttpResponse.json(
{ success: true, data: { id: ITEM_ID, name: "First item" }, meta: META },
{ status: 201, headers: { Location: \`\${API}${apiPath}/\${ITEM_ID}\` } },
);
}
function refusedName() {
return HttpResponse.json(
{
success: false,
error: {
code: "${write.invalidCode}",
category: "VALIDATION",
message: "backend message",
retryable: false,
},
meta: META,
},
{ status: 400 },
);
}
/** Answers POST ${apiPath} and keeps a copy of each request it receives. */
function answerCreate(respond: () => Response, posts: Request[] = []) {
api.use(
http.post(\`\${API}${apiPath}\`, ({ request }) => {
posts.push(request.clone());
return respond();
}),
);
return posts;
}
function answerItem(body: JsonBodyType = { id: ITEM_ID, name: "First item" }) {
api.use(
http.get(\`\${API}${apiPath}/:id\`, () =>
HttpResponse.json({ success: true, data: body, meta: META }),
),
);
}
function answerList() {
api.use(
http.get(\`\${API}${apiPath}\`, () =>
HttpResponse.json({ success: true, data: [{ id: ITEM_ID, name: "First item" }], meta: META }),
),
);
}
async function openForm() {
const user = await openSignedIn(${camel}RouteUrl("${write.create.routeId}"));
expect(
await screen.findByRole("heading", { level: 1, name: MESSAGES["${camel}.form.title"] }),
).toBeVisible();
return user;
}
// The label also holds the required mark, so the name is matched, not equal.
const nameField = () =>
screen.findByRole("textbox", { name: new RegExp(MESSAGES["${camel}.form.name"], "u") });
const saveButton = () => screen.getByRole("button", { name: MESSAGES["${camel}.form.save"] });
describe("${names.id} create form on the paired backend", () => {
it("saves a new item and opens it", async () => {
const posts = answerCreate(created);
answerItem();
const user = await openForm();
await user.type(await nameField(), " First item ");
await user.click(saveButton());
expect(await screen.findByRole("heading", { level: 1, name: "First item" })).toBeVisible();
expect(await posts[0]!.json()).toEqual({ name: "First item" });
});
// 1103/03-01. refusedBeforeWrite makes this NOT_APPLIED, so the form takes
// the next save instead of holding an unknown result.
it("shows the backend's refusal of the name on the field and saves again", async () => {
const posts = answerCreate(refusedName);
const user = await openForm();
await user.type(await nameField(), "Refused name");
await user.click(saveButton());
expect(await screen.findAllByText(KO_MESSAGES["form.validation.invalid"])).not.toHaveLength(0);
expect(await nameField()).toHaveAttribute("aria-invalid", "true");
expect(saveButton()).toBeEnabled();
answerCreate(created, posts);
answerItem();
await user.clear(await nameField());
await user.type(await nameField(), "First item");
await user.click(saveButton());
expect(await screen.findByRole("heading", { level: 1, name: "First item" })).toBeVisible();
expect(posts).toHaveLength(2);
});
${unknownTest}
// 1105/08-02. Confirming an unknown create opens the list, which shows
// whether the item was saved; the form alone showed nothing.
it("opens the list after the user confirms a create whose response was lost", async () => {
const posts = answerCreate(() => HttpResponse.error());
answerList();
const user = await openForm();
await user.type(await nameField(), "First item");
await user.click(saveButton());
expect(await screen.findByText(KO_MESSAGES["async.mutationEffectUnknown"])).toBeVisible();
await user.click(
screen.getByRole("button", { name: KO_MESSAGES["action.confirmMutationApplied"] }),
);
expect(
await screen.findByRole("heading", { level: 1, name: MESSAGES["${camel}.list.title"] }),
).toBeVisible();
expect(await screen.findByText("First item")).toBeVisible();
expect(posts).toHaveLength(1);
});
// 1106/08-02. The user leaves for the list while the save runs. The save
// that ends then does not take them to the item: they stay on the list.
it("stays on the list the user went to while the create was saving", async () => {
let answerPost: ((response: Response) => void) | undefined;
api.use(
http.post(
\`\${API}${apiPath}\`,
() =>
new Promise<Response>((resolve) => {
answerPost = resolve;
}),
),
);
let lists = 0;
api.use(
http.get(\`\${API}${apiPath}\`, () => {
lists += 1;
return HttpResponse.json({
success: true,
data: lists === 1 ? [] : [{ id: ITEM_ID, name: "First item" }],
meta: META,
});
}),
);
answerItem();
const user = await openForm();
await user.type(await nameField(), "First item");
await user.click(saveButton());
await waitFor(() => expect(answerPost).toBeDefined());
await user.click(
within(screen.getByRole("navigation", { name: KO_MESSAGES["template.breadcrumb"] })).getByRole(
"link",
{ name: MESSAGES["${camel}.list.title"] },
),
);
expect(
await screen.findByRole("heading", { level: 1, name: MESSAGES["${camel}.list.title"] }),
).toBeVisible();
answerPost?.(created());
// The create invalidates the list: the item there means the save ended.
// Opening the item would show its name as the heading within a second
// (earlier tests here loaded the detail page); it never comes.
expect(await screen.findByRole("link", { name: "First item" })).toBeVisible();
await expect(
screen.findByRole("heading", { level: 1, name: "First item" }, { timeout: 1_000 }),
).rejects.toThrow();
expect(
screen.getByRole("heading", { level: 1, name: MESSAGES["${camel}.list.title"] }),
).toBeVisible();
});
});
`;
}
/** The gateway test cases of the slice, inside the base gateway test's describe. */
export function renderWriteGatewayTests({ names, apiPath, write }: SliceShape): string {
const keyed = write.semantics === "KEYED";
const keyCases = keyed
? `
// http-contract.md §2: refused before the work ran, to be resent with the
// same key. The only answer the executor resends on its own (retryBudget 1).
it("sends the intent's key, and resends once with it after 503 IDEMPOTENCY_UNAVAILABLE", async () => {
const keys = answerCreate(201, CREATED_BODY);
// Registered last, so it answers first, once.
answerCreate(503, failure("IDEMPOTENCY_UNAVAILABLE", undefined, "TRANSIENT_DEPENDENCY"), keys, true);
await expect(gateway().create({ name: "First item" }, { intent: INTENT })).resolves.toEqual({
ok: true,
value: { itemId: ITEM_ID, name: "First item" },
});
expect(keys).toEqual(["key-1", "key-1"]);
});
// http-contract.md §2: the first request with this key still runs. The
// result is unknown; the form resends it later with the same key, the
// executor never does on its own.
it("leaves 409 IDEMPOTENT_IN_FLIGHT maybe applied and does not resend it", async () => {
const keys = answerCreate(409, failure("IDEMPOTENT_IN_FLIGHT", undefined, "CONFLICT"));
await expect(gateway().create({ name: "First item" }, { intent: INTENT })).resolves.toMatchObject({
ok: false,
error: { code: "IDEMPOTENT_IN_FLIGHT", effect: "MAYBE_APPLIED" },
});
expect(keys).toEqual(["key-1"]);
});
it("refuses a create without the intent's key before sending", async () => {
const keys = answerCreate(201, CREATED_BODY);
await expect(gateway().create({ name: "First item" }, {} as never)).resolves.toMatchObject({
ok: false,
});
expect(keys).toEqual([]);
});`
: `
it("sends no idempotency key: the backend scaffold's create reads none", async () => {
const keys = answerCreate(201, CREATED_BODY);
await gateway().create({ name: "First item" }, { intent: INTENT });
expect(keys).toEqual([null]);
});`;
return `
it("reads one item, and the backend's not-found code", async () => {
api.use(
http.get(\`\${API}${apiPath}/\${ITEM_ID}\`, () =>
HttpResponse.json({ success: true, data: { id: ITEM_ID, name: "First item" }, meta: META }),
),
);
await expect(gateway().get(ITEM_ID)).resolves.toEqual({
ok: true,
value: { itemId: ITEM_ID, name: "First item" },
});
api.use(
http.get(\`\${API}${apiPath}/\${ITEM_ID}\`, () =>
HttpResponse.json(failure("${write.notFoundCode}", undefined, "NOT_FOUND"), { status: 404 }),
),
);
await expect(gateway().get(ITEM_ID)).resolves.toMatchObject({
ok: false,
error: { kind: "NOT_FOUND", code: "${write.notFoundCode}", httpStatus: 404 },
});
});
it("reads the 201 Envelope of a create", async () => {
answerCreate(201, CREATED_BODY);
await expect(gateway().create({ name: "First item" }, { intent: INTENT })).resolves.toEqual({
ok: true,
value: { itemId: ITEM_ID, name: "First item" },
});
});
// 1103/03-01. Declared in refusedBeforeWrite: not applied, shown on the field.
it("reads 400 ${write.invalidCode} as not applied, on the name field", async () => {
answerCreate(400, failure("${write.invalidCode}"));
await expect(gateway().create({ name: "Refused" }, { intent: INTENT })).resolves.toMatchObject({
ok: false,
error: {
kind: "VALIDATION_REJECTED",
code: "${write.invalidCode}",
effect: "NOT_APPLIED",
validationIssues: [{ path: "name", code: "INVALID" }],
},
});
});
it("leaves a create whose response was lost maybe applied, and does not resend it", async () => {
const keys: (string | null)[] = [];
api.use(
http.post(\`\${API}${apiPath}\`, ({ request }) => {
keys.push(request.headers.get("idempotency-key"));
return HttpResponse.error();
}),
);
await expect(gateway().create({ name: "First item" }, { intent: INTENT })).resolves.toMatchObject({
ok: false,
error: { effect: "MAYBE_APPLIED" },
});
expect(keys).toHaveLength(1);
});
${keyCases}
`;
}
/** The slice's helpers for the gateway test, after its own. */
export function renderWriteGatewayHelpers({ apiPath, write }: SliceShape): string {
const key =
write.semantics === "KEYED"
? `
idempotencyKey: "key-1",`
: "";
return `
const ITEM_ID = "0b6f2c1e-5d4a-4f3b-9c2d-1a2b3c4d5e6f";
const CREATED_BODY = { success: true, data: { id: ITEM_ID, name: "First item" }, meta: META };
const INTENT = defineMutationIntent({
intentId: "intent-1",
operationId: "${write.createOperationId}",
canonicalInputIdentity: "create-1",${key}
createdAtMonotonicMs: 0,
});
/**
* Answers POST ${apiPath} and records the Idempotency-Key each request
* carried (\`null\` when none). The handler registered last answers first.
*/
function answerCreate(
status: number,
body: JsonBodyType,
keys: (string | null)[] = [],
once = false,
) {
api.use(
http.post(
\`\${API}${apiPath}\`,
({ request }) => {
keys.push(request.headers.get("idempotency-key"));
return HttpResponse.json(body, { status });
},
{ once },
),
);
return keys;
}
`;
}