diff --git a/src/features/tech-log/adapters/create-tech-log-feature-input.ts b/src/features/tech-log/adapters/create-tech-log-feature-input.ts index f98ba9d..dd19d1a 100644 --- a/src/features/tech-log/adapters/create-tech-log-feature-input.ts +++ b/src/features/tech-log/adapters/create-tech-log-feature-input.ts @@ -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, diff --git a/src/features/tech-log/adapters/mock/mock-management-gateway.ts b/src/features/tech-log/adapters/mock/mock-management-gateway.ts new file mode 100644 index 0000000..5bc980b --- /dev/null +++ b/src/features/tech-log/adapters/mock/mock-management-gateway.ts @@ -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> = { + "backend-skeleton": FIXTURE_IDS.projectBackend, + "auth-lab": FIXTURE_IDS.projectAuth, +}; +const DOCUMENT_KIND: Readonly> = { + CASE: "deleteCaseDraft", + REFERENCE: "deleteReferenceDraft", + QUESTION: "deleteQuestion", + CONCEPT: "deleteConceptDraft", + SETUP: "deleteSetupDraft", +}; + +const clone = (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(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 = {}, +): 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(); + const projects = new Map(seedProjects([...topics.values()], now()).map((project) => [project.id, project])); + const activities = new Map(); + const decisions = new Map(); + 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(); + + async function boundary(options?: RequestOptions) { + options?.signal?.throwIfAborted(); + await Promise.resolve(); + options?.signal?.throwIfAborted(); + } + + async function read(options: RequestOptions | undefined, run: () => T): Promise { + await boundary(options); + return clone(run()); + } + + async function command(options: IdempotentOptions, run: () => T): Promise { + 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(map: ReadonlyMap, 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)); + }), + }); +} diff --git a/src/features/tech-log/adapters/mock/mock-studio-gateway.ts b/src/features/tech-log/adapters/mock/mock-studio-gateway.ts index 0005072..3de3a33 100644 --- a/src/features/tech-log/adapters/mock/mock-studio-gateway.ts +++ b/src/features/tech-log/adapters/mock/mock-studio-gateway.ts @@ -39,6 +39,13 @@ export type MockStudioDependencies = { * seeing exactly today's behavior. */ assets: ReadonlyMap; + /** + * 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(); 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(); diff --git a/tests/features/tech-log/mock-management-gateway.test.ts b/tests/features/tech-log/mock-management-gateway.test.ts new file mode 100644 index 0000000..4c93d69 --- /dev/null +++ b/tests/features/tech-log/mock-management-gateway.test.ts @@ -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, 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" }); +});