Drafts and publishing

Version history on by default, plus an opt-in draft/publish workflow. Save unpublished edits, restore prior versions, and gate publish via RBAC.

Every entity and global keeps a version history by default (History without drafts, last 50 versions). Mark an entity with versions: true and the engine adds a complete drafts-and-publishing pipeline: every save is recorded as a version row, drafts layer on top of the published state without affecting public reads, and a single FK pointer tracks the pending draft and the published marker.

          import { entity, text } from "@cms/config";

const posts = entity("posts", {
  versions: true,
  fields: [text("title", { required: true }), text("body")],
});
        

The storage model is two FK columns on canonical (pending_draft_version_id, published_version_id) plus a shared _versions table. Restoring a version validates its stored data against the current schema — if the data no longer parses (e.g. a field type changed), the restore is refused. The engine never migrates stored data across schema changes.

State derivation

Every response with versions enabled carries a synthesised _status field:

published_at pending_draft_version_id _status
NULL (any) "draft"
NOT NULL NULL "published"
NOT NULL NOT NULL "modified"

"modified" is the “edit a published doc without affecting live” state: canonical stays at the published data, and a draft row sits on top via the FK. Public reads see canonical; admin reads with ?draft=true see canonical merged with the draft row.

How it maps to URLs

Action URL Permission
Read published canonical GET /api/:entity/:id entity.read
Read editorial view (canonical + pending draft if any) GET /api/:entity/:id?draft=true entity.read + entity.versions.read
List or find in the editorial view (filtered, sorted and counted on the pending drafts, except multi-relation filters, which read the published values; see Querying) GET /api/:entity?draft=true entity.read + entity.versions.read
Save draft (don’t publish) PUT /api/:entity/:id?draft=true entity.versions.create
Publish PUT /api/:entity/:id entity.update
Discard pending draft DELETE /api/:entity/:id?draft=true entity.versions.discard
Unpublish (one, or _bulk-unpublish) POST /api/:entity/:id/unpublish entity.update + entity.versions.create + entity.read
List history GET /api/:entity/:id/versions entity.read + entity.versions.read
Read one history row GET /api/:entity/:id/versions/:vid entity.read + entity.versions.read
Restore a version POST /api/:entity/:id/versions/:vid entity.update + entity.read + entity.versions.read
Hard delete the doc DELETE /api/:entity/:id entity.delete

A draft or history read applies both rules: the document must pass the read filter and the versions.read filter, and the fields either one excludes are left out (draft lists too). A restore is gated the same way, and its response leaves out the fields read, versions.read or update excludes. A role with update: true but a scoped read sees drafts and history only of the documents, and the fields, its read reaches.

One exception: a hook’s system client reads drafts and history with versions.read alone. Its read is limited to published documents, which is exactly what draft: true lifts.

History is treated as an audit log: there is no per-version delete (no UI, no API). Rows are removed only by retention pruning (versions.limit) or by cascade when the canonical row is hard-deleted. The versions.discard permission gates the draft-discard endpoint — not history-row deletion.

For globals, the same endpoints exist relative to /api/:global (no :id segment). Hard-delete is not available for globals; use DELETE /?draft=true to discard the draft or POST /unpublish to take it off-air.

Globals share entity behaviour for everything else, too: every write response (publish, save draft, restore, unpublish) omits fields the role can’t read, a value a unique rule refuses returns 400 on its fields, and a global’s slug is reserved in the same registry as entities so the two can never collide.

History without drafts

This is the default: an entity or global that leaves versions out goes live on every save and keeps its last 50 versions, as if it set versions: { drafts: false, limit: 50 }. Set it explicitly to change the cap (limit: false keeps every version):

          const pdp = entity("pdp", {
  global: true, // versions left out: history, no drafts, last 50 versions
  fields: [/* … */],
});

const faqs = entity("faqs", {
  versions: { drafts: false, limit: 200 },
  fields: [/* … */],
});

const logs = entity("logs", {
  versions: false, // no history: saves overwrite, nothing is kept
  fields: [/* … */],
});
        

Every write goes live and leaves a version, so one wrong save can be restored from History. The rest of this guide applies with these differences:

Action versions: true versions: { drafts: false }
Create, translate Draft; the first version is the pending draft Live; the first version is the published one
PUT (save) Publishes, writes a version Same: goes live, writes a version
Restore The version becomes the pending draft The version goes live as a new version
Draft save, discard draft, unpublish Available 400
_bulk-publish, _bulk-unpublish Available Not registered (404)
Draft read (?draft=true) Overlays the pending draft Returns canonical content, under read
_status draft / published / modified Omitted, as with versions: false
Admin Save draft + Publish, status badge One Save button; History with restore
  • Permissions are those of an entity with versions: false: create needs create, save and restore need update, and History needs versions.read. versions.create and versions.discard have nothing to gate, so a drafter-only role can’t write.
  • Hooks: whenever content goes live, beforePublish/afterPublish fire next to the create or update hooks, so revalidation and shared-field propagation keep working. Restore fires beforeRestore, then afterRestore and afterPublish.
  • Switching an entity from versions: true needs no migration. A pending draft left behind is ignored: reads serve canonical content, the next save clears it, and its version stays restorable in History. A document that was never published stays unpublished until it is saved.

