From a458b070fae2214c16e382ffc44247f7b324370e Mon Sep 17 00:00:00 2001 From: olliethedev <5933733+olliethedev@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:32:12 -0500 Subject: [PATCH 1/3] feat(cms): add revision history, rollback and publishAt metadata (#339) --- docs/content/docs/plugins/cms.mdx | 71 +++ e2e/tests/smoke.cms.spec.ts | 128 +++++ packages/plugin-cms/package.json | 1 + .../src/__tests__/authorization.test.ts | 4 + .../src/__tests__/revisions.test.ts | 440 +++++++++++++++ .../src/__tests__/schema-migration.test.ts | 87 +++ packages/plugin-cms/src/api/getters.ts | 1 + packages/plugin-cms/src/api/index.ts | 2 + packages/plugin-cms/src/api/mutations.ts | 81 ++- packages/plugin-cms/src/api/operations.ts | 516 ++++++++++++------ packages/plugin-cms/src/api/plugin.ts | 27 + .../client/components/forms/content-form.tsx | 41 +- .../pages/content-editor-page.internal.tsx | 22 +- .../client/components/revision-history.tsx | 213 ++++++++ .../plugin-cms/src/client/hooks/cms-hooks.tsx | 46 +- packages/plugin-cms/src/db.ts | 25 + packages/plugin-cms/src/query-keys.ts | 55 +- packages/plugin-cms/src/types.ts | 33 +- packages/stack/registry/btst-cms.json | 13 +- packages/stack/registry/registry.json | 1 + pnpm-lock.yaml | 3 + 21 files changed, 1592 insertions(+), 218 deletions(-) create mode 100644 packages/plugin-cms/src/__tests__/revisions.test.ts create mode 100644 packages/plugin-cms/src/__tests__/schema-migration.test.ts create mode 100644 packages/plugin-cms/src/client/components/revision-history.tsx diff --git a/docs/content/docs/plugins/cms.mdx b/docs/content/docs/plugins/cms.mdx index 0c7ed271a..de4dfbe4b 100644 --- a/docs/content/docs/plugins/cms.mdx +++ b/docs/content/docs/plugins/cms.mdx @@ -1495,6 +1495,77 @@ export default function DirectoryPage() { } ``` +## Revision history and scheduling + +The entry editor's **Revision history** drawer lists saved versions, newest first, +with a timestamp, writer identity (or System for trusted jobs), slug, schedule, +and field snapshot. Expand a version and choose **Restore this version** to +replace the active entry. The confirmation warns that unsaved editor changes +will be discarded. Restoring keeps all existing revisions and appends a new one. + +Successful content creation, updates (including schedule-only updates), rollback, +inline related-item creation, and `createCMSContentItem()` append an immutable +`contentRevision` row in the same transaction as the content write. Rejected +validation, authorization, duplicate slugs, and before-hook failures do not append +revisions. There is no operation to edit or individually delete a revision; +revision rows cascade when their content item is deleted. + +`publishAt` is optional **top-level scheduling metadata**, separate from the +content type's `data`. The editor accepts local date/time and sends an ISO +timestamp with its time-zone offset converted to UTC. HTTP and operation inputs +accept ISO timestamps with a time-zone offset; omit the property to preserve the +schedule on update, or pass `null` to clear it. Serialized items and revisions +return ISO strings or `null`. + +This field does not run a publisher job, set a `data.status` field, or filter +content reads. Applications remain responsible for deciding when content becomes +visible. Existing `(contentTypeId, slug)` lookup behavior and payloads for +UI Builder, Ecommerce, School, and Job Board are unchanged. + +```ts +const cms = myStack.forRequest(request).operations.cms; +const item = await cms.createContentItem({ + typeSlug: "article", + body: { + slug: "launch", + data: { title: "Launch announcement" }, + publishAt: "2030-12-05T14:30:00Z", + }, +}); +const history = await cms.listContentRevisions({ + typeSlug: "article", id: item.id, offset: 0, +}); +await cms.restoreContentRevision({ + typeSlug: "article", id: item.id, revisionId: history.items[0].id, +}); +``` + +`GET /content/:typeSlug/:id/revisions?offset=0` returns `{ items, total }` in +pages of 20. `POST /content/:typeSlug/:id/revisions/:revisionId/restore` returns +the active item. These paths are relative to the stack API base path. +Listing requires `cms.record.read` for the authoritative record plus +`cms.contentType.read`. Restoring requires the existing record update and read +permissions, content-type read, and permission to read any restored relation +targets. Rollback runs the normal update lifecycle hooks and validates against +the current content-type schema. Incompatible old schemas, missing relation +targets, and slug conflicts fail without changing the active item. + +Client hooks `useContentRevisions(typeSlug, id, enabled?)` and +`useRestoreContentRevision()` are exported from `@btst/plugin-cms/client/hooks`. +Restore refreshes content, revision history, and relation queries. The existing +create/update hooks accept optional `publishAt` alongside `slug` and `data`. + +### Database upgrade + +Regenerate and apply the database migration from your stack's `dbSchema` before +serving the updated plugin. The additive schema introduces `contentRevision` +(with a unique item/version `revisionKey` and cascading `contentItemId` reference) +and a nullable `contentItem.publishAt` date column. It does not rewrite content +payloads, IDs, slugs, or author ownership. Existing items start with empty history; +their first successful post-upgrade write creates version 1. Earlier versions +cannot be reconstructed. The lower-level `createCMSContentItem()` helper now +also needs the migrated schema and supports `publishAt` as a `Date` or `null`. + ## API Reference ### Backend (`@btst/plugin-cms/api`) diff --git a/e2e/tests/smoke.cms.spec.ts b/e2e/tests/smoke.cms.spec.ts index 9a68ed0a4..cfa648798 100644 --- a/e2e/tests/smoke.cms.spec.ts +++ b/e2e/tests/smoke.cms.spec.ts @@ -747,3 +747,131 @@ test.describe("CMS Image Upload", () => { ); }); }); + +test("CMS revisions restore saved fields and publishAt in the editor", async ({ + page, + request, +}) => { + const slug = `revision-${Date.now()}`; + const schedule = "2030-12-05T14:30:00.000Z"; + const created = await request.post("/api/data/content/category", { + data: { + slug, + data: { name: "Original category", description: "Original fields" }, + publishAt: schedule, + }, + }); + expect(created.ok()).toBeTruthy(); + const item = await created.json(); + const editor = `/pages/cms/category/${item.id}`; + await page.goto(editor, { waitUntil: "networkidle" }); + await expect(page.locator('input[name="name"]')).toHaveValue( + "Original category", + ); + await page.locator('input[name="name"]').fill("Updated category"); + await page.getByLabel("Publish at", { exact: true }).fill("2031-12-05T15:45"); + await page.getByRole("button", { name: "Save", exact: true }).click(); + await page.waitForURL(/\/pages\/cms\/category$/); + await page.goto(editor, { waitUntil: "networkidle" }); + await expect(page.locator('input[name="name"]')).toHaveValue( + "Updated category", + ); + await page + .getByRole("button", { name: "Revision history", exact: true }) + .click(); + const drawer = page.getByRole("dialog", { + name: "Revision history", + exact: true, + }); + const first = drawer + .locator("details") + .filter({ has: page.getByText("Version 1", { exact: true }) }); + await first.locator("summary").click(); + await expect(first.getByLabel("Field snapshot")).toContainText( + "Original category", + ); + await first.getByRole("button", { name: "Restore this version" }).click(); + await page.getByRole("button", { name: "Cancel", exact: true }).click(); + await expect(drawer).toBeVisible(); + await first.getByRole("button", { name: "Restore this version" }).click(); + await page + .getByRole("button", { name: "Restore version", exact: true }) + .click(); + await expect(drawer).not.toBeVisible(); + await expect(page.locator('input[name="name"]')).toHaveValue( + "Original category", + ); + const localSchedule = await page.evaluate((value) => { + const date = new Date(value); + return new Date(date.getTime() - date.getTimezoneOffset() * 60_000) + .toISOString() + .slice(0, 16); + }, schedule); + await expect(page.getByLabel("Publish at", { exact: true })).toHaveValue( + localSchedule, + ); + const history = await ( + await request.get(`/api/data/content/category/${item.id}/revisions`) + ).json(); + expect( + history.items.map((revision: { version: number }) => revision.version), + ).toEqual([3, 2, 1]); + expect(history.items[0].publishAt).toBe(schedule); + await page.getByLabel("Publish at", { exact: true }).fill(""); + await page.getByRole("button", { name: "Save", exact: true }).click(); + await page.waitForURL(/\/pages\/cms\/category$/); + expect( + (await (await request.get(`/api/data/content/category/${item.id}`)).json()) + .publishAt, + ).toBeNull(); + await request.delete(`/api/data/content/category/${item.id}`); +}); + +test("CMS revision drawer recovers from a failed history request and supports mobile keyboard dismissal", async ({ + page, + request, +}) => { + const response = await request.post("/api/data/content/category", { + data: { + slug: `history-retry-${Date.now()}`, + data: { name: "History retry" }, + }, + }); + expect(response.ok()).toBeTruthy(); + const item = await response.json(); + await page.setViewportSize({ width: 390, height: 844 }); + await page.goto(`/pages/cms/category/${item.id}`, { + waitUntil: "networkidle", + }); + await expect(page.locator('input[name="name"]')).toHaveValue("History retry"); + const historyPath = `**/content/category/${item.id}/revisions*`; + await page.route(historyPath, (route) => + route.fulfill({ + status: 500, + contentType: "application/json", + body: JSON.stringify({ message: "History unavailable" }), + }), + ); + await page + .getByRole("button", { name: "Revision history", exact: true }) + .click(); + const drawer = page.getByRole("dialog", { + name: "Revision history", + exact: true, + }); + await expect(drawer.getByRole("alert")).toBeVisible(); + await page.unroute(historyPath); + await drawer.getByRole("button", { name: "Retry", exact: true }).click(); + await expect(drawer.getByText("Version 1", { exact: true })).toBeVisible(); + expect( + await page.evaluate( + () => document.documentElement.scrollWidth <= window.innerWidth, + ), + ).toBeTruthy(); + await page.keyboard.press("Escape"); + await expect(drawer).not.toBeVisible(); + await expect( + page.getByRole("button", { name: "Revision history", exact: true }), + ).toBeFocused(); + await request.delete(`/api/data/content/category/${item.id}`); +}); diff --git a/packages/plugin-cms/package.json b/packages/plugin-cms/package.json index 1a78dd836..f3e0e8d7a 100644 --- a/packages/plugin-cms/package.json +++ b/packages/plugin-cms/package.json @@ -154,6 +154,7 @@ "react-dom": ">=19.2.6" }, "devDependencies": { + "better-auth": "1.7.14", "@btst/stack": "workspace:*", "@btst/yar": "1.3.2", "@tanstack/react-query": "5.105.0", diff --git a/packages/plugin-cms/src/__tests__/authorization.test.ts b/packages/plugin-cms/src/__tests__/authorization.test.ts index 3e7c56ef6..5dab670e5 100644 --- a/packages/plugin-cms/src/__tests__/authorization.test.ts +++ b/packages/plugin-cms/src/__tests__/authorization.test.ts @@ -558,8 +558,10 @@ describe("CMS authorization inventory", () => { "getInverseRelations", "listContentByRelation", "listContentItems", + "listContentRevisions", "listContentTypes", "listInverseRelationItems", + "restoreContentRevision", "updateContentItem", ]); expect( @@ -576,6 +578,8 @@ describe("CMS authorization inventory", () => { getContentItem: "cms:record.read", createContentItem: "cms:record.create", updateContentItem: "cms:record.update", + listContentRevisions: "cms:record.read", + restoreContentRevision: "cms:record.update", deleteContentItem: "cms:record.delete", getContentItemPopulated: "cms:record.read", listContentByRelation: "cms:record.read", diff --git a/packages/plugin-cms/src/__tests__/revisions.test.ts b/packages/plugin-cms/src/__tests__/revisions.test.ts new file mode 100644 index 000000000..522f296db --- /dev/null +++ b/packages/plugin-cms/src/__tests__/revisions.test.ts @@ -0,0 +1,440 @@ +import { createMemoryAdapter } from "@btst/adapter-memory"; +import { createBackendStack } from "@btst/stack/api"; +import { defineAuthorization } from "@btst/stack/authorization"; +import { createServerAuth } from "@btst/stack/authorization/server"; +import { describe, expect, it, vi } from "vitest"; +import { z } from "zod"; +import { + cmsBackendPlugin, + createCMSContentItem, + getContentItemBySlug, +} from "../api"; +import { cmsPermissions } from "../permissions"; +import type { CMSBackendHooks, ContentItem, ContentRevision } from "../types"; + +function setup(hooks?: CMSBackendHooks) { + let deniedReadId: string | undefined; + const authorization = defineAuthorization({ + identity: z.object({ id: z.string() }), + permissions: [cmsPermissions] as const, + rules: ({ cms }) => [ + cms.contentType.read.allow(), + cms.record.create.when(({ identity }) => identity !== null), + cms.record.read.when( + ({ identity, facts }) => + identity !== null && facts.recordId !== deniedReadId, + ), + cms.record.update.when( + ({ identity, facts }) => identity?.id === facts.authorId, + ), + cms.record.delete.when( + ({ identity, facts }) => identity?.id === facts.authorId, + ), + ], + }); + const backend = createBackendStack({ + basePath: "/api", + adapter: (db) => createMemoryAdapter(db)({}), + auth: createServerAuth({ + authorization, + getIdentity: ({ request }) => { + const id = request.headers.get("x-user"); + return id ? { id } : null; + }, + }), + plugins: { + cms: cmsBackendPlugin({ + contentTypes: [ + { + name: "Article", + slug: "article", + schema: z.object({ + title: z.string(), + subtitle: z.string().optional(), + }), + }, + { + name: "Page", + slug: "page", + schema: z.object({ + title: z.string(), + related: z + .object({ id: z.string() }) + .optional() + .meta({ + fieldType: "relation", + relation: { + type: "belongsTo", + targetType: "article", + displayField: "title", + creatable: true, + }, + }), + }), + }, + ], + hooks, + }), + }, + }); + const ops = (user = "editor") => + backend.forRequest( + new Request("http://localhost/api", { headers: { "x-user": user } }), + ).operations.cms; + const create = (slug = "hello", publishAt?: string | null) => + ops().createContentItem({ + typeSlug: "article", + body: { slug, data: { title: "First" }, publishAt }, + }); + return { + backend, + ops, + create, + denyRead: (id: string) => { + deniedReadId = id; + }, + }; +} + +const schedule = "2030-12-05T14:30:00.000Z"; + +describe("CMS revision lifecycle", () => { + it("appends immutable snapshots for create, update and rollback, including schedule and writer", async () => { + const afterUpdate = vi.fn(); + const { backend, ops, create } = setup({ + onAfterUpdateContent: afterUpdate, + }); + const item = await create("hello", schedule); + await ops().updateContentItem({ + typeSlug: "article", + id: item.id, + body: { + data: { title: "Second", subtitle: "Added later" }, + publishAt: null, + }, + }); + const history = await ops().listContentRevisions({ + typeSlug: "article", + id: item.id, + }); + expect(history.items.map((r) => r.version)).toEqual([2, 1]); + expect(history.items[1]).toMatchObject({ + authorId: "editor", + publishAt: schedule, + data: JSON.stringify({ title: "First" }), + }); + const restored = await ops().restoreContentRevision({ + typeSlug: "article", + id: item.id, + revisionId: history.items[1]!.id, + }); + expect(restored).toMatchObject({ + id: item.id, + slug: "hello", + publishAt: schedule, + parsedData: { title: "First" }, + }); + expect(restored.parsedData).not.toHaveProperty("subtitle"); + const after = await ops().listContentRevisions({ + typeSlug: "article", + id: item.id, + }); + expect(after.items.map((r) => r.version)).toEqual([3, 2, 1]); + expect(after.items.slice(1)).toEqual(history.items); + expect(afterUpdate).toHaveBeenCalledTimes(2); + expect( + await getContentItemBySlug(backend.adapter, "article", "hello"), + ).toMatchObject({ id: item.id, parsedData: { title: "First" } }); + }); + + it("denies anonymous history/restore and another writer's restore over operations and HTTP", async () => { + const { backend, ops, create } = setup(); + const item = await create(); + const revision = ( + await ops().listContentRevisions({ typeSlug: "article", id: item.id }) + ).items[0]!; + await expect( + ops("").listContentRevisions({ typeSlug: "article", id: item.id }), + ).rejects.toThrow(); + await expect( + ops("other").restoreContentRevision({ + typeSlug: "article", + id: item.id, + revisionId: revision.id, + }), + ).rejects.toThrow(); + const path = `/api/content/article/${item.id}/revisions`; + expect( + (await backend.handler(new Request(`http://localhost${path}`))).status, + ).toBe(401); + expect( + ( + await backend.handler( + new Request(`http://localhost${path}/${revision.id}/restore`, { + method: "POST", + headers: { "x-user": "other" }, + }), + ) + ).status, + ).toBe(403); + expect( + ( + await backend.adapter.findMany({ + model: "contentRevision", + }) + ).length, + ).toBe(1); + }); + + it("scopes revisions to their item and content type", async () => { + const { ops, create } = setup(); + const item = await create(); + const other = await create("other"); + const revision = ( + await ops().listContentRevisions({ typeSlug: "article", id: item.id }) + ).items[0]!; + await expect( + ops().restoreContentRevision({ + typeSlug: "article", + id: other.id, + revisionId: revision.id, + }), + ).rejects.toMatchObject({ statusCode: 404 }); + await expect( + ops().listContentRevisions({ typeSlug: "page", id: item.id }), + ).rejects.toMatchObject({ statusCode: 404 }); + }); + + it("preserves slug uniqueness and does not append a rejected rollback", async () => { + const { ops, create } = setup(); + const item = await create(); + const revision = ( + await ops().listContentRevisions({ typeSlug: "article", id: item.id }) + ).items[0]!; + await ops().updateContentItem({ + typeSlug: "article", + id: item.id, + body: { slug: "renamed" }, + }); + await create("hello"); + await expect( + ops().restoreContentRevision({ + typeSlug: "article", + id: item.id, + revisionId: revision.id, + }), + ).rejects.toMatchObject({ code: "DUPLICATE_SLUG" }); + expect( + (await ops().listContentRevisions({ typeSlug: "article", id: item.id })) + .total, + ).toBe(2); + }); + + it("validates ISO timestamps, preserves an omitted schedule and clears explicit null", async () => { + const { backend, ops, create } = setup(); + await expect(create("invalid", "tomorrow")).rejects.toThrow(); + await expect(create("invalid", "2030-12-05")).rejects.toThrow(); + const item = await create("scheduled", schedule); + expect( + ( + await ops().updateContentItem({ + typeSlug: "article", + id: item.id, + body: { data: { title: "Changed" } }, + }) + ).publishAt, + ).toBe(schedule); + expect( + ( + await ops().updateContentItem({ + typeSlug: "article", + id: item.id, + body: { publishAt: null }, + }) + ).publishAt, + ).toBeNull(); + const response = await backend.handler( + new Request(`http://localhost/api/content/article/${item.id}`, { + method: "PUT", + headers: { "x-user": "editor", "content-type": "application/json" }, + body: JSON.stringify({ publishAt: "invalid" }), + }), + ); + expect(response.status).toBe(400); + }); + + it("starts history on a pre-migration row without changing its data or slug lookup", async () => { + const { backend } = setup(); + const type = (await backend.trusted.cms.listContentTypes({})).find( + (t) => t.slug === "article", + )!; + const legacy = await backend.adapter.create({ + model: "contentItem", + data: { + contentTypeId: type.id, + slug: "legacy", + data: '{"title":"Legacy"}', + createdAt: new Date(), + updatedAt: new Date(), + }, + }); + expect( + ( + await backend.trusted.cms.listContentRevisions({ + typeSlug: "article", + id: legacy.id, + }) + ).total, + ).toBe(0); + await backend.trusted.cms.updateContentItem({ + typeSlug: "article", + id: legacy.id, + body: { publishAt: schedule }, + }); + expect( + await getContentItemBySlug(backend.adapter, "article", "legacy"), + ).toMatchObject({ data: legacy.data, publishAt: schedule }); + expect( + ( + await backend.trusted.cms.listContentRevisions({ + typeSlug: "article", + id: legacy.id, + }) + ).items[0], + ).toMatchObject({ version: 1, data: legacy.data }); + }); + + it("records revisions for the lower-level helper used by dependent plugins", async () => { + const { backend } = setup(); + await backend.trusted.cms.listContentTypes({}); + const item = await createCMSContentItem(backend.adapter, "article", { + slug: "dependent", + data: { title: "Page payload" }, + publishAt: new Date(schedule), + }); + expect( + ( + await backend.trusted.cms.listContentRevisions({ + typeSlug: "article", + id: item.id, + }) + ).items[0], + ).toMatchObject({ version: 1, publishAt: schedule, data: item.data }); + }); + + it("runs update hooks on rollback and leaves history unchanged when the hook denies it", async () => { + const before = vi.fn(); + const { ops, create } = setup({ onBeforeUpdateContent: before }); + const item = await create(); + const revision = ( + await ops().listContentRevisions({ typeSlug: "article", id: item.id }) + ).items[0]!; + before.mockImplementation(() => { + throw new Error("Approval required"); + }); + await expect( + ops().restoreContentRevision({ + typeSlug: "article", + id: item.id, + revisionId: revision.id, + }), + ).rejects.toThrow("Approval required"); + expect( + (await ops().listContentRevisions({ typeSlug: "article", id: item.id })) + .total, + ).toBe(1); + }); +}); + +it("paginates revision history without dropping versions", async () => { + const { ops, create } = setup(); + const item = await create(); + for (let index = 0; index < 21; index++) { + await ops().updateContentItem({ + typeSlug: "article", + id: item.id, + body: { data: { title: `Version ${index + 2}` } }, + }); + } + const first = await ops().listContentRevisions({ + typeSlug: "article", + id: item.id, + }); + const second = await ops().listContentRevisions({ + typeSlug: "article", + id: item.id, + offset: 20, + }); + expect(first.items).toHaveLength(20); + expect(first.total).toBe(22); + expect(second.items.map((revision) => revision.version)).toEqual([2, 1]); +}); + +it("restores relation junctions, checks target permissions, and clears relations absent from a snapshot", async () => { + const { backend, ops, create, denyRead } = setup(); + const target = await create(); + const page = await ops().createContentItem({ + typeSlug: "page", + body: { slug: "linked", data: { title: "Page" } }, + }); + const empty = ( + await ops().listContentRevisions({ typeSlug: "page", id: page.id }) + ).items[0]!; + await ops().updateContentItem({ + typeSlug: "page", + id: page.id, + body: { data: { related: { id: target.id } } }, + }); + const linked = ( + await ops().listContentRevisions({ typeSlug: "page", id: page.id }) + ).items[0]!; + await ops().restoreContentRevision({ + typeSlug: "page", + id: page.id, + revisionId: empty.id, + }); + expect( + await backend.adapter.findMany({ + model: "contentRelation", + where: [{ field: "sourceId", value: page.id }], + }), + ).toEqual([]); + await ops().restoreContentRevision({ + typeSlug: "page", + id: page.id, + revisionId: linked.id, + }); + expect( + await backend.adapter.findMany({ + model: "contentRelation", + where: [{ field: "sourceId", value: page.id }], + }), + ).toMatchObject([{ targetId: target.id }]); + denyRead(target.id); + await expect( + ops().restoreContentRevision({ + typeSlug: "page", + id: page.id, + revisionId: linked.id, + }), + ).rejects.toMatchObject({ statusCode: 403 }); +}); + +it("records a revision for inline related-item creation", async () => { + const { ops } = setup(); + const page = await ops().createContentItem({ + typeSlug: "page", + body: { + slug: "inline", + data: { + title: "Page", + related: { _new: true, data: { title: "Inline article" } }, + }, + }, + }); + const targetId = (page.parsedData.related as { id: string }).id; + expect( + (await ops().listContentRevisions({ typeSlug: "article", id: targetId })) + .items[0], + ).toMatchObject({ version: 1, authorId: "editor" }); +}); diff --git a/packages/plugin-cms/src/__tests__/schema-migration.test.ts b/packages/plugin-cms/src/__tests__/schema-migration.test.ts new file mode 100644 index 000000000..87a842446 --- /dev/null +++ b/packages/plugin-cms/src/__tests__/schema-migration.test.ts @@ -0,0 +1,87 @@ +import { DatabaseSync } from "node:sqlite"; +import { getMigrations } from "better-auth/db/migration"; +import { expect, it } from "vitest"; +import { cmsSchema } from "../db"; + +it("migrates populated CMS tables additively and leaves the next migration empty", async () => { + const database = new DatabaseSync(":memory:"); + try { + const { contentRevision: _revisions, ...legacySchema } = cmsSchema.schema; + const { publishAt: _schedule, ...legacyFields } = + legacySchema.contentItem!.fields; + const before = await getMigrations({ + database, + plugins: [ + { + id: "cms", + schema: { + ...legacySchema, + contentItem: { ...legacySchema.contentItem!, fields: legacyFields }, + }, + }, + ], + }); + await before.runMigrations(); + database + .prepare( + "INSERT INTO contentType (id, name, slug, jsonSchema, createdAt, updatedAt) VALUES (?, ?, ?, ?, 0, 0)", + ) + .run("type", "Article", "article", "{}"); + database + .prepare( + "INSERT INTO contentItem (id, contentTypeId, slug, data, authorId, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, 0, 0)", + ) + .run( + "legacy", + "type", + "legacy-slug", + '{"title":"Legacy payload"}', + "author", + ); + const options = { + database, + plugins: [{ id: "cms", schema: cmsSchema.schema }], + }; + const upgrade = await getMigrations(options); + expect(upgrade.unsafeChanges).toEqual([]); + expect(upgrade.toBeCreated.map((table) => table.table)).toEqual([ + "contentRevision", + ]); + expect( + upgrade.toBeAdded.map((table) => [ + table.table, + Object.keys(table.fields), + ]), + ).toEqual([["contentItem", ["publishAt"]]]); + await upgrade.runMigrations(); + expect( + database + .prepare( + "SELECT id, contentTypeId, slug, data, authorId, publishAt FROM contentItem", + ) + .get(), + ).toEqual({ + id: "legacy", + contentTypeId: "type", + slug: "legacy-slug", + data: '{"title":"Legacy payload"}', + authorId: "author", + publishAt: null, + }); + const insertRevision = database.prepare( + "INSERT INTO contentRevision (id, contentItemId, revisionKey, version, slug, data, createdAt) VALUES (?, ?, ?, ?, ?, ?, 0)", + ); + insertRevision.run("r1", "legacy", "legacy:1", 1, "legacy-slug", "{}"); + expect(() => + insertRevision.run("r2", "legacy", "legacy:1", 1, "legacy-slug", "{}"), + ).toThrow(/unique/i); + database.exec("PRAGMA foreign_keys = ON"); + database.prepare("DELETE FROM contentItem WHERE id = ?").run("legacy"); + expect(database.prepare("SELECT * FROM contentRevision").all()).toEqual([]); + const repeat = await getMigrations(options); + expect(repeat.toBeAdded).toEqual([]); + expect(repeat.toBeCreated).toEqual([]); + } finally { + database.close(); + } +}); diff --git a/packages/plugin-cms/src/api/getters.ts b/packages/plugin-cms/src/api/getters.ts index 68d7a3acb..ec7145598 100644 --- a/packages/plugin-cms/src/api/getters.ts +++ b/packages/plugin-cms/src/api/getters.ts @@ -144,6 +144,7 @@ export function migrateToUnifiedSchema( export function serializeContentItem(item: ContentItem): SerializedContentItem { return { ...item, + publishAt: item.publishAt?.toISOString() ?? null, createdAt: item.createdAt.toISOString(), updatedAt: item.updatedAt.toISOString(), }; diff --git a/packages/plugin-cms/src/api/index.ts b/packages/plugin-cms/src/api/index.ts index 1fa0aea67..3f6475656 100644 --- a/packages/plugin-cms/src/api/index.ts +++ b/packages/plugin-cms/src/api/index.ts @@ -41,6 +41,8 @@ export type { CMSUpdateOperationContext, CMSUpdateResultContext, ContentTypeConfig, + ContentRevision, + SerializedContentRevision, CMSReadOptions, CMSContentFields, CMSSelectedData, diff --git a/packages/plugin-cms/src/api/mutations.ts b/packages/plugin-cms/src/api/mutations.ts index 6b1265947..14f0458b3 100644 --- a/packages/plugin-cms/src/api/mutations.ts +++ b/packages/plugin-cms/src/api/mutations.ts @@ -1,5 +1,5 @@ import type { DBAdapter as Adapter } from "@btst/db"; -import type { ContentType, ContentItem } from "../types"; +import type { ContentType, ContentItem, ContentRevision } from "../types"; import { serializeContentItem } from "./getters"; import type { SerializedContentItem } from "../types"; import { @@ -16,6 +16,39 @@ export interface CreateCMSContentItemInput { slug: string; /** Arbitrary data payload — should match the content type schema */ data: Record; + /** Optional scheduled publication timestamp. */ + publishAt?: Date | null; +} + +/** + * Append a snapshot; caller owns authorization, validation, lifecycle hooks, and + * the transaction containing the item write. Revision rows are never updated. + */ +export async function recordContentRevision( + adapter: Omit, + item: ContentItem, + authorId?: string, +) { + const latest = await adapter.findMany({ + model: "contentRevision", + where: [{ field: "contentItemId", value: item.id, operator: "eq" }], + sortBy: { field: "version", direction: "desc" }, + limit: 1, + }); + const version = (latest[0]?.version ?? 0) + 1; + return adapter.create({ + model: "contentRevision", + data: { + revisionKey: `${item.id}:${version}`, + contentItemId: item.id, + version, + slug: item.slug, + data: item.data, + publishAt: item.publishAt ?? null, + ...(authorId ? { authorId } : {}), + createdAt: new Date(), + }, + }); } /** @@ -103,27 +136,33 @@ export async function createCMSContentItem( ); } - const item = await adapter.create({ - model: "contentItem", - data: { - contentTypeId: contentType.id, - slug: input.slug, - data: JSON.stringify(input.data), - createdAt: new Date(), - updatedAt: new Date(), - }, - }); + return adapter.transaction(async (tx) => { + const item = await tx.create({ + model: "contentItem", + data: { + contentTypeId: contentType.id, + slug: input.slug, + data: JSON.stringify(input.data), + ...(input.publishAt !== undefined + ? { publishAt: input.publishAt } + : {}), + createdAt: new Date(), + updatedAt: new Date(), + }, + }); - if (options.syncRelations) { - const relationFields = extractRelationFields(contentType); - if (Object.keys(relationFields).length > 0) { - const relationIds = collectExistingRelationIds( - input.data, - relationFields, - ); - await syncRelations(adapter, item.id, relationIds); + if (options.syncRelations) { + const relationFields = extractRelationFields(contentType); + if (Object.keys(relationFields).length > 0) { + const relationIds = collectExistingRelationIds( + input.data, + relationFields, + ); + await syncRelations(tx, item.id, relationIds); + } } - } - return serializeContentItem(item); + await recordContentRevision(tx, item); + return serializeContentItem(item); + }); } diff --git a/packages/plugin-cms/src/api/operations.ts b/packages/plugin-cms/src/api/operations.ts index f96edee60..21c379620 100644 --- a/packages/plugin-cms/src/api/operations.ts +++ b/packages/plugin-cms/src/api/operations.ts @@ -28,6 +28,7 @@ import type { CMSUpdateOperationContext, ContentItem, ContentItemWithType, + ContentRevision, ContentRelation, ContentType, InverseRelation, @@ -52,6 +53,8 @@ import { syncRelations, } from "./relations"; +import { recordContentRevision } from "./mutations"; + type DataAdapter = Omit; function operationContentType( @@ -146,13 +149,19 @@ export const CMSContentItemParamsSchema = z.object({ typeSlug: z.string().min(1), id: z.string().min(1), }); +const PublishAtSchema = z.iso.datetime({ offset: true }).nullable().optional(); +export const CMSRevisionParamsSchema = CMSContentItemParamsSchema.extend({ + revisionId: z.string().min(1), +}); export const CMSCreateContentItemBodySchema = z.object({ slug: z.string().min(1), data: CMSDataSchema, + publishAt: PublishAtSchema, }); export const CMSUpdateContentItemBodySchema = z.object({ slug: z.string().min(1).optional(), data: CMSDataSchema.optional(), + publishAt: PublishAtSchema, }); const ListContentTypesInputSchema = EmptyInputSchema; @@ -463,6 +472,7 @@ function assertRecordSnapshot( (current.authorId ?? undefined) !== (expected.authorId ?? undefined) || current.slug !== expected.slug || current.data !== expected.data || + current.publishAt?.getTime() !== expected.publishAt?.getTime() || current.updatedAt.getTime() !== expected.updatedAt.getTime() ) { throw staleRecordError(); @@ -645,7 +655,9 @@ async function applyRelationWritePlan( await adapter.create({ model: "contentItem", data: item, + forceAllowId: true, }); + await recordContentRevision(adapter, item, item.authorId); } } @@ -1555,12 +1567,16 @@ export function createCMSOperations( contentTypeId: contentType.id, slug, data: JSON.stringify(validatedData), + publishAt: context.input.body.publishAt + ? new Date(context.input.body.publishAt) + : null, ...(context.identity ? { authorId: context.identity.id } : {}), createdAt: new Date(), updatedAt: new Date(), }, }); await syncRelations(tx, item.id, relationPlan.relationIds); + await recordContentRevision(tx, item, context.identity?.id); const joined = await getRecordOrThrow( tx, ensureSynced, @@ -1588,70 +1604,117 @@ export function createCMSOperations( }, }); - const updateContentItem = defineOperation({ - input: UpdateContentItemInputSchema, - permission: cmsPermissions.record.update, - facts: async ({ input }) => { - const item = await getRecordOrThrow( - adapter, - ensureSynced, - input.typeSlug, - input.id, + type UpdateContext = OperationContext< + z.output, + RecordUpdateFacts + >; + const executeUpdateContentItem = async ( + context: UpdateContext, + replaceData = false, + ) => { + const lifecycleContext = updateContext(context); + const contentType = await getContentTypeOrThrow( + adapter, + ensureSynced, + context.facts.contentType, + ); + const rawSlug = context.input.body.slug; + const slug = rawSlug ? slugify(rawSlug) : undefined; + if (rawSlug && !slug) { + throw new CMSOperationError( + 400, + "Invalid slug: must contain at least one alphanumeric character", + "INVALID_SLUG", ); - const facts = recordFacts(item); - return { - contentType: facts.contentType, - recordId: facts.recordId ?? input.id, - ...(facts.authorId ? { authorId: facts.authorId } : {}), - }; - }, - additionalPermissions: async ({ input, facts }) => { - const contentTypePermission = cmsPermissions.contentType.read({ - contentType: facts.contentType, + } + const bodyData = context.input.body.data; + const relationAuthorization = bodyData + ? await recheckRelationWriteAuthorization( + context.input as object, + contentType.slug, + bodyData, + ) + : undefined; + const authorizedRecord = await getRecordOrThrow( + adapter, + ensureSynced, + context.facts.contentType, + context.facts.recordId, + ); + assertRecordFacts(authorizedRecord, context.facts); + if (slug && slug !== authorizedRecord.slug) { + const duplicate = await adapter.findOne({ + model: "contentItem", + where: [ + { + field: "contentTypeId", + value: contentType.id, + operator: "eq" as const, + }, + { field: "slug", value: slug, operator: "eq" as const }, + ], }); - if (!input.body.data) return [contentTypePermission]; - const authorization = await deriveRelationWriteAuthorization( - adapter, - await getContentTypeOrThrow(adapter, ensureSynced, facts.contentType), - input.body.data as unknown as Readonly>, - ensureSynced, - ); - relationWriteAuthorizationSnapshots.set(input as object, authorization); - return [contentTypePermission, ...authorization.permissions]; - }, - execute: async (context) => { - const lifecycleContext = updateContext(context); - const contentType = await getContentTypeOrThrow( - adapter, - ensureSynced, - context.facts.contentType, - ); - const rawSlug = context.input.body.slug; - const slug = rawSlug ? slugify(rawSlug) : undefined; - if (rawSlug && !slug) { + if (duplicate) { throw new CMSOperationError( - 400, - "Invalid slug: must contain at least one alphanumeric character", - "INVALID_SLUG", + 409, + "Content item with this slug already exists", + "DUPLICATE_SLUG", ); } - const bodyData = context.input.body.data; - const relationAuthorization = bodyData - ? await recheckRelationWriteAuthorization( - context.input as object, - contentType.slug, - bodyData, - ) - : undefined; - const authorizedRecord = await getRecordOrThrow( - adapter, + } + const relationPlan = bodyData + ? await planRelationsInData( + adapter, + contentType, + bodyData, + ensureSynced, + context.identity?.id, + ) + : undefined; + const currentData = authorizedRecord.data + ? (JSON.parse(authorizedRecord.data) as Record) + : {}; + const validation = getContentTypeZodSchema(contentType).safeParse({ + ...(replaceData ? {} : currentData), + ...(relationPlan?.processedData ?? {}), + }); + if (!validation.success) { + throw new CMSOperationError( + 400, + "Validation failed", + "RECORD_VALIDATION_FAILED", + validation.error.issues, + ); + } + const mergedData = validation.data as Record; + await runBeforeHook( + () => + hooks?.onBeforeUpdateContent?.( + context.facts.recordId, + mergedData, + lifecycleContext, + ), + "Update operation denied", + ); + return adapter.transaction(async (tx) => { + if (bodyData && relationAuthorization) { + await assertCurrentRelationWriteAuthorization( + tx, + relationAuthorization, + contentType.slug, + bodyData, + ); + } + const current = await getRecordOrThrow( + tx, ensureSynced, context.facts.contentType, context.facts.recordId, ); - assertRecordFacts(authorizedRecord, context.facts); - if (slug && slug !== authorizedRecord.slug) { - const duplicate = await adapter.findOne({ + assertRecordFacts(current, context.facts); + assertRecordSnapshot(current, authorizedRecord); + if (slug && slug !== current.slug) { + const duplicate = await tx.findOne({ model: "contentItem", where: [ { @@ -1670,141 +1733,236 @@ export function createCMSOperations( ); } } - const relationPlan = bodyData - ? await planRelationsInData( - adapter, - contentType, - bodyData, - ensureSynced, - context.identity?.id, - ) - : undefined; - const currentData = authorizedRecord.data - ? (JSON.parse(authorizedRecord.data) as Record) - : {}; - const validation = getContentTypeZodSchema(contentType).safeParse({ - ...currentData, - ...(relationPlan?.processedData ?? {}), + if (relationPlan) await applyRelationWritePlan(tx, relationPlan); + const update: Partial = { + updatedAt: new Date( + Math.max(Date.now(), current.updatedAt.getTime() + 1), + ), + }; + if (context.input.body.publishAt !== undefined) { + update.publishAt = context.input.body.publishAt + ? new Date(context.input.body.publishAt) + : null; + } + if (slug) update.slug = slug; + if (bodyData) update.data = JSON.stringify(mergedData); + const matched = await tx.updateMany({ + model: "contentItem", + where: [ + { + field: "id", + value: context.facts.recordId, + operator: "eq" as const, + }, + { + field: "contentTypeId", + value: contentType.id, + operator: "eq" as const, + }, + { + field: "authorId", + value: context.facts.authorId ?? null, + operator: "eq" as const, + }, + { + field: "updatedAt", + value: current.updatedAt, + operator: "eq" as const, + }, + ], + update, }); - if (!validation.success) { - throw new CMSOperationError( - 400, - "Validation failed", - "RECORD_VALIDATION_FAILED", - validation.error.issues, - ); + if (!didUpdateContentItem(matched, context.facts.recordId)) { + throw staleRecordError(); } - const mergedData = validation.data as Record; - await runBeforeHook( - () => - hooks?.onBeforeUpdateContent?.( - context.facts.recordId, - mergedData, - lifecycleContext, - ), - "Update operation denied", - ); - return adapter.transaction(async (tx) => { - if (bodyData && relationAuthorization) { - await assertCurrentRelationWriteAuthorization( - tx, - relationAuthorization, - contentType.slug, - bodyData, - ); - } - const current = await getRecordOrThrow( - tx, - ensureSynced, - context.facts.contentType, - context.facts.recordId, - ); - assertRecordFacts(current, context.facts); - assertRecordSnapshot(current, authorizedRecord); - if (slug && slug !== current.slug) { - const duplicate = await tx.findOne({ - model: "contentItem", - where: [ - { - field: "contentTypeId", - value: contentType.id, - operator: "eq" as const, - }, - { field: "slug", value: slug, operator: "eq" as const }, - ], - }); - if (duplicate) { - throw new CMSOperationError( - 409, - "Content item with this slug already exists", - "DUPLICATE_SLUG", - ); - } - } - if (relationPlan) await applyRelationWritePlan(tx, relationPlan); - const update: Partial = { updatedAt: new Date() }; - if (slug) update.slug = slug; - if (bodyData) update.data = JSON.stringify(mergedData); - const matched = await tx.updateMany({ - model: "contentItem", - where: [ - { - field: "id", - value: context.facts.recordId, - operator: "eq" as const, - }, - { - field: "contentTypeId", - value: contentType.id, - operator: "eq" as const, - }, - { - field: "authorId", - value: context.facts.authorId ?? null, - operator: "eq" as const, - }, - { - field: "updatedAt", - value: current.updatedAt, - operator: "eq" as const, - }, - ], - update, + if (replaceData) { + await tx.deleteMany({ + model: "contentRelation", + where: [{ field: "sourceId", value: current.id, operator: "eq" }], }); - if (!didUpdateContentItem(matched, context.facts.recordId)) { - throw staleRecordError(); - } - if (relationPlan) { - await syncRelations( - tx, - context.facts.recordId, - relationPlan.relationIds, - ); - } - const updated = await getRecordOrThrow( + } + if (relationPlan) { + await syncRelations( tx, - ensureSynced, - context.facts.contentType, context.facts.recordId, + relationPlan.relationIds, ); - return operationContentItem(serializeContentItemWithType(updated)); - }); - }, - after: async (context) => { - const base = updateContext(context); - const afterUpdateContent = hooks?.onAfterUpdateContent as - | ((item: unknown, context: unknown) => Promise | void) - | undefined; - await afterUpdateContent?.( - context.result, - Object.freeze({ ...base, result: context.result }), + } + const updated = await getRecordOrThrow( + tx, + ensureSynced, + context.facts.contentType, + context.facts.recordId, ); - }, + await recordContentRevision(tx, updated, context.identity?.id); + return operationContentItem(serializeContentItemWithType(updated)); + }); + }; + + const authorizeUpdateRelations = async ({ + input, + facts, + }: Pick) => { + const contentTypePermission = cmsPermissions.contentType.read({ + contentType: facts.contentType, + }); + if (!input.body.data) return [contentTypePermission]; + const authorization = await deriveRelationWriteAuthorization( + adapter, + await getContentTypeOrThrow(adapter, ensureSynced, facts.contentType), + input.body.data as unknown as Readonly>, + ensureSynced, + ); + relationWriteAuthorizationSnapshots.set(input as object, authorization); + return [contentTypePermission, ...authorization.permissions]; + }; + + const updateFacts = async ({ + input, + }: { + input: { typeSlug: string; id: string }; + }) => { + const item = await getRecordOrThrow( + adapter, + ensureSynced, + input.typeSlug, + input.id, + ); + const facts = recordFacts(item); + return { + contentType: facts.contentType, + recordId: facts.recordId ?? input.id, + ...(facts.authorId ? { authorId: facts.authorId } : {}), + }; + }; + const afterUpdateContentItem = async ( + context: UpdateContext & { result: unknown }, + ) => { + const base = updateContext(context); + const afterUpdateContent = hooks?.onAfterUpdateContent as + | ((item: unknown, context: unknown) => Promise | void) + | undefined; + await afterUpdateContent?.( + context.result, + Object.freeze({ ...base, result: context.result }), + ); + }; + + const updateContentItem = defineOperation({ + input: UpdateContentItemInputSchema, + permission: cmsPermissions.record.update, + facts: updateFacts, + additionalPermissions: authorizeUpdateRelations, + execute: (context) => executeUpdateContentItem(context), + after: afterUpdateContentItem, onError: async ({ error, ...context }) => { await notifyError(error, "update", updateContext(context)); }, }); + const listContentRevisions = defineOperation({ + input: CMSContentItemParamsSchema.extend({ + offset: z.coerce.number().int().min(0).default(0), + }), + permission: cmsPermissions.record.read, + facts: async ({ input }) => + recordFacts( + await getRecordOrThrow(adapter, ensureSynced, input.typeSlug, input.id), + ), + additionalPermissions: ({ facts }) => [ + cmsPermissions.contentType.read({ contentType: facts.contentType }), + ], + execute: async ({ input, facts }) => { + assertRecordFacts( + await getRecordOrThrow(adapter, ensureSynced, input.typeSlug, input.id), + facts, + ); + const where = [ + { field: "contentItemId", value: input.id, operator: "eq" as const }, + ]; + const revisions = await adapter.findMany({ + model: "contentRevision", + where, + sortBy: { field: "version", direction: "desc" }, + limit: 20, + offset: input.offset, + }); + return { + items: revisions.map((revision) => ({ + ...revision, + createdAt: revision.createdAt.toISOString(), + publishAt: revision.publishAt?.toISOString() ?? null, + })), + total: await adapter.count({ model: "contentRevision", where }), + }; + }, + onError: ({ error, ...context }) => + notifyError( + error, + "list", + genericContext(context, context.facts.contentType), + ), + }); + + const restoreInputs = new WeakMap(); + const restoreContentRevision = defineOperation({ + input: CMSRevisionParamsSchema, + permission: cmsPermissions.record.update, + facts: updateFacts, + additionalPermissions: async ({ input, facts }) => { + const revision = await adapter.findOne({ + model: "contentRevision", + where: [ + { field: "id", value: input.revisionId, operator: "eq" }, + { field: "contentItemId", value: input.id, operator: "eq" }, + ], + }); + if (!revision) + throw new CMSOperationError( + 404, + "Revision not found", + "REVISION_NOT_FOUND", + ); + const freeze = (value: unknown): void => { + if (value && typeof value === "object") { + Object.values(value).forEach(freeze); + Object.freeze(value); + } + }; + const updateInput = UpdateContentItemInputSchema.parse({ + typeSlug: input.typeSlug, + id: input.id, + body: { + slug: revision.slug, + data: JSON.parse(revision.data), + publishAt: revision.publishAt?.toISOString() ?? null, + }, + }); + freeze(updateInput); + restoreInputs.set(input as object, updateInput); + return [ + cmsPermissions.record.read({ ...facts, scope: "record" }), + ...(await authorizeUpdateRelations({ input: updateInput, facts })), + ]; + }, + execute: async (context) => + executeUpdateContentItem( + { ...context, input: restoreInputs.get(context.input as object)! }, + true, + ), + after: async (context) => { + const input = restoreInputs.get(context.input as object)!; + restoreInputs.delete(context.input as object); + await afterUpdateContentItem({ ...context, input }); + }, + onError: ({ error, ...context }) => + notifyError( + error, + "update", + genericContext(context, context.facts.contentType), + ), + }); + const deleteContentItem = defineOperation({ input: DeleteContentItemInputSchema, permission: cmsPermissions.record.delete, @@ -2277,6 +2435,8 @@ export function createCMSOperations( >, createContentItem, updateContentItem, + listContentRevisions, + restoreContentRevision, deleteContentItem, getContentItemPopulated, listContentByRelation: diff --git a/packages/plugin-cms/src/api/plugin.ts b/packages/plugin-cms/src/api/plugin.ts index 919e8a36e..cbef4ca31 100644 --- a/packages/plugin-cms/src/api/plugin.ts +++ b/packages/plugin-cms/src/api/plugin.ts @@ -27,6 +27,7 @@ import { CMSContentTypeParamsSchema, CMSCreateContentItemBodySchema, CMSUpdateContentItemBodySchema, + CMSRevisionParamsSchema, createCMSOperations, } from "./operations"; import { CMS_QUERY_KEYS } from "./query-key-defs"; @@ -376,6 +377,30 @@ export const cmsBackendPlugin = (config: CMSBackendConfig) => { }, operations.deleteContentItem.route((ctx) => ctx.params), ); + const listContentRevisions = createEndpoint( + "/content/:typeSlug/:id/revisions", + { + method: "GET", + params: CMSContentItemParamsSchema, + query: z.object({ + offset: z.coerce.number().int().min(0).default(0), + }), + requireRequest: true, + }, + operations.listContentRevisions.route((ctx) => ({ + ...ctx.params, + ...ctx.query, + })), + ); + const restoreContentRevision = createEndpoint( + "/content/:typeSlug/:id/revisions/:revisionId/restore", + { + method: "POST", + params: CMSRevisionParamsSchema, + requireRequest: true, + }, + operations.restoreContentRevision.route((ctx) => ctx.params), + ); const getContentItemPopulated = createEndpoint( "/content/:typeSlug/:id/populated", { @@ -441,6 +466,8 @@ export const cmsBackendPlugin = (config: CMSBackendConfig) => { getContentItem, createContentItem, updateContentItem, + listContentRevisions, + restoreContentRevision, deleteContentItem, getContentItemPopulated, listContentByRelation, diff --git a/packages/plugin-cms/src/client/components/forms/content-form.tsx b/packages/plugin-cms/src/client/components/forms/content-form.tsx index 8138779f7..b1e479d38 100644 --- a/packages/plugin-cms/src/client/components/forms/content-form.tsx +++ b/packages/plugin-cms/src/client/components/forms/content-form.tsx @@ -25,10 +25,12 @@ interface ContentFormProps { contentType: SerializedContentType; initialData?: Record; initialSlug?: string; + initialPublishAt?: string | null; isEditing?: boolean; onSubmit: (data: { slug: string; data: Record; + publishAt?: string | null; }) => Promise; onCancel?: () => void; /** @@ -245,6 +247,7 @@ export function ContentForm({ contentType, initialData = {}, initialSlug = "", + initialPublishAt, isEditing = false, onSubmit, onCancel, @@ -262,6 +265,13 @@ export function ContentForm({ } = usePluginOverrides(CMS_PLUGIN_ID); const [slug, setSlug] = useState(initialSlug); + const [publishAt, setPublishAt] = useState(() => { + if (!initialPublishAt) return ""; + const date = new Date(initialPublishAt); + return new Date(date.getTime() - date.getTimezoneOffset() * 60_000) + .toISOString() + .slice(0, 16); + }); const [slugManuallyEdited, setSlugManuallyEdited] = useState(isEditing); const [isSubmittingLocal, setIsSubmittingLocal] = useState(false); const [formData, setFormData] = @@ -382,7 +392,11 @@ export function ContentForm({ setIsSubmittingLocal(true); try { - await onSubmit({ slug, data }); + await onSubmit({ + slug, + data, + publishAt: publishAt ? new Date(publishAt).toISOString() : null, + }); } catch (error) { const message = error instanceof Error @@ -462,6 +476,31 @@ export function ContentForm({

+
+ + setPublishAt(event.target.value)} + disabled={isSubmitting} + aria-describedby="publishAt-description" + /> +

