fix(studio): MOCK Studio의 주제·프로젝트·릴리즈 관리도 mock으로 돈다
create-tech-log-feature-input.ts는 Studio 문서와 Asset은 studioSource에 따라 mock과 HTTP를 고르는데, 관리 표면(주제·프로젝트· 릴리즈·홈 포커스·작업본 삭제)만 언제나 HTTP gateway를 썼다. 그래서 MOCK 빌드(로컬 개발, e2e·visual 빌드)에서 로그인한 Studio의 대시보드와 편집기가 주제·프로젝트를 읽으려고 API_BASE_URL의 /api/v1/studio/session으로 나가고, 연결이 거부된다. 브라우저 시험에서는 Studio 편집기 반응형 40건, Studio 접근성 7건, 경로별 axe의 Studio 두 경로 6건이 이것으로 떨어진다. mock 문서 gateway와 같은 방식으로 mock 관리 gateway를 둔다. - 메모리 안에만 있고, Studio 애플리케이션 하나가 사는 동안 유지된다. - 주제는 MOCK_CATALOG, 프로젝트와 릴리즈는 공개 화면의 정적 콘텐츠 (public-content.ts)에서 시작한다. 같은 이름과 slug를 쓴다. - 실패는 백엔드와 같은 코드로 낸다(VERSION_CONFLICT, *_NOT_FOUND, 게시된 것을 지울 때 CONFLICT). - 같은 idempotency 키는 첫 결과를 돌려준다. - 문서 gateway와 Studio state 하나를 나눠 써서, 관리 쪽에서 작업본을 지우면 문서 목록에서도 빠진다. 그래서 createMockStudioGateway가 state를 받을 수 있게 했다(주지 않으면 지금처럼 새로 만든다). 버린 대안: e2e에서 /api/v1/studio/**를 page.route로 가로채기. 로컬 개발 빌드는 그대로 깨진 채 남고, 시험만 초록이 된다. 한계: 결정(decision)과 프로젝트 활동은 빈 목록으로 시작한다. 공개 화면의 결정·활동 fixture는 관리 계약의 모양과 달라, 옮겨 담지 않았다. 검증: - 새 단위 시험 mock-management-gateway.test.ts. 연결 전에는 첫 시험이 「HTTP executor에 닿았다」로 실패했고, 연결 뒤 5건 모두 통과한다. mock-studio-gateway·Studio 화면 smoke·게시 흐름 시험(27건)도 통과한다. - check:types, lint rc=0. - chromium에서 Studio 편집기 반응형 10건, Studio 작업 흐름, 경로별 axe의 Studio 경로가 통과한다(전에는 연결 거부로 실패).
This commit is contained in:
@@ -11,6 +11,8 @@ import { createHttpStudioAssetGateway } from "./http/http-studio-asset-gateway.t
|
||||
import { createHttpStudioGateway } from "./http/http-studio-gateway.ts";
|
||||
import type { CsrfTokenProvider } from "./http/studio-session-csrf.ts";
|
||||
import { createMockStudioAssetGateway } from "./mock/mock-studio-asset-gateway.ts";
|
||||
import { createMockManagementGateway } from "./mock/mock-management-gateway.ts";
|
||||
import { createMockStudioState } from "./mock/mock-state.ts";
|
||||
import { createMockStudioGateway } from "./mock/mock-studio-gateway.ts";
|
||||
import { createHttpManagementGateway } from "./http/http-management-gateway.ts";
|
||||
import { createHttpPublicContentGateway } from "./http/http-public-content-gateway.ts";
|
||||
@@ -66,10 +68,6 @@ export function createTechLogFeatureInstalledInput(
|
||||
}),
|
||||
});
|
||||
|
||||
const createStudioGateway = () =>
|
||||
context.studioSource === "MOCK"
|
||||
? createMockStudioGateway({ assets: mockAssets })
|
||||
: createHttpStudioGateway({ http });
|
||||
|
||||
// The public read source switches independently of Studio: the two are
|
||||
// different services, and the combination that matters today is an authoring
|
||||
@@ -79,15 +77,26 @@ export function createTechLogFeatureInstalledInput(
|
||||
? publicContentQueries
|
||||
: createHttpPublicContentGateway({ http });
|
||||
|
||||
const createManagementGateway = () =>
|
||||
createHttpManagementGateway({ http });
|
||||
|
||||
const createStudioApplication = () =>
|
||||
createTechLogStudioApplication({
|
||||
studio: createStudioGateway(),
|
||||
// MOCK: one in-memory Studio state per application, shared by the document
|
||||
// and management gateways, so deleting a draft from the management surface
|
||||
// also takes it out of the document list. Management used to be HTTP even
|
||||
// here, and a MOCK build (local development, the e2e and visual builds)
|
||||
// asked an API that is not there for its topics and projects.
|
||||
const createStudioApplication = () => {
|
||||
if (context.studioSource === "MOCK") {
|
||||
const state = createMockStudioState();
|
||||
return createTechLogStudioApplication({
|
||||
studio: createMockStudioGateway({ assets: mockAssets, state }),
|
||||
assets: createStudioAssetGateway(),
|
||||
management: createMockManagementGateway({ studioState: state }),
|
||||
});
|
||||
}
|
||||
return createTechLogStudioApplication({
|
||||
studio: createHttpStudioGateway({ http }),
|
||||
assets: createStudioAssetGateway(),
|
||||
management: createManagementGateway(),
|
||||
management: createHttpManagementGateway({ http }),
|
||||
});
|
||||
};
|
||||
|
||||
const input: TechLogFeatureInput = Object.freeze({
|
||||
publicContent,
|
||||
|
||||
@@ -0,0 +1,588 @@
|
||||
import type {
|
||||
DeletableDocumentKind,
|
||||
ManagementGateway,
|
||||
} from "../../application/ports/management-gateway.ts";
|
||||
import { ManagementGatewayError } from "../../application/ports/management-gateway-error.ts";
|
||||
import type {
|
||||
IdempotentOptions,
|
||||
RequestOptions,
|
||||
} from "../../application/ports/studio-gateway.ts";
|
||||
import type {
|
||||
CreateDraftResponse,
|
||||
DecisionResponse,
|
||||
HomeFocusResponse,
|
||||
ProjectActivityResponse,
|
||||
ProjectEditResponse,
|
||||
ProjectIndexItem,
|
||||
PublishResponse,
|
||||
ReleaseEditResponse,
|
||||
ReleaseIndexItem,
|
||||
TopicEdit,
|
||||
TopicVariantEdit,
|
||||
} from "../../contracts/management/contract.ts";
|
||||
import type { WorkingCopy } from "../../contracts/studio/contract.ts";
|
||||
import {
|
||||
projects as staticProjects,
|
||||
releases as staticReleases,
|
||||
} from "../static/public-content.ts";
|
||||
import { FIXTURE_IDS, MOCK_CATALOG } from "./fixtures.ts";
|
||||
import { createMockStudioState, type MockStudioState } from "./mock-state.ts";
|
||||
|
||||
/**
|
||||
* The MOCK `studioSource` half of the management surface (topics, projects,
|
||||
* releases, home focus, document deletion).
|
||||
*
|
||||
* `create-tech-log-feature-input.ts` used to hand the HTTP gateway to Studio
|
||||
* whatever the source was, so a MOCK build — local development, the e2e and
|
||||
* visual builds — sent `/api/v1/studio/session` to an API that is not there
|
||||
* as soon as the dashboard or an editor asked for its topics. Like the mock
|
||||
* document gateway, this keeps everything in memory for the life of one
|
||||
* Studio application and reports failures with the codes the backend uses.
|
||||
*/
|
||||
|
||||
export type MockManagementDependencies = {
|
||||
clock: { now(): Date };
|
||||
idGenerator: { next(): string };
|
||||
/**
|
||||
* The working copies `deleteDocument` removes and `listQuestions` lists.
|
||||
* `create-tech-log-feature-input.ts` passes the state of the mock document
|
||||
* gateway it builds next to this one, so a deleted draft leaves the
|
||||
* document list too. Defaults to a fresh seed.
|
||||
*/
|
||||
studioState: MockStudioState;
|
||||
};
|
||||
|
||||
export const DEFAULT_MANAGEMENT_MOCK_NOW = "2026-08-14T01:00:00.000Z";
|
||||
|
||||
const HOME_FOCUS_ID = "99999999-0000-4000-8000-000000000001";
|
||||
const RELEASE_0_1_0 = "99999999-0000-4000-8000-000000000101";
|
||||
const PROJECT_IDS: Readonly<Record<string, string>> = {
|
||||
"backend-skeleton": FIXTURE_IDS.projectBackend,
|
||||
"auth-lab": FIXTURE_IDS.projectAuth,
|
||||
};
|
||||
const DOCUMENT_KIND: Readonly<Record<DeletableDocumentKind, string>> = {
|
||||
CASE: "deleteCaseDraft",
|
||||
REFERENCE: "deleteReferenceDraft",
|
||||
QUESTION: "deleteQuestion",
|
||||
CONCEPT: "deleteConceptDraft",
|
||||
SETUP: "deleteSetupDraft",
|
||||
};
|
||||
|
||||
const clone = <T>(value: T): T => structuredClone(value);
|
||||
|
||||
function problem(operationId: string, code: string, detail: string) {
|
||||
return new ManagementGatewayError(operationId, code, detail);
|
||||
}
|
||||
|
||||
function published(path: string, at: string, version: number) {
|
||||
return {
|
||||
state: "ACTIVE" as const,
|
||||
publishedSourceVersion: version,
|
||||
hasUnpublishedChanges: false,
|
||||
canonicalPath: path,
|
||||
publishedAt: at,
|
||||
};
|
||||
}
|
||||
|
||||
const NEVER_PUBLISHED = Object.freeze({
|
||||
state: "NEVER_PUBLISHED" as const,
|
||||
hasUnpublishedChanges: false,
|
||||
});
|
||||
|
||||
function seedTopics(): TopicEdit[] {
|
||||
return MOCK_CATALOG.filter((entry) => entry.type === "TOPIC").map((entry) => ({
|
||||
id: entry.id,
|
||||
version: 1,
|
||||
name: entry.label,
|
||||
slug: entry.publicPath!.slice("/topics/".length),
|
||||
status: "ACTIVE",
|
||||
}));
|
||||
}
|
||||
|
||||
function seedProjects(topics: readonly TopicEdit[], updatedAt: string): ProjectEditResponse[] {
|
||||
const topicIdBySlug = new Map(topics.map((topic) => [topic.slug, topic.id!]));
|
||||
return staticProjects.flatMap((project) => {
|
||||
const id = PROJECT_IDS[project.slug];
|
||||
if (!id) return [];
|
||||
return [
|
||||
{
|
||||
id,
|
||||
version: 1,
|
||||
name: project.title,
|
||||
slug: project.slug,
|
||||
oneLinePurpose: project.summary,
|
||||
thesis: project.thesis,
|
||||
purposeMarkdown: project.summary,
|
||||
boundaryMarkdown: "",
|
||||
phase: project.stage,
|
||||
currentObjective: project.currentGoal,
|
||||
nextStep: project.nextStep,
|
||||
technologyLabels: project.topics.map((topic) => topic.name),
|
||||
workflowStatus: "PUBLISHED",
|
||||
targetVisibility: "PUBLIC",
|
||||
publication: published(`/projects/${project.slug}`, updatedAt, 1),
|
||||
updatedAt,
|
||||
topicIds: project.topics.flatMap((topic) => {
|
||||
const topicId = topicIdBySlug.get(topic.slug);
|
||||
return topicId ? [topicId] : [];
|
||||
}),
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
function seedReleases(): ReleaseEditResponse[] {
|
||||
return staticReleases.map((release, index) => ({
|
||||
id: index === 0 ? RELEASE_0_1_0 : `99999999-0000-4000-8000-${String(101 + index).padStart(12, "0")}`,
|
||||
version: 1,
|
||||
expectedVersion: 1,
|
||||
versionLabel: release.version,
|
||||
title: release.title,
|
||||
summary: release.summary,
|
||||
releasedOn: release.publishedAt.slice(0, 10),
|
||||
changeTypes: ["FEATURE"],
|
||||
changesMarkdown: release.changes.map((line) => `- ${line}`).join("\n"),
|
||||
reasonMarkdown: release.reasons.map((line) => `- ${line}`).join("\n"),
|
||||
userImpactMarkdown: release.impacts.map((line) => `- ${line}`).join("\n"),
|
||||
verificationMarkdown: "",
|
||||
workflowStatus: "PUBLISHED",
|
||||
publication: published(release.path, release.publishedAt, 1),
|
||||
}));
|
||||
}
|
||||
|
||||
function page<T>(operationId: string, items: readonly T[], pageNumber = 0, size = 20) {
|
||||
if (!Number.isInteger(pageNumber) || pageNumber < 0 || !Number.isInteger(size) || size < 1 || size > 100) {
|
||||
throw problem(operationId, "REQUEST_VALIDATION_FAILED", "page must be 0 or more and size 1-100.");
|
||||
}
|
||||
const totalElements = items.length;
|
||||
const totalPages = Math.ceil(totalElements / size);
|
||||
return {
|
||||
items: clone(items.slice(pageNumber * size, pageNumber * size + size)),
|
||||
page: {
|
||||
number: pageNumber,
|
||||
size,
|
||||
totalElements,
|
||||
totalPages,
|
||||
hasPrevious: pageNumber > 0,
|
||||
hasNext: pageNumber + 1 < totalPages,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createMockManagementGateway(
|
||||
supplied: Partial<MockManagementDependencies> = {},
|
||||
): ManagementGateway {
|
||||
let nextId = 9000;
|
||||
const clock = supplied.clock ?? { now: () => new Date(DEFAULT_MANAGEMENT_MOCK_NOW) };
|
||||
const ids = supplied.idGenerator ?? {
|
||||
next: () => `bbbbbbbb-bbbb-4bbb-8bbb-${String(nextId++).padStart(12, "0")}`,
|
||||
};
|
||||
const studio = supplied.studioState ?? createMockStudioState();
|
||||
const now = () => clock.now().toISOString();
|
||||
|
||||
const topics = new Map(seedTopics().map((topic) => [topic.id!, topic]));
|
||||
const variants = new Map<string, TopicVariantEdit[]>();
|
||||
const projects = new Map(seedProjects([...topics.values()], now()).map((project) => [project.id, project]));
|
||||
const activities = new Map<string, ProjectActivityResponse[]>();
|
||||
const decisions = new Map<string, DecisionResponse[]>();
|
||||
const releases = new Map(seedReleases().map((release) => [release.id, release]));
|
||||
let homeFocus: HomeFocusResponse = {
|
||||
id: HOME_FOCUS_ID,
|
||||
version: 1,
|
||||
defaultType: "CURRENT_WORK",
|
||||
currentProjectId: FIXTURE_IDS.projectBackend,
|
||||
openQuestionId: FIXTURE_IDS.edgeTokenQuestion,
|
||||
};
|
||||
// The same key replays the first outcome, as the backend's idempotency
|
||||
// store does; a retried create must not make a second draft.
|
||||
const replay = new Map<string, unknown>();
|
||||
|
||||
async function boundary(options?: RequestOptions) {
|
||||
options?.signal?.throwIfAborted();
|
||||
await Promise.resolve();
|
||||
options?.signal?.throwIfAborted();
|
||||
}
|
||||
|
||||
async function read<T>(options: RequestOptions | undefined, run: () => T): Promise<T> {
|
||||
await boundary(options);
|
||||
return clone(run());
|
||||
}
|
||||
|
||||
async function command<T>(options: IdempotentOptions, run: () => T): Promise<T> {
|
||||
await boundary(options);
|
||||
if (replay.has(options.idempotencyKey)) return clone(replay.get(options.idempotencyKey) as T);
|
||||
const value = run();
|
||||
replay.set(options.idempotencyKey, clone(value));
|
||||
return clone(value);
|
||||
}
|
||||
|
||||
function found<T>(map: ReadonlyMap<string, T>, id: string, operationId: string, code: string): T {
|
||||
const value = map.get(id);
|
||||
if (value === undefined) throw problem(operationId, code, `${id} does not exist.`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function versionOf(current: number | undefined, expected: number | undefined, operationId: string) {
|
||||
if (expected !== current) {
|
||||
throw problem(operationId, "VERSION_CONFLICT", `Expected version ${String(expected)}, current ${String(current)}.`);
|
||||
}
|
||||
}
|
||||
|
||||
function questionItems() {
|
||||
return [...studio.documents.values()]
|
||||
.filter((document: WorkingCopy) => document.kind === "QUESTION")
|
||||
.map((document: WorkingCopy) => {
|
||||
const project = document.projectId ? projects.get(document.projectId) : undefined;
|
||||
const publication = studio.publications.get(document.id);
|
||||
return {
|
||||
id: document.id,
|
||||
question: document.title,
|
||||
status: "OPEN",
|
||||
targetVisibility: "PUBLIC",
|
||||
...(project?.slug
|
||||
? { primaryProject: { name: project.name, slug: project.slug, path: `/projects/${project.slug}` } }
|
||||
: {}),
|
||||
updatedAt: document.updatedAt,
|
||||
version: document.version,
|
||||
publication:
|
||||
publication?.status === "PUBLISHED"
|
||||
? published(publication.publicPath, document.updatedAt, publication.publishedVersion)
|
||||
: NEVER_PUBLISHED,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function projectIndexItem(project: ProjectEditResponse): ProjectIndexItem {
|
||||
return {
|
||||
id: project.id,
|
||||
name: project.name,
|
||||
...(project.slug ? { slug: project.slug } : {}),
|
||||
topicIds: project.topicIds ?? [],
|
||||
phase: project.phase,
|
||||
workflowStatus: project.workflowStatus,
|
||||
targetVisibility: project.targetVisibility,
|
||||
...(project.currentObjective ? { currentObjective: project.currentObjective } : {}),
|
||||
...(project.nextStep ? { nextStep: project.nextStep } : {}),
|
||||
updatedAt: project.updatedAt,
|
||||
version: project.version,
|
||||
publication: project.publication,
|
||||
};
|
||||
}
|
||||
|
||||
function releaseIndexItem(release: ReleaseEditResponse): ReleaseIndexItem {
|
||||
return {
|
||||
id: release.id,
|
||||
versionLabel: release.versionLabel,
|
||||
title: release.title,
|
||||
...(release.releasedOn ? { releasedOn: release.releasedOn } : {}),
|
||||
workflowStatus: release.workflowStatus,
|
||||
updatedAt: now(),
|
||||
version: release.version,
|
||||
publication: release.publication,
|
||||
};
|
||||
}
|
||||
|
||||
function draft(): CreateDraftResponse {
|
||||
return { id: ids.next(), status: "DRAFT", version: 1, createdAt: now() };
|
||||
}
|
||||
|
||||
return Object.freeze({
|
||||
listTopics: (options) => read(options, () => [...topics.values()]),
|
||||
createTopic: (input, options) =>
|
||||
command(options, () => {
|
||||
const topic = { ...input, id: ids.next(), version: 1, status: input.status ?? "ACTIVE" };
|
||||
delete topic.expectedVersion;
|
||||
topics.set(topic.id, topic);
|
||||
return topic;
|
||||
}),
|
||||
updateTopic: (id, body, options) =>
|
||||
command(options, () => {
|
||||
const current = found(topics, id, "updateTopic", "TOPIC_NOT_FOUND");
|
||||
versionOf(current.version, body.expectedVersion, "updateTopic");
|
||||
const next = { ...body, id, version: current.version! + 1 };
|
||||
delete next.expectedVersion;
|
||||
topics.set(id, next);
|
||||
return next;
|
||||
}),
|
||||
deleteTopic: (id, expectedVersion, options) =>
|
||||
command(options, () => {
|
||||
const current = found(topics, id, "deleteTopic", "TOPIC_NOT_FOUND");
|
||||
versionOf(current.version, expectedVersion, "deleteTopic");
|
||||
topics.delete(id);
|
||||
variants.delete(id);
|
||||
}),
|
||||
|
||||
listTopicVariants: (topicId, options) =>
|
||||
read(options, () => {
|
||||
found(topics, topicId, "listTopicVariants", "TOPIC_NOT_FOUND");
|
||||
return variants.get(topicId) ?? [];
|
||||
}),
|
||||
createTopicVariant: (topicId, body, options) =>
|
||||
command(options, () => {
|
||||
found(topics, topicId, "createTopicVariant", "TOPIC_NOT_FOUND");
|
||||
const variant = { ...body, id: ids.next(), version: 1 };
|
||||
delete variant.expectedVersion;
|
||||
variants.set(topicId, [...(variants.get(topicId) ?? []), variant]);
|
||||
return variant;
|
||||
}),
|
||||
updateTopicVariant: (topicId, variantId, body, options) =>
|
||||
command(options, () => {
|
||||
const list = variants.get(topicId) ?? [];
|
||||
const current = list.find((variant) => variant.id === variantId);
|
||||
if (!current) throw problem("updateTopicVariant", "TOPIC_NOT_FOUND", `${variantId} does not exist.`);
|
||||
versionOf(current.version, body.expectedVersion, "updateTopicVariant");
|
||||
const next = { ...body, id: variantId, version: current.version! + 1 };
|
||||
delete next.expectedVersion;
|
||||
variants.set(topicId, list.map((variant) => (variant.id === variantId ? next : variant)));
|
||||
return next;
|
||||
}),
|
||||
deleteTopicVariant: (topicId, variantId, expectedVersion, options) =>
|
||||
command(options, () => {
|
||||
const list = variants.get(topicId) ?? [];
|
||||
const current = list.find((variant) => variant.id === variantId);
|
||||
if (!current) throw problem("deleteTopicVariant", "TOPIC_NOT_FOUND", `${variantId} does not exist.`);
|
||||
versionOf(current.version, expectedVersion, "deleteTopicVariant");
|
||||
variants.set(topicId, list.filter((variant) => variant.id !== variantId));
|
||||
}),
|
||||
|
||||
listProjects: (pageNumber, size, options) =>
|
||||
read(options, () => page("listStudioProjects", [...projects.values()].map(projectIndexItem), pageNumber, size)),
|
||||
listQuestions: (pageNumber, size, options) =>
|
||||
read(options, () => page("listStudioQuestions", questionItems(), pageNumber, size)),
|
||||
listProjectDecisions: (projectId, options) =>
|
||||
read(options, () => {
|
||||
found(projects, projectId, "listProjectDecisions", "PROJECT_NOT_FOUND");
|
||||
return decisions.get(projectId) ?? [];
|
||||
}),
|
||||
|
||||
getProject: (id, options) =>
|
||||
read(options, () => found(projects, id, "getProjectForEdit", "PROJECT_NOT_FOUND")),
|
||||
createProject: (title, options) =>
|
||||
command(options, () => {
|
||||
const created = draft();
|
||||
projects.set(created.id, {
|
||||
id: created.id,
|
||||
version: created.version,
|
||||
name: title,
|
||||
phase: "DESIGN",
|
||||
workflowStatus: "DRAFT",
|
||||
targetVisibility: "PRIVATE",
|
||||
publication: NEVER_PUBLISHED,
|
||||
updatedAt: created.createdAt,
|
||||
});
|
||||
return created;
|
||||
}),
|
||||
updateProject: (id, body, options) =>
|
||||
command(options, () => {
|
||||
const current = found(projects, id, "updateProject", "PROJECT_NOT_FOUND");
|
||||
versionOf(current.version, body.expectedVersion, "updateProject");
|
||||
const { expectedVersion, ...fields } = body;
|
||||
void expectedVersion;
|
||||
const next: ProjectEditResponse = {
|
||||
...current,
|
||||
...fields,
|
||||
version: current.version + 1,
|
||||
updatedAt: now(),
|
||||
publication:
|
||||
current.publication.state === "ACTIVE"
|
||||
? { ...current.publication, hasUnpublishedChanges: true }
|
||||
: current.publication,
|
||||
};
|
||||
projects.set(id, next);
|
||||
return next;
|
||||
}),
|
||||
deleteProject: (id, expectedVersion, options) =>
|
||||
command(options, () => {
|
||||
const current = found(projects, id, "deleteProject", "PROJECT_NOT_FOUND");
|
||||
versionOf(current.version, expectedVersion, "deleteProject");
|
||||
if (current.publication.state === "ACTIVE") {
|
||||
throw problem("deleteProject", "CONFLICT", "A published project is unpublished before it is deleted.");
|
||||
}
|
||||
projects.delete(id);
|
||||
activities.delete(id);
|
||||
decisions.delete(id);
|
||||
}),
|
||||
publishProject: (id, expectedVersion, visibility, options) =>
|
||||
command(options, (): PublishResponse => {
|
||||
const current = found(projects, id, "publishProject", "PROJECT_NOT_FOUND");
|
||||
versionOf(current.version, expectedVersion, "publishProject");
|
||||
const path = `/projects/${current.slug ?? current.id}`;
|
||||
const at = now();
|
||||
const version = current.version + 1;
|
||||
projects.set(id, {
|
||||
...current,
|
||||
version,
|
||||
workflowStatus: "PUBLISHED",
|
||||
targetVisibility: visibility ?? "PUBLIC",
|
||||
publication: published(path, at, version),
|
||||
updatedAt: at,
|
||||
});
|
||||
return { id, status: "PUBLISHED", visibility: visibility ?? "PUBLIC", canonicalPath: path, publishedAt: at, version };
|
||||
}),
|
||||
unpublishProject: (id, expectedVersion, options) =>
|
||||
command(options, () => {
|
||||
const current = found(projects, id, "unpublishProject", "PROJECT_NOT_FOUND");
|
||||
versionOf(current.version, expectedVersion, "unpublishProject");
|
||||
const next: ProjectEditResponse = {
|
||||
...current,
|
||||
version: current.version + 1,
|
||||
workflowStatus: "DRAFT",
|
||||
publication: { ...current.publication, state: "WITHDRAWN" },
|
||||
updatedAt: now(),
|
||||
};
|
||||
projects.set(id, next);
|
||||
return next;
|
||||
}),
|
||||
|
||||
listProjectActivities: (id, options) =>
|
||||
read(options, () => {
|
||||
found(projects, id, "listProjectActivities", "PROJECT_NOT_FOUND");
|
||||
return activities.get(id) ?? [];
|
||||
}),
|
||||
createProjectActivity: (id, body, options) =>
|
||||
command(options, () => {
|
||||
const project = found(projects, id, "createProjectActivity", "PROJECT_NOT_FOUND");
|
||||
versionOf(project.version, body.expectedProjectVersion, "createProjectActivity");
|
||||
const { expectedProjectVersion, ...fields } = body;
|
||||
void expectedProjectVersion;
|
||||
const activity: ProjectActivityResponse = { ...fields, id: ids.next(), projectId: id, origin: "MANUAL", version: 1 };
|
||||
activities.set(id, [...(activities.get(id) ?? []), activity]);
|
||||
return activity;
|
||||
}),
|
||||
updateProjectActivity: (id, activityId, body, options) =>
|
||||
command(options, () => {
|
||||
const list = activities.get(id) ?? [];
|
||||
const current = list.find((activity) => activity.id === activityId);
|
||||
if (!current) throw problem("updateProjectActivity", "PROJECT_NOT_FOUND", `${activityId} does not exist.`);
|
||||
versionOf(current.version, body.expectedVersion, "updateProjectActivity");
|
||||
const { expectedVersion, ...fields } = body;
|
||||
void expectedVersion;
|
||||
const next = { ...current, ...fields, version: current.version + 1 };
|
||||
activities.set(id, list.map((activity) => (activity.id === activityId ? next : activity)));
|
||||
return next;
|
||||
}),
|
||||
deleteProjectActivity: (id, activityId, expectedVersion, options) =>
|
||||
command(options, () => {
|
||||
const list = activities.get(id) ?? [];
|
||||
const current = list.find((activity) => activity.id === activityId);
|
||||
if (!current) throw problem("deleteProjectActivity", "PROJECT_NOT_FOUND", `${activityId} does not exist.`);
|
||||
versionOf(current.version, expectedVersion, "deleteProjectActivity");
|
||||
activities.set(id, list.filter((activity) => activity.id !== activityId));
|
||||
}),
|
||||
|
||||
getHomeFocus: (options) => read(options, () => homeFocus),
|
||||
updateHomeFocus: (body, options) =>
|
||||
command(options, () => {
|
||||
versionOf(homeFocus.version, body.expectedVersion, "updateHomeFocus");
|
||||
const { expectedVersion, ...fields } = body;
|
||||
void expectedVersion;
|
||||
homeFocus = { id: homeFocus.id, ...fields, version: homeFocus.version + 1 };
|
||||
return homeFocus;
|
||||
}),
|
||||
|
||||
listReleases: (pageNumber, size, options) =>
|
||||
read(options, () => page("listStudioReleases", [...releases.values()].map(releaseIndexItem), pageNumber, size)),
|
||||
getRelease: (id, options) =>
|
||||
read(options, () => found(releases, id, "getReleaseForEdit", "RELEASE_NOT_FOUND")),
|
||||
createRelease: (title, options) =>
|
||||
command(options, () => {
|
||||
const created = draft();
|
||||
releases.set(created.id, {
|
||||
id: created.id,
|
||||
version: created.version,
|
||||
expectedVersion: created.version,
|
||||
versionLabel: "",
|
||||
title,
|
||||
summary: "",
|
||||
changeTypes: [],
|
||||
changesMarkdown: "",
|
||||
verificationMarkdown: "",
|
||||
workflowStatus: "DRAFT",
|
||||
publication: NEVER_PUBLISHED,
|
||||
});
|
||||
return created;
|
||||
}),
|
||||
updateRelease: (id, body, options) =>
|
||||
command(options, () => {
|
||||
const current = found(releases, id, "updateRelease", "RELEASE_NOT_FOUND");
|
||||
versionOf(current.version, body.expectedVersion, "updateRelease");
|
||||
const version = current.version + 1;
|
||||
const next: ReleaseEditResponse = {
|
||||
...current,
|
||||
...body,
|
||||
expectedVersion: version,
|
||||
version,
|
||||
publication:
|
||||
current.publication.state === "ACTIVE"
|
||||
? { ...current.publication, hasUnpublishedChanges: true }
|
||||
: current.publication,
|
||||
};
|
||||
releases.set(id, next);
|
||||
return next;
|
||||
}),
|
||||
deleteRelease: (id, expectedVersion, options) =>
|
||||
command(options, () => {
|
||||
const current = found(releases, id, "deleteRelease", "RELEASE_NOT_FOUND");
|
||||
versionOf(current.version, expectedVersion, "deleteRelease");
|
||||
if (current.publication.state === "ACTIVE") {
|
||||
throw problem("deleteRelease", "CONFLICT", "A published release is archived, not deleted.");
|
||||
}
|
||||
releases.delete(id);
|
||||
}),
|
||||
publishRelease: (id, expectedVersion, options) =>
|
||||
command(options, (): PublishResponse => {
|
||||
const current = found(releases, id, "publishRelease", "RELEASE_NOT_FOUND");
|
||||
versionOf(current.version, expectedVersion, "publishRelease");
|
||||
const path = `/releases/${current.versionLabel || current.id}`;
|
||||
const at = now();
|
||||
const version = current.version + 1;
|
||||
releases.set(id, {
|
||||
...current,
|
||||
version,
|
||||
expectedVersion: version,
|
||||
workflowStatus: "PUBLISHED",
|
||||
publication: published(path, at, version),
|
||||
});
|
||||
return { id, status: "PUBLISHED", visibility: "PUBLIC", canonicalPath: path, publishedAt: at, version };
|
||||
}),
|
||||
archiveRelease: (id, expectedVersion, options) =>
|
||||
command(options, () => {
|
||||
const current = found(releases, id, "archiveRelease", "RELEASE_NOT_FOUND");
|
||||
versionOf(current.version, expectedVersion, "archiveRelease");
|
||||
const version = current.version + 1;
|
||||
const next: ReleaseEditResponse = {
|
||||
...current,
|
||||
version,
|
||||
expectedVersion: version,
|
||||
workflowStatus: "ARCHIVED",
|
||||
publication: { ...current.publication, state: "WITHDRAWN" },
|
||||
};
|
||||
releases.set(id, next);
|
||||
return next;
|
||||
}),
|
||||
|
||||
deleteDocument: (kind, id, expectedVersion, options) =>
|
||||
command(options, () => {
|
||||
const operationId = DOCUMENT_KIND[kind];
|
||||
const document = studio.documents.get(id);
|
||||
if (!document || document.kind !== kind) {
|
||||
throw problem(operationId, "DOCUMENT_NOT_FOUND", `${id} does not exist.`);
|
||||
}
|
||||
versionOf(document.version, expectedVersion, operationId);
|
||||
if (studio.publications.get(id)?.status === "PUBLISHED") {
|
||||
throw problem(operationId, "CONFLICT", "A published document is unpublished before it is deleted.");
|
||||
}
|
||||
studio.documents.delete(id);
|
||||
studio.validations.delete(id);
|
||||
studio.previews.delete(id);
|
||||
}),
|
||||
deleteDecision: (projectId, decisionId, expectedVersion, options) =>
|
||||
command(options, () => {
|
||||
const list = decisions.get(projectId) ?? [];
|
||||
const current = list.find((decision) => decision.id === decisionId);
|
||||
if (!current) throw problem("deleteDecision", "DECISION_NOT_FOUND", `${decisionId} does not exist.`);
|
||||
versionOf(current.version, expectedVersion, "deleteDecision");
|
||||
decisions.set(projectId, list.filter((decision) => decision.id !== decisionId));
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -39,6 +39,13 @@ export type MockStudioDependencies = {
|
||||
* seeing exactly today's behavior.
|
||||
*/
|
||||
assets: ReadonlyMap<string, Asset>;
|
||||
/**
|
||||
* The documents, validations, previews and publications this gateway
|
||||
* serves. `create-tech-log-feature-input.ts` shares one with the mock
|
||||
* management gateway, whose `deleteDocument` removes drafts from it.
|
||||
* Defaults to a fresh seed per gateway, as before.
|
||||
*/
|
||||
state?: MockStudioState;
|
||||
};
|
||||
|
||||
export const DEFAULT_STUDIO_MOCK_NOW = "2026-08-14T01:00:00.000Z";
|
||||
@@ -136,7 +143,7 @@ export function createMockStudioGateway(supplied: Partial<MockStudioDependencies
|
||||
const assets = supplied.assets ?? new Map<string, Asset>();
|
||||
const fallback = defaults(assets);
|
||||
const dependencies: MockStudioDependencies = { clock: supplied.clock ?? fallback.clock, idGenerator: supplied.idGenerator ?? fallback.idGenerator, dependencyRevision: supplied.dependencyRevision ?? fallback.dependencyRevision, assets };
|
||||
const state: MockStudioState = createMockStudioState();
|
||||
const state: MockStudioState = supplied.state ?? createMockStudioState();
|
||||
|
||||
async function boundary(options?: RequestOptions) {
|
||||
options?.signal?.throwIfAborted(); await Promise.resolve(); options?.signal?.throwIfAborted();
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "vitest";
|
||||
|
||||
import { createTechLogFeatureInstalledInput } from "../../../src/features/tech-log/adapters/create-tech-log-feature-input.ts";
|
||||
import { FIXTURE_IDS } from "../../../src/features/tech-log/adapters/mock/fixtures.ts";
|
||||
import { createMockManagementGateway } from "../../../src/features/tech-log/adapters/mock/mock-management-gateway.ts";
|
||||
import { createMockStudioState } from "../../../src/features/tech-log/adapters/mock/mock-state.ts";
|
||||
import { ManagementGatewayError } from "../../../src/features/tech-log/application/ports/management-gateway-error.ts";
|
||||
import { MOCK_STUDIO_INSTALL_CONTEXT } from "../../helpers/studio-install-context.ts";
|
||||
|
||||
function key(name: string) {
|
||||
return { idempotencyKey: `mock-management-${name}` };
|
||||
}
|
||||
|
||||
async function rejectsWith(promise: Promise<unknown>, code: string) {
|
||||
await assert.rejects(promise, (error: unknown) => {
|
||||
assert.ok(error instanceof ManagementGatewayError);
|
||||
assert.equal(error.code, code);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
test("MOCK Studio reads its management surface without the HTTP executor", async () => {
|
||||
const calls: string[] = [];
|
||||
const { input } = createTechLogFeatureInstalledInput({
|
||||
...MOCK_STUDIO_INSTALL_CONTEXT,
|
||||
http: Object.freeze({
|
||||
async execute(...args: unknown[]) {
|
||||
calls.push(JSON.stringify(args[0]));
|
||||
throw new Error("a MOCK Studio call reached the HTTP executor");
|
||||
},
|
||||
}),
|
||||
});
|
||||
const studio = input.createStudioApplication();
|
||||
|
||||
const [topics, projects, questions, focus, releases] = await Promise.all([
|
||||
studio.managementQueries.listTopics(),
|
||||
studio.managementQueries.listProjects(),
|
||||
studio.managementQueries.listQuestions(),
|
||||
studio.managementQueries.getHomeFocus(),
|
||||
studio.managementQueries.listReleases(),
|
||||
]);
|
||||
|
||||
assert.deepEqual(calls, []);
|
||||
assert.deepEqual(
|
||||
topics.map((topic) => topic.slug),
|
||||
["jpa", "redis", "authentication"],
|
||||
);
|
||||
assert.deepEqual(
|
||||
projects.items.map((project) => project.slug),
|
||||
["backend-skeleton", "auth-lab"],
|
||||
);
|
||||
assert.deepEqual(
|
||||
questions.items.map((question) => question.id),
|
||||
[FIXTURE_IDS.edgeTokenQuestion],
|
||||
);
|
||||
assert.equal(questions.items[0]?.primaryProject?.slug, "auth-lab");
|
||||
assert.equal(focus.currentProjectId, FIXTURE_IDS.projectBackend);
|
||||
assert.deepEqual(
|
||||
releases.items.map((release) => release.versionLabel),
|
||||
["0.1.0"],
|
||||
);
|
||||
});
|
||||
|
||||
test("the mock refuses a stale version with the backend's codes", async () => {
|
||||
const gateway = createMockManagementGateway();
|
||||
const project = await gateway.getProject(FIXTURE_IDS.projectBackend);
|
||||
|
||||
await rejectsWith(
|
||||
gateway.updateProject(
|
||||
project.id,
|
||||
{
|
||||
expectedVersion: project.version + 1,
|
||||
name: project.name,
|
||||
oneLinePurpose: "",
|
||||
purposeMarkdown: "",
|
||||
boundaryMarkdown: "",
|
||||
phase: project.phase,
|
||||
technologyLabels: [],
|
||||
targetVisibility: "PUBLIC",
|
||||
},
|
||||
key("stale"),
|
||||
),
|
||||
"VERSION_CONFLICT",
|
||||
);
|
||||
await rejectsWith(gateway.getProject("99999999-9999-4999-8999-999999999999"), "PROJECT_NOT_FOUND");
|
||||
await rejectsWith(gateway.getRelease("99999999-9999-4999-8999-999999999999"), "RELEASE_NOT_FOUND");
|
||||
});
|
||||
|
||||
test("a replayed idempotency key returns the first draft instead of a second one", async () => {
|
||||
const gateway = createMockManagementGateway();
|
||||
const first = await gateway.createProject("새 프로젝트", key("create"));
|
||||
const again = await gateway.createProject("새 프로젝트", key("create"));
|
||||
|
||||
assert.deepEqual(again, first);
|
||||
const projects = await gateway.listProjects();
|
||||
assert.equal(projects.page.totalElements, 3);
|
||||
});
|
||||
|
||||
test("deleting a draft removes it from the shared document state", async () => {
|
||||
const state = createMockStudioState();
|
||||
const gateway = createMockManagementGateway({ studioState: state });
|
||||
const draft = state.documents.get(FIXTURE_IDS.conflictCase)!;
|
||||
|
||||
await rejectsWith(
|
||||
gateway.deleteDocument("CASE", FIXTURE_IDS.fetchJoinCase, state.documents.get(FIXTURE_IDS.fetchJoinCase)!.version, key("published")),
|
||||
"CONFLICT",
|
||||
);
|
||||
await rejectsWith(
|
||||
gateway.deleteDocument("REFERENCE", draft.id, draft.version, key("wrong-kind")),
|
||||
"DOCUMENT_NOT_FOUND",
|
||||
);
|
||||
await gateway.deleteDocument("CASE", draft.id, draft.version, key("delete"));
|
||||
|
||||
assert.equal(state.documents.has(draft.id), false);
|
||||
});
|
||||
|
||||
test("an aborted read rejects before it touches the store", async () => {
|
||||
const gateway = createMockManagementGateway();
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
|
||||
await assert.rejects(gateway.listTopics({ signal: controller.signal }), { name: "AbortError" });
|
||||
});
|
||||
Reference in New Issue
Block a user