Typed SDK

@cms/client ships typed methods for every endpoint above. Reads keep a draft flag as a view selector (so a preview cookie can flip the whole client into draft mode via client.config({ draft: true }) or ClientOptions.draft). State transitions live on dedicated namespaces, so the call site reads as the intent.

          import { createClient } from "@cms/client";
import type cmsConfig from "./cms.config";

const client = createClient<typeof cmsConfig>({ url: "http://localhost:4000" });

// Reads — `draft: true` selects the editorial view. Drafts are fully valid,
// so the return type is the same either way; only `_status` differs.
const published = await client.get("posts", id);
const editorial = await client.get("posts", id, { draft: true });
// `find` and `list` take the same flag, and filter on the draft's values: a slug
// changed in a pending draft finds the document by its new slug.
const { data: bySlug } = await client.find("posts", { filter: { slug }, draft: true });

// Writes — namespaces match the lifecycle step. Bodies are typed from the config.
await client.create("posts", { title: "WIP" });
await client.drafts.save("posts", id, { title: "Edited" });
await client.update("posts", id, fullBody);       // publish
await client.unpublish("posts", id);
await client.drafts.discard("posts", id);

// History.
const { data: rows } = await client.versions.list("posts", id);
await client.versions.restore("posts", id, versionId);

// Globals — same surface, no id arg. Pass `locale` on translatable globals.
await client.drafts.save("site-settings", { siteName: "WIP" }, { locale: "en" });
await client.versions.list("site-settings");
        

The client-level draft default is overridden by a per-call value (including false to force canonical on a single read).

Lifecycle by example

          # 1. Create — lands as draft with publishedAt NULL. The body must contain
#    every required field; drafts are fully valid.
curl -X POST /api/posts -d '{"title": "WIP"}'
# → { "data": { "id": "abc", "title": "WIP", "_status": "draft", ... } }

# 2. Save more drafts. Each save creates a new version row; canonical mirrors
#    the latest version while unpublished. PATCH semantics — only changed
#    fields need to be in the body; the server merges onto the prior draft
#    and strict-validates the merged result.
curl -X PUT /api/posts/abc?draft=true -d '{"title": "WIP v2"}'
curl -X PUT /api/posts/abc?draft=true -d '{"body": "intro paragraph"}'
# Pending draft now: { title: "WIP v2", body: "intro paragraph" }.

# 3. Publish. Strict-validates the merged state; sets publishedAt; the new
#    version row becomes the "published marker" (canonical.published_version_id).
curl -X PUT /api/posts/abc -d '{"title": "Final"}'
# → { "data": { "_status": "published", "publishedAt": "...", ... } }

# 4. Edit live without affecting the public-visible row. Canonical stays
#    frozen; a new version row sits on top via pending_draft_version_id.
curl -X PUT /api/posts/abc?draft=true -d '{"title": "Final (edited)"}'

# 5. View the pending edit (admin only — needs versions.read).
curl /api/posts/abc?draft=true
# → { "data": { "title": "Final (edited)", "_status": "modified", "_draftCreatedAt": "..." } }

# 6. Publish the pending edit. The pending draft becomes the new published
#    marker; FK clears.
curl -X PUT /api/posts/abc -d '{}'  # empty body — publishes what's pending

# 7. Or discard the pending edit.
curl -X DELETE /api/posts/abc?draft=true
# Canonical untouched; pending draft row(s) deleted.

# 8. Unpublish — keeps data, hides from public.
curl -X POST /api/posts/abc/unpublish
# publishedAt cleared, published_version_id cleared, _status becomes "draft".

# 9. Restore an old version. Creates a new version row with the chosen data,
#    sets pending_draft_version_id to it. Publication state unchanged.
curl -X GET /api/posts/abc/versions
curl -X POST /api/posts/abc/versions/v123
        

Drafts are PATCH-merged and strict-valid

Every PUT ?draft=true accepts a partial body and merges onto the prior pending draft (or canonical when no draft exists). The merged result must pass strict validation — drafts are fully valid documents that simply aren’t published yet. So:

          # Canonical published with { title: "A", body: "old" }.
curl -X PUT /api/posts/abc?draft=true -d '{"title": "B"}'
# Pending draft now: { title: "B", body: "old" }.    ← merged + strict-valid.
curl -X PUT /api/posts/abc?draft=true -d '{"body": "new"}'
# Pending draft now: { title: "B", body: "new" }.    ← title preserved.
        