+ {t( + "cms.editor.publishAtDescription", + "Optional. Uses your local time zone. Leave empty to clear the schedule.", + )} +

+ {serverFieldErrors.publishAt && ( +

+ {serverFieldErrors.publishAt} +

+ )} +
+ {/* Submit error message */} {bannerMessage && (
diff --git a/packages/plugin-cms/src/client/components/pages/content-editor-page.internal.tsx b/packages/plugin-cms/src/client/components/pages/content-editor-page.internal.tsx index 3ee901bca..4e9fe35a4 100644 --- a/packages/plugin-cms/src/client/components/pages/content-editor-page.internal.tsx +++ b/packages/plugin-cms/src/client/components/pages/content-editor-page.internal.tsx @@ -18,6 +18,7 @@ import { } from "../../hooks"; import { ContentForm } from "../forms/content-form"; import { InverseRelationsPanel } from "../inverse-relations-panel"; +import { RevisionHistory } from "../revision-history"; import { EmptyState } from "../shared/empty-state"; import { PageWrapper } from "../shared/page-wrapper"; import { EditorSkeleton } from "../loading/editor-skeleton"; @@ -165,6 +166,7 @@ export function ContentEditorPage({ typeSlug, id }: ContentEditorPageProps) { const contentType = contentTypes.find((ct) => ct.slug === typeSlug); const isEditing = !!id; + const [restoreCount, setRestoreCount] = useState(0); // useContentItem has enabled: !!id built-in, so it won't fetch when creating new items // This avoids conditional hook calls which violate React's Rules of Hooks @@ -176,6 +178,7 @@ export function ContentEditorPage({ typeSlug, id }: ContentEditorPageProps) { const resourceForm = useContentItemForm<{ slug: string; data: Record; + publishAt?: string | null; }>({ action: isEditing ? "edit" : "create", record: isEditing ? item : null, @@ -189,11 +192,16 @@ export function ContentEditorPage({ typeSlug, id }: ContentEditorPageProps) { typeSlug, slug: values.slug, data: values.data, + publishAt: values.publishAt, }), toUpdateVars: (values) => ({ typeSlug, id: id ?? "", - data: { slug: values.slug, data: values.data }, + data: { + slug: values.slug, + data: values.data, + publishAt: values.publishAt, + }, }), onSuccess: () => { void navigate?.(joinBasePath(basePath, `/cms/${typeSlug}`)); @@ -273,7 +281,7 @@ export function ContentEditorPage({ typeSlug, id }: ContentEditorPageProps) { return (
-
+

{title}

+ {isEditing && id && ( + setRestoreCount((count) => count + 1)} + /> + )}
diff --git a/packages/plugin-cms/src/client/components/revision-history.tsx b/packages/plugin-cms/src/client/components/revision-history.tsx new file mode 100644 index 000000000..45ce529d8 --- /dev/null +++ b/packages/plugin-cms/src/client/components/revision-history.tsx @@ -0,0 +1,213 @@ +"use client"; + +import { useState } from "react"; +import { Button } from "@workspace/ui/components/button"; +import { + Sheet, + SheetContent, + SheetDescription, + SheetHeader, + SheetTitle, + SheetTrigger, +} from "@workspace/ui/components/sheet"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@workspace/ui/components/alert-dialog"; +import { useTranslate } from "@btst/stack/context"; +import { useContentRevisions, useRestoreContentRevision } from "../hooks"; +import type { SerializedContentRevision } from "../../types"; + +export function RevisionHistory({ + typeSlug, + itemId, + onRestored, +}: { + typeSlug: string; + itemId: string; + onRestored: () => void; +}) { + const t = useTranslate(); + const [open, setOpen] = useState(false); + const [selected, setSelected] = useState( + null, + ); + const [restoreError, setRestoreError] = useState(null); + const history = useContentRevisions(typeSlug, itemId, open); + const restore = useRestoreContentRevision(); + const restoreSelected = async () => { + if (!selected) return; + setRestoreError(null); + try { + await restore.mutateAsync({ + typeSlug, + id: itemId, + revisionId: selected.id, + }); + onRestored(); + setSelected(null); + setOpen(false); + } catch (error) { + setRestoreError( + error instanceof Error + ? error.message + : t("cms.revisions.restoreError", "Could not restore revision"), + ); + } + }; + + return ( + + + + + + + + {t("cms.revisions.title", "Revision history")} + + + {t( + "cms.revisions.description", + "Inspect saved versions. Restoring a version replaces the editor state and creates a new revision.", + )} + + +
+ {history.isLoading && ( +

+ {t("cms.revisions.loading", "Loading revisions...")} +

+ )} + {history.error && ( +
+

{history.error.message}

+ +
+ )} + {!history.isLoading && + !history.error && + history.revisions.length === 0 && ( +

+ {t( + "cms.revisions.empty", + "No revisions yet. Saving this entry will create its first revision.", + )} +

+ )} + {history.revisions.map((revision) => ( +
+ + + {t("cms.revisions.version", "Version {version}").replace( + "{version}", + String(revision.version), + )} + + + + + + {t("cms.revisions.author", "Author")}:{" "} + {revision.authorId ?? t("cms.revisions.system", "System")} + + +
+

+ {t("cms.common.slugLabel", "Slug")}: {revision.slug} +

+

+ {t("cms.editor.publishAt", "Publish at")}:{" "} + {revision.publishAt + ? new Date(revision.publishAt).toLocaleString() + : t("cms.revisions.unscheduled", "Not scheduled")} +

+
+									{JSON.stringify(JSON.parse(revision.data), null, 2)}
+								
+ +
+
+ ))} + {history.hasNextPage && ( + + )} +
+
+ { + if (!value && !restore.isPending) setSelected(null); + }} + > + + + + {t( + "cms.revisions.confirmTitle", + "Restore version {version}?", + ).replace("{version}", String(selected?.version ?? ""))} + + + {t( + "cms.revisions.confirmDescription", + "This replaces the active entry, including its slug and schedule. Unsaved editor changes will be discarded. Existing revisions are kept.", + )} + + + {restoreError && ( +

+ {restoreError} +

+ )} + + + {t("cms.common.cancel", "Cancel")} + + { + event.preventDefault(); + void restoreSelected(); + }} + > + {restore.isPending + ? t("cms.revisions.restoring", "Restoring...") + : t("cms.revisions.confirm", "Restore version")} + + +
+
+
+ ); +} diff --git a/packages/plugin-cms/src/client/hooks/cms-hooks.tsx b/packages/plugin-cms/src/client/hooks/cms-hooks.tsx index 0712a158f..8fcaa80ec 100644 --- a/packages/plugin-cms/src/client/hooks/cms-hooks.tsx +++ b/packages/plugin-cms/src/client/hooks/cms-hooks.tsx @@ -566,17 +566,23 @@ export function useCreateContent>( return { ...mutation, - mutate: (vars: { slug: string; data: TData }) => + mutate: (vars: { slug: string; data: TData; publishAt?: string | null }) => mutation.mutate({ typeSlug, slug: vars.slug, data: vars.data as Record, + publishAt: vars.publishAt, }), - mutateAsync: async (vars: { slug: string; data: TData }) => + mutateAsync: async (vars: { + slug: string; + data: TData; + publishAt?: string | null; + }) => (await mutation.mutateAsync({ typeSlug, slug: vars.slug, data: vars.data as Record, + publishAt: vars.publishAt, })) as SerializedContentItemWithType, }; } @@ -604,20 +610,26 @@ export function useUpdateContent>( const toVars = (vars: { id: string; - data: { slug?: string; data?: TData }; + data: { slug?: string; data?: TData; publishAt?: string | null }; }) => ({ typeSlug, id: vars.id, - data: vars.data as { slug?: string; data?: Record }, + data: vars.data as { + slug?: string; + data?: Record; + publishAt?: string | null; + }, }); return { ...mutation, - mutate: (vars: { id: string; data: { slug?: string; data?: TData } }) => - mutation.mutate(toVars(vars)), + mutate: (vars: { + id: string; + data: { slug?: string; data?: TData; publishAt?: string | null }; + }) => mutation.mutate(toVars(vars)), mutateAsync: async (vars: { id: string; - data: { slug?: string; data?: TData }; + data: { slug?: string; data?: TData; publishAt?: string | null }; }) => (await mutation.mutateAsync( toVars(vars), @@ -1048,3 +1060,23 @@ export function useInverseRelationItems< refetch, }; } + +/** Paginated revision snapshots, newest first. Fetches only when enabled. */ +export function useContentRevisions( + typeSlug: string, + id: string, + enabled = true, +) { + const result = cms.cmsRevisions.list.useInfinite([typeSlug, id], { + enabled: enabled && !!id, + }); + return { + ...result, + revisions: result.data?.pages.flatMap((page) => page.items) ?? [], + }; +} + +/** Restore a saved revision and refresh the editor, history and relation queries. */ +export function useRestoreContentRevision() { + return cms.cmsRevisions.restore.use(); +} diff --git a/packages/plugin-cms/src/db.ts b/packages/plugin-cms/src/db.ts index 876c6062d..44b9b8ba3 100644 --- a/packages/plugin-cms/src/db.ts +++ b/packages/plugin-cms/src/db.ts @@ -67,6 +67,10 @@ export const cmsSchema = createDbPlugin("cms", { type: "string", required: false, }, + publishAt: { + type: "date", + required: false, + }, createdAt: { type: "date", defaultValue: () => new Date(), @@ -77,6 +81,27 @@ export const cmsSchema = createDbPlugin("cms", { }, }, }, + contentRevision: { + modelName: "contentRevision", + fields: { + contentItemId: { + type: "string", + required: true, + references: { + model: "contentItem", + field: "id", + onDelete: "cascade", + }, + }, + revisionKey: { type: "string", required: true, unique: true }, + version: { type: "number", required: true }, + slug: { type: "string", required: true }, + data: { type: "string", required: true }, + publishAt: { type: "date", required: false }, + authorId: { type: "string", required: false }, + createdAt: { type: "date", defaultValue: () => new Date() }, + }, + }, /** * Junction table for content item relationships * Stores many-to-many and one-to-many relations between content items diff --git a/packages/plugin-cms/src/query-keys.ts b/packages/plugin-cms/src/query-keys.ts index 870b27c23..e39eb66b8 100644 --- a/packages/plugin-cms/src/query-keys.ts +++ b/packages/plugin-cms/src/query-keys.ts @@ -7,6 +7,7 @@ import { } from "@btst/stack/plugins/client"; import type { SerializedContentType, + SerializedContentRevision, SerializedContentItemWithType, PaginatedContentItems, InverseRelation, @@ -96,8 +97,8 @@ function relationPageKey( * loaded-item offset. */ function paginatedNextPageParam( - lastPage: PaginatedContentItems, - allPages: PaginatedContentItems[], + lastPage: { items: unknown[]; total: number }, + allPages: { items: unknown[]; total: number }[], limit: number, ): number | undefined { const items = Array.isArray(lastPage?.items) ? lastPage.items : []; @@ -177,6 +178,44 @@ export const cmsResources = { }, }, + cmsRevisions: { + queries: { + list: { + path: "/content/:typeSlug/:id/revisions", + params: (typeSlug: string, id: string) => ({ typeSlug, id }), + key: (typeSlug: string, id: string) => [typeSlug, id], + select: ( + data: any, + ): { items: SerializedContentRevision[]; total: number } => + data ?? { items: [], total: 0 }, + infinite: true, + pageSize: () => 20, + nextPageParam: ( + lastPage: { items: SerializedContentRevision[]; total: number }, + allPages: { items: SerializedContentRevision[]; total: number }[], + ) => paginatedNextPageParam(lastPage, allPages, 20), + }, + }, + mutations: { + restore: { + path: "@post/content/:typeSlug/:id/revisions/:revisionId/restore", + method: "POST" as const, + input: (vars: { + typeSlug: string; + id: string; + revisionId: string; + }) => ({ params: vars }), + select: (data: any) => data as SerializedContentItemWithType, + invalidates: [ + "cmsContent", + "cmsRevisions", + "cmsTypes.inverseRelationItems", + "cmsTypes.inverseRelations", + ], + }, + }, + }, + cmsContent: { queries: { list: { @@ -312,13 +351,15 @@ export const cmsResources = { typeSlug: string; slug: string; data: Record; + publishAt?: string | null; }) => ({ params: { typeSlug: vars.typeSlug }, - body: { slug: vars.slug, data: vars.data }, + body: { slug: vars.slug, data: vars.data, publishAt: vars.publishAt }, }), select: (data: any) => data as SerializedContentItemWithType | null, invalidates: [ "cmsContent", + "cmsRevisions", "cmsTypes.list", "cmsTypes.inverseRelationItems", "cmsTypes.inverseRelations", @@ -330,7 +371,11 @@ export const cmsResources = { input: (vars: { typeSlug: string; id: string; - data: { slug?: string; data?: Record }; + data: { + slug?: string; + data?: Record; + publishAt?: string | null; + }; }) => ({ params: { typeSlug: vars.typeSlug, id: vars.id }, body: vars.data, @@ -338,6 +383,7 @@ export const cmsResources = { select: (data: any) => data as SerializedContentItemWithType | null, invalidates: [ "cmsContent", + "cmsRevisions", "cmsTypes.inverseRelationItems", "cmsTypes.inverseRelations", ], @@ -358,6 +404,7 @@ export const cmsResources = { select: (data: any) => data as { success: boolean }, invalidates: [ "cmsContent", + "cmsRevisions", "cmsTypes.list", "cmsTypes.inverseRelationItems", "cmsTypes.inverseRelations", diff --git a/packages/plugin-cms/src/types.ts b/packages/plugin-cms/src/types.ts index 2e847e427..b4795b526 100644 --- a/packages/plugin-cms/src/types.ts +++ b/packages/plugin-cms/src/types.ts @@ -57,10 +57,36 @@ export type ContentItem = { data: string; /** Optional author ID for tracking who created/modified */ authorId?: string; + /** Optional scheduling metadata; visibility remains the consuming application's policy. */ + publishAt?: Date | null; createdAt: Date; updatedAt: Date; }; +/** Immutable snapshot appended after each successful CMS write. */ +export type ContentRevision = { + id: string; + contentItemId: string; + /** Unique item/version key protects against concurrent revision numbering. */ + revisionKey: string; + version: number; + slug: string; + data: string; + publishAt?: Date | null; + /** Identity that performed the write; absent for trusted jobs. */ + authorId?: string | null; + createdAt: Date; +}; + +/** Revision transported over HTTP, with dates as ISO strings. */ +export type SerializedContentRevision = Omit< + ContentRevision, + "createdAt" | "publishAt" +> & { + createdAt: string; + publishAt?: string | null; +}; + /** * Content item with its content type joined */ @@ -167,9 +193,10 @@ export interface SerializedContentType * Serialized content item for API responses (dates as strings) */ export interface SerializedContentItem - extends Omit { + extends Omit { createdAt: string; updatedAt: string; + publishAt?: string | null; } /** @@ -334,6 +361,7 @@ export interface CMSCreateOperationContext readonly body: { readonly slug: string; readonly data: Readonly>; + readonly publishAt?: string | null; }; }, { contentType: string } @@ -346,6 +374,7 @@ export interface CMSCreateOperationContext readonly slug: string; /** Validated JSON-safe request fields, including any inline `_new` relation values. */ readonly data: Readonly>; + readonly publishAt?: string | null; }; } @@ -364,6 +393,7 @@ export interface CMSUpdateOperationContext readonly body: { readonly slug?: string; readonly data?: Readonly>; + readonly publishAt?: string | null; }; }, { contentType: string; recordId: string; authorId?: string } @@ -378,6 +408,7 @@ export interface CMSUpdateOperationContext readonly slug?: string; /** Optional record-field fragment; hooks receive its merged validated result. */ readonly data?: Readonly>; + readonly publishAt?: string | null; }; } diff --git a/packages/stack/registry/btst-cms.json b/packages/stack/registry/btst-cms.json index 20df264ab..29450fa89 100644 --- a/packages/stack/registry/btst-cms.json +++ b/packages/stack/registry/btst-cms.json @@ -24,6 +24,7 @@ "https://raw.githubusercontent.com/better-stack-ai/form-builder/refs/heads/main/registry/auto-form.json", "input", "label", + "sheet", "skeleton", "table", "textarea" @@ -32,7 +33,7 @@ { "path": "btst/cms/types.ts", "type": "registry:lib", - "content": "import type { z } from \"zod\";\n\n/**\n * Configuration for a content type defined by the developer.\n *\n * Field types are now specified directly in the Zod schema via .meta():\n * @example\n * ```typescript\n * const ProductSchema = z.object({\n * description: z.string().meta({ fieldType: \"textarea\" }),\n * image: z.string().optional().meta({ fieldType: \"file\" }),\n * });\n * ```\n */\nexport interface ContentTypeConfig {\n\t/** Display name for the content type (e.g., \"Product\", \"Testimonial\") */\n\tname: string;\n\t/** URL-friendly slug (e.g., \"product\", \"testimonial\") */\n\tslug: string;\n\t/** Optional description shown in the admin UI */\n\tdescription?: string;\n\t/** Zod schema defining the content type's fields. Use .meta({ fieldType: \"...\" }) for field type overrides. */\n\tschema: z.ZodObject;\n}\n\n/**\n * Content type stored in the database\n */\nexport type ContentType = {\n\tid: string;\n\t/** Display name */\n\tname: string;\n\t/** URL-friendly slug - unique identifier */\n\tslug: string;\n\t/** Optional description */\n\tdescription?: string;\n\t/** JSON Schema representation of the Zod schema (stringified) */\n\tjsonSchema: string;\n\t/** @deprecated Legacy field config - now embedded in jsonSchema. Kept for backwards compat. */\n\tfieldConfig?: string;\n\t/** AutoForm schema version. 1 = legacy (separate fieldConfig), 2 = unified (fieldType in jsonSchema) */\n\tautoFormVersion?: number;\n\tcreatedAt: Date;\n\tupdatedAt: Date;\n};\n\n/**\n * Content item stored in the database\n */\nexport type ContentItem = {\n\tid: string;\n\t/** Reference to the content type */\n\tcontentTypeId: string;\n\t/** URL-friendly slug - unique within content type */\n\tslug: string;\n\t/** JSON data matching the content type's schema (stringified) */\n\tdata: string;\n\t/** Optional author ID for tracking who created/modified */\n\tauthorId?: string;\n\tcreatedAt: Date;\n\tupdatedAt: Date;\n};\n\n/**\n * Content item with its content type joined\n */\nexport type ContentItemWithType = ContentItem & {\n\tcontentType?: ContentType;\n};\n\n/**\n * Content relation stored in the database (junction table)\n * Links source content items to target content items for relationship fields\n */\nexport type ContentRelation = {\n\tid: string;\n\t/** The content item that has the relation field */\n\tsourceId: string;\n\t/** The content item being referenced */\n\ttargetId: string;\n\t/** The field name in the source content type schema (e.g., \"categoryIds\") */\n\tfieldName: string;\n\tcreatedAt: Date;\n};\n\n// ========== Relation Field Types ==========\n\n/**\n * Configuration for a relation field in schema metadata.\n * Use with .meta({ fieldType: \"relation\", relation: {...} })\n *\n * The schema stores relation values as simple `{ id: string }` references.\n * When `creatable: true`, the frontend sends `{ _new: true, data: {...} }`\n * which the API processes before validation - creating new items and\n * converting them to ID references.\n *\n * @example\n * ```typescript\n * const ResourceSchema = z.object({\n * // Simple array of ID references - API handles _new items before validation\n * categoryIds: z.array(z.object({ id: z.string() })).default([]).meta({\n * fieldType: \"relation\",\n * relation: {\n * type: \"manyToMany\",\n * targetType: \"category\",\n * displayField: \"name\",\n * creatable: true,\n * },\n * }),\n * });\n * ```\n */\nexport interface RelationConfig {\n\t/** Relation type */\n\ttype: \"belongsTo\" | \"hasMany\" | \"manyToMany\";\n\t/** Target content type slug */\n\ttargetType: string;\n\t/** Field to display in the dropdown (e.g., \"name\", \"title\") */\n\tdisplayField: string;\n\t/** Allow creating new items inline via modal (default: false) */\n\tcreatable?: boolean;\n}\n\n/**\n * Value for a relation field - either a reference to existing item or a new item to create.\n *\n * @example\n * ```typescript\n * // Reference to existing item\n * const existing: RelationValue = { id: \"abc123\" };\n *\n * // New item to create on save\n * const newItem: RelationValue = {\n * _new: true,\n * data: { name: \"New Category\", description: \"...\" }\n * };\n * ```\n */\nexport type RelationValue =\n\t| { id: string }\n\t| { _new: true; data: Record };\n\n/**\n * Represents an inverse relation (content types that reference this type via belongsTo)\n */\nexport interface InverseRelation {\n\t/** The content type slug that has the belongsTo relation */\n\tsourceType: string;\n\t/** Display name of the source content type */\n\tsourceTypeName: string;\n\t/** The field name that contains the belongsTo relation */\n\tfieldName: string;\n\t/** Count of items with this relation (when itemId is provided) */\n\tcount: number;\n}\n\n/**\n * Serialized content type for API responses (dates as strings)\n */\nexport interface SerializedContentType\n\textends Omit {\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\n/**\n * Serialized content item for API responses (dates as strings)\n */\nexport interface SerializedContentItem\n\textends Omit {\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\n/**\n * Serialized content item with parsed data and joined content type\n * @template TData - The type of the parsed data (defaults to Record)\n */\nexport interface SerializedContentItemWithType>\n\textends SerializedContentItem {\n\t/** Parsed data object (JSON.parse of data field). */\n\tparsedData: TData;\n\t/** Joined content type */\n\tcontentType?: SerializedContentType;\n\t/**\n\t * Populated relation data (only present when using populated endpoints/hooks).\n\t * Keys are field names, values are arrays of related content items.\n\t */\n\t_relations?: Record;\n}\n\n/** Output shape for CMS reads; omission retains the full editor envelope. */\nexport type CMSReadView = \"content\" | undefined;\n\n/** Literal top-level property names selected from parsed content. */\nexport type CMSContentFields = readonly string[] | undefined;\n\n/** Select known literal properties, or an honest partial shape for dynamic arrays. */\nexport type CMSSelectedData<\n\tTData,\n\tTFields extends CMSContentFields = undefined,\n> = TFields extends readonly string[]\n\t? string extends TFields[number]\n\t\t? Partial\n\t\t: Pick>\n\t: TData;\n\n/** Optional output controls for CMS reads. These do not change access checks. */\nexport interface CMSReadOptions<\n\tTView extends CMSReadView = CMSReadView,\n\tTFields extends CMSContentFields = CMSContentFields,\n> {\n\t/** Return identity, parsed content and timestamps without editor metadata. */\n\tview?: TView;\n\t/** Literal declared top-level content properties. Requires content view. */\n\tfields?: TFields;\n}\n\n/** Serialized content envelope without raw JSON or editor metadata. */\nexport type SerializedContentItemContent> =\n\tPick<\n\t\tSerializedContentItemWithType,\n\t\t\"id\" | \"slug\" | \"parsedData\" | \"createdAt\" | \"updatedAt\"\n\t>;\n\n/** Result envelope selected by a statically known read view. */\nexport type CMSContentItemResult<\n\tTData = Record,\n\tTView extends CMSReadView = undefined,\n\tTFields extends CMSContentFields = undefined,\n> = TView extends \"content\"\n\t? SerializedContentItemContent>\n\t: SerializedContentItemWithType;\n\n/**\n * Paginated list response for content items\n * @template TData - The type of the parsed data (defaults to Record)\n */\nexport interface PaginatedContentItems<\n\tTData = Record,\n\tTView extends CMSReadView = undefined,\n\tTFields extends CMSContentFields = undefined,\n> {\n\titems: CMSContentItemResult[];\n\ttotal: number;\n\tlimit: number;\n\toffset: number;\n}\n\n/**\n * Type helper to define a map of content type slugs to their data types.\n * Use with z.infer to get the type from your Zod schemas.\n *\n * @example\n * ```typescript\n * import { z } from \"zod\"\n *\n * // Define your schemas\n * export const ProductSchema = z.object({\n * name: z.string(),\n * price: z.number(),\n * })\n *\n * export const TestimonialSchema = z.object({\n * author: z.string(),\n * quote: z.string(),\n * })\n *\n * // Create the type map\n * export type MyCMSTypes = {\n * product: z.infer\n * testimonial: z.infer\n * }\n *\n * // Use in hooks for type-safe parsedData\n * const { items } = useContent(\"product\")\n * // items[0].parsedData.name is typed as string\n * // items[0].parsedData.price is typed as number\n * ```\n */\nexport type CMSContentTypeMap = Record>;\n\n/** JSON-safe values accepted at the CMS operation boundary. */\nexport type CMSOperationData =\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| readonly CMSOperationData[]\n\t| { readonly [key: string]: CMSOperationData };\n\n/** @deprecated Use the operation-specific CMS lifecycle contexts instead. */\nexport interface CMSHookContext {\n\treadonly typeSlug: string;\n\treadonly userId?: string;\n\treadonly headers?: Headers;\n}\n\ninterface CMSOperationIdentity {\n\treadonly id: string;\n\treadonly [key: string]: unknown;\n}\n\ntype CMSDeepReadonly = T extends (...args: any[]) => unknown\n\t? T\n\t: T extends readonly unknown[]\n\t\t? { readonly [TKey in keyof T]: CMSDeepReadonly }\n\t\t: T extends object\n\t\t\t? { readonly [TKey in keyof T]: CMSDeepReadonly }\n\t\t\t: T;\n\ninterface CMSOperationContextBase {\n\t/** Validated, deeply readonly input supplied to the operation. */\n\treadonly input: Readonly;\n\t/** Trusted server-derived facts used by the authorization rule. */\n\treadonly facts: Readonly;\n\t/** Authorized request identity, or `null` for anonymous and trusted calls. */\n\treadonly identity: Readonly | null;\n\t/** Transport request when the operation was invoked through HTTP or `forRequest()`. */\n\treadonly request?: Request;\n\t/** Compatibility view of the transport request headers. */\n\treadonly headers?: Headers;\n\t/** Compatibility alias for the authorized identity ID. */\n\treadonly userId?: string;\n\t/** Compatibility alias for the operation's CMS content-type slug. */\n\treadonly typeSlug?: string;\n}\n\n/** Authorized context supplied before a CMS record is created. */\nexport interface CMSCreateOperationContext\n\textends CMSOperationContextBase<\n\t\t{\n\t\t\treadonly typeSlug: string;\n\t\t\treadonly body: {\n\t\t\t\treadonly slug: string;\n\t\t\t\treadonly data: Readonly>;\n\t\t\t};\n\t\t},\n\t\t{ contentType: string }\n\t> {\n\t/** Server-resolved content-type slug for the record being created. */\n\treadonly typeSlug: string;\n\t/** Validated create payload supplied to the operation. */\n\treadonly body: {\n\t\t/** Requested record slug before canonical slugification. */\n\t\treadonly slug: string;\n\t\t/** Validated JSON-safe request fields, including any inline `_new` relation values. */\n\t\treadonly data: Readonly>;\n\t};\n}\n\n/** CMS create context after execution. */\nexport interface CMSCreateResultContext extends CMSCreateOperationContext {\n\t/** Fully serialized record returned by the successful create operation. */\n\treadonly result: CMSDeepReadonly;\n}\n\n/** Authorized context supplied before a CMS record is updated. */\nexport interface CMSUpdateOperationContext\n\textends CMSOperationContextBase<\n\t\t{\n\t\t\treadonly typeSlug: string;\n\t\t\treadonly id: string;\n\t\t\treadonly body: {\n\t\t\t\treadonly slug?: string;\n\t\t\t\treadonly data?: Readonly>;\n\t\t\t};\n\t\t},\n\t\t{ contentType: string; recordId: string; authorId?: string }\n\t> {\n\t/** Server-resolved content-type slug for the record being updated. */\n\treadonly typeSlug: string;\n\t/** Canonical route parameters for the authorized record. */\n\treadonly params: { readonly typeSlug: string; readonly id: string };\n\t/** Validated partial update payload supplied to the operation. */\n\treadonly body: {\n\t\t/** Optional replacement slug before canonical slugification. */\n\t\treadonly slug?: string;\n\t\t/** Optional record-field fragment; hooks receive its merged validated result. */\n\t\treadonly data?: Readonly>;\n\t};\n}\n\n/** CMS update context after execution. */\nexport interface CMSUpdateResultContext extends CMSUpdateOperationContext {\n\t/** Fully serialized record returned by the successful update operation. */\n\treadonly result: CMSDeepReadonly;\n}\n\n/** Authorized context supplied before a CMS record is deleted. */\nexport interface CMSDeleteOperationContext\n\textends CMSOperationContextBase<\n\t\t{ readonly typeSlug: string; readonly id: string },\n\t\t{ contentType: string; recordId: string; authorId?: string }\n\t> {\n\t/** Server-resolved content-type slug for the record being deleted. */\n\treadonly typeSlug: string;\n\t/** Canonical route parameters for the authorized record. */\n\treadonly params: { readonly typeSlug: string; readonly id: string };\n}\n\n/** CMS delete context after execution. */\nexport interface CMSDeleteResultContext extends CMSDeleteOperationContext {\n\t/** Successful delete result. */\n\treadonly result: { readonly success: true };\n}\n\ninterface CMSReadOperationContext\n\textends CMSOperationContextBase<\n\t\tunknown,\n\t\t{\n\t\t\tcontentType?: string;\n\t\t\tscope?: \"collection\" | \"record\";\n\t\t\trecordId?: string;\n\t\t\tauthorId?: string;\n\t\t}\n\t> {}\n\n/** Authorized context shared by the CMS operation lifecycle hooks. */\nexport type CMSOperationLifecycleContext =\n\t| CMSReadOperationContext\n\t| CMSCreateOperationContext\n\t| CMSUpdateOperationContext\n\t| CMSDeleteOperationContext;\n\n/** Authorized lifecycle context supplied to the observational error hook. */\nexport type CMSOperationErrorContext = CMSOperationLifecycleContext & {\n\t/** Original post-authorization operation error observed by `onErrorExecuteContentOperation`. */\n\treadonly error: unknown;\n};\n\n/** Domain lifecycle hooks that run only after successful CMS authorization. */\nexport interface CMSBackendHooks {\n\t/** Runs with validated canonical record data after authorization and before any database write. */\n\tonBeforeCreateContent?: (\n\t\tdata: Readonly>,\n\t\tcontext: CMSCreateOperationContext,\n\t) => Promise | void;\n\t/** Observes the fully created record after the atomic create succeeds. */\n\tonAfterCreateContent?: (\n\t\titem: CMSDeepReadonly,\n\t\tcontext: CMSCreateResultContext,\n\t) => Promise | void;\n\t/** Runs for every update with the complete merged, validated record before any database write. */\n\tonBeforeUpdateContent?: (\n\t\tid: string,\n\t\tdata: Readonly>,\n\t\tcontext: CMSUpdateOperationContext,\n\t) => Promise | void;\n\t/** Observes the fully updated record after the atomic update succeeds. */\n\tonAfterUpdateContent?: (\n\t\titem: CMSDeepReadonly,\n\t\tcontext: CMSUpdateResultContext,\n\t) => Promise | void;\n\t/** Runs after authorization and before the record is deleted. */\n\tonBeforeDeleteContent?: (\n\t\tid: string,\n\t\tcontext: CMSDeleteOperationContext,\n\t) => Promise | void;\n\t/** Observes the deleted record ID after the atomic delete succeeds. */\n\tonAfterDeleteContent?: (\n\t\tid: string,\n\t\tcontext: CMSDeleteResultContext,\n\t) => Promise | void;\n\t/** Observes post-authorization failures without replacing the original error. */\n\tonErrorExecuteContentOperation?: (\n\t\terror: Error,\n\t\toperation: \"create\" | \"update\" | \"delete\" | \"list\" | \"get\",\n\t\tcontext: CMSOperationErrorContext,\n\t) => Promise | void;\n}\n\n/**\n * Configuration for the CMS backend plugin\n */\nexport interface CMSBackendConfig {\n\t/** Content types defined by the developer */\n\tcontentTypes: ContentTypeConfig[];\n\t/** Optional hooks for customizing behavior */\n\thooks?: CMSBackendHooks;\n\t/**\n\t * Maximum number of items that can be requested in a single page.\n\t * Applied to all list endpoints (`/content/:typeSlug`, by-relation, and inverse-relation).\n\t *\n\t * Raise this when your content types have many items and you need to fetch\n\t * large pages (e.g. for SSG, CSV export, or programmatic access).\n\t *\n\t * @default 1000\n\t */\n\tmaxPageSize?: number;\n}\n", + "content": "import type { z } from \"zod\";\n\n/**\n * Configuration for a content type defined by the developer.\n *\n * Field types are now specified directly in the Zod schema via .meta():\n * @example\n * ```typescript\n * const ProductSchema = z.object({\n * description: z.string().meta({ fieldType: \"textarea\" }),\n * image: z.string().optional().meta({ fieldType: \"file\" }),\n * });\n * ```\n */\nexport interface ContentTypeConfig {\n\t/** Display name for the content type (e.g., \"Product\", \"Testimonial\") */\n\tname: string;\n\t/** URL-friendly slug (e.g., \"product\", \"testimonial\") */\n\tslug: string;\n\t/** Optional description shown in the admin UI */\n\tdescription?: string;\n\t/** Zod schema defining the content type's fields. Use .meta({ fieldType: \"...\" }) for field type overrides. */\n\tschema: z.ZodObject;\n}\n\n/**\n * Content type stored in the database\n */\nexport type ContentType = {\n\tid: string;\n\t/** Display name */\n\tname: string;\n\t/** URL-friendly slug - unique identifier */\n\tslug: string;\n\t/** Optional description */\n\tdescription?: string;\n\t/** JSON Schema representation of the Zod schema (stringified) */\n\tjsonSchema: string;\n\t/** @deprecated Legacy field config - now embedded in jsonSchema. Kept for backwards compat. */\n\tfieldConfig?: string;\n\t/** AutoForm schema version. 1 = legacy (separate fieldConfig), 2 = unified (fieldType in jsonSchema) */\n\tautoFormVersion?: number;\n\tcreatedAt: Date;\n\tupdatedAt: Date;\n};\n\n/**\n * Content item stored in the database\n */\nexport type ContentItem = {\n\tid: string;\n\t/** Reference to the content type */\n\tcontentTypeId: string;\n\t/** URL-friendly slug - unique within content type */\n\tslug: string;\n\t/** JSON data matching the content type's schema (stringified) */\n\tdata: string;\n\t/** Optional author ID for tracking who created/modified */\n\tauthorId?: string;\n\t/** Optional scheduling metadata; visibility remains the consuming application's policy. */\n\tpublishAt?: Date | null;\n\tcreatedAt: Date;\n\tupdatedAt: Date;\n};\n\n/** Immutable snapshot appended after each successful CMS write. */\nexport type ContentRevision = {\n\tid: string;\n\tcontentItemId: string;\n\t/** Unique item/version key protects against concurrent revision numbering. */\n\trevisionKey: string;\n\tversion: number;\n\tslug: string;\n\tdata: string;\n\tpublishAt?: Date | null;\n\t/** Identity that performed the write; absent for trusted jobs. */\n\tauthorId?: string | null;\n\tcreatedAt: Date;\n};\n\n/** Revision transported over HTTP, with dates as ISO strings. */\nexport type SerializedContentRevision = Omit<\n\tContentRevision,\n\t\"createdAt\" | \"publishAt\"\n> & {\n\tcreatedAt: string;\n\tpublishAt?: string | null;\n};\n\n/**\n * Content item with its content type joined\n */\nexport type ContentItemWithType = ContentItem & {\n\tcontentType?: ContentType;\n};\n\n/**\n * Content relation stored in the database (junction table)\n * Links source content items to target content items for relationship fields\n */\nexport type ContentRelation = {\n\tid: string;\n\t/** The content item that has the relation field */\n\tsourceId: string;\n\t/** The content item being referenced */\n\ttargetId: string;\n\t/** The field name in the source content type schema (e.g., \"categoryIds\") */\n\tfieldName: string;\n\tcreatedAt: Date;\n};\n\n// ========== Relation Field Types ==========\n\n/**\n * Configuration for a relation field in schema metadata.\n * Use with .meta({ fieldType: \"relation\", relation: {...} })\n *\n * The schema stores relation values as simple `{ id: string }` references.\n * When `creatable: true`, the frontend sends `{ _new: true, data: {...} }`\n * which the API processes before validation - creating new items and\n * converting them to ID references.\n *\n * @example\n * ```typescript\n * const ResourceSchema = z.object({\n * // Simple array of ID references - API handles _new items before validation\n * categoryIds: z.array(z.object({ id: z.string() })).default([]).meta({\n * fieldType: \"relation\",\n * relation: {\n * type: \"manyToMany\",\n * targetType: \"category\",\n * displayField: \"name\",\n * creatable: true,\n * },\n * }),\n * });\n * ```\n */\nexport interface RelationConfig {\n\t/** Relation type */\n\ttype: \"belongsTo\" | \"hasMany\" | \"manyToMany\";\n\t/** Target content type slug */\n\ttargetType: string;\n\t/** Field to display in the dropdown (e.g., \"name\", \"title\") */\n\tdisplayField: string;\n\t/** Allow creating new items inline via modal (default: false) */\n\tcreatable?: boolean;\n}\n\n/**\n * Value for a relation field - either a reference to existing item or a new item to create.\n *\n * @example\n * ```typescript\n * // Reference to existing item\n * const existing: RelationValue = { id: \"abc123\" };\n *\n * // New item to create on save\n * const newItem: RelationValue = {\n * _new: true,\n * data: { name: \"New Category\", description: \"...\" }\n * };\n * ```\n */\nexport type RelationValue =\n\t| { id: string }\n\t| { _new: true; data: Record };\n\n/**\n * Represents an inverse relation (content types that reference this type via belongsTo)\n */\nexport interface InverseRelation {\n\t/** The content type slug that has the belongsTo relation */\n\tsourceType: string;\n\t/** Display name of the source content type */\n\tsourceTypeName: string;\n\t/** The field name that contains the belongsTo relation */\n\tfieldName: string;\n\t/** Count of items with this relation (when itemId is provided) */\n\tcount: number;\n}\n\n/**\n * Serialized content type for API responses (dates as strings)\n */\nexport interface SerializedContentType\n\textends Omit {\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\n/**\n * Serialized content item for API responses (dates as strings)\n */\nexport interface SerializedContentItem\n\textends Omit {\n\tcreatedAt: string;\n\tupdatedAt: string;\n\tpublishAt?: string | null;\n}\n\n/**\n * Serialized content item with parsed data and joined content type\n * @template TData - The type of the parsed data (defaults to Record)\n */\nexport interface SerializedContentItemWithType>\n\textends SerializedContentItem {\n\t/** Parsed data object (JSON.parse of data field). */\n\tparsedData: TData;\n\t/** Joined content type */\n\tcontentType?: SerializedContentType;\n\t/**\n\t * Populated relation data (only present when using populated endpoints/hooks).\n\t * Keys are field names, values are arrays of related content items.\n\t */\n\t_relations?: Record;\n}\n\n/** Output shape for CMS reads; omission retains the full editor envelope. */\nexport type CMSReadView = \"content\" | undefined;\n\n/** Literal top-level property names selected from parsed content. */\nexport type CMSContentFields = readonly string[] | undefined;\n\n/** Select known literal properties, or an honest partial shape for dynamic arrays. */\nexport type CMSSelectedData<\n\tTData,\n\tTFields extends CMSContentFields = undefined,\n> = TFields extends readonly string[]\n\t? string extends TFields[number]\n\t\t? Partial\n\t\t: Pick>\n\t: TData;\n\n/** Optional output controls for CMS reads. These do not change access checks. */\nexport interface CMSReadOptions<\n\tTView extends CMSReadView = CMSReadView,\n\tTFields extends CMSContentFields = CMSContentFields,\n> {\n\t/** Return identity, parsed content and timestamps without editor metadata. */\n\tview?: TView;\n\t/** Literal declared top-level content properties. Requires content view. */\n\tfields?: TFields;\n}\n\n/** Serialized content envelope without raw JSON or editor metadata. */\nexport type SerializedContentItemContent> =\n\tPick<\n\t\tSerializedContentItemWithType,\n\t\t\"id\" | \"slug\" | \"parsedData\" | \"createdAt\" | \"updatedAt\"\n\t>;\n\n/** Result envelope selected by a statically known read view. */\nexport type CMSContentItemResult<\n\tTData = Record,\n\tTView extends CMSReadView = undefined,\n\tTFields extends CMSContentFields = undefined,\n> = TView extends \"content\"\n\t? SerializedContentItemContent>\n\t: SerializedContentItemWithType;\n\n/**\n * Paginated list response for content items\n * @template TData - The type of the parsed data (defaults to Record)\n */\nexport interface PaginatedContentItems<\n\tTData = Record,\n\tTView extends CMSReadView = undefined,\n\tTFields extends CMSContentFields = undefined,\n> {\n\titems: CMSContentItemResult[];\n\ttotal: number;\n\tlimit: number;\n\toffset: number;\n}\n\n/**\n * Type helper to define a map of content type slugs to their data types.\n * Use with z.infer to get the type from your Zod schemas.\n *\n * @example\n * ```typescript\n * import { z } from \"zod\"\n *\n * // Define your schemas\n * export const ProductSchema = z.object({\n * name: z.string(),\n * price: z.number(),\n * })\n *\n * export const TestimonialSchema = z.object({\n * author: z.string(),\n * quote: z.string(),\n * })\n *\n * // Create the type map\n * export type MyCMSTypes = {\n * product: z.infer\n * testimonial: z.infer\n * }\n *\n * // Use in hooks for type-safe parsedData\n * const { items } = useContent(\"product\")\n * // items[0].parsedData.name is typed as string\n * // items[0].parsedData.price is typed as number\n * ```\n */\nexport type CMSContentTypeMap = Record>;\n\n/** JSON-safe values accepted at the CMS operation boundary. */\nexport type CMSOperationData =\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| readonly CMSOperationData[]\n\t| { readonly [key: string]: CMSOperationData };\n\n/** @deprecated Use the operation-specific CMS lifecycle contexts instead. */\nexport interface CMSHookContext {\n\treadonly typeSlug: string;\n\treadonly userId?: string;\n\treadonly headers?: Headers;\n}\n\ninterface CMSOperationIdentity {\n\treadonly id: string;\n\treadonly [key: string]: unknown;\n}\n\ntype CMSDeepReadonly = T extends (...args: any[]) => unknown\n\t? T\n\t: T extends readonly unknown[]\n\t\t? { readonly [TKey in keyof T]: CMSDeepReadonly }\n\t\t: T extends object\n\t\t\t? { readonly [TKey in keyof T]: CMSDeepReadonly }\n\t\t\t: T;\n\ninterface CMSOperationContextBase {\n\t/** Validated, deeply readonly input supplied to the operation. */\n\treadonly input: Readonly;\n\t/** Trusted server-derived facts used by the authorization rule. */\n\treadonly facts: Readonly;\n\t/** Authorized request identity, or `null` for anonymous and trusted calls. */\n\treadonly identity: Readonly | null;\n\t/** Transport request when the operation was invoked through HTTP or `forRequest()`. */\n\treadonly request?: Request;\n\t/** Compatibility view of the transport request headers. */\n\treadonly headers?: Headers;\n\t/** Compatibility alias for the authorized identity ID. */\n\treadonly userId?: string;\n\t/** Compatibility alias for the operation's CMS content-type slug. */\n\treadonly typeSlug?: string;\n}\n\n/** Authorized context supplied before a CMS record is created. */\nexport interface CMSCreateOperationContext\n\textends CMSOperationContextBase<\n\t\t{\n\t\t\treadonly typeSlug: string;\n\t\t\treadonly body: {\n\t\t\t\treadonly slug: string;\n\t\t\t\treadonly data: Readonly>;\n\t\t\t\treadonly publishAt?: string | null;\n\t\t\t};\n\t\t},\n\t\t{ contentType: string }\n\t> {\n\t/** Server-resolved content-type slug for the record being created. */\n\treadonly typeSlug: string;\n\t/** Validated create payload supplied to the operation. */\n\treadonly body: {\n\t\t/** Requested record slug before canonical slugification. */\n\t\treadonly slug: string;\n\t\t/** Validated JSON-safe request fields, including any inline `_new` relation values. */\n\t\treadonly data: Readonly>;\n\t\treadonly publishAt?: string | null;\n\t};\n}\n\n/** CMS create context after execution. */\nexport interface CMSCreateResultContext extends CMSCreateOperationContext {\n\t/** Fully serialized record returned by the successful create operation. */\n\treadonly result: CMSDeepReadonly;\n}\n\n/** Authorized context supplied before a CMS record is updated. */\nexport interface CMSUpdateOperationContext\n\textends CMSOperationContextBase<\n\t\t{\n\t\t\treadonly typeSlug: string;\n\t\t\treadonly id: string;\n\t\t\treadonly body: {\n\t\t\t\treadonly slug?: string;\n\t\t\t\treadonly data?: Readonly>;\n\t\t\t\treadonly publishAt?: string | null;\n\t\t\t};\n\t\t},\n\t\t{ contentType: string; recordId: string; authorId?: string }\n\t> {\n\t/** Server-resolved content-type slug for the record being updated. */\n\treadonly typeSlug: string;\n\t/** Canonical route parameters for the authorized record. */\n\treadonly params: { readonly typeSlug: string; readonly id: string };\n\t/** Validated partial update payload supplied to the operation. */\n\treadonly body: {\n\t\t/** Optional replacement slug before canonical slugification. */\n\t\treadonly slug?: string;\n\t\t/** Optional record-field fragment; hooks receive its merged validated result. */\n\t\treadonly data?: Readonly>;\n\t\treadonly publishAt?: string | null;\n\t};\n}\n\n/** CMS update context after execution. */\nexport interface CMSUpdateResultContext extends CMSUpdateOperationContext {\n\t/** Fully serialized record returned by the successful update operation. */\n\treadonly result: CMSDeepReadonly;\n}\n\n/** Authorized context supplied before a CMS record is deleted. */\nexport interface CMSDeleteOperationContext\n\textends CMSOperationContextBase<\n\t\t{ readonly typeSlug: string; readonly id: string },\n\t\t{ contentType: string; recordId: string; authorId?: string }\n\t> {\n\t/** Server-resolved content-type slug for the record being deleted. */\n\treadonly typeSlug: string;\n\t/** Canonical route parameters for the authorized record. */\n\treadonly params: { readonly typeSlug: string; readonly id: string };\n}\n\n/** CMS delete context after execution. */\nexport interface CMSDeleteResultContext extends CMSDeleteOperationContext {\n\t/** Successful delete result. */\n\treadonly result: { readonly success: true };\n}\n\ninterface CMSReadOperationContext\n\textends CMSOperationContextBase<\n\t\tunknown,\n\t\t{\n\t\t\tcontentType?: string;\n\t\t\tscope?: \"collection\" | \"record\";\n\t\t\trecordId?: string;\n\t\t\tauthorId?: string;\n\t\t}\n\t> {}\n\n/** Authorized context shared by the CMS operation lifecycle hooks. */\nexport type CMSOperationLifecycleContext =\n\t| CMSReadOperationContext\n\t| CMSCreateOperationContext\n\t| CMSUpdateOperationContext\n\t| CMSDeleteOperationContext;\n\n/** Authorized lifecycle context supplied to the observational error hook. */\nexport type CMSOperationErrorContext = CMSOperationLifecycleContext & {\n\t/** Original post-authorization operation error observed by `onErrorExecuteContentOperation`. */\n\treadonly error: unknown;\n};\n\n/** Domain lifecycle hooks that run only after successful CMS authorization. */\nexport interface CMSBackendHooks {\n\t/** Runs with validated canonical record data after authorization and before any database write. */\n\tonBeforeCreateContent?: (\n\t\tdata: Readonly>,\n\t\tcontext: CMSCreateOperationContext,\n\t) => Promise | void;\n\t/** Observes the fully created record after the atomic create succeeds. */\n\tonAfterCreateContent?: (\n\t\titem: CMSDeepReadonly,\n\t\tcontext: CMSCreateResultContext,\n\t) => Promise | void;\n\t/** Runs for every update with the complete merged, validated record before any database write. */\n\tonBeforeUpdateContent?: (\n\t\tid: string,\n\t\tdata: Readonly>,\n\t\tcontext: CMSUpdateOperationContext,\n\t) => Promise | void;\n\t/** Observes the fully updated record after the atomic update succeeds. */\n\tonAfterUpdateContent?: (\n\t\titem: CMSDeepReadonly,\n\t\tcontext: CMSUpdateResultContext,\n\t) => Promise | void;\n\t/** Runs after authorization and before the record is deleted. */\n\tonBeforeDeleteContent?: (\n\t\tid: string,\n\t\tcontext: CMSDeleteOperationContext,\n\t) => Promise | void;\n\t/** Observes the deleted record ID after the atomic delete succeeds. */\n\tonAfterDeleteContent?: (\n\t\tid: string,\n\t\tcontext: CMSDeleteResultContext,\n\t) => Promise | void;\n\t/** Observes post-authorization failures without replacing the original error. */\n\tonErrorExecuteContentOperation?: (\n\t\terror: Error,\n\t\toperation: \"create\" | \"update\" | \"delete\" | \"list\" | \"get\",\n\t\tcontext: CMSOperationErrorContext,\n\t) => Promise | void;\n}\n\n/**\n * Configuration for the CMS backend plugin\n */\nexport interface CMSBackendConfig {\n\t/** Content types defined by the developer */\n\tcontentTypes: ContentTypeConfig[];\n\t/** Optional hooks for customizing behavior */\n\thooks?: CMSBackendHooks;\n\t/**\n\t * Maximum number of items that can be requested in a single page.\n\t * Applied to all list endpoints (`/content/:typeSlug`, by-relation, and inverse-relation).\n\t *\n\t * Raise this when your content types have many items and you need to fetch\n\t * large pages (e.g. for SSG, CSV export, or programmatic access).\n\t *\n\t * @default 1000\n\t */\n\tmaxPageSize?: number;\n}\n", "target": "src/components/btst/cms/types.ts" }, { @@ -56,7 +57,7 @@ { "path": "btst/cms/client/components/forms/content-form.tsx", "type": "registry:component", - "content": "\"use client\";\n\nimport { useState, useMemo, useEffect, useRef } from \"react\";\nimport { z } from \"zod\";\nimport type { FieldPath, FieldValues, UseFormReturn } from \"react-hook-form\";\nimport { SteppedAutoForm } from \"@/components/ui/auto-form/stepped-auto-form\";\nimport type {\n\tFieldConfig,\n\tAutoFormInputComponentProps,\n} from \"@/components/ui/auto-form/types\";\nimport { buildFieldConfigFromJsonSchema as buildFieldConfigBase } from \"@/components/ui/auto-form/helpers\";\nimport { formSchemaToZod } from \"@/lib/schema-converter\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Badge } from \"@/components/ui/badge\";\nimport { usePluginOverrides, useTranslate } from \"@btst/stack/context\";\nimport type { CMSPluginOverrides } from \"../../overrides\";\nimport { CMS_PLUGIN_ID } from \"../../constants\";\nimport type { SerializedContentType, RelationConfig } from \"../../../types\";\nimport { slugify } from \"../../../utils\";\nimport { CMSFileUpload } from \"./file-upload\";\nimport { RelationField } from \"./relation-field\";\n\ninterface ContentFormProps {\n\tcontentType: SerializedContentType;\n\tinitialData?: Record;\n\tinitialSlug?: string;\n\tisEditing?: boolean;\n\tonSubmit: (data: {\n\t\tslug: string;\n\t\tdata: Record;\n\t}) => Promise;\n\tonCancel?: () => void;\n\t/**\n\t * Server-side field validation errors (`StackError.errors`), applied to\n\t * the matching form fields for inline display.\n\t */\n\tfieldErrors?: Record;\n\t/** Non-field submit error to display above the form */\n\terrorMessage?: string;\n\t/** External submit-in-flight state (e.g. from a resource `useForm`) */\n\tisSubmitting?: boolean;\n}\n\n/**\n * Applies server-side field validation errors onto react-hook-form field\n * state, and clears previously applied server errors that are no longer\n * present. The form instance arrives asynchronously (captured from\n * SteppedAutoForm's `onValuesChange`) and is `null` for multi-step forms.\n */\nfunction useServerFieldErrors(\n\tform: UseFormReturn | null,\n\tfieldErrors: Record,\n) {\n\tconst appliedFieldsRef = useRef([]);\n\n\tuseEffect(() => {\n\t\tif (!form) return;\n\n\t\t// Clear stale server errors from fields that are no longer failing\n\t\tfor (const field of appliedFieldsRef.current) {\n\t\t\tif (field in fieldErrors) continue;\n\t\t\tconst { error } = form.getFieldState(field as FieldPath);\n\t\t\tif (error?.type === \"server\") {\n\t\t\t\tform.clearErrors(field as FieldPath);\n\t\t\t}\n\t\t}\n\t\tappliedFieldsRef.current = Object.keys(fieldErrors);\n\n\t\tfor (const [field, message] of Object.entries(fieldErrors)) {\n\t\t\tform.setError(field as FieldPath, {\n\t\t\t\ttype: \"server\",\n\t\t\t\tmessage: Array.isArray(message) ? message.join(\", \") : message,\n\t\t\t});\n\t\t}\n\t}, [fieldErrors, form]);\n}\n\n/**\n * Build field configuration for AutoForm with CMS-specific file upload handling.\n *\n * Uses the shared buildFieldConfigFromJsonSchema from auto-form/helpers as a base,\n * then adds special handling for \"file\" fieldType to inject CMSFileUpload component\n * ONLY if no custom component is provided via fieldComponents.\n *\n * @param jsonSchema - The JSON Schema from the content type (with fieldType embedded in properties)\n * @param uploadImage - The uploadImage function from overrides (for file fields)\n * @param fieldComponents - Custom field components from overrides\n */\ninterface JsonSchemaProperty {\n\tfieldType?: string;\n\trelation?: RelationConfig;\n\t[key: string]: unknown;\n}\n\nfunction buildFieldConfigFromJsonSchema(\n\tjsonSchema: Record,\n\tuploadImage?: (file: File) => Promise,\n\tfieldComponents?: Record<\n\t\tstring,\n\t\tReact.ComponentType\n\t>,\n\timagePicker?: React.ComponentType<{ onSelect: (url: string) => void }>,\n\timageInputField?: React.ComponentType<{\n\t\tvalue: string;\n\t\tonChange: (value: string) => void;\n\t\tisRequired?: boolean;\n\t}>,\n): FieldConfig> {\n\t// Get base config from shared utility (handles fieldType from JSON Schema,\n\t// including per-item configs for arrays of objects).\n\tconst baseConfig = buildFieldConfigBase(jsonSchema, fieldComponents);\n\n\tconst properties = jsonSchema.properties as\n\t\t| Record\n\t\t| undefined;\n\n\tif (!properties) return baseConfig;\n\n\t// Recursively walk the JSON Schema properties and inject CMS-specific custom\n\t// components (file upload, relation picker) for any field with a matching\n\t// fieldType, regardless of nesting depth. Targets:\n\t// - top-level fields\n\t// - properties of nested object fields\n\t// - properties of array items (e.g. `components: z.array(z.object({...}))`)\n\t//\n\t// `targetConfig` is the FieldConfigObject slot to mutate for the property at\n\t// `key`. The recursion mirrors how AutoFormObject + AutoFormArray look up\n\t// per-property configs: nested object/array per-item configs live as keys\n\t// alongside their parent's meta on the same FieldConfigObject.\n\tconst injectCustomFieldTypes = (\n\t\tprops: Record,\n\t\ttargetConfig: Record,\n\t) => {\n\t\tfor (const [key, prop] of Object.entries(props)) {\n\t\t\t// Ensure a slot exists so we can mutate it whether or not the base\n\t\t\t// helper produced an entry for this key.\n\t\t\tconst existing =\n\t\t\t\t(targetConfig[key] as Record | undefined) ?? {};\n\n\t\t\tlet updated = existing;\n\n\t\t\t// Handle \"file\" fieldType when there's NO custom component for \"file\"\n\t\t\tif (prop.fieldType === \"file\" && !fieldComponents?.[\"file\"]) {\n\t\t\t\tif (!uploadImage && !imageInputField) {\n\t\t\t\t\tupdated = {\n\t\t\t\t\t\t...updated,\n\t\t\t\t\t\tfieldType: () => (\n\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\tFile upload requires an uploadImage or{\" \"}\n\t\t\t\t\t\t\t\timageInputField function in CMS overrides.\n\t\t\t\t\t\t\t
\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t} else {\n\t\t\t\t\tupdated = {\n\t\t\t\t\t\t...updated,\n\t\t\t\t\t\tfieldType: (componentProps: AutoFormInputComponentProps) => (\n\t\t\t\t\t\t\t Promise.resolve(\"\"))}\n\t\t\t\t\t\t\t\timageInputField={imageInputField}\n\t\t\t\t\t\t\t\timagePicker={imagePicker}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Handle \"relation\" fieldType when there's NO custom component for \"relation\"\n\t\t\tif (\n\t\t\t\tprop.fieldType === \"relation\" &&\n\t\t\t\tprop.relation &&\n\t\t\t\t!fieldComponents?.[\"relation\"]\n\t\t\t) {\n\t\t\t\tconst relationConfig = prop.relation;\n\t\t\t\tupdated = {\n\t\t\t\t\t...updated,\n\t\t\t\t\tfieldType: (componentProps: AutoFormInputComponentProps) => (\n\t\t\t\t\t\t\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Recurse into nested objects — their per-property configs live as\n\t\t\t// keys on the same parent FieldConfigObject.\n\t\t\tif (prop.properties) {\n\t\t\t\tinjectCustomFieldTypes(\n\t\t\t\t\tprop.properties as Record,\n\t\t\t\t\tupdated,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Recurse into array items — same convention as nested objects.\n\t\t\tconst items = prop.items as JsonSchemaProperty | undefined;\n\t\t\tif (items?.properties) {\n\t\t\t\tinjectCustomFieldTypes(\n\t\t\t\t\titems.properties as Record,\n\t\t\t\t\tupdated,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (Object.keys(updated).length > 0) {\n\t\t\t\ttargetConfig[key] = updated;\n\t\t\t}\n\t\t}\n\t};\n\n\tinjectCustomFieldTypes(\n\t\tproperties,\n\t\tbaseConfig as unknown as Record,\n\t);\n\n\treturn baseConfig;\n}\n\n/**\n * Determine the first string field in the schema for slug auto-generation\n */\nfunction findSlugSourceField(\n\tjsonSchema: Record,\n): string | null {\n\tconst properties = jsonSchema.properties as Record;\n\tif (!properties) return null;\n\n\t// Look for common name fields first\n\tconst priorityFields = [\"name\", \"title\", \"heading\", \"label\"];\n\tfor (const field of priorityFields) {\n\t\tif (properties[field]?.type === \"string\") {\n\t\t\treturn field;\n\t\t}\n\t}\n\n\t// Fall back to first string field\n\tfor (const [key, value] of Object.entries(properties)) {\n\t\tif (value.type === \"string\") {\n\t\t\treturn key;\n\t\t}\n\t}\n\n\treturn null;\n}\n\nexport function ContentForm({\n\tcontentType,\n\tinitialData = {},\n\tinitialSlug = \"\",\n\tisEditing = false,\n\tonSubmit,\n\tonCancel,\n\tfieldErrors,\n\terrorMessage,\n\tisSubmitting: isSubmittingProp,\n}: ContentFormProps) {\n\tconst t = useTranslate();\n\tconst {\n\t\tlocalization,\n\t\tuploadImage,\n\t\timagePicker,\n\t\timageInputField,\n\t\tfieldComponents,\n\t} = usePluginOverrides(CMS_PLUGIN_ID);\n\n\tconst [slug, setSlug] = useState(initialSlug);\n\tconst [slugManuallyEdited, setSlugManuallyEdited] = useState(isEditing);\n\tconst [isSubmittingLocal, setIsSubmittingLocal] = useState(false);\n\tconst [formData, setFormData] =\n\t\tuseState>(initialData);\n\tconst [slugError, setSlugError] = useState(null);\n\tconst [submitError, setSubmitError] = useState(null);\n\n\tconst isSubmitting = isSubmittingProp || isSubmittingLocal;\n\n\t// Single-step forms pass their react-hook-form instance through\n\t// onValuesChange; multi-step forms pass undefined (no single instance).\n\tconst [formInstance, setFormInstance] = useState\n\t> | null>(null);\n\n\tconst serverFieldErrors = useMemo(() => fieldErrors ?? {}, [fieldErrors]);\n\tuseServerFieldErrors(formInstance, serverFieldErrors);\n\tconst hasFieldErrors = Object.keys(serverFieldErrors).length > 0;\n\n\t// Track if we've already synced prefill data to avoid overwriting user input\n\tconst hasSyncedPrefillRef = useRef(false);\n\n\t// Sync formData with initialData when it changes\n\t// This handles both:\n\t// 1. Editing mode: always sync when item data is loaded (isEditing=true)\n\t// 2. Create mode: only sync prefill data ONCE to avoid overwriting user input\n\t// useState only uses the initial value on mount, so we need this effect for updates\n\tuseEffect(() => {\n\t\tconst hasData = Object.keys(initialData).length > 0;\n\t\t// In edit mode, always sync (user is loading existing data)\n\t\t// In create mode, only sync prefill data once\n\t\tconst shouldSync = hasData && (isEditing || !hasSyncedPrefillRef.current);\n\n\t\tif (shouldSync) {\n\t\t\tsetFormData(initialData);\n\t\t\tif (!isEditing) {\n\t\t\t\thasSyncedPrefillRef.current = true;\n\t\t\t}\n\t\t}\n\t}, [initialData, isEditing]);\n\n\t// Also sync slug when initialSlug changes\n\tuseEffect(() => {\n\t\tif (isEditing && initialSlug) {\n\t\t\tsetSlug(initialSlug);\n\t\t}\n\t}, [initialSlug, isEditing]);\n\n\t// Parse JSON Schema (now includes fieldType embedded in properties)\n\tconst jsonSchema = useMemo(() => {\n\t\ttry {\n\t\t\treturn JSON.parse(contentType.jsonSchema) as Record;\n\t\t} catch {\n\t\t\treturn {};\n\t\t}\n\t}, [contentType.jsonSchema]);\n\n\t// Convert JSON Schema to Zod schema using formSchemaToZod utility\n\t// This properly handles date fields (format: \"date-time\") and min/max date constraints\n\tconst zodSchema = useMemo(() => {\n\t\ttry {\n\t\t\treturn formSchemaToZod(jsonSchema);\n\t\t} catch {\n\t\t\treturn z.object({});\n\t\t}\n\t}, [jsonSchema]);\n\n\t// Build field config for AutoForm (fieldType is now embedded in jsonSchema)\n\tconst fieldConfig = useMemo(\n\t\t() =>\n\t\t\tbuildFieldConfigFromJsonSchema(\n\t\t\t\tjsonSchema,\n\t\t\t\tuploadImage,\n\t\t\t\tfieldComponents,\n\t\t\t\timagePicker,\n\t\t\t\timageInputField,\n\t\t\t),\n\t\t[jsonSchema, uploadImage, fieldComponents, imagePicker, imageInputField],\n\t);\n\n\t// Find the field to use for slug auto-generation\n\tconst slugSourceField = useMemo(\n\t\t() => findSlugSourceField(jsonSchema),\n\t\t[jsonSchema],\n\t);\n\n\t// Handle form value changes for slug auto-generation\n\tconst handleValuesChange = (\n\t\tvalues: Record,\n\t\tform?: UseFormReturn>,\n\t) => {\n\t\tif (form) {\n\t\t\tsetFormInstance((current) => (current === form ? current : form));\n\t\t}\n\t\tsetFormData(values);\n\n\t\t// Auto-generate slug from source field if not manually edited\n\t\tif (!isEditing && !slugManuallyEdited && slugSourceField) {\n\t\t\tconst sourceValue = values[slugSourceField];\n\t\t\tif (typeof sourceValue === \"string\" && sourceValue.trim()) {\n\t\t\t\tsetSlug(slugify(sourceValue));\n\t\t\t}\n\t\t}\n\t};\n\n\t// Handle form submission\n\tconst handleSubmit = async (data: Record) => {\n\t\tsetSlugError(null);\n\t\tsetSubmitError(null);\n\n\t\tif (!slug.trim()) {\n\t\t\tsetSlugError(\n\t\t\t\tlocalization?.CMS_EDITOR_SLUG_REQUIRED ??\n\t\t\t\t\tt(\"cms.editor.slugRequired\", \"Slug is required\"),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tsetIsSubmittingLocal(true);\n\t\ttry {\n\t\t\tawait onSubmit({ slug, data });\n\t\t} catch (error) {\n\t\t\tconst message =\n\t\t\t\terror instanceof Error\n\t\t\t\t\t? error.message\n\t\t\t\t\t: (localization?.CMS_TOAST_ERROR ??\n\t\t\t\t\t\tt(\"cms.toasts.error\", \"An error occurred. Please try again.\"));\n\t\t\tsetSubmitError(message);\n\t\t} finally {\n\t\t\tsetIsSubmittingLocal(false);\n\t\t}\n\t};\n\n\t// Non-field error from the parent (resource form), or a local submit\n\t// failure. Field errors display inline instead — unless the form\n\t// instance is unavailable (multi-step), where they land in the banner.\n\tconst bannerMessage =\n\t\terrorMessage ??\n\t\tsubmitError ??\n\t\t(hasFieldErrors && !formInstance\n\t\t\t? Object.entries(serverFieldErrors)\n\t\t\t\t\t.map(\n\t\t\t\t\t\t([field, message]) =>\n\t\t\t\t\t\t\t`${field}: ${Array.isArray(message) ? message.join(\", \") : message}`,\n\t\t\t\t\t)\n\t\t\t\t\t.join(\" · \")\n\t\t\t: undefined);\n\n\treturn (\n\t\t
\n\t\t\t{/* Slug field */}\n\t\t\t
\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t\t{!isEditing && (\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t{slugManuallyEdited\n\t\t\t\t\t\t\t\t? (localization?.CMS_EDITOR_SLUG_MANUAL ??\n\t\t\t\t\t\t\t\t\tt(\"cms.editor.slugManual\", \"Manually set\"))\n\t\t\t\t\t\t\t\t: (localization?.CMS_EDITOR_SLUG_AUTO ??\n\t\t\t\t\t\t\t\t\tt(\"cms.editor.slugAuto\", \"Auto-generated from first field\"))}\n\t\t\t\t\t\t\n\t\t\t\t\t)}\n\t\t\t\t
\n\t\t\t\t {\n\t\t\t\t\t\tsetSlug(e.target.value);\n\t\t\t\t\t\tsetSlugError(null);\n\t\t\t\t\t\tif (!isEditing) {\n\t\t\t\t\t\t\tsetSlugManuallyEdited(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}}\n\t\t\t\t\tdisabled={isEditing}\n\t\t\t\t\tplaceholder={\n\t\t\t\t\t\tslugSourceField\n\t\t\t\t\t\t\t? (\n\t\t\t\t\t\t\t\t\tlocalization?.CMS_EDITOR_SLUG_PLACEHOLDER_AUTO ??\n\t\t\t\t\t\t\t\t\tt(\n\t\t\t\t\t\t\t\t\t\t\"cms.editor.slugPlaceholderAuto\",\n\t\t\t\t\t\t\t\t\t\t\"Auto-generated from {field}\",\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t).replace(\"{field}\", slugSourceField)\n\t\t\t\t\t\t\t: (localization?.CMS_EDITOR_SLUG_PLACEHOLDER ??\n\t\t\t\t\t\t\t\tt(\"cms.editor.slugPlaceholder\", \"Enter slug...\"))\n\t\t\t\t\t}\n\t\t\t\t/>\n\t\t\t\t{slugError &&

{slugError}

}\n\t\t\t\t

\n\t\t\t\t\t{localization?.CMS_LABEL_SLUG_DESCRIPTION ??\n\t\t\t\t\t\tt(\n\t\t\t\t\t\t\t\"cms.common.slugDescription\",\n\t\t\t\t\t\t\t\"URL-friendly identifier for this item\",\n\t\t\t\t\t\t)}\n\t\t\t\t

\n\t\t\t
\n\n\t\t\t{/* Submit error message */}\n\t\t\t{bannerMessage && (\n\t\t\t\t
\n\t\t\t\t\t

{bannerMessage}

\n\t\t\t\t
\n\t\t\t)}\n\n\t\t\t{/* Dynamic form from Zod schema */}\n\t\t\t{/* Uses SteppedAutoForm which automatically handles both single-step and multi-step content types */}\n\t\t\t}\n\t\t\t\tvalues={formData as any}\n\t\t\t\tonValuesChange={handleValuesChange as any}\n\t\t\t\tonSubmit={handleSubmit as any}\n\t\t\t\tfieldConfig={fieldConfig as any}\n\t\t\t\tisSubmitting={isSubmitting}\n\t\t\t\tsubmitButtonText={\n\t\t\t\t\tisSubmitting\n\t\t\t\t\t\t? (localization?.CMS_STATUS_SAVING ??\n\t\t\t\t\t\t\tt(\"cms.common.saving\", \"Saving...\"))\n\t\t\t\t\t\t: (localization?.CMS_BUTTON_SAVE ?? t(\"cms.common.save\", \"Save\"))\n\t\t\t\t}\n\t\t\t>\n\t\t\t\t{onCancel && (\n\t\t\t\t\t\n\t\t\t\t\t\t{localization?.CMS_BUTTON_CANCEL ??\n\t\t\t\t\t\t\tt(\"cms.common.cancel\", \"Cancel\")}\n\t\t\t\t\t\n\t\t\t\t)}\n\t\t\t\n\t\t
\n\t);\n}\n", + "content": "\"use client\";\n\nimport { useState, useMemo, useEffect, useRef } from \"react\";\nimport { z } from \"zod\";\nimport type { FieldPath, FieldValues, UseFormReturn } from \"react-hook-form\";\nimport { SteppedAutoForm } from \"@/components/ui/auto-form/stepped-auto-form\";\nimport type {\n\tFieldConfig,\n\tAutoFormInputComponentProps,\n} from \"@/components/ui/auto-form/types\";\nimport { buildFieldConfigFromJsonSchema as buildFieldConfigBase } from \"@/components/ui/auto-form/helpers\";\nimport { formSchemaToZod } from \"@/lib/schema-converter\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Badge } from \"@/components/ui/badge\";\nimport { usePluginOverrides, useTranslate } from \"@btst/stack/context\";\nimport type { CMSPluginOverrides } from \"../../overrides\";\nimport { CMS_PLUGIN_ID } from \"../../constants\";\nimport type { SerializedContentType, RelationConfig } from \"../../../types\";\nimport { slugify } from \"../../../utils\";\nimport { CMSFileUpload } from \"./file-upload\";\nimport { RelationField } from \"./relation-field\";\n\ninterface ContentFormProps {\n\tcontentType: SerializedContentType;\n\tinitialData?: Record;\n\tinitialSlug?: string;\n\tinitialPublishAt?: string | null;\n\tisEditing?: boolean;\n\tonSubmit: (data: {\n\t\tslug: string;\n\t\tdata: Record;\n\t\tpublishAt?: string | null;\n\t}) => Promise;\n\tonCancel?: () => void;\n\t/**\n\t * Server-side field validation errors (`StackError.errors`), applied to\n\t * the matching form fields for inline display.\n\t */\n\tfieldErrors?: Record;\n\t/** Non-field submit error to display above the form */\n\terrorMessage?: string;\n\t/** External submit-in-flight state (e.g. from a resource `useForm`) */\n\tisSubmitting?: boolean;\n}\n\n/**\n * Applies server-side field validation errors onto react-hook-form field\n * state, and clears previously applied server errors that are no longer\n * present. The form instance arrives asynchronously (captured from\n * SteppedAutoForm's `onValuesChange`) and is `null` for multi-step forms.\n */\nfunction useServerFieldErrors(\n\tform: UseFormReturn | null,\n\tfieldErrors: Record,\n) {\n\tconst appliedFieldsRef = useRef([]);\n\n\tuseEffect(() => {\n\t\tif (!form) return;\n\n\t\t// Clear stale server errors from fields that are no longer failing\n\t\tfor (const field of appliedFieldsRef.current) {\n\t\t\tif (field in fieldErrors) continue;\n\t\t\tconst { error } = form.getFieldState(field as FieldPath);\n\t\t\tif (error?.type === \"server\") {\n\t\t\t\tform.clearErrors(field as FieldPath);\n\t\t\t}\n\t\t}\n\t\tappliedFieldsRef.current = Object.keys(fieldErrors);\n\n\t\tfor (const [field, message] of Object.entries(fieldErrors)) {\n\t\t\tform.setError(field as FieldPath, {\n\t\t\t\ttype: \"server\",\n\t\t\t\tmessage: Array.isArray(message) ? message.join(\", \") : message,\n\t\t\t});\n\t\t}\n\t}, [fieldErrors, form]);\n}\n\n/**\n * Build field configuration for AutoForm with CMS-specific file upload handling.\n *\n * Uses the shared buildFieldConfigFromJsonSchema from auto-form/helpers as a base,\n * then adds special handling for \"file\" fieldType to inject CMSFileUpload component\n * ONLY if no custom component is provided via fieldComponents.\n *\n * @param jsonSchema - The JSON Schema from the content type (with fieldType embedded in properties)\n * @param uploadImage - The uploadImage function from overrides (for file fields)\n * @param fieldComponents - Custom field components from overrides\n */\ninterface JsonSchemaProperty {\n\tfieldType?: string;\n\trelation?: RelationConfig;\n\t[key: string]: unknown;\n}\n\nfunction buildFieldConfigFromJsonSchema(\n\tjsonSchema: Record,\n\tuploadImage?: (file: File) => Promise,\n\tfieldComponents?: Record<\n\t\tstring,\n\t\tReact.ComponentType\n\t>,\n\timagePicker?: React.ComponentType<{ onSelect: (url: string) => void }>,\n\timageInputField?: React.ComponentType<{\n\t\tvalue: string;\n\t\tonChange: (value: string) => void;\n\t\tisRequired?: boolean;\n\t}>,\n): FieldConfig> {\n\t// Get base config from shared utility (handles fieldType from JSON Schema,\n\t// including per-item configs for arrays of objects).\n\tconst baseConfig = buildFieldConfigBase(jsonSchema, fieldComponents);\n\n\tconst properties = jsonSchema.properties as\n\t\t| Record\n\t\t| undefined;\n\n\tif (!properties) return baseConfig;\n\n\t// Recursively walk the JSON Schema properties and inject CMS-specific custom\n\t// components (file upload, relation picker) for any field with a matching\n\t// fieldType, regardless of nesting depth. Targets:\n\t// - top-level fields\n\t// - properties of nested object fields\n\t// - properties of array items (e.g. `components: z.array(z.object({...}))`)\n\t//\n\t// `targetConfig` is the FieldConfigObject slot to mutate for the property at\n\t// `key`. The recursion mirrors how AutoFormObject + AutoFormArray look up\n\t// per-property configs: nested object/array per-item configs live as keys\n\t// alongside their parent's meta on the same FieldConfigObject.\n\tconst injectCustomFieldTypes = (\n\t\tprops: Record,\n\t\ttargetConfig: Record,\n\t) => {\n\t\tfor (const [key, prop] of Object.entries(props)) {\n\t\t\t// Ensure a slot exists so we can mutate it whether or not the base\n\t\t\t// helper produced an entry for this key.\n\t\t\tconst existing =\n\t\t\t\t(targetConfig[key] as Record | undefined) ?? {};\n\n\t\t\tlet updated = existing;\n\n\t\t\t// Handle \"file\" fieldType when there's NO custom component for \"file\"\n\t\t\tif (prop.fieldType === \"file\" && !fieldComponents?.[\"file\"]) {\n\t\t\t\tif (!uploadImage && !imageInputField) {\n\t\t\t\t\tupdated = {\n\t\t\t\t\t\t...updated,\n\t\t\t\t\t\tfieldType: () => (\n\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\tFile upload requires an uploadImage or{\" \"}\n\t\t\t\t\t\t\t\timageInputField function in CMS overrides.\n\t\t\t\t\t\t\t
\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t} else {\n\t\t\t\t\tupdated = {\n\t\t\t\t\t\t...updated,\n\t\t\t\t\t\tfieldType: (componentProps: AutoFormInputComponentProps) => (\n\t\t\t\t\t\t\t Promise.resolve(\"\"))}\n\t\t\t\t\t\t\t\timageInputField={imageInputField}\n\t\t\t\t\t\t\t\timagePicker={imagePicker}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Handle \"relation\" fieldType when there's NO custom component for \"relation\"\n\t\t\tif (\n\t\t\t\tprop.fieldType === \"relation\" &&\n\t\t\t\tprop.relation &&\n\t\t\t\t!fieldComponents?.[\"relation\"]\n\t\t\t) {\n\t\t\t\tconst relationConfig = prop.relation;\n\t\t\t\tupdated = {\n\t\t\t\t\t...updated,\n\t\t\t\t\tfieldType: (componentProps: AutoFormInputComponentProps) => (\n\t\t\t\t\t\t\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Recurse into nested objects — their per-property configs live as\n\t\t\t// keys on the same parent FieldConfigObject.\n\t\t\tif (prop.properties) {\n\t\t\t\tinjectCustomFieldTypes(\n\t\t\t\t\tprop.properties as Record,\n\t\t\t\t\tupdated,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Recurse into array items — same convention as nested objects.\n\t\t\tconst items = prop.items as JsonSchemaProperty | undefined;\n\t\t\tif (items?.properties) {\n\t\t\t\tinjectCustomFieldTypes(\n\t\t\t\t\titems.properties as Record,\n\t\t\t\t\tupdated,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (Object.keys(updated).length > 0) {\n\t\t\t\ttargetConfig[key] = updated;\n\t\t\t}\n\t\t}\n\t};\n\n\tinjectCustomFieldTypes(\n\t\tproperties,\n\t\tbaseConfig as unknown as Record,\n\t);\n\n\treturn baseConfig;\n}\n\n/**\n * Determine the first string field in the schema for slug auto-generation\n */\nfunction findSlugSourceField(\n\tjsonSchema: Record,\n): string | null {\n\tconst properties = jsonSchema.properties as Record;\n\tif (!properties) return null;\n\n\t// Look for common name fields first\n\tconst priorityFields = [\"name\", \"title\", \"heading\", \"label\"];\n\tfor (const field of priorityFields) {\n\t\tif (properties[field]?.type === \"string\") {\n\t\t\treturn field;\n\t\t}\n\t}\n\n\t// Fall back to first string field\n\tfor (const [key, value] of Object.entries(properties)) {\n\t\tif (value.type === \"string\") {\n\t\t\treturn key;\n\t\t}\n\t}\n\n\treturn null;\n}\n\nexport function ContentForm({\n\tcontentType,\n\tinitialData = {},\n\tinitialSlug = \"\",\n\tinitialPublishAt,\n\tisEditing = false,\n\tonSubmit,\n\tonCancel,\n\tfieldErrors,\n\terrorMessage,\n\tisSubmitting: isSubmittingProp,\n}: ContentFormProps) {\n\tconst t = useTranslate();\n\tconst {\n\t\tlocalization,\n\t\tuploadImage,\n\t\timagePicker,\n\t\timageInputField,\n\t\tfieldComponents,\n\t} = usePluginOverrides(CMS_PLUGIN_ID);\n\n\tconst [slug, setSlug] = useState(initialSlug);\n\tconst [publishAt, setPublishAt] = useState(() => {\n\t\tif (!initialPublishAt) return \"\";\n\t\tconst date = new Date(initialPublishAt);\n\t\treturn new Date(date.getTime() - date.getTimezoneOffset() * 60_000)\n\t\t\t.toISOString()\n\t\t\t.slice(0, 16);\n\t});\n\tconst [slugManuallyEdited, setSlugManuallyEdited] = useState(isEditing);\n\tconst [isSubmittingLocal, setIsSubmittingLocal] = useState(false);\n\tconst [formData, setFormData] =\n\t\tuseState>(initialData);\n\tconst [slugError, setSlugError] = useState(null);\n\tconst [submitError, setSubmitError] = useState(null);\n\n\tconst isSubmitting = isSubmittingProp || isSubmittingLocal;\n\n\t// Single-step forms pass their react-hook-form instance through\n\t// onValuesChange; multi-step forms pass undefined (no single instance).\n\tconst [formInstance, setFormInstance] = useState\n\t> | null>(null);\n\n\tconst serverFieldErrors = useMemo(() => fieldErrors ?? {}, [fieldErrors]);\n\tuseServerFieldErrors(formInstance, serverFieldErrors);\n\tconst hasFieldErrors = Object.keys(serverFieldErrors).length > 0;\n\n\t// Track if we've already synced prefill data to avoid overwriting user input\n\tconst hasSyncedPrefillRef = useRef(false);\n\n\t// Sync formData with initialData when it changes\n\t// This handles both:\n\t// 1. Editing mode: always sync when item data is loaded (isEditing=true)\n\t// 2. Create mode: only sync prefill data ONCE to avoid overwriting user input\n\t// useState only uses the initial value on mount, so we need this effect for updates\n\tuseEffect(() => {\n\t\tconst hasData = Object.keys(initialData).length > 0;\n\t\t// In edit mode, always sync (user is loading existing data)\n\t\t// In create mode, only sync prefill data once\n\t\tconst shouldSync = hasData && (isEditing || !hasSyncedPrefillRef.current);\n\n\t\tif (shouldSync) {\n\t\t\tsetFormData(initialData);\n\t\t\tif (!isEditing) {\n\t\t\t\thasSyncedPrefillRef.current = true;\n\t\t\t}\n\t\t}\n\t}, [initialData, isEditing]);\n\n\t// Also sync slug when initialSlug changes\n\tuseEffect(() => {\n\t\tif (isEditing && initialSlug) {\n\t\t\tsetSlug(initialSlug);\n\t\t}\n\t}, [initialSlug, isEditing]);\n\n\t// Parse JSON Schema (now includes fieldType embedded in properties)\n\tconst jsonSchema = useMemo(() => {\n\t\ttry {\n\t\t\treturn JSON.parse(contentType.jsonSchema) as Record;\n\t\t} catch {\n\t\t\treturn {};\n\t\t}\n\t}, [contentType.jsonSchema]);\n\n\t// Convert JSON Schema to Zod schema using formSchemaToZod utility\n\t// This properly handles date fields (format: \"date-time\") and min/max date constraints\n\tconst zodSchema = useMemo(() => {\n\t\ttry {\n\t\t\treturn formSchemaToZod(jsonSchema);\n\t\t} catch {\n\t\t\treturn z.object({});\n\t\t}\n\t}, [jsonSchema]);\n\n\t// Build field config for AutoForm (fieldType is now embedded in jsonSchema)\n\tconst fieldConfig = useMemo(\n\t\t() =>\n\t\t\tbuildFieldConfigFromJsonSchema(\n\t\t\t\tjsonSchema,\n\t\t\t\tuploadImage,\n\t\t\t\tfieldComponents,\n\t\t\t\timagePicker,\n\t\t\t\timageInputField,\n\t\t\t),\n\t\t[jsonSchema, uploadImage, fieldComponents, imagePicker, imageInputField],\n\t);\n\n\t// Find the field to use for slug auto-generation\n\tconst slugSourceField = useMemo(\n\t\t() => findSlugSourceField(jsonSchema),\n\t\t[jsonSchema],\n\t);\n\n\t// Handle form value changes for slug auto-generation\n\tconst handleValuesChange = (\n\t\tvalues: Record,\n\t\tform?: UseFormReturn>,\n\t) => {\n\t\tif (form) {\n\t\t\tsetFormInstance((current) => (current === form ? current : form));\n\t\t}\n\t\tsetFormData(values);\n\n\t\t// Auto-generate slug from source field if not manually edited\n\t\tif (!isEditing && !slugManuallyEdited && slugSourceField) {\n\t\t\tconst sourceValue = values[slugSourceField];\n\t\t\tif (typeof sourceValue === \"string\" && sourceValue.trim()) {\n\t\t\t\tsetSlug(slugify(sourceValue));\n\t\t\t}\n\t\t}\n\t};\n\n\t// Handle form submission\n\tconst handleSubmit = async (data: Record) => {\n\t\tsetSlugError(null);\n\t\tsetSubmitError(null);\n\n\t\tif (!slug.trim()) {\n\t\t\tsetSlugError(\n\t\t\t\tlocalization?.CMS_EDITOR_SLUG_REQUIRED ??\n\t\t\t\t\tt(\"cms.editor.slugRequired\", \"Slug is required\"),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tsetIsSubmittingLocal(true);\n\t\ttry {\n\t\t\tawait onSubmit({\n\t\t\t\tslug,\n\t\t\t\tdata,\n\t\t\t\tpublishAt: publishAt ? new Date(publishAt).toISOString() : null,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst message =\n\t\t\t\terror instanceof Error\n\t\t\t\t\t? error.message\n\t\t\t\t\t: (localization?.CMS_TOAST_ERROR ??\n\t\t\t\t\t\tt(\"cms.toasts.error\", \"An error occurred. Please try again.\"));\n\t\t\tsetSubmitError(message);\n\t\t} finally {\n\t\t\tsetIsSubmittingLocal(false);\n\t\t}\n\t};\n\n\t// Non-field error from the parent (resource form), or a local submit\n\t// failure. Field errors display inline instead — unless the form\n\t// instance is unavailable (multi-step), where they land in the banner.\n\tconst bannerMessage =\n\t\terrorMessage ??\n\t\tsubmitError ??\n\t\t(hasFieldErrors && !formInstance\n\t\t\t? Object.entries(serverFieldErrors)\n\t\t\t\t\t.map(\n\t\t\t\t\t\t([field, message]) =>\n\t\t\t\t\t\t\t`${field}: ${Array.isArray(message) ? message.join(\", \") : message}`,\n\t\t\t\t\t)\n\t\t\t\t\t.join(\" · \")\n\t\t\t: undefined);\n\n\treturn (\n\t\t
\n\t\t\t{/* Slug field */}\n\t\t\t
\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t\t{!isEditing && (\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t{slugManuallyEdited\n\t\t\t\t\t\t\t\t? (localization?.CMS_EDITOR_SLUG_MANUAL ??\n\t\t\t\t\t\t\t\t\tt(\"cms.editor.slugManual\", \"Manually set\"))\n\t\t\t\t\t\t\t\t: (localization?.CMS_EDITOR_SLUG_AUTO ??\n\t\t\t\t\t\t\t\t\tt(\"cms.editor.slugAuto\", \"Auto-generated from first field\"))}\n\t\t\t\t\t\t\n\t\t\t\t\t)}\n\t\t\t\t
\n\t\t\t\t {\n\t\t\t\t\t\tsetSlug(e.target.value);\n\t\t\t\t\t\tsetSlugError(null);\n\t\t\t\t\t\tif (!isEditing) {\n\t\t\t\t\t\t\tsetSlugManuallyEdited(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}}\n\t\t\t\t\tdisabled={isEditing}\n\t\t\t\t\tplaceholder={\n\t\t\t\t\t\tslugSourceField\n\t\t\t\t\t\t\t? (\n\t\t\t\t\t\t\t\t\tlocalization?.CMS_EDITOR_SLUG_PLACEHOLDER_AUTO ??\n\t\t\t\t\t\t\t\t\tt(\n\t\t\t\t\t\t\t\t\t\t\"cms.editor.slugPlaceholderAuto\",\n\t\t\t\t\t\t\t\t\t\t\"Auto-generated from {field}\",\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t).replace(\"{field}\", slugSourceField)\n\t\t\t\t\t\t\t: (localization?.CMS_EDITOR_SLUG_PLACEHOLDER ??\n\t\t\t\t\t\t\t\tt(\"cms.editor.slugPlaceholder\", \"Enter slug...\"))\n\t\t\t\t\t}\n\t\t\t\t/>\n\t\t\t\t{slugError &&

{slugError}

}\n\t\t\t\t

\n\t\t\t\t\t{localization?.CMS_LABEL_SLUG_DESCRIPTION ??\n\t\t\t\t\t\tt(\n\t\t\t\t\t\t\t\"cms.common.slugDescription\",\n\t\t\t\t\t\t\t\"URL-friendly identifier for this item\",\n\t\t\t\t\t\t)}\n\t\t\t\t

\n\t\t\t
\n\n\t\t\t
\n\t\t\t\t\n\t\t\t\t setPublishAt(event.target.value)}\n\t\t\t\t\tdisabled={isSubmitting}\n\t\t\t\t\taria-describedby=\"publishAt-description\"\n\t\t\t\t/>\n\t\t\t\t

\n\t\t\t\t\t{t(\n\t\t\t\t\t\t\"cms.editor.publishAtDescription\",\n\t\t\t\t\t\t\"Optional. Uses your local time zone. Leave empty to clear the schedule.\",\n\t\t\t\t\t)}\n\t\t\t\t

\n\t\t\t\t{serverFieldErrors.publishAt && (\n\t\t\t\t\t

\n\t\t\t\t\t\t{serverFieldErrors.publishAt}\n\t\t\t\t\t

\n\t\t\t\t)}\n\t\t\t
\n\n\t\t\t{/* Submit error message */}\n\t\t\t{bannerMessage && (\n\t\t\t\t
\n\t\t\t\t\t

{bannerMessage}

\n\t\t\t\t
\n\t\t\t)}\n\n\t\t\t{/* Dynamic form from Zod schema */}\n\t\t\t{/* Uses SteppedAutoForm which automatically handles both single-step and multi-step content types */}\n\t\t\t}\n\t\t\t\tvalues={formData as any}\n\t\t\t\tonValuesChange={handleValuesChange as any}\n\t\t\t\tonSubmit={handleSubmit as any}\n\t\t\t\tfieldConfig={fieldConfig as any}\n\t\t\t\tisSubmitting={isSubmitting}\n\t\t\t\tsubmitButtonText={\n\t\t\t\t\tisSubmitting\n\t\t\t\t\t\t? (localization?.CMS_STATUS_SAVING ??\n\t\t\t\t\t\t\tt(\"cms.common.saving\", \"Saving...\"))\n\t\t\t\t\t\t: (localization?.CMS_BUTTON_SAVE ?? t(\"cms.common.save\", \"Save\"))\n\t\t\t\t}\n\t\t\t>\n\t\t\t\t{onCancel && (\n\t\t\t\t\t\n\t\t\t\t\t\t{localization?.CMS_BUTTON_CANCEL ??\n\t\t\t\t\t\t\tt(\"cms.common.cancel\", \"Cancel\")}\n\t\t\t\t\t\n\t\t\t\t)}\n\t\t\t\n\t\t
\n\t);\n}\n", "target": "src/components/btst/cms/client/components/forms/content-form.tsx" }, { @@ -110,7 +111,7 @@ { "path": "btst/cms/client/components/pages/content-editor-page.internal.tsx", "type": "registry:component", - "content": "\"use client\";\n\nimport { useState, useEffect } from \"react\";\nimport { ArrowLeft } from \"lucide-react\";\nimport { Button } from \"@/components/ui/button\";\nimport {\n\tjoinBasePath,\n\tusePluginOverrides,\n\tuseStack,\n\tuseTranslate,\n} from \"@btst/stack/context\";\nimport { orderCMSContentTypes, type CMSPluginOverrides } from \"../../overrides\";\nimport { CMS_PLUGIN_ID } from \"../../constants\";\nimport {\n\tuseSuspenseContentTypes,\n\tuseContentItem,\n\tuseContentItemForm,\n} from \"@btst/plugin-cms/client/hooks\";\nimport { ContentForm } from \"../forms/content-form\";\nimport { InverseRelationsPanel } from \"../inverse-relations-panel\";\nimport { EmptyState } from \"../shared/empty-state\";\nimport { PageWrapper } from \"../shared/page-wrapper\";\nimport { EditorSkeleton } from \"../loading/editor-skeleton\";\nimport { useRouteLifecycle } from \"@/hooks/use-route-lifecycle\";\n\n/**\n * Parse prefill query parameters from the URL.\n * Looks for query params with the format `prefill_=`\n * and returns a record of field names to values.\n *\n * Uses useState + useEffect pattern to work correctly with SSR/hydration.\n * During SSR, returns empty object. After hydration, parses URL params.\n * Also listens for popstate events to handle browser back/forward navigation.\n *\n * @example\n * URL: /cms/comment/new?prefill_resourceId=123&prefill_author=John\n * Returns: { resourceId: \"123\", author: \"John\" }\n */\nfunction usePrefillParams(): Record {\n\tconst [prefillData, setPrefillData] = useState>({});\n\n\tuseEffect(() => {\n\t\tif (typeof window === \"undefined\") {\n\t\t\treturn;\n\t\t}\n\n\t\tconst parseAndSetPrefillData = () => {\n\t\t\tconst params = new URLSearchParams(window.location.search);\n\t\t\tconst data: Record = {};\n\n\t\t\tfor (const [key, value] of params.entries()) {\n\t\t\t\tif (key.startsWith(\"prefill_\")) {\n\t\t\t\t\tconst fieldName = key.slice(\"prefill_\".length);\n\t\t\t\t\tif (fieldName) {\n\t\t\t\t\t\tdata[fieldName] = value;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Always update state to ensure stale data is cleared when navigating\n\t\t\t// to a URL without prefill params (e.g., via browser back/forward)\n\t\t\tsetPrefillData(data);\n\t\t};\n\n\t\t// Parse on mount\n\t\tparseAndSetPrefillData();\n\n\t\t// Listen for popstate events (browser back/forward navigation)\n\t\twindow.addEventListener(\"popstate\", parseAndSetPrefillData);\n\n\t\treturn () => {\n\t\t\twindow.removeEventListener(\"popstate\", parseAndSetPrefillData);\n\t\t};\n\t}, []);\n\n\treturn prefillData;\n}\n\ninterface JsonSchemaProperty {\n\tfieldType?: string;\n\trelation?: {\n\t\ttype: \"belongsTo\" | \"hasMany\" | \"manyToMany\";\n\t\ttargetType: string;\n\t};\n}\n\n/**\n * Convert prefill params to the correct format for the form.\n * Relation fields need special handling:\n * - belongsTo: value should be { id: \"uuid\" }\n * - hasMany/manyToMany: value should be [{ id: \"uuid\" }]\n *\n * @param prefillParams - Raw prefill params from URL\n * @param jsonSchema - The content type's JSON schema\n * @returns Converted data suitable for initialData\n */\nfunction convertPrefillToFormData(\n\tprefillParams: Record,\n\tjsonSchema: Record,\n): Record {\n\tconst properties = jsonSchema.properties as\n\t\t| Record\n\t\t| undefined;\n\n\tif (!properties) {\n\t\treturn prefillParams;\n\t}\n\n\tconst result: Record = {};\n\n\tfor (const [fieldName, value] of Object.entries(prefillParams)) {\n\t\tconst fieldSchema = properties[fieldName];\n\n\t\tif (fieldSchema?.fieldType === \"relation\" && fieldSchema.relation) {\n\t\t\t// Convert relation field value to the correct format\n\t\t\tif (fieldSchema.relation.type === \"belongsTo\") {\n\t\t\t\t// belongsTo expects { id: \"uuid\" }\n\t\t\t\tresult[fieldName] = { id: value };\n\t\t\t} else {\n\t\t\t\t// hasMany/manyToMany expect [{ id: \"uuid\" }]\n\t\t\t\tresult[fieldName] = [{ id: value }];\n\t\t\t}\n\t\t} else {\n\t\t\t// Non-relation fields: pass through as-is\n\t\t\tresult[fieldName] = value;\n\t\t}\n\t}\n\n\treturn result;\n}\n\ninterface ContentEditorPageProps {\n\ttypeSlug: string;\n\tid?: string;\n}\n\nexport function ContentEditorPage({ typeSlug, id }: ContentEditorPageProps) {\n\tconst t = useTranslate();\n\tconst overrides = usePluginOverrides(CMS_PLUGIN_ID);\n\tconst { localization } = overrides;\n\tconst { router, plugins, basePath: stackBasePath } = useStack();\n\tconst navigate = router?.navigate;\n\tconst basePath = plugins?.[CMS_PLUGIN_ID]?.site.basePath ?? stackBasePath;\n\n\t// Parse prefill query parameters for pre-populating fields when creating new items\n\t// This is used by the inverse relations panel to pre-fill the parent relation\n\tconst prefillParams = usePrefillParams();\n\n\t// Call route lifecycle hooks for telemetry and application behavior.\n\tuseRouteLifecycle({\n\t\trouteName: \"contentEditor\",\n\t\tcontext: {\n\t\t\tpath: id ? `/cms/${typeSlug}/${id}` : `/cms/${typeSlug}/new`,\n\t\t\tparams: id ? { typeSlug, id } : { typeSlug },\n\t\t\tisSSR: typeof window === \"undefined\",\n\t\t},\n\t\toverrides,\n\t});\n\n\tconst { contentTypes: serverContentTypes } = useSuspenseContentTypes();\n\tconst contentTypes = orderCMSContentTypes(\n\t\tserverContentTypes,\n\t\tplugins?.[CMS_PLUGIN_ID]?.config,\n\t);\n\tconst contentType = contentTypes.find((ct) => ct.slug === typeSlug);\n\n\tconst isEditing = !!id;\n\n\t// useContentItem has enabled: !!id built-in, so it won't fetch when creating new items\n\t// This avoids conditional hook calls which violate React's Rules of Hooks\n\tconst { item, isLoading: isLoadingItem } = useContentItem(typeSlug, id ?? \"\");\n\n\t// Core resource form: submits the right mutation, awaits invalidation,\n\t// notifies success/error via useNotify(), and exposes server validation\n\t// issues as fieldErrors for inline display.\n\tconst resourceForm = useContentItemForm<{\n\t\tslug: string;\n\t\tdata: Record;\n\t}>({\n\t\taction: isEditing ? \"edit\" : \"create\",\n\t\trecord: isEditing ? item : null,\n\t\tsuccessMessage: (_result, action) =>\n\t\t\taction === \"create\"\n\t\t\t\t? (localization?.CMS_TOAST_CREATE_SUCCESS ??\n\t\t\t\t\tt(\"cms.toasts.createSuccess\", \"Item created successfully\"))\n\t\t\t\t: (localization?.CMS_TOAST_UPDATE_SUCCESS ??\n\t\t\t\t\tt(\"cms.toasts.updateSuccess\", \"Item updated successfully\")),\n\t\ttoCreateVars: (values) => ({\n\t\t\ttypeSlug,\n\t\t\tslug: values.slug,\n\t\t\tdata: values.data,\n\t\t}),\n\t\ttoUpdateVars: (values) => ({\n\t\t\ttypeSlug,\n\t\t\tid: id ?? \"\",\n\t\t\tdata: { slug: values.slug, data: values.data },\n\t\t}),\n\t\tonSuccess: () => {\n\t\t\tvoid navigate?.(joinBasePath(basePath, `/cms/${typeSlug}`));\n\t\t},\n\t});\n\n\tif (!contentType) {\n\t\treturn (\n\t\t\t\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t
\n\t\t);\n\t}\n\n\t// Show loading skeleton while fetching item in edit mode\n\tif (isEditing && isLoadingItem) {\n\t\treturn (\n\t\t\t\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t
\n\t\t);\n\t}\n\n\tif (isEditing && !item) {\n\t\treturn (\n\t\t\t\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t
\n\t\t);\n\t}\n\n\t// resourceForm.submit never throws: success notifies + navigates via the\n\t// config above; errors land on resourceForm.error / fieldErrors.\n\tconst handleSubmit = async (data: {\n\t\tslug: string;\n\t\tdata: Record;\n\t}) => {\n\t\tawait resourceForm.submit(data);\n\t};\n\n\tconst hasFieldErrors = Object.keys(resourceForm.fieldErrors).length > 0;\n\n\tconst title = isEditing\n\t\t? (\n\t\t\t\tlocalization?.CMS_EDITOR_TITLE_EDIT ??\n\t\t\t\tt(\"cms.editor.titleEdit\", \"Edit {typeName}\")\n\t\t\t).replace(\"{typeName}\", contentType.name)\n\t\t: (\n\t\t\t\tlocalization?.CMS_EDITOR_TITLE_NEW ??\n\t\t\t\tt(\"cms.editor.titleNew\", \"New {typeName}\")\n\t\t\t).replace(\"{typeName}\", contentType.name);\n\n\treturn (\n\t\t\n\t\t\t
\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t\t\t\tvoid navigate?.(joinBasePath(basePath, `/cms/${typeSlug}`))\n\t\t\t\t\t\t}\n\t\t\t\t\t>\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t

{title}

\n\t\t\t\t
\n\n\t\t\t\t 0\n\t\t\t\t\t\t\t\t? convertPrefillToFormData(\n\t\t\t\t\t\t\t\t\t\tprefillParams,\n\t\t\t\t\t\t\t\t\t\tJSON.parse(contentType.jsonSchema),\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t: undefined\n\t\t\t\t\t}\n\t\t\t\t\tinitialSlug={item?.slug}\n\t\t\t\t\tisEditing={isEditing}\n\t\t\t\t\tonSubmit={handleSubmit}\n\t\t\t\t\tonCancel={() =>\n\t\t\t\t\t\tvoid navigate?.(joinBasePath(basePath, `/cms/${typeSlug}`))\n\t\t\t\t\t}\n\t\t\t\t\tfieldErrors={resourceForm.fieldErrors}\n\t\t\t\t\terrorMessage={\n\t\t\t\t\t\thasFieldErrors ? undefined : resourceForm.error?.message\n\t\t\t\t\t}\n\t\t\t\t\tisSubmitting={resourceForm.isSubmitting}\n\t\t\t\t/>\n\n\t\t\t\t{/* Show inverse relations panel when editing (not creating) */}\n\t\t\t\t{isEditing && id && (\n\t\t\t\t\t\n\t\t\t\t)}\n\t\t\t
\n\t\t
\n\t);\n}\n", + "content": "\"use client\";\n\nimport { useState, useEffect } from \"react\";\nimport { ArrowLeft } from \"lucide-react\";\nimport { Button } from \"@/components/ui/button\";\nimport {\n\tjoinBasePath,\n\tusePluginOverrides,\n\tuseStack,\n\tuseTranslate,\n} from \"@btst/stack/context\";\nimport { orderCMSContentTypes, type CMSPluginOverrides } from \"../../overrides\";\nimport { CMS_PLUGIN_ID } from \"../../constants\";\nimport {\n\tuseSuspenseContentTypes,\n\tuseContentItem,\n\tuseContentItemForm,\n} from \"@btst/plugin-cms/client/hooks\";\nimport { ContentForm } from \"../forms/content-form\";\nimport { InverseRelationsPanel } from \"../inverse-relations-panel\";\nimport { RevisionHistory } from \"../revision-history\";\nimport { EmptyState } from \"../shared/empty-state\";\nimport { PageWrapper } from \"../shared/page-wrapper\";\nimport { EditorSkeleton } from \"../loading/editor-skeleton\";\nimport { useRouteLifecycle } from \"@/hooks/use-route-lifecycle\";\n\n/**\n * Parse prefill query parameters from the URL.\n * Looks for query params with the format `prefill_=`\n * and returns a record of field names to values.\n *\n * Uses useState + useEffect pattern to work correctly with SSR/hydration.\n * During SSR, returns empty object. After hydration, parses URL params.\n * Also listens for popstate events to handle browser back/forward navigation.\n *\n * @example\n * URL: /cms/comment/new?prefill_resourceId=123&prefill_author=John\n * Returns: { resourceId: \"123\", author: \"John\" }\n */\nfunction usePrefillParams(): Record {\n\tconst [prefillData, setPrefillData] = useState>({});\n\n\tuseEffect(() => {\n\t\tif (typeof window === \"undefined\") {\n\t\t\treturn;\n\t\t}\n\n\t\tconst parseAndSetPrefillData = () => {\n\t\t\tconst params = new URLSearchParams(window.location.search);\n\t\t\tconst data: Record = {};\n\n\t\t\tfor (const [key, value] of params.entries()) {\n\t\t\t\tif (key.startsWith(\"prefill_\")) {\n\t\t\t\t\tconst fieldName = key.slice(\"prefill_\".length);\n\t\t\t\t\tif (fieldName) {\n\t\t\t\t\t\tdata[fieldName] = value;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Always update state to ensure stale data is cleared when navigating\n\t\t\t// to a URL without prefill params (e.g., via browser back/forward)\n\t\t\tsetPrefillData(data);\n\t\t};\n\n\t\t// Parse on mount\n\t\tparseAndSetPrefillData();\n\n\t\t// Listen for popstate events (browser back/forward navigation)\n\t\twindow.addEventListener(\"popstate\", parseAndSetPrefillData);\n\n\t\treturn () => {\n\t\t\twindow.removeEventListener(\"popstate\", parseAndSetPrefillData);\n\t\t};\n\t}, []);\n\n\treturn prefillData;\n}\n\ninterface JsonSchemaProperty {\n\tfieldType?: string;\n\trelation?: {\n\t\ttype: \"belongsTo\" | \"hasMany\" | \"manyToMany\";\n\t\ttargetType: string;\n\t};\n}\n\n/**\n * Convert prefill params to the correct format for the form.\n * Relation fields need special handling:\n * - belongsTo: value should be { id: \"uuid\" }\n * - hasMany/manyToMany: value should be [{ id: \"uuid\" }]\n *\n * @param prefillParams - Raw prefill params from URL\n * @param jsonSchema - The content type's JSON schema\n * @returns Converted data suitable for initialData\n */\nfunction convertPrefillToFormData(\n\tprefillParams: Record,\n\tjsonSchema: Record,\n): Record {\n\tconst properties = jsonSchema.properties as\n\t\t| Record\n\t\t| undefined;\n\n\tif (!properties) {\n\t\treturn prefillParams;\n\t}\n\n\tconst result: Record = {};\n\n\tfor (const [fieldName, value] of Object.entries(prefillParams)) {\n\t\tconst fieldSchema = properties[fieldName];\n\n\t\tif (fieldSchema?.fieldType === \"relation\" && fieldSchema.relation) {\n\t\t\t// Convert relation field value to the correct format\n\t\t\tif (fieldSchema.relation.type === \"belongsTo\") {\n\t\t\t\t// belongsTo expects { id: \"uuid\" }\n\t\t\t\tresult[fieldName] = { id: value };\n\t\t\t} else {\n\t\t\t\t// hasMany/manyToMany expect [{ id: \"uuid\" }]\n\t\t\t\tresult[fieldName] = [{ id: value }];\n\t\t\t}\n\t\t} else {\n\t\t\t// Non-relation fields: pass through as-is\n\t\t\tresult[fieldName] = value;\n\t\t}\n\t}\n\n\treturn result;\n}\n\ninterface ContentEditorPageProps {\n\ttypeSlug: string;\n\tid?: string;\n}\n\nexport function ContentEditorPage({ typeSlug, id }: ContentEditorPageProps) {\n\tconst t = useTranslate();\n\tconst overrides = usePluginOverrides(CMS_PLUGIN_ID);\n\tconst { localization } = overrides;\n\tconst { router, plugins, basePath: stackBasePath } = useStack();\n\tconst navigate = router?.navigate;\n\tconst basePath = plugins?.[CMS_PLUGIN_ID]?.site.basePath ?? stackBasePath;\n\n\t// Parse prefill query parameters for pre-populating fields when creating new items\n\t// This is used by the inverse relations panel to pre-fill the parent relation\n\tconst prefillParams = usePrefillParams();\n\n\t// Call route lifecycle hooks for telemetry and application behavior.\n\tuseRouteLifecycle({\n\t\trouteName: \"contentEditor\",\n\t\tcontext: {\n\t\t\tpath: id ? `/cms/${typeSlug}/${id}` : `/cms/${typeSlug}/new`,\n\t\t\tparams: id ? { typeSlug, id } : { typeSlug },\n\t\t\tisSSR: typeof window === \"undefined\",\n\t\t},\n\t\toverrides,\n\t});\n\n\tconst { contentTypes: serverContentTypes } = useSuspenseContentTypes();\n\tconst contentTypes = orderCMSContentTypes(\n\t\tserverContentTypes,\n\t\tplugins?.[CMS_PLUGIN_ID]?.config,\n\t);\n\tconst contentType = contentTypes.find((ct) => ct.slug === typeSlug);\n\n\tconst isEditing = !!id;\n\tconst [restoreCount, setRestoreCount] = useState(0);\n\n\t// useContentItem has enabled: !!id built-in, so it won't fetch when creating new items\n\t// This avoids conditional hook calls which violate React's Rules of Hooks\n\tconst { item, isLoading: isLoadingItem } = useContentItem(typeSlug, id ?? \"\");\n\n\t// Core resource form: submits the right mutation, awaits invalidation,\n\t// notifies success/error via useNotify(), and exposes server validation\n\t// issues as fieldErrors for inline display.\n\tconst resourceForm = useContentItemForm<{\n\t\tslug: string;\n\t\tdata: Record;\n\t\tpublishAt?: string | null;\n\t}>({\n\t\taction: isEditing ? \"edit\" : \"create\",\n\t\trecord: isEditing ? item : null,\n\t\tsuccessMessage: (_result, action) =>\n\t\t\taction === \"create\"\n\t\t\t\t? (localization?.CMS_TOAST_CREATE_SUCCESS ??\n\t\t\t\t\tt(\"cms.toasts.createSuccess\", \"Item created successfully\"))\n\t\t\t\t: (localization?.CMS_TOAST_UPDATE_SUCCESS ??\n\t\t\t\t\tt(\"cms.toasts.updateSuccess\", \"Item updated successfully\")),\n\t\ttoCreateVars: (values) => ({\n\t\t\ttypeSlug,\n\t\t\tslug: values.slug,\n\t\t\tdata: values.data,\n\t\t\tpublishAt: values.publishAt,\n\t\t}),\n\t\ttoUpdateVars: (values) => ({\n\t\t\ttypeSlug,\n\t\t\tid: id ?? \"\",\n\t\t\tdata: {\n\t\t\t\tslug: values.slug,\n\t\t\t\tdata: values.data,\n\t\t\t\tpublishAt: values.publishAt,\n\t\t\t},\n\t\t}),\n\t\tonSuccess: () => {\n\t\t\tvoid navigate?.(joinBasePath(basePath, `/cms/${typeSlug}`));\n\t\t},\n\t});\n\n\tif (!contentType) {\n\t\treturn (\n\t\t\t\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t
\n\t\t);\n\t}\n\n\t// Show loading skeleton while fetching item in edit mode\n\tif (isEditing && isLoadingItem) {\n\t\treturn (\n\t\t\t\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t
\n\t\t);\n\t}\n\n\tif (isEditing && !item) {\n\t\treturn (\n\t\t\t\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t
\n\t\t);\n\t}\n\n\t// resourceForm.submit never throws: success notifies + navigates via the\n\t// config above; errors land on resourceForm.error / fieldErrors.\n\tconst handleSubmit = async (data: {\n\t\tslug: string;\n\t\tdata: Record;\n\t}) => {\n\t\tawait resourceForm.submit(data);\n\t};\n\n\tconst hasFieldErrors = Object.keys(resourceForm.fieldErrors).length > 0;\n\n\tconst title = isEditing\n\t\t? (\n\t\t\t\tlocalization?.CMS_EDITOR_TITLE_EDIT ??\n\t\t\t\tt(\"cms.editor.titleEdit\", \"Edit {typeName}\")\n\t\t\t).replace(\"{typeName}\", contentType.name)\n\t\t: (\n\t\t\t\tlocalization?.CMS_EDITOR_TITLE_NEW ??\n\t\t\t\tt(\"cms.editor.titleNew\", \"New {typeName}\")\n\t\t\t).replace(\"{typeName}\", contentType.name);\n\n\treturn (\n\t\t\n\t\t\t
\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t\t\t\tvoid navigate?.(joinBasePath(basePath, `/cms/${typeSlug}`))\n\t\t\t\t\t\t}\n\t\t\t\t\t>\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t

{title}

\n\t\t\t\t\t{isEditing && id && (\n\t\t\t\t\t\t setRestoreCount((count) => count + 1)}\n\t\t\t\t\t\t/>\n\t\t\t\t\t)}\n\t\t\t\t
\n\n\t\t\t\t 0\n\t\t\t\t\t\t\t\t? convertPrefillToFormData(\n\t\t\t\t\t\t\t\t\t\tprefillParams,\n\t\t\t\t\t\t\t\t\t\tJSON.parse(contentType.jsonSchema),\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t: undefined\n\t\t\t\t\t}\n\t\t\t\t\tinitialSlug={item?.slug}\n\t\t\t\t\tinitialPublishAt={item?.publishAt}\n\t\t\t\t\tisEditing={isEditing}\n\t\t\t\t\tonSubmit={handleSubmit}\n\t\t\t\t\tonCancel={() =>\n\t\t\t\t\t\tvoid navigate?.(joinBasePath(basePath, `/cms/${typeSlug}`))\n\t\t\t\t\t}\n\t\t\t\t\tfieldErrors={resourceForm.fieldErrors}\n\t\t\t\t\terrorMessage={\n\t\t\t\t\t\thasFieldErrors ? undefined : resourceForm.error?.message\n\t\t\t\t\t}\n\t\t\t\t\tisSubmitting={resourceForm.isSubmitting}\n\t\t\t\t/>\n\n\t\t\t\t{/* Show inverse relations panel when editing (not creating) */}\n\t\t\t\t{isEditing && id && (\n\t\t\t\t\t\n\t\t\t\t)}\n\t\t\t
\n\t\t
\n\t);\n}\n", "target": "src/components/btst/cms/client/components/pages/content-editor-page.internal.tsx" }, { @@ -143,6 +144,12 @@ "content": "\"use client\";\n\nimport { lazy } from \"react\";\nimport { usePluginOverrides } from \"@btst/stack/context\";\nimport type { CMSPluginOverrides } from \"../../overrides\";\nimport { CMS_PLUGIN_ID } from \"../../constants\";\nimport { ComposedRoute } from \"@btst/stack/client/components\";\nimport { DefaultError } from \"../shared/default-error\";\nimport { DashboardSkeleton } from \"../loading\";\nimport { NotFoundPage } from \"./404-page\";\nimport { cmsPermissions } from \"../../../permissions\";\n\nconst DashboardPageInternal = lazy(() =>\n\timport(\"./dashboard-page.internal\").then((m) => ({\n\t\tdefault: m.DashboardPage,\n\t})),\n);\n\nexport function DashboardPageComponent() {\n\tconst { onRouteError } =\n\t\tusePluginOverrides(CMS_PLUGIN_ID);\n\n\treturn (\n\t\t {\n\t\t\t\tif (onRouteError) {\n\t\t\t\t\tonRouteError(\"dashboard\", error, {\n\t\t\t\t\t\tpath: \"/cms\",\n\t\t\t\t\t\tisSSR: typeof window === \"undefined\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}}\n\t\t/>\n\t);\n}\n", "target": "src/components/btst/cms/client/components/pages/dashboard-page.tsx" }, + { + "path": "btst/cms/client/components/revision-history.tsx", + "type": "registry:component", + "content": "\"use client\";\n\nimport { useState } from \"react\";\nimport { Button } from \"@/components/ui/button\";\nimport {\n\tSheet,\n\tSheetContent,\n\tSheetDescription,\n\tSheetHeader,\n\tSheetTitle,\n\tSheetTrigger,\n} from \"@/components/ui/sheet\";\nimport {\n\tAlertDialog,\n\tAlertDialogAction,\n\tAlertDialogCancel,\n\tAlertDialogContent,\n\tAlertDialogDescription,\n\tAlertDialogFooter,\n\tAlertDialogHeader,\n\tAlertDialogTitle,\n} from \"@/components/ui/alert-dialog\";\nimport { useTranslate } from \"@btst/stack/context\";\nimport { useContentRevisions, useRestoreContentRevision } from \"@btst/plugin-cms/client/hooks\";\nimport type { SerializedContentRevision } from \"../../types\";\n\nexport function RevisionHistory({\n\ttypeSlug,\n\titemId,\n\tonRestored,\n}: {\n\ttypeSlug: string;\n\titemId: string;\n\tonRestored: () => void;\n}) {\n\tconst t = useTranslate();\n\tconst [open, setOpen] = useState(false);\n\tconst [selected, setSelected] = useState(\n\t\tnull,\n\t);\n\tconst [restoreError, setRestoreError] = useState(null);\n\tconst history = useContentRevisions(typeSlug, itemId, open);\n\tconst restore = useRestoreContentRevision();\n\tconst restoreSelected = async () => {\n\t\tif (!selected) return;\n\t\tsetRestoreError(null);\n\t\ttry {\n\t\t\tawait restore.mutateAsync({\n\t\t\t\ttypeSlug,\n\t\t\t\tid: itemId,\n\t\t\t\trevisionId: selected.id,\n\t\t\t});\n\t\t\tonRestored();\n\t\t\tsetSelected(null);\n\t\t\tsetOpen(false);\n\t\t} catch (error) {\n\t\t\tsetRestoreError(\n\t\t\t\terror instanceof Error\n\t\t\t\t\t? error.message\n\t\t\t\t\t: t(\"cms.revisions.restoreError\", \"Could not restore revision\"),\n\t\t\t);\n\t\t}\n\t};\n\n\treturn (\n\t\t\n\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t{t(\"cms.revisions.title\", \"Revision history\")}\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t{t(\n\t\t\t\t\t\t\t\"cms.revisions.description\",\n\t\t\t\t\t\t\t\"Inspect saved versions. Restoring a version replaces the editor state and creates a new revision.\",\n\t\t\t\t\t\t)}\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t
\n\t\t\t\t\t{history.isLoading && (\n\t\t\t\t\t\t

\n\t\t\t\t\t\t\t{t(\"cms.revisions.loading\", \"Loading revisions...\")}\n\t\t\t\t\t\t

\n\t\t\t\t\t)}\n\t\t\t\t\t{history.error && (\n\t\t\t\t\t\t
\n\t\t\t\t\t\t\t

{history.error.message}

\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t
\n\t\t\t\t\t)}\n\t\t\t\t\t{!history.isLoading &&\n\t\t\t\t\t\t!history.error &&\n\t\t\t\t\t\thistory.revisions.length === 0 && (\n\t\t\t\t\t\t\t

\n\t\t\t\t\t\t\t\t{t(\n\t\t\t\t\t\t\t\t\t\"cms.revisions.empty\",\n\t\t\t\t\t\t\t\t\t\"No revisions yet. Saving this entry will create its first revision.\",\n\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t

\n\t\t\t\t\t\t)}\n\t\t\t\t\t{history.revisions.map((revision) => (\n\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t{t(\"cms.revisions.version\", \"Version {version}\").replace(\n\t\t\t\t\t\t\t\t\t\t\"{version}\",\n\t\t\t\t\t\t\t\t\t\tString(revision.version),\n\t\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t{t(\"cms.revisions.author\", \"Author\")}:{\" \"}\n\t\t\t\t\t\t\t\t\t{revision.authorId ?? t(\"cms.revisions.system\", \"System\")}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t

\n\t\t\t\t\t\t\t\t\t{t(\"cms.common.slugLabel\", \"Slug\")}: {revision.slug}\n\t\t\t\t\t\t\t\t

\n\t\t\t\t\t\t\t\t

\n\t\t\t\t\t\t\t\t\t{t(\"cms.editor.publishAt\", \"Publish at\")}:{\" \"}\n\t\t\t\t\t\t\t\t\t{revision.publishAt\n\t\t\t\t\t\t\t\t\t\t? new Date(revision.publishAt).toLocaleString()\n\t\t\t\t\t\t\t\t\t\t: t(\"cms.revisions.unscheduled\", \"Not scheduled\")}\n\t\t\t\t\t\t\t\t

\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t{JSON.stringify(JSON.parse(revision.data), null, 2)}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\t\tsetRestoreError(null);\n\t\t\t\t\t\t\t\t\t\tsetSelected(revision);\n\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{t(\"cms.revisions.restore\", \"Restore this version\")}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t
\n\t\t\t\t\t\t
\n\t\t\t\t\t))}\n\t\t\t\t\t{history.hasNextPage && (\n\t\t\t\t\t\t void history.fetchNextPage()}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{t(\"cms.revisions.loadMore\", \"Load older revisions\")}\n\t\t\t\t\t\t\n\t\t\t\t\t)}\n\t\t\t\t
\n\t\t\t
\n\t\t\t {\n\t\t\t\t\tif (!value && !restore.isPending) setSelected(null);\n\t\t\t\t}}\n\t\t\t>\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t{t(\n\t\t\t\t\t\t\t\t\"cms.revisions.confirmTitle\",\n\t\t\t\t\t\t\t\t\"Restore version {version}?\",\n\t\t\t\t\t\t\t).replace(\"{version}\", String(selected?.version ?? \"\"))}\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t{t(\n\t\t\t\t\t\t\t\t\"cms.revisions.confirmDescription\",\n\t\t\t\t\t\t\t\t\"This replaces the active entry, including its slug and schedule. Unsaved editor changes will be discarded. Existing revisions are kept.\",\n\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t{restoreError && (\n\t\t\t\t\t\t

\n\t\t\t\t\t\t\t{restoreError}\n\t\t\t\t\t\t

\n\t\t\t\t\t)}\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t{t(\"cms.common.cancel\", \"Cancel\")}\n\t\t\t\t\t\t\n\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\tevent.preventDefault();\n\t\t\t\t\t\t\t\tvoid restoreSelected();\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{restore.isPending\n\t\t\t\t\t\t\t\t? t(\"cms.revisions.restoring\", \"Restoring...\")\n\t\t\t\t\t\t\t\t: t(\"cms.revisions.confirm\", \"Restore version\")}\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t\n\t\t
\n\t);\n}\n", + "target": "src/components/btst/cms/client/components/revision-history.tsx" + }, { "path": "btst/cms/client/components/shared/default-error.tsx", "type": "registry:component", diff --git a/packages/stack/registry/registry.json b/packages/stack/registry/registry.json index f344f9913..7a892aebc 100644 --- a/packages/stack/registry/registry.json +++ b/packages/stack/registry/registry.json @@ -180,6 +180,7 @@ "https://raw.githubusercontent.com/better-stack-ai/form-builder/refs/heads/main/registry/auto-form.json", "input", "label", + "sheet", "skeleton", "table", "textarea" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index adf783c8a..0d7b7a029 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -886,6 +886,9 @@ importers: specifier: 4.6.7 version: 4.6.7 devDependencies: + better-auth: + specifier: 1.7.14 + version: 1.7.14(@tanstack/react-start@1.169.4(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.2.15)(rollup@4.66.0)(vite@8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)))(next@16.4.3(@babel/core@7.29.7)(@playwright/test@1.64.1)(@types/node@24.19.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(solid-js@1.9.17)(vitest@4.1.12(@types/node@24.19.2)(jsdom@28.1.0(@noble/hashes@2.4.0))(vite@8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)))(vue@3.5.44(typescript@5.9.3)) '@btst/adapter-memory': specifier: 3.0.1 version: 3.0.1(@better-auth/core@1.7.14(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(better-call@1.4.4(zod@4.6.7))(jose@6.2.13)(kysely@0.29.7)(nanostores@1.5.5))(@better-auth/utils@0.5.1)(better-auth@1.7.14(@tanstack/react-start@1.169.4(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.2.15)(rollup@4.66.0)(vite@8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)))(next@16.4.3(@babel/core@7.29.7)(@playwright/test@1.64.1)(@types/node@24.19.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(solid-js@1.9.17)(vitest@4.1.12(@types/node@24.19.2)(jsdom@28.1.0(@noble/hashes@2.4.0))(vite@8.3.5(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)))(vue@3.5.44(typescript@5.9.3))) From ee7b8bac3e34fce32f170a794cc2f46e9c7cfc1e Mon Sep 17 00:00:00 2001 From: olliethedev <5933733+olliethedev@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:36:30 -0500 Subject: [PATCH 2/3] test(cms): cover revision pagination and settled restore dialogs --- e2e/tests/smoke.cms.spec.ts | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/e2e/tests/smoke.cms.spec.ts b/e2e/tests/smoke.cms.spec.ts index cfa648798..1ee63989a 100644 --- a/e2e/tests/smoke.cms.spec.ts +++ b/e2e/tests/smoke.cms.spec.ts @@ -797,7 +797,8 @@ test("CMS revisions restore saved fields and publishAt in the editor", async ({ await page .getByRole("button", { name: "Restore version", exact: true }) .click(); - await expect(drawer).not.toBeVisible(); + await expect(page.getByRole("alertdialog")).not.toBeVisible(); + await expect(page.locator('[data-slot="sheet-content"]')).not.toBeVisible(); await expect(page.locator('input[name="name"]')).toHaveValue( "Original category", ); @@ -839,6 +840,12 @@ test("CMS revision drawer recovers from a failed history request and supports mo }); expect(response.ok()).toBeTruthy(); const item = await response.json(); + for (let index = 0; index < 20; index++) { + const update = await request.put(`/api/data/content/category/${item.id}`, { + data: { data: { description: `Save ${index + 2}` } }, + }); + expect(update.ok()).toBeTruthy(); + } await page.setViewportSize({ width: 390, height: 844 }); await page.goto(`/pages/cms/category/${item.id}`, { waitUntil: "networkidle", @@ -862,7 +869,14 @@ test("CMS revision drawer recovers from a failed history request and supports mo await expect(drawer.getByRole("alert")).toBeVisible(); await page.unroute(historyPath); await drawer.getByRole("button", { name: "Retry", exact: true }).click(); + await expect(drawer.getByText("Version 21", { exact: true })).toBeVisible(); + await drawer + .getByRole("button", { name: "Load older revisions", exact: true }) + .click(); await expect(drawer.getByText("Version 1", { exact: true })).toBeVisible(); + await expect( + drawer.getByRole("button", { name: "Load older revisions", exact: true }), + ).not.toBeVisible(); expect( await page.evaluate( () => document.documentElement.scrollWidth <= window.innerWidth, From bc7f2ec0228aef60f9ae154899d6b299bf8302cc Mon Sep 17 00:00:00 2001 From: olliethedev <5933733+olliethedev@users.noreply.github.com> Date: Thu, 5 Nov 2026 22:17:29 -0500 Subject: [PATCH 3/3] fix(cms): preserve schedules and record dependent plugin revisions --- docs/content/docs/plugins/cms.mdx | 8 +++ .../src/__tests__/client-sweep.test.tsx | 65 +++++++++++++++++++ packages/plugin-cms/src/api/index.ts | 1 + packages/plugin-cms/src/api/operations.ts | 7 +- packages/plugin-cms/src/api/plugin.ts | 5 +- .../client/components/forms/content-form.tsx | 12 +++- .../src/__tests__/plugin.test.ts | 19 ++++++ .../plugin-job-board/src/api/mutations.ts | 31 ++++++--- .../src/__tests__/plugin.test.ts | 36 ++++++++++ packages/plugin-school/src/api/mutations.ts | 10 ++- packages/plugin-school/src/api/operations.ts | 25 ++++--- packages/stack/registry/btst-cms.json | 2 +- .../src/__tests__/endpoint-inventory.test.ts | 4 +- 13 files changed, 195 insertions(+), 30 deletions(-) diff --git a/docs/content/docs/plugins/cms.mdx b/docs/content/docs/plugins/cms.mdx index de4dfbe4b..e23b1468a 100644 --- a/docs/content/docs/plugins/cms.mdx +++ b/docs/content/docs/plugins/cms.mdx @@ -1510,12 +1510,20 @@ validation, authorization, duplicate slugs, and before-hook failures do not appe revisions. There is no operation to edit or individually delete a revision; revision rows cascade when their content item is deleted. +School course creation, edits and archival, and automatic Job Board archival +also append snapshots in their write transactions. Custom lower-level writers +can call `recordContentRevision(tx, item, authorId?)` from +`@btst/plugin-cms/api` after writing the item in the same transaction; callers +own validation, authorization and lifecycle hooks. + `publishAt` is optional **top-level scheduling metadata**, separate from the content type's `data`. The editor accepts local date/time and sends an ISO timestamp with its time-zone offset converted to UTC. HTTP and operation inputs accept ISO timestamps with a time-zone offset; omit the property to preserve the schedule on update, or pass `null` to clear it. Serialized items and revisions return ISO strings or `null`. +Saving other editor fields preserves the original timestamp's precision until +the schedule control is edited. This field does not run a publisher job, set a `data.status` field, or filter content reads. Applications remain responsible for deciding when content becomes diff --git a/packages/plugin-cms/src/__tests__/client-sweep.test.tsx b/packages/plugin-cms/src/__tests__/client-sweep.test.tsx index 1bd0448dc..15df00380 100644 --- a/packages/plugin-cms/src/__tests__/client-sweep.test.tsx +++ b/packages/plugin-cms/src/__tests__/client-sweep.test.tsx @@ -254,6 +254,71 @@ describe("CMSFileUpload notifications (useNotify)", () => { }); describe("ContentForm inline errors", () => { + it("preserves an untouched publication timestamp when saving content", async () => { + const onSubmit = vi.fn().mockResolvedValue(undefined); + await render( + + + , + ); + await act(async () => { + container + .querySelector("form")! + .dispatchEvent( + new Event("submit", { bubbles: true, cancelable: true }), + ); + }); + expect(onSubmit).toHaveBeenCalledWith({ + slug: "hello", + data: { title: "Updated content" }, + publishAt: "2030-12-05T14:30:45.123Z", + }); + }); + + it("clears the publication timestamp when the schedule is explicitly emptied", async () => { + const onSubmit = vi.fn().mockResolvedValue(undefined); + await render( + + + , + ); + const input = container.querySelector("#publishAt")!; + const setValue = Object.getOwnPropertyDescriptor( + HTMLInputElement.prototype, + "value", + )!.set!; + await act(async () => { + setValue.call(input, ""); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + await act(async () => { + container + .querySelector("form")! + .dispatchEvent( + new Event("submit", { bubbles: true, cancelable: true }), + ); + }); + expect(onSubmit).toHaveBeenCalledWith({ + slug: "hello", + data: { title: "Updated content" }, + publishAt: null, + }); + }); + it("shows a non-field error message above the form", async () => { await render( diff --git a/packages/plugin-cms/src/api/index.ts b/packages/plugin-cms/src/api/index.ts index 3f6475656..0001ecff1 100644 --- a/packages/plugin-cms/src/api/index.ts +++ b/packages/plugin-cms/src/api/index.ts @@ -18,6 +18,7 @@ export { } from "./getters"; export { createCMSContentItem, + recordContentRevision, type CreateCMSContentItemInput, type CreateCMSContentItemOptions, } from "./mutations"; diff --git a/packages/plugin-cms/src/api/operations.ts b/packages/plugin-cms/src/api/operations.ts index 21c379620..d670fd42e 100644 --- a/packages/plugin-cms/src/api/operations.ts +++ b/packages/plugin-cms/src/api/operations.ts @@ -153,6 +153,9 @@ const PublishAtSchema = z.iso.datetime({ offset: true }).nullable().optional(); export const CMSRevisionParamsSchema = CMSContentItemParamsSchema.extend({ revisionId: z.string().min(1), }); +export const CMSRevisionsQuerySchema = z.object({ + offset: z.coerce.number().int().min(0).default(0), +}); export const CMSCreateContentItemBodySchema = z.object({ slug: z.string().min(1), data: CMSDataSchema, @@ -1861,9 +1864,7 @@ export function createCMSOperations( }); const listContentRevisions = defineOperation({ - input: CMSContentItemParamsSchema.extend({ - offset: z.coerce.number().int().min(0).default(0), - }), + input: CMSContentItemParamsSchema.extend(CMSRevisionsQuerySchema.shape), permission: cmsPermissions.record.read, facts: async ({ input }) => recordFacts( diff --git a/packages/plugin-cms/src/api/plugin.ts b/packages/plugin-cms/src/api/plugin.ts index cbef4ca31..9b4ef4009 100644 --- a/packages/plugin-cms/src/api/plugin.ts +++ b/packages/plugin-cms/src/api/plugin.ts @@ -28,6 +28,7 @@ import { CMSCreateContentItemBodySchema, CMSUpdateContentItemBodySchema, CMSRevisionParamsSchema, + CMSRevisionsQuerySchema, createCMSOperations, } from "./operations"; import { CMS_QUERY_KEYS } from "./query-key-defs"; @@ -382,9 +383,7 @@ export const cmsBackendPlugin = (config: CMSBackendConfig) => { { method: "GET", params: CMSContentItemParamsSchema, - query: z.object({ - offset: z.coerce.number().int().min(0).default(0), - }), + query: CMSRevisionsQuerySchema, requireRequest: true, }, operations.listContentRevisions.route((ctx) => ({ diff --git a/packages/plugin-cms/src/client/components/forms/content-form.tsx b/packages/plugin-cms/src/client/components/forms/content-form.tsx index b1e479d38..0eee2a3e8 100644 --- a/packages/plugin-cms/src/client/components/forms/content-form.tsx +++ b/packages/plugin-cms/src/client/components/forms/content-form.tsx @@ -265,6 +265,7 @@ export function ContentForm({ } = usePluginOverrides(CMS_PLUGIN_ID); const [slug, setSlug] = useState(initialSlug); + const publishAtEditedRef = useRef(false); const [publishAt, setPublishAt] = useState(() => { if (!initialPublishAt) return ""; const date = new Date(initialPublishAt); @@ -395,7 +396,11 @@ export function ContentForm({ await onSubmit({ slug, data, - publishAt: publishAt ? new Date(publishAt).toISOString() : null, + publishAt: publishAtEditedRef.current + ? publishAt + ? new Date(publishAt).toISOString() + : null + : (initialPublishAt ?? null), }); } catch (error) { const message = @@ -484,7 +489,10 @@ export function ContentForm({ id="publishAt" type="datetime-local" value={publishAt} - onChange={(event) => setPublishAt(event.target.value)} + onChange={(event) => { + publishAtEditedRef.current = true; + setPublishAt(event.target.value); + }} disabled={isSubmitting} aria-describedby="publishAt-description" /> diff --git a/packages/plugin-job-board/src/__tests__/plugin.test.ts b/packages/plugin-job-board/src/__tests__/plugin.test.ts index 459d263f1..c7736bcb5 100644 --- a/packages/plugin-job-board/src/__tests__/plugin.test.ts +++ b/packages/plugin-job-board/src/__tests__/plugin.test.ts @@ -299,6 +299,25 @@ describe("Job Board public API and SSG", () => { }); }); + it("records automatic job archival in CMS history exactly once", async () => { + const ctx = setup(); + const job = await ctx.create("expired-history", { + closingDate: "2030-01-09", + }); + expect((await ctx.request("/jobs")).status).toBe(200); + const history = () => + ctx.stack.trusted.cms.listContentRevisions({ + typeSlug: "job-posting", + id: job.id, + }); + const revisions = (await history()).items; + expect(revisions.map((revision) => revision.version)).toEqual([2, 1]); + expect(JSON.parse(revisions[0]!.data).status).toBe("archived"); + expect(JSON.parse(revisions[1]!.data).status).toBe("published"); + expect((await ctx.request("/jobs")).status).toBe(200); + expect((await history()).total).toBe(2); + }); + it("does not overwrite a concurrent CMS deadline extension when archival uses an older snapshot", async () => { const ctx = setup(); const job = await ctx.create("extended", { closingDate: "2030-01-09" }); diff --git a/packages/plugin-job-board/src/api/mutations.ts b/packages/plugin-job-board/src/api/mutations.ts index aaeb50909..329a1623a 100644 --- a/packages/plugin-job-board/src/api/mutations.ts +++ b/packages/plugin-job-board/src/api/mutations.ts @@ -1,4 +1,6 @@ import type { DBAdapter as Adapter } from "@btst/db"; +import { recordContentRevision } from "@btst/plugin-cms/api"; +import type { ContentItem } from "@btst/plugin-cms/types"; import { jobSchema } from "../schemas"; import type { JobContentItem } from "../types"; @@ -22,16 +24,25 @@ export async function archiveExpiredJobs( parsed.data.closingDate >= today ) continue; - archived += await adapter.updateMany({ - model: "contentItem", - where: [ - { field: "id", value: item.id, operator: "eq" }, - { field: "data", value: item.data, operator: "eq" }, - ], - update: { - data: JSON.stringify({ ...item.parsedData, status: "archived" }), - updatedAt: now, - }, + archived += await adapter.transaction(async (tx) => { + const updated = await tx.updateMany({ + model: "contentItem", + where: [ + { field: "id", value: item.id, operator: "eq" }, + { field: "data", value: item.data, operator: "eq" }, + ], + update: { + data: JSON.stringify({ ...item.parsedData, status: "archived" }), + updatedAt: now, + }, + }); + if (!updated) return 0; + const record = await tx.findOne({ + model: "contentItem", + where: [{ field: "id", value: item.id, operator: "eq" }], + }); + await recordContentRevision(tx, record!); + return updated; }); } return archived; diff --git a/packages/plugin-school/src/__tests__/plugin.test.ts b/packages/plugin-school/src/__tests__/plugin.test.ts index f43fdb83c..d4c137409 100644 --- a/packages/plugin-school/src/__tests__/plugin.test.ts +++ b/packages/plugin-school/src/__tests__/plugin.test.ts @@ -145,6 +145,42 @@ async function setup( } describe("School learning lifecycle", () => { + it("records CMS history for course creation, instructor edits and archival", async () => { + const { stack, course, request } = await setup(); + const history = () => + stack.trusted.cms.listContentRevisions({ + typeSlug: "school-course", + id: course.id, + }); + expect((await history()).items.map((revision) => revision.version)).toEqual( + [1], + ); + expect( + ( + await request( + `/courses/${course.id}`, + "PATCH", + { title: "Revised course" }, + "teacher", + ) + ).status, + ).toBe(200); + expect( + (await request(`/courses/${course.id}`, "DELETE", undefined, "teacher")) + .status, + ).toBe(200); + const revisions = (await history()).items; + expect(revisions.map((revision) => revision.version)).toEqual([3, 2, 1]); + expect(JSON.parse(revisions[0]!.data)).toMatchObject({ + title: "Revised course", + status: "archived", + }); + expect(JSON.parse(revisions[1]!.data).title).toBe("Revised course"); + expect(JSON.parse(revisions[2]!.data).title).toBe("TypeScript foundations"); + expect(revisions[0]!.authorId).toBe("teacher"); + expect(revisions[1]!.authorId).toBe("teacher"); + }); + it("protects instructor records and paid lessons while keeping previews and the SSG cache public", async () => { const { stack, course, text, quiz, request } = await setup(); for (const slug of ["me", "instructor"]) { diff --git a/packages/plugin-school/src/api/mutations.ts b/packages/plugin-school/src/api/mutations.ts index 174f15b65..2528e34ed 100644 --- a/packages/plugin-school/src/api/mutations.ts +++ b/packages/plugin-school/src/api/mutations.ts @@ -3,6 +3,7 @@ type Adapter = Omit; import type { z } from "zod"; import { zodToFormSchema } from "@workspace/ui/lib/schema-converter"; import type { ContentItem, ContentType } from "@btst/plugin-cms/types"; +import { recordContentRevision } from "@btst/plugin-cms/api"; import { courseSchema, type lessonSchema } from "../schemas"; import { getCourse, parseLesson, whereField, whereId } from "./getters"; import type { @@ -44,10 +45,11 @@ export async function ensureSchoolCourseType( throw error; } } -/** Lower-level write primitives. Callers own input validation, authorization, and lifecycle. */ +/** Lower-level CMS write; callers own validation, authorization, lifecycle, and the enclosing transaction. */ export async function createCourse( adapter: Adapter, data: z.output, + authorId?: string, ) { const type = await ensureSchoolCourseType(adapter); const record = await adapter.create({ @@ -61,14 +63,17 @@ export async function createCourse( updatedAt: new Date(), }, }); + await recordContentRevision(adapter, record, authorId); return (await getCourse(adapter, record.id))!; } +/** Lower-level CMS write; callers own validation, authorization, lifecycle, and the enclosing transaction. */ export async function updateCourse( adapter: Adapter, id: string, data: z.output, + authorId?: string, ) { - await adapter.update({ + const record = await adapter.update({ model: "contentItem", where: whereId(id), update: { @@ -77,6 +82,7 @@ export async function updateCourse( updatedAt: new Date(), }, }); + if (record) await recordContentRevision(adapter, record, authorId); return (await getCourse(adapter, id))!; } export async function createSection( diff --git a/packages/plugin-school/src/api/operations.ts b/packages/plugin-school/src/api/operations.ts index 3fa2455cb..66a3780cb 100644 --- a/packages/plugin-school/src/api/operations.ts +++ b/packages/plugin-school/src/api/operations.ts @@ -295,7 +295,10 @@ export function createSchoolOperations( instructorId: identity?.id ?? input.instructorId, }); await assertUniqueSlug(adapter, data.slug); - return mutations.createCourse(adapter, data); + await mutations.ensureSchoolCourseType(adapter); + return adapter.transaction((tx) => + mutations.createCourse(tx, data, identity?.id), + ); }, }); const updateCourse = defineOperation({ @@ -304,7 +307,7 @@ export function createSchoolOperations( facts: async ({ input }) => factsFor(await requireCourse(adapter, input.id)), before: requireIdentity, - execute: async ({ input, facts }) => { + execute: async ({ input, facts, identity }) => { const old = await requireCourse(adapter, input.id); if (old.instructorId !== facts.instructorId) fail(409, "Course changed; reload before saving"); @@ -314,7 +317,9 @@ export function createSchoolOperations( instructorId: old.instructorId, }); await assertUniqueSlug(adapter, data.slug, old.id); - return mutations.updateCourse(adapter, old.id, data); + return adapter.transaction((tx) => + mutations.updateCourse(tx, old.id, data, identity?.id), + ); }, }); const deleteCourse = defineOperation({ @@ -323,12 +328,16 @@ export function createSchoolOperations( facts: async ({ input }) => factsFor(await requireCourse(adapter, input.id)), before: requireIdentity, - execute: async ({ input }) => { + execute: async ({ input, identity }) => { const course = await requireCourse(adapter, input.id); - await mutations.updateCourse(adapter, input.id, { - ...course, - status: "archived", - }); + await adapter.transaction((tx) => + mutations.updateCourse( + tx, + input.id, + { ...course, status: "archived" }, + identity?.id, + ), + ); return { success: true }; }, }); diff --git a/packages/stack/registry/btst-cms.json b/packages/stack/registry/btst-cms.json index 29450fa89..dc4da4f61 100644 --- a/packages/stack/registry/btst-cms.json +++ b/packages/stack/registry/btst-cms.json @@ -57,7 +57,7 @@ { "path": "btst/cms/client/components/forms/content-form.tsx", "type": "registry:component", - "content": "\"use client\";\n\nimport { useState, useMemo, useEffect, useRef } from \"react\";\nimport { z } from \"zod\";\nimport type { FieldPath, FieldValues, UseFormReturn } from \"react-hook-form\";\nimport { SteppedAutoForm } from \"@/components/ui/auto-form/stepped-auto-form\";\nimport type {\n\tFieldConfig,\n\tAutoFormInputComponentProps,\n} from \"@/components/ui/auto-form/types\";\nimport { buildFieldConfigFromJsonSchema as buildFieldConfigBase } from \"@/components/ui/auto-form/helpers\";\nimport { formSchemaToZod } from \"@/lib/schema-converter\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Badge } from \"@/components/ui/badge\";\nimport { usePluginOverrides, useTranslate } from \"@btst/stack/context\";\nimport type { CMSPluginOverrides } from \"../../overrides\";\nimport { CMS_PLUGIN_ID } from \"../../constants\";\nimport type { SerializedContentType, RelationConfig } from \"../../../types\";\nimport { slugify } from \"../../../utils\";\nimport { CMSFileUpload } from \"./file-upload\";\nimport { RelationField } from \"./relation-field\";\n\ninterface ContentFormProps {\n\tcontentType: SerializedContentType;\n\tinitialData?: Record;\n\tinitialSlug?: string;\n\tinitialPublishAt?: string | null;\n\tisEditing?: boolean;\n\tonSubmit: (data: {\n\t\tslug: string;\n\t\tdata: Record;\n\t\tpublishAt?: string | null;\n\t}) => Promise;\n\tonCancel?: () => void;\n\t/**\n\t * Server-side field validation errors (`StackError.errors`), applied to\n\t * the matching form fields for inline display.\n\t */\n\tfieldErrors?: Record;\n\t/** Non-field submit error to display above the form */\n\terrorMessage?: string;\n\t/** External submit-in-flight state (e.g. from a resource `useForm`) */\n\tisSubmitting?: boolean;\n}\n\n/**\n * Applies server-side field validation errors onto react-hook-form field\n * state, and clears previously applied server errors that are no longer\n * present. The form instance arrives asynchronously (captured from\n * SteppedAutoForm's `onValuesChange`) and is `null` for multi-step forms.\n */\nfunction useServerFieldErrors(\n\tform: UseFormReturn | null,\n\tfieldErrors: Record,\n) {\n\tconst appliedFieldsRef = useRef([]);\n\n\tuseEffect(() => {\n\t\tif (!form) return;\n\n\t\t// Clear stale server errors from fields that are no longer failing\n\t\tfor (const field of appliedFieldsRef.current) {\n\t\t\tif (field in fieldErrors) continue;\n\t\t\tconst { error } = form.getFieldState(field as FieldPath);\n\t\t\tif (error?.type === \"server\") {\n\t\t\t\tform.clearErrors(field as FieldPath);\n\t\t\t}\n\t\t}\n\t\tappliedFieldsRef.current = Object.keys(fieldErrors);\n\n\t\tfor (const [field, message] of Object.entries(fieldErrors)) {\n\t\t\tform.setError(field as FieldPath, {\n\t\t\t\ttype: \"server\",\n\t\t\t\tmessage: Array.isArray(message) ? message.join(\", \") : message,\n\t\t\t});\n\t\t}\n\t}, [fieldErrors, form]);\n}\n\n/**\n * Build field configuration for AutoForm with CMS-specific file upload handling.\n *\n * Uses the shared buildFieldConfigFromJsonSchema from auto-form/helpers as a base,\n * then adds special handling for \"file\" fieldType to inject CMSFileUpload component\n * ONLY if no custom component is provided via fieldComponents.\n *\n * @param jsonSchema - The JSON Schema from the content type (with fieldType embedded in properties)\n * @param uploadImage - The uploadImage function from overrides (for file fields)\n * @param fieldComponents - Custom field components from overrides\n */\ninterface JsonSchemaProperty {\n\tfieldType?: string;\n\trelation?: RelationConfig;\n\t[key: string]: unknown;\n}\n\nfunction buildFieldConfigFromJsonSchema(\n\tjsonSchema: Record,\n\tuploadImage?: (file: File) => Promise,\n\tfieldComponents?: Record<\n\t\tstring,\n\t\tReact.ComponentType\n\t>,\n\timagePicker?: React.ComponentType<{ onSelect: (url: string) => void }>,\n\timageInputField?: React.ComponentType<{\n\t\tvalue: string;\n\t\tonChange: (value: string) => void;\n\t\tisRequired?: boolean;\n\t}>,\n): FieldConfig> {\n\t// Get base config from shared utility (handles fieldType from JSON Schema,\n\t// including per-item configs for arrays of objects).\n\tconst baseConfig = buildFieldConfigBase(jsonSchema, fieldComponents);\n\n\tconst properties = jsonSchema.properties as\n\t\t| Record\n\t\t| undefined;\n\n\tif (!properties) return baseConfig;\n\n\t// Recursively walk the JSON Schema properties and inject CMS-specific custom\n\t// components (file upload, relation picker) for any field with a matching\n\t// fieldType, regardless of nesting depth. Targets:\n\t// - top-level fields\n\t// - properties of nested object fields\n\t// - properties of array items (e.g. `components: z.array(z.object({...}))`)\n\t//\n\t// `targetConfig` is the FieldConfigObject slot to mutate for the property at\n\t// `key`. The recursion mirrors how AutoFormObject + AutoFormArray look up\n\t// per-property configs: nested object/array per-item configs live as keys\n\t// alongside their parent's meta on the same FieldConfigObject.\n\tconst injectCustomFieldTypes = (\n\t\tprops: Record,\n\t\ttargetConfig: Record,\n\t) => {\n\t\tfor (const [key, prop] of Object.entries(props)) {\n\t\t\t// Ensure a slot exists so we can mutate it whether or not the base\n\t\t\t// helper produced an entry for this key.\n\t\t\tconst existing =\n\t\t\t\t(targetConfig[key] as Record | undefined) ?? {};\n\n\t\t\tlet updated = existing;\n\n\t\t\t// Handle \"file\" fieldType when there's NO custom component for \"file\"\n\t\t\tif (prop.fieldType === \"file\" && !fieldComponents?.[\"file\"]) {\n\t\t\t\tif (!uploadImage && !imageInputField) {\n\t\t\t\t\tupdated = {\n\t\t\t\t\t\t...updated,\n\t\t\t\t\t\tfieldType: () => (\n\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\tFile upload requires an uploadImage or{\" \"}\n\t\t\t\t\t\t\t\timageInputField function in CMS overrides.\n\t\t\t\t\t\t\t
\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t} else {\n\t\t\t\t\tupdated = {\n\t\t\t\t\t\t...updated,\n\t\t\t\t\t\tfieldType: (componentProps: AutoFormInputComponentProps) => (\n\t\t\t\t\t\t\t Promise.resolve(\"\"))}\n\t\t\t\t\t\t\t\timageInputField={imageInputField}\n\t\t\t\t\t\t\t\timagePicker={imagePicker}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Handle \"relation\" fieldType when there's NO custom component for \"relation\"\n\t\t\tif (\n\t\t\t\tprop.fieldType === \"relation\" &&\n\t\t\t\tprop.relation &&\n\t\t\t\t!fieldComponents?.[\"relation\"]\n\t\t\t) {\n\t\t\t\tconst relationConfig = prop.relation;\n\t\t\t\tupdated = {\n\t\t\t\t\t...updated,\n\t\t\t\t\tfieldType: (componentProps: AutoFormInputComponentProps) => (\n\t\t\t\t\t\t\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Recurse into nested objects — their per-property configs live as\n\t\t\t// keys on the same parent FieldConfigObject.\n\t\t\tif (prop.properties) {\n\t\t\t\tinjectCustomFieldTypes(\n\t\t\t\t\tprop.properties as Record,\n\t\t\t\t\tupdated,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Recurse into array items — same convention as nested objects.\n\t\t\tconst items = prop.items as JsonSchemaProperty | undefined;\n\t\t\tif (items?.properties) {\n\t\t\t\tinjectCustomFieldTypes(\n\t\t\t\t\titems.properties as Record,\n\t\t\t\t\tupdated,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (Object.keys(updated).length > 0) {\n\t\t\t\ttargetConfig[key] = updated;\n\t\t\t}\n\t\t}\n\t};\n\n\tinjectCustomFieldTypes(\n\t\tproperties,\n\t\tbaseConfig as unknown as Record,\n\t);\n\n\treturn baseConfig;\n}\n\n/**\n * Determine the first string field in the schema for slug auto-generation\n */\nfunction findSlugSourceField(\n\tjsonSchema: Record,\n): string | null {\n\tconst properties = jsonSchema.properties as Record;\n\tif (!properties) return null;\n\n\t// Look for common name fields first\n\tconst priorityFields = [\"name\", \"title\", \"heading\", \"label\"];\n\tfor (const field of priorityFields) {\n\t\tif (properties[field]?.type === \"string\") {\n\t\t\treturn field;\n\t\t}\n\t}\n\n\t// Fall back to first string field\n\tfor (const [key, value] of Object.entries(properties)) {\n\t\tif (value.type === \"string\") {\n\t\t\treturn key;\n\t\t}\n\t}\n\n\treturn null;\n}\n\nexport function ContentForm({\n\tcontentType,\n\tinitialData = {},\n\tinitialSlug = \"\",\n\tinitialPublishAt,\n\tisEditing = false,\n\tonSubmit,\n\tonCancel,\n\tfieldErrors,\n\terrorMessage,\n\tisSubmitting: isSubmittingProp,\n}: ContentFormProps) {\n\tconst t = useTranslate();\n\tconst {\n\t\tlocalization,\n\t\tuploadImage,\n\t\timagePicker,\n\t\timageInputField,\n\t\tfieldComponents,\n\t} = usePluginOverrides(CMS_PLUGIN_ID);\n\n\tconst [slug, setSlug] = useState(initialSlug);\n\tconst [publishAt, setPublishAt] = useState(() => {\n\t\tif (!initialPublishAt) return \"\";\n\t\tconst date = new Date(initialPublishAt);\n\t\treturn new Date(date.getTime() - date.getTimezoneOffset() * 60_000)\n\t\t\t.toISOString()\n\t\t\t.slice(0, 16);\n\t});\n\tconst [slugManuallyEdited, setSlugManuallyEdited] = useState(isEditing);\n\tconst [isSubmittingLocal, setIsSubmittingLocal] = useState(false);\n\tconst [formData, setFormData] =\n\t\tuseState>(initialData);\n\tconst [slugError, setSlugError] = useState(null);\n\tconst [submitError, setSubmitError] = useState(null);\n\n\tconst isSubmitting = isSubmittingProp || isSubmittingLocal;\n\n\t// Single-step forms pass their react-hook-form instance through\n\t// onValuesChange; multi-step forms pass undefined (no single instance).\n\tconst [formInstance, setFormInstance] = useState\n\t> | null>(null);\n\n\tconst serverFieldErrors = useMemo(() => fieldErrors ?? {}, [fieldErrors]);\n\tuseServerFieldErrors(formInstance, serverFieldErrors);\n\tconst hasFieldErrors = Object.keys(serverFieldErrors).length > 0;\n\n\t// Track if we've already synced prefill data to avoid overwriting user input\n\tconst hasSyncedPrefillRef = useRef(false);\n\n\t// Sync formData with initialData when it changes\n\t// This handles both:\n\t// 1. Editing mode: always sync when item data is loaded (isEditing=true)\n\t// 2. Create mode: only sync prefill data ONCE to avoid overwriting user input\n\t// useState only uses the initial value on mount, so we need this effect for updates\n\tuseEffect(() => {\n\t\tconst hasData = Object.keys(initialData).length > 0;\n\t\t// In edit mode, always sync (user is loading existing data)\n\t\t// In create mode, only sync prefill data once\n\t\tconst shouldSync = hasData && (isEditing || !hasSyncedPrefillRef.current);\n\n\t\tif (shouldSync) {\n\t\t\tsetFormData(initialData);\n\t\t\tif (!isEditing) {\n\t\t\t\thasSyncedPrefillRef.current = true;\n\t\t\t}\n\t\t}\n\t}, [initialData, isEditing]);\n\n\t// Also sync slug when initialSlug changes\n\tuseEffect(() => {\n\t\tif (isEditing && initialSlug) {\n\t\t\tsetSlug(initialSlug);\n\t\t}\n\t}, [initialSlug, isEditing]);\n\n\t// Parse JSON Schema (now includes fieldType embedded in properties)\n\tconst jsonSchema = useMemo(() => {\n\t\ttry {\n\t\t\treturn JSON.parse(contentType.jsonSchema) as Record;\n\t\t} catch {\n\t\t\treturn {};\n\t\t}\n\t}, [contentType.jsonSchema]);\n\n\t// Convert JSON Schema to Zod schema using formSchemaToZod utility\n\t// This properly handles date fields (format: \"date-time\") and min/max date constraints\n\tconst zodSchema = useMemo(() => {\n\t\ttry {\n\t\t\treturn formSchemaToZod(jsonSchema);\n\t\t} catch {\n\t\t\treturn z.object({});\n\t\t}\n\t}, [jsonSchema]);\n\n\t// Build field config for AutoForm (fieldType is now embedded in jsonSchema)\n\tconst fieldConfig = useMemo(\n\t\t() =>\n\t\t\tbuildFieldConfigFromJsonSchema(\n\t\t\t\tjsonSchema,\n\t\t\t\tuploadImage,\n\t\t\t\tfieldComponents,\n\t\t\t\timagePicker,\n\t\t\t\timageInputField,\n\t\t\t),\n\t\t[jsonSchema, uploadImage, fieldComponents, imagePicker, imageInputField],\n\t);\n\n\t// Find the field to use for slug auto-generation\n\tconst slugSourceField = useMemo(\n\t\t() => findSlugSourceField(jsonSchema),\n\t\t[jsonSchema],\n\t);\n\n\t// Handle form value changes for slug auto-generation\n\tconst handleValuesChange = (\n\t\tvalues: Record,\n\t\tform?: UseFormReturn>,\n\t) => {\n\t\tif (form) {\n\t\t\tsetFormInstance((current) => (current === form ? current : form));\n\t\t}\n\t\tsetFormData(values);\n\n\t\t// Auto-generate slug from source field if not manually edited\n\t\tif (!isEditing && !slugManuallyEdited && slugSourceField) {\n\t\t\tconst sourceValue = values[slugSourceField];\n\t\t\tif (typeof sourceValue === \"string\" && sourceValue.trim()) {\n\t\t\t\tsetSlug(slugify(sourceValue));\n\t\t\t}\n\t\t}\n\t};\n\n\t// Handle form submission\n\tconst handleSubmit = async (data: Record) => {\n\t\tsetSlugError(null);\n\t\tsetSubmitError(null);\n\n\t\tif (!slug.trim()) {\n\t\t\tsetSlugError(\n\t\t\t\tlocalization?.CMS_EDITOR_SLUG_REQUIRED ??\n\t\t\t\t\tt(\"cms.editor.slugRequired\", \"Slug is required\"),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tsetIsSubmittingLocal(true);\n\t\ttry {\n\t\t\tawait onSubmit({\n\t\t\t\tslug,\n\t\t\t\tdata,\n\t\t\t\tpublishAt: publishAt ? new Date(publishAt).toISOString() : null,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst message =\n\t\t\t\terror instanceof Error\n\t\t\t\t\t? error.message\n\t\t\t\t\t: (localization?.CMS_TOAST_ERROR ??\n\t\t\t\t\t\tt(\"cms.toasts.error\", \"An error occurred. Please try again.\"));\n\t\t\tsetSubmitError(message);\n\t\t} finally {\n\t\t\tsetIsSubmittingLocal(false);\n\t\t}\n\t};\n\n\t// Non-field error from the parent (resource form), or a local submit\n\t// failure. Field errors display inline instead — unless the form\n\t// instance is unavailable (multi-step), where they land in the banner.\n\tconst bannerMessage =\n\t\terrorMessage ??\n\t\tsubmitError ??\n\t\t(hasFieldErrors && !formInstance\n\t\t\t? Object.entries(serverFieldErrors)\n\t\t\t\t\t.map(\n\t\t\t\t\t\t([field, message]) =>\n\t\t\t\t\t\t\t`${field}: ${Array.isArray(message) ? message.join(\", \") : message}`,\n\t\t\t\t\t)\n\t\t\t\t\t.join(\" · \")\n\t\t\t: undefined);\n\n\treturn (\n\t\t
\n\t\t\t{/* Slug field */}\n\t\t\t
\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t\t{!isEditing && (\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t{slugManuallyEdited\n\t\t\t\t\t\t\t\t? (localization?.CMS_EDITOR_SLUG_MANUAL ??\n\t\t\t\t\t\t\t\t\tt(\"cms.editor.slugManual\", \"Manually set\"))\n\t\t\t\t\t\t\t\t: (localization?.CMS_EDITOR_SLUG_AUTO ??\n\t\t\t\t\t\t\t\t\tt(\"cms.editor.slugAuto\", \"Auto-generated from first field\"))}\n\t\t\t\t\t\t\n\t\t\t\t\t)}\n\t\t\t\t
\n\t\t\t\t {\n\t\t\t\t\t\tsetSlug(e.target.value);\n\t\t\t\t\t\tsetSlugError(null);\n\t\t\t\t\t\tif (!isEditing) {\n\t\t\t\t\t\t\tsetSlugManuallyEdited(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}}\n\t\t\t\t\tdisabled={isEditing}\n\t\t\t\t\tplaceholder={\n\t\t\t\t\t\tslugSourceField\n\t\t\t\t\t\t\t? (\n\t\t\t\t\t\t\t\t\tlocalization?.CMS_EDITOR_SLUG_PLACEHOLDER_AUTO ??\n\t\t\t\t\t\t\t\t\tt(\n\t\t\t\t\t\t\t\t\t\t\"cms.editor.slugPlaceholderAuto\",\n\t\t\t\t\t\t\t\t\t\t\"Auto-generated from {field}\",\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t).replace(\"{field}\", slugSourceField)\n\t\t\t\t\t\t\t: (localization?.CMS_EDITOR_SLUG_PLACEHOLDER ??\n\t\t\t\t\t\t\t\tt(\"cms.editor.slugPlaceholder\", \"Enter slug...\"))\n\t\t\t\t\t}\n\t\t\t\t/>\n\t\t\t\t{slugError &&

{slugError}

}\n\t\t\t\t

\n\t\t\t\t\t{localization?.CMS_LABEL_SLUG_DESCRIPTION ??\n\t\t\t\t\t\tt(\n\t\t\t\t\t\t\t\"cms.common.slugDescription\",\n\t\t\t\t\t\t\t\"URL-friendly identifier for this item\",\n\t\t\t\t\t\t)}\n\t\t\t\t

\n\t\t\t
\n\n\t\t\t
\n\t\t\t\t\n\t\t\t\t setPublishAt(event.target.value)}\n\t\t\t\t\tdisabled={isSubmitting}\n\t\t\t\t\taria-describedby=\"publishAt-description\"\n\t\t\t\t/>\n\t\t\t\t

\n\t\t\t\t\t{t(\n\t\t\t\t\t\t\"cms.editor.publishAtDescription\",\n\t\t\t\t\t\t\"Optional. Uses your local time zone. Leave empty to clear the schedule.\",\n\t\t\t\t\t)}\n\t\t\t\t

\n\t\t\t\t{serverFieldErrors.publishAt && (\n\t\t\t\t\t

\n\t\t\t\t\t\t{serverFieldErrors.publishAt}\n\t\t\t\t\t

\n\t\t\t\t)}\n\t\t\t
\n\n\t\t\t{/* Submit error message */}\n\t\t\t{bannerMessage && (\n\t\t\t\t
\n\t\t\t\t\t

{bannerMessage}

\n\t\t\t\t
\n\t\t\t)}\n\n\t\t\t{/* Dynamic form from Zod schema */}\n\t\t\t{/* Uses SteppedAutoForm which automatically handles both single-step and multi-step content types */}\n\t\t\t}\n\t\t\t\tvalues={formData as any}\n\t\t\t\tonValuesChange={handleValuesChange as any}\n\t\t\t\tonSubmit={handleSubmit as any}\n\t\t\t\tfieldConfig={fieldConfig as any}\n\t\t\t\tisSubmitting={isSubmitting}\n\t\t\t\tsubmitButtonText={\n\t\t\t\t\tisSubmitting\n\t\t\t\t\t\t? (localization?.CMS_STATUS_SAVING ??\n\t\t\t\t\t\t\tt(\"cms.common.saving\", \"Saving...\"))\n\t\t\t\t\t\t: (localization?.CMS_BUTTON_SAVE ?? t(\"cms.common.save\", \"Save\"))\n\t\t\t\t}\n\t\t\t>\n\t\t\t\t{onCancel && (\n\t\t\t\t\t\n\t\t\t\t\t\t{localization?.CMS_BUTTON_CANCEL ??\n\t\t\t\t\t\t\tt(\"cms.common.cancel\", \"Cancel\")}\n\t\t\t\t\t\n\t\t\t\t)}\n\t\t\t\n\t\t
\n\t);\n}\n", + "content": "\"use client\";\n\nimport { useState, useMemo, useEffect, useRef } from \"react\";\nimport { z } from \"zod\";\nimport type { FieldPath, FieldValues, UseFormReturn } from \"react-hook-form\";\nimport { SteppedAutoForm } from \"@/components/ui/auto-form/stepped-auto-form\";\nimport type {\n\tFieldConfig,\n\tAutoFormInputComponentProps,\n} from \"@/components/ui/auto-form/types\";\nimport { buildFieldConfigFromJsonSchema as buildFieldConfigBase } from \"@/components/ui/auto-form/helpers\";\nimport { formSchemaToZod } from \"@/lib/schema-converter\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Badge } from \"@/components/ui/badge\";\nimport { usePluginOverrides, useTranslate } from \"@btst/stack/context\";\nimport type { CMSPluginOverrides } from \"../../overrides\";\nimport { CMS_PLUGIN_ID } from \"../../constants\";\nimport type { SerializedContentType, RelationConfig } from \"../../../types\";\nimport { slugify } from \"../../../utils\";\nimport { CMSFileUpload } from \"./file-upload\";\nimport { RelationField } from \"./relation-field\";\n\ninterface ContentFormProps {\n\tcontentType: SerializedContentType;\n\tinitialData?: Record;\n\tinitialSlug?: string;\n\tinitialPublishAt?: string | null;\n\tisEditing?: boolean;\n\tonSubmit: (data: {\n\t\tslug: string;\n\t\tdata: Record;\n\t\tpublishAt?: string | null;\n\t}) => Promise;\n\tonCancel?: () => void;\n\t/**\n\t * Server-side field validation errors (`StackError.errors`), applied to\n\t * the matching form fields for inline display.\n\t */\n\tfieldErrors?: Record;\n\t/** Non-field submit error to display above the form */\n\terrorMessage?: string;\n\t/** External submit-in-flight state (e.g. from a resource `useForm`) */\n\tisSubmitting?: boolean;\n}\n\n/**\n * Applies server-side field validation errors onto react-hook-form field\n * state, and clears previously applied server errors that are no longer\n * present. The form instance arrives asynchronously (captured from\n * SteppedAutoForm's `onValuesChange`) and is `null` for multi-step forms.\n */\nfunction useServerFieldErrors(\n\tform: UseFormReturn | null,\n\tfieldErrors: Record,\n) {\n\tconst appliedFieldsRef = useRef([]);\n\n\tuseEffect(() => {\n\t\tif (!form) return;\n\n\t\t// Clear stale server errors from fields that are no longer failing\n\t\tfor (const field of appliedFieldsRef.current) {\n\t\t\tif (field in fieldErrors) continue;\n\t\t\tconst { error } = form.getFieldState(field as FieldPath);\n\t\t\tif (error?.type === \"server\") {\n\t\t\t\tform.clearErrors(field as FieldPath);\n\t\t\t}\n\t\t}\n\t\tappliedFieldsRef.current = Object.keys(fieldErrors);\n\n\t\tfor (const [field, message] of Object.entries(fieldErrors)) {\n\t\t\tform.setError(field as FieldPath, {\n\t\t\t\ttype: \"server\",\n\t\t\t\tmessage: Array.isArray(message) ? message.join(\", \") : message,\n\t\t\t});\n\t\t}\n\t}, [fieldErrors, form]);\n}\n\n/**\n * Build field configuration for AutoForm with CMS-specific file upload handling.\n *\n * Uses the shared buildFieldConfigFromJsonSchema from auto-form/helpers as a base,\n * then adds special handling for \"file\" fieldType to inject CMSFileUpload component\n * ONLY if no custom component is provided via fieldComponents.\n *\n * @param jsonSchema - The JSON Schema from the content type (with fieldType embedded in properties)\n * @param uploadImage - The uploadImage function from overrides (for file fields)\n * @param fieldComponents - Custom field components from overrides\n */\ninterface JsonSchemaProperty {\n\tfieldType?: string;\n\trelation?: RelationConfig;\n\t[key: string]: unknown;\n}\n\nfunction buildFieldConfigFromJsonSchema(\n\tjsonSchema: Record,\n\tuploadImage?: (file: File) => Promise,\n\tfieldComponents?: Record<\n\t\tstring,\n\t\tReact.ComponentType\n\t>,\n\timagePicker?: React.ComponentType<{ onSelect: (url: string) => void }>,\n\timageInputField?: React.ComponentType<{\n\t\tvalue: string;\n\t\tonChange: (value: string) => void;\n\t\tisRequired?: boolean;\n\t}>,\n): FieldConfig> {\n\t// Get base config from shared utility (handles fieldType from JSON Schema,\n\t// including per-item configs for arrays of objects).\n\tconst baseConfig = buildFieldConfigBase(jsonSchema, fieldComponents);\n\n\tconst properties = jsonSchema.properties as\n\t\t| Record\n\t\t| undefined;\n\n\tif (!properties) return baseConfig;\n\n\t// Recursively walk the JSON Schema properties and inject CMS-specific custom\n\t// components (file upload, relation picker) for any field with a matching\n\t// fieldType, regardless of nesting depth. Targets:\n\t// - top-level fields\n\t// - properties of nested object fields\n\t// - properties of array items (e.g. `components: z.array(z.object({...}))`)\n\t//\n\t// `targetConfig` is the FieldConfigObject slot to mutate for the property at\n\t// `key`. The recursion mirrors how AutoFormObject + AutoFormArray look up\n\t// per-property configs: nested object/array per-item configs live as keys\n\t// alongside their parent's meta on the same FieldConfigObject.\n\tconst injectCustomFieldTypes = (\n\t\tprops: Record,\n\t\ttargetConfig: Record,\n\t) => {\n\t\tfor (const [key, prop] of Object.entries(props)) {\n\t\t\t// Ensure a slot exists so we can mutate it whether or not the base\n\t\t\t// helper produced an entry for this key.\n\t\t\tconst existing =\n\t\t\t\t(targetConfig[key] as Record | undefined) ?? {};\n\n\t\t\tlet updated = existing;\n\n\t\t\t// Handle \"file\" fieldType when there's NO custom component for \"file\"\n\t\t\tif (prop.fieldType === \"file\" && !fieldComponents?.[\"file\"]) {\n\t\t\t\tif (!uploadImage && !imageInputField) {\n\t\t\t\t\tupdated = {\n\t\t\t\t\t\t...updated,\n\t\t\t\t\t\tfieldType: () => (\n\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\tFile upload requires an uploadImage or{\" \"}\n\t\t\t\t\t\t\t\timageInputField function in CMS overrides.\n\t\t\t\t\t\t\t
\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t} else {\n\t\t\t\t\tupdated = {\n\t\t\t\t\t\t...updated,\n\t\t\t\t\t\tfieldType: (componentProps: AutoFormInputComponentProps) => (\n\t\t\t\t\t\t\t Promise.resolve(\"\"))}\n\t\t\t\t\t\t\t\timageInputField={imageInputField}\n\t\t\t\t\t\t\t\timagePicker={imagePicker}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Handle \"relation\" fieldType when there's NO custom component for \"relation\"\n\t\t\tif (\n\t\t\t\tprop.fieldType === \"relation\" &&\n\t\t\t\tprop.relation &&\n\t\t\t\t!fieldComponents?.[\"relation\"]\n\t\t\t) {\n\t\t\t\tconst relationConfig = prop.relation;\n\t\t\t\tupdated = {\n\t\t\t\t\t...updated,\n\t\t\t\t\tfieldType: (componentProps: AutoFormInputComponentProps) => (\n\t\t\t\t\t\t\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Recurse into nested objects — their per-property configs live as\n\t\t\t// keys on the same parent FieldConfigObject.\n\t\t\tif (prop.properties) {\n\t\t\t\tinjectCustomFieldTypes(\n\t\t\t\t\tprop.properties as Record,\n\t\t\t\t\tupdated,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Recurse into array items — same convention as nested objects.\n\t\t\tconst items = prop.items as JsonSchemaProperty | undefined;\n\t\t\tif (items?.properties) {\n\t\t\t\tinjectCustomFieldTypes(\n\t\t\t\t\titems.properties as Record,\n\t\t\t\t\tupdated,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (Object.keys(updated).length > 0) {\n\t\t\t\ttargetConfig[key] = updated;\n\t\t\t}\n\t\t}\n\t};\n\n\tinjectCustomFieldTypes(\n\t\tproperties,\n\t\tbaseConfig as unknown as Record,\n\t);\n\n\treturn baseConfig;\n}\n\n/**\n * Determine the first string field in the schema for slug auto-generation\n */\nfunction findSlugSourceField(\n\tjsonSchema: Record,\n): string | null {\n\tconst properties = jsonSchema.properties as Record;\n\tif (!properties) return null;\n\n\t// Look for common name fields first\n\tconst priorityFields = [\"name\", \"title\", \"heading\", \"label\"];\n\tfor (const field of priorityFields) {\n\t\tif (properties[field]?.type === \"string\") {\n\t\t\treturn field;\n\t\t}\n\t}\n\n\t// Fall back to first string field\n\tfor (const [key, value] of Object.entries(properties)) {\n\t\tif (value.type === \"string\") {\n\t\t\treturn key;\n\t\t}\n\t}\n\n\treturn null;\n}\n\nexport function ContentForm({\n\tcontentType,\n\tinitialData = {},\n\tinitialSlug = \"\",\n\tinitialPublishAt,\n\tisEditing = false,\n\tonSubmit,\n\tonCancel,\n\tfieldErrors,\n\terrorMessage,\n\tisSubmitting: isSubmittingProp,\n}: ContentFormProps) {\n\tconst t = useTranslate();\n\tconst {\n\t\tlocalization,\n\t\tuploadImage,\n\t\timagePicker,\n\t\timageInputField,\n\t\tfieldComponents,\n\t} = usePluginOverrides(CMS_PLUGIN_ID);\n\n\tconst [slug, setSlug] = useState(initialSlug);\n\tconst publishAtEditedRef = useRef(false);\n\tconst [publishAt, setPublishAt] = useState(() => {\n\t\tif (!initialPublishAt) return \"\";\n\t\tconst date = new Date(initialPublishAt);\n\t\treturn new Date(date.getTime() - date.getTimezoneOffset() * 60_000)\n\t\t\t.toISOString()\n\t\t\t.slice(0, 16);\n\t});\n\tconst [slugManuallyEdited, setSlugManuallyEdited] = useState(isEditing);\n\tconst [isSubmittingLocal, setIsSubmittingLocal] = useState(false);\n\tconst [formData, setFormData] =\n\t\tuseState>(initialData);\n\tconst [slugError, setSlugError] = useState(null);\n\tconst [submitError, setSubmitError] = useState(null);\n\n\tconst isSubmitting = isSubmittingProp || isSubmittingLocal;\n\n\t// Single-step forms pass their react-hook-form instance through\n\t// onValuesChange; multi-step forms pass undefined (no single instance).\n\tconst [formInstance, setFormInstance] = useState\n\t> | null>(null);\n\n\tconst serverFieldErrors = useMemo(() => fieldErrors ?? {}, [fieldErrors]);\n\tuseServerFieldErrors(formInstance, serverFieldErrors);\n\tconst hasFieldErrors = Object.keys(serverFieldErrors).length > 0;\n\n\t// Track if we've already synced prefill data to avoid overwriting user input\n\tconst hasSyncedPrefillRef = useRef(false);\n\n\t// Sync formData with initialData when it changes\n\t// This handles both:\n\t// 1. Editing mode: always sync when item data is loaded (isEditing=true)\n\t// 2. Create mode: only sync prefill data ONCE to avoid overwriting user input\n\t// useState only uses the initial value on mount, so we need this effect for updates\n\tuseEffect(() => {\n\t\tconst hasData = Object.keys(initialData).length > 0;\n\t\t// In edit mode, always sync (user is loading existing data)\n\t\t// In create mode, only sync prefill data once\n\t\tconst shouldSync = hasData && (isEditing || !hasSyncedPrefillRef.current);\n\n\t\tif (shouldSync) {\n\t\t\tsetFormData(initialData);\n\t\t\tif (!isEditing) {\n\t\t\t\thasSyncedPrefillRef.current = true;\n\t\t\t}\n\t\t}\n\t}, [initialData, isEditing]);\n\n\t// Also sync slug when initialSlug changes\n\tuseEffect(() => {\n\t\tif (isEditing && initialSlug) {\n\t\t\tsetSlug(initialSlug);\n\t\t}\n\t}, [initialSlug, isEditing]);\n\n\t// Parse JSON Schema (now includes fieldType embedded in properties)\n\tconst jsonSchema = useMemo(() => {\n\t\ttry {\n\t\t\treturn JSON.parse(contentType.jsonSchema) as Record;\n\t\t} catch {\n\t\t\treturn {};\n\t\t}\n\t}, [contentType.jsonSchema]);\n\n\t// Convert JSON Schema to Zod schema using formSchemaToZod utility\n\t// This properly handles date fields (format: \"date-time\") and min/max date constraints\n\tconst zodSchema = useMemo(() => {\n\t\ttry {\n\t\t\treturn formSchemaToZod(jsonSchema);\n\t\t} catch {\n\t\t\treturn z.object({});\n\t\t}\n\t}, [jsonSchema]);\n\n\t// Build field config for AutoForm (fieldType is now embedded in jsonSchema)\n\tconst fieldConfig = useMemo(\n\t\t() =>\n\t\t\tbuildFieldConfigFromJsonSchema(\n\t\t\t\tjsonSchema,\n\t\t\t\tuploadImage,\n\t\t\t\tfieldComponents,\n\t\t\t\timagePicker,\n\t\t\t\timageInputField,\n\t\t\t),\n\t\t[jsonSchema, uploadImage, fieldComponents, imagePicker, imageInputField],\n\t);\n\n\t// Find the field to use for slug auto-generation\n\tconst slugSourceField = useMemo(\n\t\t() => findSlugSourceField(jsonSchema),\n\t\t[jsonSchema],\n\t);\n\n\t// Handle form value changes for slug auto-generation\n\tconst handleValuesChange = (\n\t\tvalues: Record,\n\t\tform?: UseFormReturn>,\n\t) => {\n\t\tif (form) {\n\t\t\tsetFormInstance((current) => (current === form ? current : form));\n\t\t}\n\t\tsetFormData(values);\n\n\t\t// Auto-generate slug from source field if not manually edited\n\t\tif (!isEditing && !slugManuallyEdited && slugSourceField) {\n\t\t\tconst sourceValue = values[slugSourceField];\n\t\t\tif (typeof sourceValue === \"string\" && sourceValue.trim()) {\n\t\t\t\tsetSlug(slugify(sourceValue));\n\t\t\t}\n\t\t}\n\t};\n\n\t// Handle form submission\n\tconst handleSubmit = async (data: Record) => {\n\t\tsetSlugError(null);\n\t\tsetSubmitError(null);\n\n\t\tif (!slug.trim()) {\n\t\t\tsetSlugError(\n\t\t\t\tlocalization?.CMS_EDITOR_SLUG_REQUIRED ??\n\t\t\t\t\tt(\"cms.editor.slugRequired\", \"Slug is required\"),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tsetIsSubmittingLocal(true);\n\t\ttry {\n\t\t\tawait onSubmit({\n\t\t\t\tslug,\n\t\t\t\tdata,\n\t\t\t\tpublishAt: publishAtEditedRef.current\n\t\t\t\t\t? publishAt\n\t\t\t\t\t\t? new Date(publishAt).toISOString()\n\t\t\t\t\t\t: null\n\t\t\t\t\t: (initialPublishAt ?? null),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst message =\n\t\t\t\terror instanceof Error\n\t\t\t\t\t? error.message\n\t\t\t\t\t: (localization?.CMS_TOAST_ERROR ??\n\t\t\t\t\t\tt(\"cms.toasts.error\", \"An error occurred. Please try again.\"));\n\t\t\tsetSubmitError(message);\n\t\t} finally {\n\t\t\tsetIsSubmittingLocal(false);\n\t\t}\n\t};\n\n\t// Non-field error from the parent (resource form), or a local submit\n\t// failure. Field errors display inline instead — unless the form\n\t// instance is unavailable (multi-step), where they land in the banner.\n\tconst bannerMessage =\n\t\terrorMessage ??\n\t\tsubmitError ??\n\t\t(hasFieldErrors && !formInstance\n\t\t\t? Object.entries(serverFieldErrors)\n\t\t\t\t\t.map(\n\t\t\t\t\t\t([field, message]) =>\n\t\t\t\t\t\t\t`${field}: ${Array.isArray(message) ? message.join(\", \") : message}`,\n\t\t\t\t\t)\n\t\t\t\t\t.join(\" · \")\n\t\t\t: undefined);\n\n\treturn (\n\t\t
\n\t\t\t{/* Slug field */}\n\t\t\t
\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t\t{!isEditing && (\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t{slugManuallyEdited\n\t\t\t\t\t\t\t\t? (localization?.CMS_EDITOR_SLUG_MANUAL ??\n\t\t\t\t\t\t\t\t\tt(\"cms.editor.slugManual\", \"Manually set\"))\n\t\t\t\t\t\t\t\t: (localization?.CMS_EDITOR_SLUG_AUTO ??\n\t\t\t\t\t\t\t\t\tt(\"cms.editor.slugAuto\", \"Auto-generated from first field\"))}\n\t\t\t\t\t\t\n\t\t\t\t\t)}\n\t\t\t\t
\n\t\t\t\t {\n\t\t\t\t\t\tsetSlug(e.target.value);\n\t\t\t\t\t\tsetSlugError(null);\n\t\t\t\t\t\tif (!isEditing) {\n\t\t\t\t\t\t\tsetSlugManuallyEdited(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}}\n\t\t\t\t\tdisabled={isEditing}\n\t\t\t\t\tplaceholder={\n\t\t\t\t\t\tslugSourceField\n\t\t\t\t\t\t\t? (\n\t\t\t\t\t\t\t\t\tlocalization?.CMS_EDITOR_SLUG_PLACEHOLDER_AUTO ??\n\t\t\t\t\t\t\t\t\tt(\n\t\t\t\t\t\t\t\t\t\t\"cms.editor.slugPlaceholderAuto\",\n\t\t\t\t\t\t\t\t\t\t\"Auto-generated from {field}\",\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t).replace(\"{field}\", slugSourceField)\n\t\t\t\t\t\t\t: (localization?.CMS_EDITOR_SLUG_PLACEHOLDER ??\n\t\t\t\t\t\t\t\tt(\"cms.editor.slugPlaceholder\", \"Enter slug...\"))\n\t\t\t\t\t}\n\t\t\t\t/>\n\t\t\t\t{slugError &&

{slugError}

}\n\t\t\t\t

\n\t\t\t\t\t{localization?.CMS_LABEL_SLUG_DESCRIPTION ??\n\t\t\t\t\t\tt(\n\t\t\t\t\t\t\t\"cms.common.slugDescription\",\n\t\t\t\t\t\t\t\"URL-friendly identifier for this item\",\n\t\t\t\t\t\t)}\n\t\t\t\t

\n\t\t\t
\n\n\t\t\t
\n\t\t\t\t\n\t\t\t\t {\n\t\t\t\t\t\tpublishAtEditedRef.current = true;\n\t\t\t\t\t\tsetPublishAt(event.target.value);\n\t\t\t\t\t}}\n\t\t\t\t\tdisabled={isSubmitting}\n\t\t\t\t\taria-describedby=\"publishAt-description\"\n\t\t\t\t/>\n\t\t\t\t

\n\t\t\t\t\t{t(\n\t\t\t\t\t\t\"cms.editor.publishAtDescription\",\n\t\t\t\t\t\t\"Optional. Uses your local time zone. Leave empty to clear the schedule.\",\n\t\t\t\t\t)}\n\t\t\t\t

\n\t\t\t\t{serverFieldErrors.publishAt && (\n\t\t\t\t\t

\n\t\t\t\t\t\t{serverFieldErrors.publishAt}\n\t\t\t\t\t

\n\t\t\t\t)}\n\t\t\t
\n\n\t\t\t{/* Submit error message */}\n\t\t\t{bannerMessage && (\n\t\t\t\t
\n\t\t\t\t\t

{bannerMessage}

\n\t\t\t\t
\n\t\t\t)}\n\n\t\t\t{/* Dynamic form from Zod schema */}\n\t\t\t{/* Uses SteppedAutoForm which automatically handles both single-step and multi-step content types */}\n\t\t\t}\n\t\t\t\tvalues={formData as any}\n\t\t\t\tonValuesChange={handleValuesChange as any}\n\t\t\t\tonSubmit={handleSubmit as any}\n\t\t\t\tfieldConfig={fieldConfig as any}\n\t\t\t\tisSubmitting={isSubmitting}\n\t\t\t\tsubmitButtonText={\n\t\t\t\t\tisSubmitting\n\t\t\t\t\t\t? (localization?.CMS_STATUS_SAVING ??\n\t\t\t\t\t\t\tt(\"cms.common.saving\", \"Saving...\"))\n\t\t\t\t\t\t: (localization?.CMS_BUTTON_SAVE ?? t(\"cms.common.save\", \"Save\"))\n\t\t\t\t}\n\t\t\t>\n\t\t\t\t{onCancel && (\n\t\t\t\t\t\n\t\t\t\t\t\t{localization?.CMS_BUTTON_CANCEL ??\n\t\t\t\t\t\t\tt(\"cms.common.cancel\", \"Cancel\")}\n\t\t\t\t\t\n\t\t\t\t)}\n\t\t\t\n\t\t
\n\t);\n}\n", "target": "src/components/btst/cms/client/components/forms/content-form.tsx" }, { diff --git a/packages/stack/src/__tests__/endpoint-inventory.test.ts b/packages/stack/src/__tests__/endpoint-inventory.test.ts index 4582fdcc2..67ba61a7a 100644 --- a/packages/stack/src/__tests__/endpoint-inventory.test.ts +++ b/packages/stack/src/__tests__/endpoint-inventory.test.ts @@ -56,9 +56,11 @@ const FIRST_PARTY_HTTP_ROUTES = { "listContentTypes", "getContentTypeBySlug", "listContentItems", + "listContentRevisions", "getContentItem", "createContentItem", "updateContentItem", + "restoreContentRevision", "deleteContentItem", "getContentItemPopulated", "listContentByRelation", @@ -214,7 +216,7 @@ describe("composed endpoint inventory", () => { const documented = Object.values(schema.paths).flatMap((methods) => Object.values(methods), ); - expect(documented).toHaveLength(65); + expect(documented).toHaveLength(67); expect( documented.every( (operation) =>