Skip to content
tapedbPublic

About

A CMS on tapedb: content types in code, drafts, releases and an editor studio, in your own Cloudflare account

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

@tapedb/cms

A content management system on TapeDB, running in your own Cloudflare account: content types defined in code, drafts and publishing with revisions, releases and scheduled publishing, real-time co-editing, an editing studio you can brand and extend, a cached delivery path with a typed SDK for websites, and an importer.

The full guide, with screenshots of the studio, is at tapedb.dev/docs/cms.

Everything is enforced on the server: TapeDB's rules check every write inside its transaction (roles, validation, revision order, locks), so the studio, a script and an API client all meet the same rules.

Adding it to a TapeDB app

The CMS is a TapeDB extension (TapeDB 0.5 or later). In a project made by tapedb init:

npx tapedb-cli add @tapedb/cms
npx tapedb-cli migrate dev --name cms
npx tapedb-cli dev                      # the studio at http://localhost:8787/cms

add installs the package, lists it under "tapedb": { "extensions": [...] } in package.json and sets the project up:

  • cms.content.ts with a first content type;
  • content in the schema's extensions and cms({ content }) in the Worker's;
  • the CONTENT R2 bucket, the IMAGES binding and a one-minute cron trigger in wrangler.jsonc, which tapedb deploy provisions.

Running it again changes nothing. Code it cannot edit with certainty (options built elsewhere, say) it leaves alone and says what to add. By hand, the whole set-up is:

// tapedb.schema.ts
export default schema(appModels, { extensions: [content] });

// worker.ts
import { cms } from "@tapedb/cms/worker";
const tapedb = defineTapeDB({ schema, migrations, extensions: [cms({ content })] });

The CMS adds its models to the schema next to the app's, and its file rules for public/; the app's own models and rules are unchanged. TapeDB serves the CMS's routes, hands it every content change after the commit (in the workspace's Durable Object, in order, retried until it succeeds) and runs it on the Worker's cron, so there is no webhook, secret or public URL to configure.

Content types

// cms.content.ts
import { defineContent, field } from "@tapedb/cms";

export const content = defineContent({
  author: {
    name: field.string({ required: true, max: 80 }),
    bio: field.richText(),
  },
  post: {
    title: field.string({ required: true, max: 120 }),
    slug: field.slug({ required: true }),
    cover: field.image(),
    body: field.richText({ required: true }),
    author: field.reference("author", { required: true }),
    related: field.reference("post", { weak: true }),
  },
});
Field Stores
string({ max, pattern, multiline }) text
slug() lowercase words joined by hyphens; unique among published documents of the type
number({ min, max }) a number
boolean() true or false
select(options) one of a fixed list of strings
date({ time }) "2026-11-28", or with time an ISO date-time in UTC
richText({ lock }) ProseMirror JSON
reference(type, { weak }) a document of another type: strong (deleting the target is refused) or weak (may dangle)
image() { path, alt, x, y }: a workspace file and its focal point
json() any JSON value, usually with a custom input

Every field takes required, label, description (help under the label) and input (a custom input from the studio extension).

Each content type compiles to four models:

Model Holds
post the published values, rev, publishedAt
postDraft the working copy, one per document (id draftId(postId)), with editedBy, the last person to write it
postRevision an immutable snapshot per publish and unpublish
postVersion the document's values inside a release