Required fields are enforced at every write — POST, PUT, PUT?draft=true, and restore all run the same strict validation. The DB-layer backstop is plain NOT NULL on required columns; a raw-SQL write that nulls a required column is rejected by Postgres.

Trying to create or save a draft with a required field missing returns 400 VALIDATION_ERROR with per-field details. There’s no “save partial then fill in later” state — fill the required fields, then save. The versions feature is for the unpublished-but-valid workflow (work-in-progress entries that aren’t ready to go live), not for half-typed drafts.

PATCH semantics are shallow per top-level field

The merge is JS spread, not a deep merge. Top-level scalar fields behave intuitively. Composite fields replace wholesale:

Patch Existing Result
{title: "B"} {title: "A", body: "X"} {title: "B", body: "X"}
{tags: ["a"]} {tags: ["a", "b", "c"]} {tags: ["a"]} — b, c dropped
{seo: {metaTitle: "X"}} {seo: {metaTitle, metaDescription}} {seo: {metaTitle: "X"}} — metaDescription dropped
{author: {id, _entity}} (single relation) Whole relation ref replaces

For array, object, richText, union, and single relations, send the full composite value. There is no null-as-delete or per-key merge. If you want to update a nested field, read the current state first and merge client-side.

Multi-relations (relation(..., {multiple: true})) live in a junction table, not the canonical row. The first draft save on a published document must include any required multi-relation field — the merge base derived from canonical doesn’t carry it.

Upgrading from the partial-drafts release

Earlier versions of the engine modelled required fields as <entity>_<field>_required_when_published CHECK constraints instead of column-level NOT NULL. The upgrade has two parts: a schema migration (CHECK → NOT NULL) and a data audit (existing nulls must be scrubbed first, otherwise the migration aborts).

1. Audit your data. For every entity with versions enabled, list rows where any required column is currently NULL:

          SELECT id, pending_draft_version_id, <required_col_1>, <required_col_2>, ...
  FROM "<entity_table>"
  WHERE <required_col_1> IS NULL
     OR <required_col_2> IS NULL;
        

These are the partial drafts the new contract forbids. For each, either:

  • Fill it via the admin — opening the doc and saving any change will populate required fields and persist a strict-valid row, OR
  • Discard the pending draft so the row reverts to its last-published state:
          -- For published docs with an incomplete pending draft: detach the FK and
-- delete the post-publish version rows so the doc reverts to canonical.
WITH bad AS (
  SELECT id FROM "<entity_table>"
   WHERE <required_col_1> IS NULL
     OR <required_col_2> IS NULL
)
UPDATE "<entity_table>" SET pending_draft_version_id = NULL
  WHERE id IN (SELECT id FROM bad);
        

For never-published docs (the canonical row itself is incomplete), delete them or fill them via the admin — there’s no “revert” target.

2. Generate and apply the migration.

          pnpm cms migration generate strict_drafts
        

The generator flags ALTER COLUMN SET NOT NULL as destructive (added in this release) — review the printed statements, confirm your audit is clean, then re-run with --accept-data-loss to write the migration. Then:

          pnpm cms migration apply
        

If apply fails with null value in column "<field>" violates not-null constraint, the entire migration transaction rolls back cleanly — your schema stays on the old version. Re-run step 1 against the row from the error message and retry.

3. After upgrading, every POST / PUT?draft=true strict-validates the merged result. Admin forms surface field-level errors via the existing 400 → ClientError.details path, no UI changes needed.

Lifecycle hooks

Every transition fires both a specific hook AND the catch-all afterUpdate (when canonical’s user data changed).

Event Specific hook(s) Catch-all beforeUpdate/afterUpdate fires?
POST /:entity (create) beforeCreate, afterCreate No (separate event)
PUT /:id?draft=true on unpublished beforeDraftSave, afterDraftSave Yes (canonical data changes)
PUT /:id?draft=true on published beforeDraftSave, afterDraftSave No (only FK moves)
PUT /:id (publish) beforePublish, afterPublish Yes
POST /:entity and PUT /:id with drafts: false beforePublish, afterPublish (plus beforeCreate/afterCreate on create) Yes, on save
POST /:id/versions/:vid with drafts: false beforeRestore, afterRestore, afterPublish Yes
POST /:id/unpublish beforeUnpublish, afterUnpublish No (only published_at clears)
POST /:id/versions/:vid (restore on unpublished) beforeRestore, afterRestore Yes
POST /:id/versions/:vid (restore on published) beforeRestore, afterRestore No (only FK moves)
DELETE /:id?draft=true (discard) beforeDiscardDraft, afterDiscardDraft No
DELETE /:id (hard delete) beforeDelete, afterDelete No
          const posts = entity("posts", {
  versions: true,
  fields: [text("title", { required: true })],
  hooks: {
    // Fires on publish (first publish + subsequent updates while published).
    afterPublish: async (post) => {
      await fetch(process.env.SITE_REBUILD_HOOK, { method: "POST" });
    },
    // Fires on every draft save (pre- or post-publish).
    afterDraftSave: async (post, ctx) => {
      await notifyEditor(ctx.user, post);
    },
    // Fires when the doc goes off-air.
    afterUnpublish: async (post) => {
      await cdn.purge(`/posts/${post.id}`);
    },
  },
});
        

