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 & { bodyBlocks: CaseAuthoringBlock[]; }) | (Omit & { bodyBlocks: CaseAuthoringBlock[]; }) | (Omit & { 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, 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, 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, ): 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, string> = { CASE: "cases", REFERENCE: "references", CONCEPT: "concepts", QUESTION: "questions", SETUP: "setups", }; return `/${PREFIXES[input.kind]}/${input.slug}`; } function resolvedRelations( input: WorkingCopyInput, catalog: ReadonlyArray, ): 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(items: ReadonlyArray): T[] { return items .map((item) => ({ ...item })) .sort((left, right) => left.order - right.order); } export function projectWorkingCopy( input: WorkingCopyInput, catalog: ReadonlyArray, 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), }; } }