다섯 종류는 전부 끝난 일을 남긴다. 없는 것은 읽는 사람이 자기 손으로 다시 하려면 무엇부터 하는가다. Case 의 environment 는 평문 한 칸이라 명령이 들어가지 않고, 같은 셋업을 쓰는 Case 가 넷이면 같은 문장이 네 벌 복제된다. 프로젝트는 필수, 주제는 선택으로 둔다. 주제 없는 셋업이 그 프로젝트의 공통 구성이고, 주제를 붙이면 그 주제의 구성이다 — 스키마를 나누지 않고 두 범위를 같은 종류로 받는다. 버전만 본문 밖에 둔다(pinnedVersions). 이 절차가 어느 버전 위에서 성립했는지는 그 기록의 유효 범위이고, 목록과 머리말이 본문을 열지 않고 보여 줘야 한다. 나머지 셋(실행 절차·구성 값·확인 방법)은 명령과 표를 담아야 하므로 본문이다. 이름은 SETUP 이다. ENVIRONMENT 가 영어로는 자연스럽지만 case_detail.environment 와 겹친다 — 이 저장소가 열네 번 밟은 실패가 「종류를 손으로 나열한 곳을 빠뜨린다」이고 그걸 찾는 수단이 grep 이다. 손으로 나열해 두었던 자리를 이번에 표로 바꿨다. publicPath 의 삼항 사슬은 마지막 else 가 「나머지 전부」여서 새 종류의 주소가 조용히 /questions/… 가 됐고, document-editor 의 칸 경로도 같은 모양이었다. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PTnWufiY9ATv57egkKKVAV
379 lines
13 KiB
TypeScript
379 lines
13 KiB
TypeScript
import type { components } from "../../contracts/studio/generated.ts";
|
|
import type { SupportsEvidenceKey } from "../public-render-content.ts";
|
|
import {
|
|
ContentFormatError,
|
|
parseCaseContent,
|
|
type CaseAuthoringBlock,
|
|
} from "./parse-case-content.ts";
|
|
|
|
type WorkingCopyInput = components["schemas"]["WorkingCopyInput"];
|
|
type RecordKind = components["schemas"]["RecordKind"];
|
|
type CatalogEntry = components["schemas"]["CatalogEntry"];
|
|
type PublicRenderModel = components["schemas"]["PublicRenderModel"];
|
|
type CasePublicRenderModel = components["schemas"]["CasePublicRenderModel"];
|
|
type ConceptPublicRenderModel = components["schemas"]["ConceptPublicRenderModel"];
|
|
type SetupPublicRenderModel = components["schemas"]["SetupPublicRenderModel"];
|
|
type RenderContext = components["schemas"]["RenderContext"];
|
|
|
|
/**
|
|
* `projectWorkingCopy` has no asset catalog access (that is an adapter concern),
|
|
* so a CASE or CONCEPT projection cannot resolve `EvidenceFigureBlock.asset`.
|
|
* Everything else matches `PublicRenderModel` exactly; only those two variants'
|
|
* `bodyBlocks` narrow to the authoring shape until an adapter attaches the
|
|
* resolved asset descriptor.
|
|
*/
|
|
export type AuthoringRenderModel =
|
|
| (Omit<CasePublicRenderModel, "bodyBlocks"> & {
|
|
bodyBlocks: CaseAuthoringBlock[];
|
|
})
|
|
| (Omit<ConceptPublicRenderModel, "bodyBlocks"> & {
|
|
bodyBlocks: CaseAuthoringBlock[];
|
|
})
|
|
| (Omit<SetupPublicRenderModel, "bodyBlocks"> & {
|
|
bodyBlocks: CaseAuthoringBlock[];
|
|
})
|
|
| Exclude<
|
|
PublicRenderModel,
|
|
CasePublicRenderModel | ConceptPublicRenderModel | SetupPublicRenderModel
|
|
>;
|
|
|
|
export type ProjectionContext =
|
|
| RenderContext
|
|
| {
|
|
mode: "PREVIEW" | "PUBLIC";
|
|
publishedAt: string | null;
|
|
generatedAt?: string;
|
|
dependencyRevision?: string;
|
|
};
|
|
|
|
/**
|
|
* Attaches the resolved asset descriptor to every EVIDENCE_FIGURE block of the
|
|
* kinds that carry a markdown body — CASE, CONCEPT and SETUP — turning an
|
|
* `AuthoringRenderModel` into a genuine `PublicRenderModel`. Callers own the
|
|
* actual asset catalog (a mock gateway's static registry, a preview's own
|
|
* fixture data, ...), so this stays a pure mapping over a supplied resolver.
|
|
*/
|
|
export function resolveCaseEvidenceAssets(
|
|
model: AuthoringRenderModel,
|
|
resolveAsset: (key: string) => components["schemas"]["ResolvedAsset"],
|
|
): PublicRenderModel {
|
|
if (model.kind !== "CASE" && model.kind !== "CONCEPT" && model.kind !== "SETUP") return model;
|
|
|
|
return {
|
|
...model,
|
|
bodyBlocks: model.bodyBlocks.map((block) =>
|
|
block.type === "EVIDENCE_FIGURE"
|
|
? { ...block, asset: resolveAsset(block.key) }
|
|
: block,
|
|
),
|
|
};
|
|
}
|
|
|
|
function fail(detail: string): never {
|
|
throw new ContentFormatError([{ line: 1, column: 1, detail }]);
|
|
}
|
|
|
|
/**
|
|
* The one place that decides whether a `CatalogEntry` stands for a given
|
|
* evidence key -- an `EVIDENCE`-typed entry matches by `id`, `label`, or the
|
|
* legacy static `publicPath` convention. Exported so callers that need to
|
|
* synthesize additional `EVIDENCE` entries (from an Asset list, e.g.
|
|
* `evidenceCatalogEntriesFromAssets`) test membership against the exact same
|
|
* rule this gate itself uses, instead of re-declaring a subset of it.
|
|
*/
|
|
export function evidenceCatalogEntryFor(
|
|
catalog: ReadonlyArray<CatalogEntry>,
|
|
key: string,
|
|
): CatalogEntry | undefined {
|
|
return catalog.find(
|
|
(entry) =>
|
|
entry.type === "EVIDENCE" &&
|
|
(entry.id === key ||
|
|
entry.label === key ||
|
|
entry.publicPath === `/media/${key}.svg`),
|
|
);
|
|
}
|
|
|
|
function catalogEntry(
|
|
catalog: ReadonlyArray<CatalogEntry>,
|
|
id: string | null,
|
|
type: CatalogEntry["type"],
|
|
required: boolean,
|
|
): CatalogEntry | null {
|
|
if (!id) {
|
|
if (required) fail(`${type} catalog entry is required`);
|
|
return null;
|
|
}
|
|
|
|
const entry = catalog.find((candidate) => candidate.id === id);
|
|
if (!entry || entry.type !== type) {
|
|
fail(`${type} catalog entry not found: ${id}`);
|
|
}
|
|
return entry;
|
|
}
|
|
|
|
function displayTarget(
|
|
entry: CatalogEntry,
|
|
): components["schemas"]["DisplayTarget"] {
|
|
return {
|
|
id: entry.id,
|
|
label: entry.label,
|
|
publicPath: entry.publicPath ?? null,
|
|
};
|
|
}
|
|
|
|
function renderContext(
|
|
context: ProjectionContext,
|
|
catalog: ReadonlyArray<CatalogEntry>,
|
|
): RenderContext {
|
|
if (!("mode" in context)) return { ...context };
|
|
|
|
return {
|
|
generatedAt:
|
|
context.generatedAt ??
|
|
context.publishedAt ??
|
|
"1970-01-01T00:00:00.000Z",
|
|
dependencyRevision:
|
|
context.dependencyRevision ??
|
|
catalog
|
|
.map((entry) => entry.dependencyRevision)
|
|
.sort()
|
|
.at(-1) ??
|
|
"preview",
|
|
};
|
|
}
|
|
|
|
function publicPath(input: WorkingCopyInput, project: CatalogEntry | null) {
|
|
if (input.kind === "PROJECT_DECISION") {
|
|
/*
|
|
Decision 의 공개 주소는 자기 slug 가 아니라 프로젝트 주소 아래에 있다. 그래서 프로젝트가
|
|
공개되어 있지 않으면 이 문서에는 아직 주소가 없다.
|
|
|
|
예전 문구는 "PROJECT public path is required" 였다. 사실이지만 작성자가 할 일을 말해 주지
|
|
않는다 — 무엇을 어디서 눌러야 하는지 적는다.
|
|
*/
|
|
if (!project?.publicPath) {
|
|
fail(
|
|
"이 Decision 의 공개 주소는 프로젝트 주소 아래에 있습니다. 주제·프로젝트 화면에서 이 프로젝트를 먼저 게시해 주세요.",
|
|
);
|
|
}
|
|
return `${project.publicPath}/decisions#${input.slug}`;
|
|
}
|
|
/*
|
|
삼항 사슬이던 동안 마지막 `else` 가 「나머지 전부」였다. 종류를 더하면 그 종류의 주소가
|
|
조용히 `/questions/…` 가 된다 — 게시는 되고 링크만 다른 곳을 가리킨다. 표로 두면
|
|
컴파일러가 빈 자리를 잡는다. Decision 은 위에서 먼저 돌아가므로 이 표에 없다.
|
|
*/
|
|
const PREFIXES: Record<Exclude<RecordKind, "PROJECT_DECISION">, string> = {
|
|
CASE: "cases",
|
|
REFERENCE: "references",
|
|
CONCEPT: "concepts",
|
|
QUESTION: "questions",
|
|
SETUP: "setups",
|
|
};
|
|
return `/${PREFIXES[input.kind]}/${input.slug}`;
|
|
}
|
|
|
|
function resolvedRelations(
|
|
input: WorkingCopyInput,
|
|
catalog: ReadonlyArray<CatalogEntry>,
|
|
): components["schemas"]["ResolvedRelation"][] {
|
|
return [...input.relations]
|
|
.sort((left, right) => left.order - right.order)
|
|
.map((relation, index) => {
|
|
if (!relation.targetId) fail("RELATION catalog entry is required");
|
|
const target = catalogEntry(
|
|
catalog,
|
|
relation.targetId,
|
|
"RELATION",
|
|
true,
|
|
);
|
|
if (!target?.kind) fail(`RELATION kind is required: ${relation.targetId}`);
|
|
return {
|
|
id: relation.id ?? `relation-${index + 1}`,
|
|
targetId: target.id,
|
|
targetKind: target.kind,
|
|
title: target.label,
|
|
publicPath: target.publicPath ?? null,
|
|
reason: relation.reason,
|
|
order: relation.order,
|
|
};
|
|
});
|
|
}
|
|
|
|
function ordered<T extends { order: number }>(items: ReadonlyArray<T>): T[] {
|
|
return items
|
|
.map((item) => ({ ...item }))
|
|
.sort((left, right) => left.order - right.order);
|
|
}
|
|
|
|
export function projectWorkingCopy(
|
|
input: WorkingCopyInput,
|
|
catalog: ReadonlyArray<CatalogEntry>,
|
|
context: ProjectionContext,
|
|
supportsEvidenceKey: SupportsEvidenceKey,
|
|
): AuthoringRenderModel {
|
|
const topic = catalogEntry(catalog, input.topicId, "TOPIC", true);
|
|
const project = catalogEntry(catalog, input.projectId, "PROJECT", false);
|
|
if (!topic) fail("TOPIC catalog entry is required");
|
|
if (input.kind === "PROJECT_DECISION" && !project) {
|
|
fail("Decision 은 프로젝트에 속합니다. 기본 정보에서 프로젝트를 골라 주세요.");
|
|
}
|
|
/*
|
|
셋업은 언제나 어떤 프로젝트의 셋업이다. 프로젝트가 없으면 어느 코드를 띄우는 절차인지
|
|
화면이 말할 수 없다. 주제는 비어도 된다 — 주제 없는 셋업이 그 프로젝트의 공통 구성이다.
|
|
*/
|
|
if (input.kind === "SETUP" && !project) {
|
|
fail("환경 구성은 프로젝트에 속합니다. 기본 정보에서 프로젝트를 골라 주세요.");
|
|
}
|
|
|
|
const base = {
|
|
kind: input.kind,
|
|
slug: input.slug,
|
|
title: input.title,
|
|
summary: input.summary,
|
|
publicPath: publicPath(input, project),
|
|
topic: displayTarget(topic),
|
|
project: project ? displayTarget(project) : null,
|
|
relations: resolvedRelations(input, catalog),
|
|
renderContext: renderContext(context, catalog),
|
|
};
|
|
|
|
switch (input.kind) {
|
|
case "CASE": {
|
|
const bodyBlocks = parseCaseContent(input.bodyMarkdown);
|
|
for (const block of bodyBlocks) {
|
|
if (block.type !== "EVIDENCE_FIGURE") continue;
|
|
if (!supportsEvidenceKey(block.key)) {
|
|
fail(`supported local evidence key not found: ${block.key}`);
|
|
}
|
|
if (!evidenceCatalogEntryFor(catalog, block.key)) {
|
|
fail(`EVIDENCE catalog entry not found: ${block.key}`);
|
|
}
|
|
}
|
|
|
|
return {
|
|
...base,
|
|
kind: "CASE",
|
|
problem: input.problem,
|
|
conclusion: input.conclusion,
|
|
environment: input.environment,
|
|
reproduction: input.reproduction,
|
|
lastVerifiedOn: input.lastVerifiedOn ?? "",
|
|
bodyBlocks,
|
|
};
|
|
}
|
|
|
|
case "CONCEPT": {
|
|
/*
|
|
개념의 본문은 Case 와 같은 규칙을 탄다 — `:::evidence` 가 도식을 끌어오고, 그 키가
|
|
실제로 있는지 여기서 먼저 확인한다. 확인하지 않으면 미리보기는 열리지만 게시한 화면에서
|
|
그림 자리가 비어 버린다.
|
|
*/
|
|
const bodyBlocks = parseCaseContent(input.bodyMarkdown);
|
|
for (const block of bodyBlocks) {
|
|
if (block.type !== "EVIDENCE_FIGURE") continue;
|
|
if (!supportsEvidenceKey(block.key)) {
|
|
fail(`supported local evidence key not found: ${block.key}`);
|
|
}
|
|
if (!evidenceCatalogEntryFor(catalog, block.key)) {
|
|
fail(`EVIDENCE catalog entry not found: ${block.key}`);
|
|
}
|
|
}
|
|
|
|
return {
|
|
...base,
|
|
kind: "CONCEPT",
|
|
basisVersion: input.basisVersion,
|
|
bodyBlocks,
|
|
};
|
|
}
|
|
|
|
case "SETUP": {
|
|
/*
|
|
셋업의 본문도 Case 와 같은 규칙을 탄다 — `:::evidence` 가 도식을 끌어오고, 그 키가
|
|
실제로 있는지 여기서 먼저 확인한다.
|
|
*/
|
|
const bodyBlocks = parseCaseContent(input.bodyMarkdown);
|
|
for (const block of bodyBlocks) {
|
|
if (block.type !== "EVIDENCE_FIGURE") continue;
|
|
if (!supportsEvidenceKey(block.key)) {
|
|
fail(`supported local evidence key not found: ${block.key}`);
|
|
}
|
|
if (!evidenceCatalogEntryFor(catalog, block.key)) {
|
|
fail(`EVIDENCE catalog entry not found: ${block.key}`);
|
|
}
|
|
}
|
|
|
|
return {
|
|
...base,
|
|
kind: "SETUP",
|
|
pinnedVersions: input.pinnedVersions.map((pinned) => ({ ...pinned })),
|
|
bodyBlocks,
|
|
};
|
|
}
|
|
|
|
case "REFERENCE":
|
|
return {
|
|
...base,
|
|
kind: "REFERENCE",
|
|
purpose: input.purpose,
|
|
rules: ordered(input.rules),
|
|
applyWhen: ordered(input.applyWhen),
|
|
exceptions: ordered(input.exceptions),
|
|
examples: ordered(input.examples),
|
|
verifiedOn: input.verifiedOn ?? "",
|
|
};
|
|
|
|
case "QUESTION": {
|
|
if (!input.questionStatus) fail("Question status is required");
|
|
let resolution:
|
|
| components["schemas"]["ResolvedQuestionResolution"]
|
|
| null = null;
|
|
if (input.resolution) {
|
|
const evidence = catalogEntry(
|
|
catalog,
|
|
input.resolution.evidenceTargetId,
|
|
"EVIDENCE",
|
|
true,
|
|
);
|
|
if (!evidence) fail("EVIDENCE catalog entry is required");
|
|
resolution = {
|
|
summary: input.resolution.summary,
|
|
evidenceTarget: displayTarget(evidence),
|
|
linkLabel: input.resolution.linkLabel,
|
|
};
|
|
}
|
|
return {
|
|
...base,
|
|
kind: "QUESTION",
|
|
status: input.questionStatus,
|
|
facts: ordered(input.facts),
|
|
assumptions: ordered(input.assumptions),
|
|
unknowns: ordered(input.unknowns),
|
|
constraints: ordered(input.constraints),
|
|
options: ordered(input.options),
|
|
nextValidation: input.nextValidation,
|
|
resolution,
|
|
};
|
|
}
|
|
|
|
case "PROJECT_DECISION":
|
|
if (!input.decisionStatus) fail("Decision status is required");
|
|
/*
|
|
결정일은 비어 있어도 모델을 만든다. 검증이 그것을 경고로만 다루므로 날짜 없이 게시할 수
|
|
있는데, 여기서 막으면 그 문서는 미리보기조차 열리지 않는다 — 작성자는 "경고라면서 왜
|
|
안 되냐"를 만난다. 화면이 "미정"이라고 말하면 된다.
|
|
*/
|
|
return {
|
|
...base,
|
|
kind: "PROJECT_DECISION",
|
|
status: input.decisionStatus,
|
|
decidedOn: input.decidedOn ?? null,
|
|
statement: input.statement,
|
|
rationale: input.rationale,
|
|
consequences: ordered(input.consequences),
|
|
};
|
|
}
|
|
}
|