The before-variants can transform the data (return the new shape) or throw to abort. The after-variants are fire-and-forget — errors are logged, the request succeeds.

The drafter role pattern

The versions.read / versions.create / versions.discard sub-permissions let you grant draft-editing rights without canonical update rights. An editor who can save drafts but not publish:

          role("drafter", {
  permissions: {
    posts: {
      read: true,
      create: true,
      update: false,   // ← can't publish (PUT /:id needs entity.update)
      delete: false,
      versions: { read: true, create: true, discard: true },
    },
  },
});
        

This drafter can:

  • Create new docs (POST /api/posts) — they land as draft (published_at = NULL).
  • Save drafts (PUT /api/posts/:id?draft=true).
  • List, view, and discard their drafts.

They cannot:

  • Publish via PUT /api/posts/:id (no update).
  • Unpublish (POST /:id/unpublish requires update).
  • Restore a version to canonical (POST /:id/versions/:vid requires update).

Pair the drafter role with an editor who has update: true and you’ve got a review/approval workflow with no schema additions.

Storage shape

_versions.data mirrors the canonical row’s column shape: flat columns, not the nested {id, _entity} API shape. Single-target relations store the bare UUID string; polymorphic single relations store the (name, name_type) column pair. Engine-managed fields (id, timestamps, publishedAt, FK pointers, _entity, locale columns) are stripped from the snapshot so they can’t override canonical on overlay reads. Multi-relations live in junction tables, which hold the canonical values; a version carries them as an array of { id, _entity } refs under the field’s name. A draft save on a published document keeps its multi-relation edits in the pending draft, a draft read resolves them from there, publish writes them to the junction, and restoring a version brings its values back. Versions written before this was the case carry no multi-relation values: restoring one leaves the junction as it is.

The wire shape is unchanged. normalizeRelationShape runs once at the response boundary to project flat columns into nested refs.

Schema compatibility

Versions store the document’s data as JSONB. Schema changes that drop fields or relax types are fine; type-incompatible changes (e.g. a text field that became a number) leave older version data unparseable against the new schema.

  • POST /versions/:vid (restore) strict-validates the stored data against the current schema and rejects with VERSION_INCOMPATIBLE if it doesn’t parse. The version row itself stays in history.
  • GET /versions/:vid returns the stored JSONB as-is — useful for inspecting what the doc looked like at that schema generation.
  • The overlay read GET /:id?draft=true strips engine-managed columns from the snapshot and whitelists the rest by canonical’s live column set before spreading. Fields dropped from the schema (and therefore absent from canonical) don’t leak; engine state (id, timestamps, FK pointers, _entity) is never overridden even if the snapshot’s JSONB is tampered. Type-incompatible changes still pass through — the consumer’s Zod parse catches those.

Retention

Every versioned entity keeps its last 50 versions per document, whether it leaves versions out, sets versions: true or passes an object. Set limit to change the cap, or limit: false to keep every version:

          const posts = entity("posts", {
  versions: { limit: 200 },
  fields: [...],
});

const contracts = entity("contracts", {
  versions: { limit: false }, // every version is kept
  fields: [...],
});
        

The engine prunes oldest rows after each save. The currently-published row and the current pending draft are pinned via FK and never pruned, so the limit applies to plain history rows only.

Public API scoping

The engine does not automatically filter published_at IS NOT NULL for the public role — you set the policy. Add it to your public role’s read permission:

          role("public", {
  public: true,
  permissions: {
    posts: {
      read: { filter: { publishedAt: { $exists: true } } },
    },
  },
});
        

Without this filter, the public role sees rows in any state. Best practice: every versions-enabled entity that’s exposed publicly should have this filter on the public role.

What’s not built in

  • Autosave. Each PUT?draft=true is one save event. Layer debouncing in the admin if you want high-frequency autosave; the engine endpoint is ready when you are.
  • Scheduled publish. Requires a background job runner. Out of scope for v1; userland can implement it with a cron + a scheduledFor field.
  • Multi-stage workflow (draft → review → approved → published). Composable from a select field + RBAC + the lifecycle hooks. The engine doesn’t model state machines beyond the draft/published/modified primitive.

Previous

Hooks

Next

Emails