Two more models serve every type: cmsRelease (releases) and cmsPerson (each person's display name, written by that person, so the studio shows names rather than ids).

Run npx tapedb-cli migrate dev after changing content types. An added field is an additive migration; a removed field needs --accept-data-loss.

Rules

The rules run on the server, inside the write's transaction:

  • A draft may be incomplete. A published document must be complete and valid.
  • Every write to a document advances rev by one, so a publish based on an older revision is refused.
  • A strong reference is a foreign key: its target cannot be deleted while referenced. A weak reference may point at nothing.
  • Published slugs are unique per type.
  • Rich-text fields are locked per editor while they are edited (30 seconds, renewed by the editor). A write to a locked field from anyone else is refused.
  • A revision is written in the writer's own name and never changes; a draft records its last editor, also only in the writer's own name.
  • Only editors schedule, in their own name; a release publishes only if its documents are still at the revisions they were added at.
  • Files under public/ are readable by anyone (the delivery path serves them); contributors add new images under public/media/ and delete their own.
Role Can
user read published documents
member (contributor) read and write drafts and release versions, upload images, make preview links
editor publish, unpublish, publish and schedule releases, manage all media
admin delete documents
owner manage members (with TapeDB sign-in)

Operations

import { createCms } from "@tapedb/cms/client";

const cms = createCms(db, content, { sub: user.id });

const id = await cms.create("post", { title: "Hello" });
await cms.lock("post", id, "body");
await cms.edit("post", id, { body, slug: "hello", authorId });
await cms.unlock("post", id, "body");
await cms.publish("post", id, 0);   // publishes as rev 1

await cms.draft("post", id);        // a new draft from the published values
await cms.discard("post", id);
await cms.unpublish("post", id, 1);
await cms.revisions("post", id);
await cms.restore("post", id, 1);   // revision 1's values into the draft

const release = await cms.releases.create("Spring");
await cms.releases.add(release, "post", id, { title: "Spring" });
await cms.releases.publish(release); // every version in one transaction
await cms.releases.schedule(release, Date.parse("2026-12-01T09:00:00Z"));

await cms.delete("post", id);       // admins; refused while another document refers to it

A release version records its document's revision when it is added; if the document is published separately in the meantime, the release is refused until the version is added again, so a release never overwrites newer work.

Scheduled publishing

An editor schedules a release (or, from the studio's review sheet, a single document). The CMS keeps the schedule from the changes to cmsRelease and publishes what is due from the Worker's cron ("triggers": { "crons": ["* * * * *"] }, which add writes), acting as the editor who scheduled it, so their role is checked at that moment and the revisions carry their name. A release that can no longer publish cleanly is unscheduled and carries scheduleError.

Outside production, POST /_cms/tick with { "now": <epoch ms> } runs the same pass on demand, as if the time were now.

Co-editing

Rich-text fields default to one editor at a time: a lock taken on focus, renewed while typing, released on blur, and enforced by the rules. field.richText({ collaborative: true }) lets several people edit at once: each editor holds a Yjs document, changes travel on a TapeDB broadcast topic and merge as they type, and the merged state is saved beside the field so later editors continue the same history. A change made outside co-editing (a restore, an import) restarts every editor from it.

Importing

npx tapedb-cli cms import records.ndjson --url https://<worker>.workers.dev --workspace <id> --token <editor claim> --publish

--url defaults to tapedb dev on port 8787, and --dev <name> takes a development claim there instead of --token; the content types come from cms.content.ts (or --content <file>). One record per line (or a JSON array): { "type": "post", "id": "<source id>", "fields": { … } }. References are { "ref": "<source id>" }; rich text is ProseMirror JSON, { "markdown": "…" } or plain text; images are { "url" | "file", "alt" } and are uploaded to the media library. Every record is checked against the content types before anything is written, and all problems are listed at once (--dry-run stops there). Documents keep their source ids where they can, so a second run updates them. @tapedb/cms/import exposes the same as importContent(db, content, records, options).

Each operation is one transaction. A refused write rejects with TapeDB's permission_denied.

Studio

The CMS serves the editing studio from the same Worker, at /cms?workspace=<id>:

  • Home: what waits for review (or, for contributors, their open drafts), the latest publishes across types, and who is in the studio and which document and field each person is in.
  • Lists: each type's documents with an excerpt, status, revision, last editor and time; search (/) and filters for drafts, documents in review and published ones. People working on a document show beside it.
  • Documents: forms generated from the fields; rich text with locks (another editor sees who is editing a field, and their saved changes appear as they land); autosave; a margin mark on every field whose draft differs from the published revision; history with restore.
  • Review and publish: the review sheet lists each changed field with word-level proof marks (deletions struck, insertions underlined) and publishes the draft as the next revision (⌘↵).
  • Preview (⌘.): the document as a reader sees it, beside the form, live, switching between the draft and the published revision.
  • Media: images uploaded to the workspace's files under public/media/, which /img serves to websites. An image field holds { path, alt, x, y }; clicking the image sets the focal point, and the field shows the wide, square and tall crops it produces.
  • Jump to (⌘K): any document, type or action by name.
  • Releases: documents grouped to publish together, now or at a set time; "Add to release" on any document, "Schedule" in the review sheet.
  • Preview links: a signed link (72 hours) to a draft, for someone without an account; it opens a read-only page in the studio's brand.
  • People (with TapeDB sign-in): members, their roles and pending invites. An owner invites someone by email or with a link anyone can use once, picks the role and how long it works (1, 7 or 30 days), and can withdraw it until it is used. The invite is emailed when the app has an email sender; the link opens the studio, signs the person in and puts them in the workspace with that role. An invite for an address works only for that address, once it is verified.
  • Co-editing: collaborative fields merge as people type, and the toolbar says who is editing with you.

Every control is the studio's own (listboxes, calendars, steppers, tooltips, scrollbars), so it looks and behaves the same in every browser and theme, with full keyboard use. What each person can do follows the role rules above. Light and dark follow the system setting.

On your own site

Editors can open the studio at /studio on your own site. A site on Cloudflare Workers (a Worker, or Astro, Next.js, SvelteKit, Nuxt or React Router on Workers) binds the CMS Worker and lets mountStudio answer first:

// the site's wrangler.jsonc
"services": [{ "binding": "CMS", "service": "<the CMS Worker's name>" }]
import { mountStudio } from "@tapedb/cms/site";

let studio: ReturnType<typeof mountStudio> | undefined;

export default {
  async fetch(request: Request, env: { CMS: Fetcher }) {
    studio ??= mountStudio({ worker: env.CMS });
    return (await studio(request)) ?? site(request, env);
  },
};

It forwards /studio/… to the Worker's studio (studioPath, default /cms), and the paths the studio talks to: /engine/… and /_tapedb/…, plus /auth and /api/auth/… for TapeDB's sign-in (auth: false keeps those for the site's own). Everything else returns null. The Worker gets each request with the site's address, so sign-in, its emails and cookie, preview links and live editing all stay on the site. path sets where the site serves it; one mountStudio per studio serves several. example-site/ mounts the example's two studios at /studio and /newsroom on port 8795.

Branding

Without a brand the studio wears tapedb's identity: the cassette and wordmark, tapedb orange, Space Grotesk, Inter and JetBrains Mono. With one it carries the app's own:

cms({
  content,
  studio: {
    brand: {
      name: "Northwind Newsroom",
      logo: "<svg viewBox='0 0 32 32'>…</svg>", // or "/logo.svg", or an https URL
      accent: { light: "#0f6b73", dark: "#5cc4c9" },
      palette: { light: { ground: "#f7f4ee", card: "#fffdf9" } },
      fonts: { display: "'Fraunces', serif" },
      css: "@font-face { font-family: 'Fraunces'; src: url(/fonts/fraunces.woff2) }",
      radius: { control: 8, panel: 12 },
    },
  },
});
Option Sets
name the sidebar, the sign-in page and the browser tab
logo, favicon SVG markup (served from <path>/brand/), a same-origin path, a data:image URL or an https URL; the favicon defaults to the logo
accent primary actions, focus and change marks; one colour or { light, dark }
palette any colour token per scheme: ground, surface, card, raised, line, lineStrong, text, text2, text3, accent, accentSoft, onAccent, ok, danger
fonts display, ui, reading (rich text and preview), mono: font-family lists
css a stylesheet added after the studio's; https origins in its url()s are allowed by the page's CSP
radius control and panel, in px
scheme "system" (default), "light" or "dark"
poweredBy a small "Built on tapedb" line under the sidebar; default true, false removes it

Colours, font lists and assets are checked when the Worker starts; a value the page can't use throws. studio also takes path (default /cms), and a list of studios serves the same content at several paths: the example has /cms in tapedb's identity and /newsroom under a sample brand (studio: [{}, { path: "/newsroom", brand, extension }]). studio: false serves none.

Sign-in

studio.signIn:

Value People sign in
"tapedb" with TapeDB's built-in auth. A signed-out visit goes to /auth?returnTo=/cms (TapeDB's page, or the app's own tapedb.auth.tsx) and comes back. The studio lists the person's workspaces, offers to create one when they have none, and takes each claim from /_tapedb/claim with the person's workspace role.
{ tokenPath } through the app's own route, which answers GET <tokenPath>?workspace=<id> with { token, sub, role, name?, workspace? } for the signed-in person
"development" with a name and a role, through TapeDB's development claim route, which answers only outside production
"auto" (default) "tapedb" when the Worker serves TapeDB's auth routes, otherwise "development"

example-auth/ serves the example's content behind TapeDB's built-in auth; cms({ content, studio: { signIn: "tapedb" } }) is all the CMS needs.

Extensions

An app adds its own field inputs, previews and front-page panels in tapedb.cms.tsx, next to tapedb.auth.tsx:

import { defineStudio, type FieldInputProps, type PreviewProps, RichText } from "@tapedb/cms/studio";

const SWATCHES = ["#0f6b73", "#b8440a", "#5b3fa6"];

function Colour({ value, onChange, editable }: FieldInputProps<string>) {
  return (
    <div className="swatches">
      {SWATCHES.map((c) => (
        <button key={c} type="button" aria-pressed={value === c} disabled={!editable} style={{ background: c }} onClick={() => onChange(c)} />
      ))}
    </div>
  );
}

function Article({ row }: PreviewProps) {
  return (
    <article>
      <h1>{row.title}</h1>
      <RichText doc={row.body} />
    </article>
  );
}

export default defineStudio({
  inputs: { colour: Colour },        // used by fields with { input: "colour" }
  previews: { post: Article },       // replaces the generic preview for posts
  panels: [{ title: "Content health", component: Health }], // Health: any component
});

tapedb dev builds it to tapedb/cms-studio.gen.ts and rebuilds it when it or anything it imports changes; tapedb deploy builds it before deploying; npx tapedb-cli build builds it on its own, for a typecheck or a raw wrangler command. The build needs esbuild (npm i -D esbuild). The Worker passes it to the studio:

import { studioExtension } from "./tapedb/cms-studio.gen";
cms({ content, studio: { extension: studioExtension } });

A field uses the input named by its input option, else one registered as "<type>.<field>", else one registered for its kind ("string", "image", …), else the studio's own. An input receives value, onChange(next, { now }) (saved through the studio's autosave), editable, field, name, type, documentId and row. A preview receives type, row (the draft or the published revision), which and published. @tapedb/cms/studio also exports useStudio() (the client, content operations, the signed-in person, nameOf, go), useLiveQuery, FileImage, RichText, Avatar, MediaPicker, labelOf, excerptOf and textOf.

The extension is its own script. React, React DOM and @tapedb/cms/studio are the studio's own copies, shared at run time, so the build stays small and an extension's components are ordinary components inside the studio. CSS it imports is served with it. The example's newsroom studio (example/tapedb.cms.tsx) has a colour input, an article preview and a panel.

Delivery

The CMS serves read routes for websites, anonymous and cached:

Route Serves
GET /content/:workspace/:type/:id a published document as JSON
GET /content/:workspace/:type?slug=:slug the same, by slug
GET /content/:workspace/:type published documents, a page at a time: limit (1–100), cursor, order (publishedAt or a boolean, select, date, number, slug or reference field; - for descending), where.<field>=<value> on the same fields
…?expand=<field>,… any of the above with reference fields replaced by the referenced published documents
GET /img/:workspace/:path?w&h&fx&fy&f an image file under public/, resized and cropped around the focal point (fx, fy from 0 to 1)

Published documents are copied to the CONTENT R2 bucket from the changes TapeDB hands the CMS, ordered by rev, so a repeated change never replaces a newer revision. Nothing outside the Worker can write there: there is no endpoint to post changes to. Responses are cached for 10 seconds. A change purges the cache in the data center it is handled in; elsewhere a cached response is served until it expires. Under tapedb dev a publish reaches the delivery routes in about a second.

Bindings: CONTENT (R2) for delivery, IMAGES (Cloudflare Images) for resizing in /img. Without CONTENT the studio works and the delivery routes answer 501. Without IMAGES, or on an account that cannot use Images, /img serves each image as uploaded, at full size, with x-cms-image: original and the reason in x-cms-image-reason; resized responses carry x-cms-image: transformed.

Reading content from a website

@tapedb/cms/delivery reads the delivery routes with types taken from the content types. It needs only fetch, so it runs in browsers, Workers, Node, Deno and static-site builds, and it holds no credentials.

import { createDelivery, toHtml } from "@tapedb/cms/delivery";
import { content } from "./cms.content";

const site = createDelivery({ url: "https://<worker>.workers.dev", workspace, types: content.types });

const post = await site.bySlug("post", "hello-world", { expand: ["author"] });
post?.title;          // string | null
post?.author?.name;   // the referenced author, expanded
toHtml(post?.body);   // escaped HTML; links other than http(s), mailto and same-site paths are dropped
site.image(post?.cover, { width: 1200, height: 630 }); // resized around the focal point

const { items, cursor } = await site.list("post", { where: { section: "News" }, order: "-publishOn", limit: 10 });
for await (const p of site.all("post")) { /* every published post, page by page */ }

get and bySlug return null for anything not published. toText gives plain text for excerpts and meta descriptions. In React, @tapedb/cms/react has <RichText doc={post.body} components={{ heading: … }} /> and <Image site={site} image={post.cover} width={1200} height={630} />.

Development

npm install
npm test              # builds, then the example app under tapedb dev
npm run test:deployed # deploys the example to a temporary Worker, runs the tests, deletes it
npm run build
python3 scripts/studio-walkthrough.py        # with npm run dev: editors, a reader, the newsroom brand and extension
python3 scripts/studio-auth-walkthrough.py   # with npm run dev:auth: built-in sign-in, workspaces, roles, invites, People
python3 scripts/studio-coedit-walkthrough.py # with npm run dev: two browsers typing into one field
python3 scripts/studio-narrow-walkthrough.py # with npm run dev: the studio on a 390 px phone, and nothing of it at 1440 px

example/ is a complete app that lists @tapedb/cms as an extension (linked from this checkout): its schema, Worker, tapedb.cms.tsx and migrations are what the tests run against. example-auth/ serves the same content types with TapeDB's built-in auth on port 8794. example-site/ is a site with both studios at /studio and /newsroom over a service binding to example/ (npm run dev, then npm run dev:site in a second terminal).

License

MIT

About

A CMS on tapedb: content types in code, drafts, releases and an editor studio, in your own Cloudflare account

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages