diff --git a/.changeset/definition-split.md b/.changeset/definition-split.md new file mode 100644 index 00000000..2711b838 --- /dev/null +++ b/.changeset/definition-split.md @@ -0,0 +1,63 @@ +--- +'@tanstack/cms-core': minor +'@tanstack/cms-cli': minor +'@tanstack/cms-skills': minor +'@tanstack/cms-connect-atproto': minor +--- + +Split plugins into a definition and a runtime, and attach a collection's +server-bound hooks, access, and storage in the runtime config. + +**Breaking: `definePlugin({ definition, runtime })`.** A plugin's `name`, +`collections`, `adminNav`, `routes`, and `adminRoutes` go in +`definition: definePluginDefinition({ … })`; its `blockTypes`, `fieldTypes`, +`ops`, `eventHandlers`, and `onEvent` go in `runtime`. The flat +`definePlugin({ name, … })` form throws, and so does a key on the wrong side. +`@tanstack/cms-core/definition` exports `definePluginDefinition` (and the +`CmsPluginDefinition` type) in place of `definePlugin`, which is now +root-only. To migrate, run this from a TanStack CMS checkout: + +```bash +pnpm codemod definition-split +``` + +```ts +// before +definePlugin({ name: 'analytics', collections: [pageview], ops: [topPages] }) +// after +definePlugin({ + definition: definePluginDefinition({ + name: 'analytics', + collections: [pageview], + }), + runtime: { ops: [topPages] }, +}) +``` + +List the plugin's definition in `defineCmsDefinition({ plugins })` and the +plugin in the runtime config's `plugins`; the runtime entry replaces the +definition entry of the same name. A plugin with no collections or routes, +like the AT Protocol connector, can sit in the runtime config alone. One-file +apps list the plugin once in `defineCms({ plugins })`, as before. + +**Breaking: the runtime config's `collections` is an object keyed by +collection name.** `defineCms(definition, { collections: { post: { hooks, +access, storage } } })` attaches the server-bound half of a collection the +definition declares. Hooks are typed from the collection's fields. An unknown +name, any other key, or a hook or rule the definition already sets throws. +Before, the runtime config couldn't name `collections` at all. + +- The same codemod writes `cms.definition.ts` next to each `cms.config.ts` + (collections, `admin`, plugin definitions, and what they depend on) and + rewrites the config to `defineCms(definition, runtime)` with + `Register { cms: typeof definition }`. Hooks and access that import server + code have to be moved to the runtime `collections` by hand. +- `defineInterfaceCollection` is exported from `@tanstack/cms-core/definition`. +- `@tanstack/cms-cli`: `tanstack-cms init` writes `src/cms.definition.ts` and a + `src/cms.config.ts` that calls `defineCms(definition, { … })`. If either file + exists, both are kept unless `--force` is passed. +- `@tanstack/cms-skills`: code-mode `applySkillToCode` adds a skill's + collections to `cms.definition.ts`, creating it and a `cms.config.ts` in a + new app. A one-file app still gets them appended to `cms.config.ts`. +- `@tanstack/cms-connect-atproto`: `createAtprotoConnector()` returns a + runtime-only plugin; add it to the runtime config's `plugins`. diff --git a/.claude/skills/astro-starlight-to-tanstack-cms/SKILL.md b/.claude/skills/astro-starlight-to-tanstack-cms/SKILL.md index 0182e466..ed998507 100644 --- a/.claude/skills/astro-starlight-to-tanstack-cms/SKILL.md +++ b/.claude/skills/astro-starlight-to-tanstack-cms/SKILL.md @@ -7,7 +7,8 @@ description: Migrate an Astro Starlight docs site to TanStack CMS 1.0 (@tanstack Port an [Astro Starlight](https://starlight.astro.build) docs site onto TanStack CMS: the target is a TanStack Start app whose app-specific code is a -`cms.config.ts` (the mapped schema and theme) plus the migrated content. The +`cms.definition.ts` (the mapped schema) and a `cms.config.ts` (blocks, seed, +theme) plus the migrated content. The admin UI, docs layout with sidebar, block editor, drafts and review queue, redirects, sitemap, HTTP API, and MCP come from `@tanstack/cms-core`, `@tanstack/cms-api`, and `@tanstack/cms-ui-react`. @@ -78,7 +79,17 @@ shape of [`examples/blog`](../../../examples/blog) (same as the Payload skill - `src/router.tsx` — `import './cms.config'` then build the router from `./routeTree.gen` (generated on first `dev`/`build`). -## 3. Map the schema → `src/cms.config.ts` +## 3. Map the schema → `src/cms.definition.ts` + +Write `cms.definition.ts` calling `defineCmsDefinition({ collections })`, +importing only from `@tanstack/cms-core/definition` (`defineCollection`, +`redirectsCollection`, …): Vite config and client code load this file, and +`pnpm test:definitions` fails if it reaches React, Start, or server code. +Then write `cms.config.ts` calling +`defineCms(definition, { blockTypes, seed, theme, … })`. Hooks and access +rules that need server code attach there by collection name +(`collections: { post: { hooks, access } }`). A small app may keep one file +(`defineCms({ collections, … })`). One Starlight `docs` collection → one core collection. **Name it `page`** with a `blocks` field: the public renderer (`/p/$id`), the docs layout, and the diff --git a/.claude/skills/astro-starlight-to-tanstack-cms/scripts/migrate-starlight.mjs b/.claude/skills/astro-starlight-to-tanstack-cms/scripts/migrate-starlight.mjs index 4c592490..9180bce2 100644 --- a/.claude/skills/astro-starlight-to-tanstack-cms/scripts/migrate-starlight.mjs +++ b/.claude/skills/astro-starlight-to-tanstack-cms/scripts/migrate-starlight.mjs @@ -16,7 +16,7 @@ * block — there is no Lexical step. With `--export ` it also writes a * CMS export (`tanstack-cms-export` v1) to load with `tanstack-cms import`. * - * This is the data half. The schema half is the hand-written src/cms.config.ts + * This is the data half. The schema half is the hand-written src/cms.definition.ts * (see SKILL.md's frontmatter → field mapping table). */ import { readFileSync, writeFileSync, readdirSync, statSync } from 'node:fs' diff --git a/.claude/skills/emdash-to-tanstack-cms/SKILL.md b/.claude/skills/emdash-to-tanstack-cms/SKILL.md index 911b1c98..c10e9c8a 100644 --- a/.claude/skills/emdash-to-tanstack-cms/SKILL.md +++ b/.claude/skills/emdash-to-tanstack-cms/SKILL.md @@ -6,8 +6,9 @@ description: Migrate an EmDash CMS site to TanStack CMS 1.0 (@tanstack/cms-core # EmDash → TanStack CMS migration Port an [EmDash](https://emdashcms.com) site onto TanStack CMS: the target is a -TanStack Start app whose app-specific code is a `cms.config.ts` (the mapped -schema) plus the migrated content. The admin UI, block editor, public renderer, +TanStack Start app whose app-specific code is a `cms.definition.ts` (the +mapped schema) and a `cms.config.ts` (blocks, seed, theme) plus the migrated +content. The admin UI, block editor, public renderer, drafts, revisions, scheduling, review queue, search, HTTP API, and MCP/WebMCP come from `@tanstack/cms-core`, `@tanstack/cms-api`, and `@tanstack/cms-ui-react`. @@ -92,9 +93,17 @@ Keep the real EmDash source app **out of the pnpm workspace** (it's an external npm project with a large dependency tree) — see `examples/emdash-before` and the `!examples/emdash-before` line in the root `pnpm-workspace.yaml`. -## 3. Map the schema → `src/cms.config.ts` - -Write `cms.config.ts` calling `defineCms({ collections, blockTypes, … })`. +## 3. Map the schema → `src/cms.definition.ts` + +Write `cms.definition.ts` calling `defineCmsDefinition({ collections })`, +importing only from `@tanstack/cms-core/definition` (`defineCollection`, +`redirectsCollection`, …): Vite config and client code load this file, and +`pnpm test:definitions` fails if it reaches React, Start, or server code. +Then write `cms.config.ts` calling +`defineCms(definition, { blockTypes, seed, theme, … })`. Hooks and access +rules that need server code attach there by collection name +(`collections: { post: { hooks, access } }`). A small app may keep one file +(`defineCms({ collections, … })`). **Collections.** Each EmDash collection → a core `Collection`. Name the public page collection **`page` with a `blocks` field** and the blog diff --git a/.claude/skills/emdash-to-tanstack-cms/scripts/migrate-emdash.mjs b/.claude/skills/emdash-to-tanstack-cms/scripts/migrate-emdash.mjs index bc880711..344cdfd6 100644 --- a/.claude/skills/emdash-to-tanstack-cms/scripts/migrate-emdash.mjs +++ b/.claude/skills/emdash-to-tanstack-cms/scripts/migrate-emdash.mjs @@ -16,7 +16,7 @@ * seed. With `--export ` it also writes a CMS export * (`tanstack-cms-export` v1) to load with `tanstack-cms import `. * - * This is the data half. The schema half is the hand-written src/cms.config.ts + * This is the data half. The schema half is the hand-written src/cms.definition.ts * (see SKILL.md's field/collection mapping tables). */ import { readFileSync, writeFileSync } from 'node:fs' @@ -183,7 +183,7 @@ function main() { ) } - // multiselect options for cms.config.ts: every taxonomy's terms + // multiselect options for cms.definition.ts: every taxonomy's terms for (const tax of seed.taxonomies ?? []) { const terms = (tax.terms ?? []).map((t) => `${t.slug} (${t.label})`) console.log(` taxonomy ${tax.name} options: ${terms.join(', ')}`) diff --git a/.claude/skills/payload-to-tanstack-cms/SKILL.md b/.claude/skills/payload-to-tanstack-cms/SKILL.md index 83e70408..9e31b983 100644 --- a/.claude/skills/payload-to-tanstack-cms/SKILL.md +++ b/.claude/skills/payload-to-tanstack-cms/SKILL.md @@ -6,8 +6,9 @@ description: Migrate a Payload CMS (v3) project to TanStack CMS 1.0 (@tanstack/c # Payload → TanStack CMS migration Port a [Payload v3](https://payloadcms.com) project onto TanStack CMS: the -target is a TanStack Start app whose app-specific code is a `cms.config.ts` -(the mapped schema, access rules, and hooks) plus the migrated content. +target is a TanStack Start app whose app-specific code is a +`cms.definition.ts` (the mapped schema) and a `cms.config.ts` (the runtime: +blocks, auth, server-bound access rules and hooks) plus the migrated content. The admin UI, block editor, public renderer, drafts and review queue, media library, HTTP API, and MCP come from `@tanstack/cms-core`, `@tanstack/cms-api`, and `@tanstack/cms-ui-react`. @@ -48,7 +49,7 @@ nested docs), and custom React admin components — these drive the gap report. Outside this repo, start from a TanStack Start app and run `npx tanstack-cms init` (from `@tanstack/cms-cli`): it creates -`src/cms.config.ts`, adds `tanstackCms()` and `cmsVirtualRoutes()` to +`src/cms.definition.ts` and `src/cms.config.ts`, adds `tanstackCms()` and `cmsVirtualRoutes()` to `vite.config.ts`, imports the config from `src/router.tsx`, and ignores `.data/`. In this repo, copy the shape of [`examples/blog`](../../../examples/blog): @@ -66,7 +67,7 @@ Outside this repo, start from a TanStack Start app and run with `tanstackCms` from `@tanstack/cms-ui-react/vite` and `cmsVirtualRoutes` from `@tanstack/cms-ui-react/virtual-routes`. Payload serves its admin at `/admin`; keep that URL with `cmsVirtualRoutes({ adminBasePath: '/admin' })` - plus `defineCms({ admin: { basePath: '/admin' } })`. + plus `defineCmsDefinition({ admin: { basePath: '/admin' } })`. - `vitest.config.ts` — a plain `defineConfig({ test: { environment: 'node', include: ['src/**/*.test.ts'] } })` from `vitest/config`, so tests don't load the Start/Nitro plugins. - `tsconfig.json` — `{ "extends": "../../tsconfig.base.json", "include": ["src/**/*.ts","src/**/*.tsx"] }`. @@ -74,10 +75,22 @@ Outside this repo, start from a TanStack Start app and run model) then build the router from `./routeTree.gen` (generated on first `dev`/`build`). -## 3. Map the schema → `src/cms.config.ts` - -Write `cms.config.ts` calling `defineCms({ collections, blockTypes, … })` and -register its type (`declare module '@tanstack/cms-core' { interface Register { cms: typeof cms } }`). +## 3. Map the schema → `src/cms.definition.ts` + +Write `cms.definition.ts` calling `defineCmsDefinition({ collections, admin })`, +importing only from `@tanstack/cms-core/definition` (`defineCollection`, +`redirectsCollection`, …): Vite config and client code load this file, and +`pnpm test:definitions` fails if it reaches React, Start, or server code. +Then write `cms.config.ts` calling +`defineCms(definition, { blockTypes, auth, seed, collections, … })` and +register the definition's type +(`declare module '@tanstack/cms-core' { interface Register { cms: typeof definition } }`). +The runtime `collections` is an object keyed by collection name that attaches +`hooks`, `access`, and `storage` to the definition's collections: +`collections: { post: { hooks: { afterChange }, access: { read } } }`. Put a +hook or access predicate there when it needs server code (store reads, +a database, secrets); role arrays and pure predicates can stay on the +collection. A small app may keep one file (`defineCms({ collections, … })`). `cms.config.ts` is imported on the client too: read secrets lazily inside functions (AI adapter factories, `webhooks[].secret: () => process.env.X`). @@ -162,7 +175,9 @@ Payload `{ data, originalDoc, req, operation }` → core `{ doc, id }` (`postRead`), `{ id, actor }` (`preDelete`). Return the transformed doc from `preValidate` / `postValidate` / `postRead`; throw to abort a write. Keep hooks under about 50ms. Replace `req.payload.find(…)` with -`queryDocuments`/`readDocument` from `@tanstack/cms-core/server`. Hooks that +`queryDocuments`/`readDocument` from `@tanstack/cms-core/server`, and attach +those hooks in the runtime config +(`defineCms(definition, { collections: { post: { hooks } } })`). Hooks that only fan out to other systems (cache purges, search indexing) usually become `defineCms({ webhooks })` instead. No equivalent: `beforeOperation`, `afterOperation`, `beforeRead`, `afterError`, auth hooks. @@ -288,7 +303,9 @@ judgment. Check at least: - **Richer Lexical** — node types not converted. - **Custom admin components** — Payload React field/view overrides don't carry over automatically; rebuild custom field inputs with `field.input` or - `defineFieldType()`, and custom views or hooks with routes or `definePlugin()`. + `defineFieldType()`, and custom views or hooks with routes or + `definePlugin({ definition, runtime })` (collections and routes in + `definition`, ops and event handlers in `runtime`). - **Databases** — Postgres/MongoDB adapters have no built-in equivalent (SQLite and libSQL/Turso ship; custom `StorageAdapter`s are possible). diff --git a/.claude/skills/payload-to-tanstack-cms/scripts/migrate-data.mjs b/.claude/skills/payload-to-tanstack-cms/scripts/migrate-data.mjs index 205accdc..76df6422 100644 --- a/.claude/skills/payload-to-tanstack-cms/scripts/migrate-data.mjs +++ b/.claude/skills/payload-to-tanstack-cms/scripts/migrate-data.mjs @@ -15,7 +15,7 @@ * `--export ` it also writes a CMS export (`tanstack-cms-export` v1) to * load with `tanstack-cms import `. * - * This is the data half. The schema half is the hand-written src/cms.config.ts + * This is the data half. The schema half is the hand-written src/cms.definition.ts * (see SKILL.md's field/block mapping tables). */ import { writeFileSync } from 'node:fs' @@ -54,7 +54,7 @@ const OUT = join(here, '..', 'src', 'seed-data.ts') const CONFIG = [ { source: 'pages', // Payload collection slug - target: 'page', // core collection name (must match cms.config.ts) + target: 'page', // core collection name (must match cms.definition.ts) id: (doc) => (doc.slug ?? '').replace(/^\//, '') || 'home', fields: [ { name: 'title', kind: 'scalar' }, diff --git a/.claude/skills/voting/SKILL.md b/.claude/skills/voting/SKILL.md index 3617e6f6..d25faf50 100644 --- a/.claude/skills/voting/SKILL.md +++ b/.claude/skills/voting/SKILL.md @@ -8,7 +8,7 @@ description: Build a native upvote/downvote (voting) feature on a TanStack CMS 1 Add Reddit/HN-style upvote/downvote voting to a TanStack CMS app. The worked reference for everything below is [`examples/blog-voting`](../../../examples/blog-voting): the blog example plus -`src/cms.config.ts` (the `vote` collection + count fields), `src/voting/` +`src/cms.definition.ts` (the `vote` collection + count fields), `src/voting/` (the write/read paths, component, and tests), and `src/routes/top.tsx`. When in doubt, read that. @@ -25,7 +25,8 @@ All store functions from `@tanstack/cms-core/server` are **async** — ## 0. Prerequisites -- A TanStack CMS app (`cms.config.ts` + `cmsVirtualRoutes()`), e.g. a copy of +- A TanStack CMS app (`cms.definition.ts` + `cms.config.ts` + + `cmsVirtualRoutes()`), e.g. a copy of [`examples/blog`](../../../examples/blog). - An `auth` config (`createMockAuth()` from `@tanstack/cms-ui-react` for demos, `auth: { getUser }` in production) so votes have a voter. @@ -44,9 +45,11 @@ All store functions from `@tanstack/cms-core/server` are **async** — | Review queue? | **No.** Votes commit directly | The review queue is for _content_ awaiting human approval. Votes are user interactions; the vote documents themselves are the audit trail (revisions give you who-voted-what-when) | | Anonymous votes | Not by default | Anonymous voting invites brigading and can't do one-vote-per-user. If the product needs it, say so explicitly and accept the tradeoffs (§4) | -## 2. Model the schema → `src/cms.config.ts` +## 2. Model the schema → `src/cms.definition.ts` -Add a `vote` collection to the `collections` array and count fields on the votable collection: +Add a `vote` collection to the definition's `collections` array (in a one-file +app, `defineCms({ collections })` in `cms.config.ts`) and count fields on the +votable collection: ```ts defineCollection({ @@ -267,7 +270,7 @@ A small component: up arrow, score, down arrow. Requirements: Agents can read `post` scores through the standard tools, and you can expose voting as a first-class operation and MCP/WebMCP/content-agent tool with `defineOp({ name: 'cast_vote', access: 'content.write', agent: { kind: 'write' }, input, run })` -in `defineCms({ ops })` (where `ctx.session.user?.id` provides the authenticated +in `defineCms(definition, { ops })` (where `ctx.session.user?.id` provides the authenticated voter id). Alternatively, keep `castVote` as a Start server function for the UI only, or serve a custom MCP endpoint that checks `verifyMcpAccess(request)` from `@tanstack/cms-core/server` and calls `castVoteForVoter` with the resolved diff --git a/.claude/skills/wordpress-to-tanstack-cms/SKILL.md b/.claude/skills/wordpress-to-tanstack-cms/SKILL.md index c091353a..cad61a14 100644 --- a/.claude/skills/wordpress-to-tanstack-cms/SKILL.md +++ b/.claude/skills/wordpress-to-tanstack-cms/SKILL.md @@ -6,8 +6,9 @@ description: Migrate a WordPress site to TanStack CMS 1.0 (@tanstack/cms-core + # WordPress → TanStack CMS migration Port a [WordPress](https://wordpress.org) site onto TanStack CMS: the target is -a TanStack Start app whose app-specific code is a `cms.config.ts` (the mapped -schema) plus the migrated content. The admin UI, block editor, public renderer, +a TanStack Start app whose app-specific code is a `cms.definition.ts` (the +mapped schema) and a `cms.config.ts` (blocks, seed, theme) plus the migrated +content. The admin UI, block editor, public renderer, drafts, revisions, review queue, redirects, sitemap, HTTP API, and MCP/WebMCP come from `@tanstack/cms-core`, `@tanstack/cms-api`, and `@tanstack/cms-ui-react`. @@ -85,9 +86,17 @@ migration skills' §2): The WXR source (`-before`) is just the export file + a README — not a workspace app. -## 3. Map the schema → `src/cms.config.ts` - -Write `cms.config.ts` calling `defineCms({ collections, blockTypes, … })`. +## 3. Map the schema → `src/cms.definition.ts` + +Write `cms.definition.ts` calling `defineCmsDefinition({ collections })`, +importing only from `@tanstack/cms-core/definition` (`defineCollection`, +`redirectsCollection`, …): Vite config and client code load this file, and +`pnpm test:definitions` fails if it reaches React, Start, or server code. +Then write `cms.config.ts` calling +`defineCms(definition, { blockTypes, seed, theme, … })`. Hooks and access +rules that need server code attach there by collection name +(`collections: { post: { hooks, access } }`). A small app may keep one file +(`defineCms({ collections, … })`). **Post types → collections.** Map the `page` post type to a core collection **named `page` with a `blocks` field** and `post` to a core **`post`** diff --git a/.claude/skills/wordpress-to-tanstack-cms/scripts/migrate-wordpress.mjs b/.claude/skills/wordpress-to-tanstack-cms/scripts/migrate-wordpress.mjs index ef1c06fd..d13f85f4 100644 --- a/.claude/skills/wordpress-to-tanstack-cms/scripts/migrate-wordpress.mjs +++ b/.claude/skills/wordpress-to-tanstack-cms/scripts/migrate-wordpress.mjs @@ -16,7 +16,7 @@ * `--export ` it also writes a CMS export (`tanstack-cms-export` v1) to * load with `tanstack-cms import `. * - * This is the data half. The schema half is the hand-written src/cms.config.ts + * This is the data half. The schema half is the hand-written src/cms.definition.ts * (see SKILL.md's field/collection mapping tables). */ import { readFileSync, writeFileSync } from 'node:fs' @@ -71,7 +71,7 @@ const CONFIG = { }), }, } -const REDIRECTS = 'redirect' // the redirectsCollection() name in cms.config.ts +const REDIRECTS = 'redirect' // the redirectsCollection() name in cms.definition.ts // =========================================================================== /** Path of a WordPress permalink (`https://site/a-post/` → `/a-post/`), or null. */ diff --git a/.gitignore b/.gitignore index c327f299..dc0ff3a4 100644 --- a/.gitignore +++ b/.gitignore @@ -73,3 +73,6 @@ docs/superpowers .claude/worktrees/* /worktrees/ .claude/scheduled_tasks.lock + +# Scratch apps scripts/verify-definitions.ts scaffolds +packages/cli/.verify-definitions-*/ diff --git a/README.md b/README.md index 5fbcb365..2fc3dab3 100644 --- a/README.md +++ b/README.md @@ -128,8 +128,11 @@ for your app's own routes and components. See ## A minimal app ```ts -// src/cms.config.ts -import { defineCms, defineCollection } from '@tanstack/cms-core' +// src/cms.definition.ts — the content model; safe to load anywhere +import { + defineCmsDefinition, + defineCollection, +} from '@tanstack/cms-core/definition' const post = defineCollection({ name: 'post', @@ -143,15 +146,25 @@ const post = defineCollection({ ], }) -export const cms = defineCms({ collections: [post], blockTypes: [] }) +export const definition = defineCmsDefinition({ collections: [post] }) +``` + +```ts +// src/cms.config.ts — the runtime: storage, auth, AI, ops, server-bound hooks +import { defineCms } from '@tanstack/cms-core' +import { definition } from './cms.definition' + +export const cms = defineCms(definition, { blockTypes: [] }) declare module '@tanstack/cms-core' { interface Register { - cms: typeof cms + cms: typeof definition } } ``` +A small app can keep both halves in one `defineCms({ collections, … })` call. + ```ts // vite.config.ts import { defineConfig } from 'vite' diff --git a/app/base/src/cms.config.ts b/app/base/src/cms.config.ts index b8656779..026a5e52 100644 --- a/app/base/src/cms.config.ts +++ b/app/base/src/cms.config.ts @@ -1,11 +1,12 @@ import { createServerOnlyFn } from '@tanstack/react-start' import { defineCms, interfaceScheduleHandlers } from '@tanstack/cms-core' -import { collections } from './model' import { seed } from './seed' import { baseOps } from './operations' +import { definition } from './cms.definition' +import { collectionRuntimes } from './collection-runtime' -export const cms = defineCms({ - collections, +export const cms = defineCms(definition, { + collections: collectionRuntimes, blockTypes: [], seed, ops: baseOps, @@ -44,6 +45,6 @@ export const cms = defineCms({ }) declare module '@tanstack/cms-core' { interface Register { - cms: typeof cms + cms: typeof definition } } diff --git a/app/base/src/cms.definition.ts b/app/base/src/cms.definition.ts new file mode 100644 index 00000000..e90a980a --- /dev/null +++ b/app/base/src/cms.definition.ts @@ -0,0 +1,6 @@ +import { defineCmsDefinition } from '@tanstack/cms-core/definition' +import { collections } from './model' + +export const definition = defineCmsDefinition({ + collections, +}) diff --git a/app/base/src/collection-runtime.ts b/app/base/src/collection-runtime.ts new file mode 100644 index 00000000..773e7224 --- /dev/null +++ b/app/base/src/collection-runtime.ts @@ -0,0 +1,86 @@ +import { createServerOnlyFn } from '@tanstack/react-start' +import { reportReadAccess } from './report-access' +import { collections } from './model' +import type { + ChangeHookArgs, + CmsCollectionRuntime, + Collection, + CollectionAccess, + Doc, +} from '@tanstack/cms-core' + +/** + * The server-bound half of every Base collection: audit each write and + * delete, and recheck the session's collection rules on every returned + * document (the CMS public-site query path intentionally serves published + * records). + */ +function baseHooks(name: string): NonNullable { + return { + afterChange: createServerOnlyFn( + async ({ id, operation }: ChangeHookArgs) => { + const { currentSession, recordAdminAudit } = + await import('@tanstack/cms-core/server') + const session = currentSession() + if (session?.user) + await recordAdminAudit({ + action: `base.document.${operation}`, + target: `${name}/${id}`, + actor: session.user.id, + }) + }, + ), + afterDelete: createServerOnlyFn( + async ({ id }: { id: string; actor: string }) => { + const { currentSession, recordAdminAudit } = + await import('@tanstack/cms-core/server') + const session = currentSession() + if (session?.user) + await recordAdminAudit({ + action: 'base.document.delete', + target: `${name}/${id}`, + actor: session.user.id, + }) + }, + ), + postRead: createServerOnlyFn(async ({ doc }: { doc: Doc; id: string }) => { + const { currentSession, assertCollectionAccess } = + await import('@tanstack/cms-core/server') + const session = currentSession() + if (session) assertCollectionAccess(session, name, 'read', doc) + return doc + }), + } +} + +/** Access rules that read the live config, so they can't sit in the model. */ +const serverAccess: Record = { + reports: { read: reportReadAccess }, +} + +/** The Interfaces collection is the CMS's own; it gets no Base hooks. */ +const unhooked = new Set(['interfaces']) + +/** The runtime half of collection `name` (also for a schema added later). */ +export function collectionRuntime(name: string): CmsCollectionRuntime { + if (unhooked.has(name)) return {} + return { + hooks: baseHooks(name), + ...(serverAccess[name] ? { access: serverAccess[name] } : {}), + } +} + +/** The runtime config's `collections`: the server-bound half of each template. */ +export const collectionRuntimes = Object.fromEntries( + collections.map((c) => [c.name, collectionRuntime(c.name)]), +) + +/** `collection` with its runtime half attached, as `defineCms` attaches it. */ +export function withCollectionRuntime(collection: Collection): Collection { + const { hooks, access } = collectionRuntime(collection.name) + return { + ...collection, + ...(hooks ? { hooks: { ...collection.hooks, ...hooks } } : {}), + ...(access ? { access: { ...collection.access, ...access } } : {}), + } +} diff --git a/app/base/src/model.ts b/app/base/src/model.ts index 62ef509e..5958e1b3 100644 --- a/app/base/src/model.ts +++ b/app/base/src/model.ts @@ -1,9 +1,15 @@ -import { createServerOnlyFn } from '@tanstack/react-start' -import { defineCollection, defineInterfaceCollection } from '@tanstack/cms-core' -import { reportReadAccess } from './report-access' -import type { ChangeHookArgs, Collection, Doc, Field } from '@tanstack/cms-core' +import { + defineCollection, + defineInterfaceCollection, +} from '@tanstack/cms-core/definition' +import type { Collection, Field } from '@tanstack/cms-core/definition' const readRoles = ['admin', 'editor', 'viewer'] +/** + * A Base collection's pure half. Its audit hooks and server-side read checks + * are attached at runtime (`collection-runtime.ts`), so the definition loads + * without server code. + */ export function baseCollection( name: string, label: string, @@ -19,45 +25,6 @@ export function baseCollection( ...fields, { name: 'published', label: 'Published', type: 'boolean' }, ], - // The CMS public-site query path intentionally serves published records. - // Base applies its authenticated collection rules on every returned document. - hooks: { - afterChange: createServerOnlyFn( - async ({ id, operation }: ChangeHookArgs) => { - const { currentSession, recordAdminAudit } = - await import('@tanstack/cms-core/server') - const session = currentSession() - if (session?.user) - await recordAdminAudit({ - action: `base.document.${operation}`, - target: `${name}/${id}`, - actor: session.user.id, - }) - }, - ), - afterDelete: createServerOnlyFn( - async ({ id }: { id: string; actor: string }) => { - const { currentSession, recordAdminAudit } = - await import('@tanstack/cms-core/server') - const session = currentSession() - if (session?.user) - await recordAdminAudit({ - action: 'base.document.delete', - target: `${name}/${id}`, - actor: session.user.id, - }) - }, - ), - postRead: createServerOnlyFn( - async ({ doc }: { doc: Doc; id: string }) => { - const { currentSession, assertCollectionAccess } = - await import('@tanstack/cms-core/server') - const session = currentSession() - if (session) assertCollectionAccess(session, name, 'read', doc) - return doc - }, - ), - }, access: { read: readRoles, write: ['admin', 'editor'], @@ -171,8 +138,8 @@ export const collections = [ { name: 'result', label: 'Snapshot', type: 'json' }, ], { + // `read` is `reportReadAccess`, attached at runtime. access: { - read: reportReadAccess, write: ['admin', 'editor'], publish: ['admin', 'editor'], delete: ['admin', 'editor'], diff --git a/app/base/src/schema-registry.ts b/app/base/src/schema-registry.ts index 1ba59bff..0cce837e 100644 --- a/app/base/src/schema-registry.ts +++ b/app/base/src/schema-registry.ts @@ -6,6 +6,7 @@ import { } from '@tanstack/cms-core' import type { Collection, DataField } from '@tanstack/cms-core' import { baseCollection, collections as templateCollections } from './model' +import { withCollectionRuntime } from './collection-runtime' export const SCHEMA_META_KEY = 'base:schema-registry:v1' export const fieldTypes = dataFieldTypes @@ -141,13 +142,15 @@ export function runtimeCollection( (c) => c.name === entry.name, ) return { - ...(template ?? - baseCollection( - definition.name, - definition.label, - definition.titleField, - [], - )), + ...withCollectionRuntime( + template ?? + baseCollection( + definition.name, + definition.label, + definition.titleField, + [], + ), + ), ...definition, // Executable access/validation rules come from the protected CMS template, // never its serializable metadata copy. diff --git a/app/base/tests/base.test.ts b/app/base/tests/base.test.ts index bad8aa7f..2b13c8ec 100644 --- a/app/base/tests/base.test.ts +++ b/app/base/tests/base.test.ts @@ -24,6 +24,8 @@ import { import type { CmsOpContext, Field } from '@tanstack/cms-core' import { invokeAnyOp } from '@tanstack/cms-api' import { collections } from '../src/model' +import { definition as cmsDefinition } from '../src/cms.definition' +import { collectionRuntimes } from '../src/collection-runtime' import { seed, DEMO_END_DATE } from '../src/seed' import { baseOps } from '../src/operations' import { calculateTrends, trendsInput } from '../src/trends' @@ -74,8 +76,8 @@ beforeEach(() => { process.env.CMS_DATA_DIR = dir delete process.env.CMS_AUTH_SECRET delete process.env.BASE_ORIGIN - defineCms({ - collections, + defineCms(cmsDefinition, { + collections: collectionRuntimes, blockTypes: [], seed, ops: baseOps, diff --git a/app/base/tests/chat.test.ts b/app/base/tests/chat.test.ts index 2825bbdb..ec5bfdd5 100644 --- a/app/base/tests/chat.test.ts +++ b/app/base/tests/chat.test.ts @@ -10,7 +10,8 @@ import { listPending, } from '@tanstack/cms-core/server' import { invokeAnyOp } from '@tanstack/cms-api' -import { collections } from '../src/model' +import { definition as cmsDefinition } from '../src/cms.definition' +import { collectionRuntimes } from '../src/collection-runtime' import { baseOps } from '../src/operations' import { instructions } from '../src/chat.server' import { readRegistry, withSchemaRegistry } from '../src/schema-registry.server' @@ -51,9 +52,9 @@ async function call(name: string, input: unknown, role = 'admin') { } beforeEach(() => { directory = mkdtempSync(join(tmpdir(), 'base-chat-')) - defineCms({ + defineCms(cmsDefinition, { dataDir: directory, - collections, + collections: collectionRuntimes, blockTypes: [], ops: baseOps, events: { dispatch: 'manual' }, diff --git a/app/base/tests/schema-registry.test.ts b/app/base/tests/schema-registry.test.ts index 7666c7d1..5836fee9 100644 --- a/app/base/tests/schema-registry.test.ts +++ b/app/base/tests/schema-registry.test.ts @@ -14,7 +14,8 @@ import { approve, } from '@tanstack/cms-core/server' import { invokeAnyOp, ops } from '@tanstack/cms-api' -import { collections } from '../src/model' +import { definition as cmsDefinition } from '../src/cms.definition' +import { collectionRuntimes } from '../src/collection-runtime' import { seed } from '../src/seed' import { baseOps } from '../src/operations' import { SCHEMA_META_KEY } from '../src/schema-registry' @@ -75,8 +76,8 @@ async function call(name: string, input: unknown, role = 'admin') { beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'base-schema-test-')) process.env.CMS_DATA_DIR = dir - defineCms({ - collections, + defineCms(cmsDefinition, { + collections: collectionRuntimes, blockTypes: [], seed, ops: baseOps, diff --git a/app/base/tests/worker.test.ts b/app/base/tests/worker.test.ts index e0fb93a2..5d57437d 100644 --- a/app/base/tests/worker.test.ts +++ b/app/base/tests/worker.test.ts @@ -20,7 +20,8 @@ import { setDbUserDisabled, setUserRole, } from '@tanstack/cms-core/server' -import { collections } from '../src/model' +import { definition as cmsDefinition } from '../src/cms.definition' +import { collectionRuntimes } from '../src/collection-runtime' import { seed } from '../src/seed' import { saveSchemaDraft, @@ -44,8 +45,8 @@ describe('Base background interface worker', () => { vi.setSystemTime(new Date('2026-10-11T09:00:00Z')) dir = mkdtempSync(join(tmpdir(), 'base-worker-')) process.env.CMS_DATA_DIR = dir - defineCms({ - collections, + defineCms(cmsDefinition, { + collections: collectionRuntimes, seed, blockTypes: [], dataDir: dir, diff --git a/app/base/tests/wp-evacuation.test.ts b/app/base/tests/wp-evacuation.test.ts index 07a9d8e7..13d68f98 100644 --- a/app/base/tests/wp-evacuation.test.ts +++ b/app/base/tests/wp-evacuation.test.ts @@ -10,7 +10,8 @@ import { } from '@tanstack/cms-core/server' import { invokeAnyOp } from '@tanstack/cms-api' import { createCmsSearch } from '@tanstack/search-cms' -import { collections } from '../src/model' +import { definition as cmsDefinition } from '../src/cms.definition' +import { collectionRuntimes } from '../src/collection-runtime' import { baseOps } from '../src/operations' import { readRegistry, withSchemaRegistry } from '../src/schema-registry.server' @@ -161,9 +162,9 @@ function build50PageSmbAgencyWxr(): string { beforeEach(() => { directory = mkdtempSync(join(tmpdir(), 'base-wp-evacuate-')) - defineCms({ + defineCms(cmsDefinition, { dataDir: directory, - collections, + collections: collectionRuntimes, blockTypes: [], ops: baseOps, events: { dispatch: 'manual' }, diff --git a/app/prm/src/cms.config.ts b/app/prm/src/cms.config.ts index 799f5d51..3bb805c5 100644 --- a/app/prm/src/cms.config.ts +++ b/app/prm/src/cms.config.ts @@ -13,12 +13,12 @@ */ import { createServerOnlyFn } from '@tanstack/react-start' import { defineCms, PERMISSIONS } from '@tanstack/cms-core' -import { crmCollections } from './collections' import { seed } from './seed' import { importPeopleOp } from './ops/import-people' import { enrichAgentConfig, ENRICHMENT_SKILL_PROMPT } from './agents/enrich' import { askAgentConfig } from './agents/ask' import { crmEventHandlers } from './events' +import { definition } from './cms.definition' const resolveServerDataDir = createServerOnlyFn(async () => { const { resolvePrmDataDir } = await import('./instance.server') @@ -35,9 +35,8 @@ if (typeof process !== 'undefined' && process.versions?.node) { } } -export const cms = defineCms({ +export const cms = defineCms(definition, { ...(initialDataDir ? { dataDir: initialDataDir } : {}), - collections: crmCollections, blockTypes: [], ops: [importPeopleOp], eventHandlers: crmEventHandlers, diff --git a/app/prm/src/cms.definition.ts b/app/prm/src/cms.definition.ts new file mode 100644 index 00000000..4e032e91 --- /dev/null +++ b/app/prm/src/cms.definition.ts @@ -0,0 +1,6 @@ +import { defineCmsDefinition } from '@tanstack/cms-core/definition' +import { crmCollections } from './collections' + +export const definition = defineCmsDefinition({ + collections: crmCollections, +}) diff --git a/docs/api/cli.md b/docs/api/cli.md index 974408d9..bfba29b5 100644 --- a/docs/api/cli.md +++ b/docs/api/cli.md @@ -51,7 +51,7 @@ tanstack-cms init [--dir ] [--force] Adds TanStack CMS to an existing TanStack Start app: -- **Config**: writes `src/cms.config.ts` (or `cms.config.ts` when there is no `src` directory) with a `post` collection, a seed post, and the `Register` augmentation for end-to-end types. An existing file is kept unless `--force` is passed. +- **Config**: writes `src/cms.definition.ts` (a `post` collection, importing only `@tanstack/cms-core/definition`) and `src/cms.config.ts` (`defineCms(definition, { … })` with a seed post and the `Register` augmentation for end-to-end types), or both in the app root when there is no `src` directory. If either file exists, both are kept unless `--force` is passed. - **Vite**: in `vite.config.ts`, `.mts`, or `.js`, replaces a plain `tanstackStart()` call with `tanstackCms()` plus `tanstackStart({ router: { virtualRouteConfig: cmsVirtualRoutes() } })` and adds the imports. A config that already passes options to `tanstackStart` is left alone and the snippet is printed instead. - **Router**: adds `import './cms.config'` to `router.tsx` / `router.ts`, so the content model is registered before any loader or server function runs. - **`.gitignore`**: adds `.data/` (the default SQLite database and uploads directory). @@ -61,7 +61,7 @@ It then prints the install command for `@tanstack/cms-core`, `@tanstack/cms-api` | Option | Description | | --- | --- | | `--dir ` | App directory. Default: the working directory. | -| `--force` | Overwrite an existing `cms.config.ts`. | +| `--force` | Overwrite an existing `cms.definition.ts` and `cms.config.ts`. | ### `migrate` diff --git a/docs/api/cms-core.md b/docs/api/cms-core.md index a3a9ae6d..6ca268e2 100644 --- a/docs/api/cms-core.md +++ b/docs/api/cms-core.md @@ -145,7 +145,43 @@ function defineCms( ): WithPlugins> ``` -`defineCmsDefinition` throws on the same collection and plugin name clashes as `defineCms`. The runtime config is every `CmsConfig` option except `collections`, `admin`, and `plugins`; repeating one of those is a type error and throws. `defineCms(definition, runtime)` resolves exactly the config `defineCms({ ...definitionConfig, ...runtime })` would, and `createCms(definition, runtime)` builds an instance the same way. `defineCms(config)` with one config keeps working, and is fine for an app whose config is already light. +`defineCmsDefinition` throws on the same collection and plugin name clashes as `defineCms`. The runtime config is every `CmsConfig` option except `admin`, plus two keys that attach to the definition rather than repeat it: + +- **`collections`** is an object keyed by collection name, not an array. Each entry attaches the collection's server-bound half — `hooks`, `access`, and `storage` — to the collection the definition (or one of its plugins) declares. Hooks are typed from that collection's fields. An unknown name, any other key (`fields`, `label`, …), or a hook or rule the definition already sets throws. Collections the runtime doesn't name are used as declared. +- **`plugins`** lists the plugins with runtimes (`definePlugin({ definition, runtime })`). Each one replaces the definition's plugin of the same name. A plugin without collections or routes may appear only here; one that has them must also be in the definition. + +`defineCms(definition, runtime)` otherwise resolves exactly the config `defineCms({ ...definitionConfig, ...runtime })` would, and `createCms(definition, runtime)` builds an instance the same way. `defineCms(config)` with one config keeps working, and is fine for an app whose config is already light. + +```ts validate=type +import { defineCms } from '@tanstack/cms-core' +import { defineCmsDefinition } from '@tanstack/cms-core/definition' + +const definition = defineCmsDefinition({ + collections: [ + { + name: 'report', + label: 'Reports', + titleField: 'title', + fields: [{ name: 'title', label: 'Title', type: 'text', required: true }], + }, + ], +}) + +export const cms = defineCms(definition, { + blockTypes: [], + collections: { + report: { + // Server-only code (a database, secrets) belongs here, not in the definition. + access: { read: ({ session }) => session.isAuthenticated }, + hooks: { + afterChange: ({ doc }) => { + console.log(`saved ${doc.title}`) + }, + }, + }, + }, +}) +``` The definition's accessors are derived from it, never written by hand, and return the same frozen values on every call: @@ -158,7 +194,7 @@ The definition's accessors are derived from it, never written by hand, and retur `definition.config` is the config as written. `isCmsDefinition(value)` tells a definition apart from a config. -`@tanstack/cms-core/definition` also exports the pure authoring helpers, so collection modules never need the package root: `defineCollection`, `defineBlock`, `defineFieldType`, `definePlugin`, `seoField`, `assetField`, `redirectsCollection`, `isSafeRedirectTarget`, and `isBuiltInFieldType`. These are the same functions the root exports. The entry also exports the types collections use, including `Collection`, `Field`, `BlockType`, `InferDoc`, `CollectionAccess`, `FieldAccess`, and `CmsPlugin`. `defineInterfaceCollection` stays root-only, because its validators need the interface schemas. +`@tanstack/cms-core/definition` also exports the pure authoring helpers, so collection modules never need the package root: `defineCollection`, `defineInterfaceCollection`, `defineBlock`, `defineFieldType`, `definePluginDefinition`, `seoField`, `assetField`, `redirectsCollection`, `isSafeRedirectTarget`, and `isBuiltInFieldType`. These are the same functions the root exports. The entry also exports the types collections use, including `Collection`, `Field`, `BlockType`, `InferDoc`, `CollectionAccess`, `FieldAccess`, and `CmsPluginDefinition`. `definePlugin` stays root-only, because a plugin's runtime half carries ops and event handlers. ```ts validate=type import { defineCms } from '@tanstack/cms-core' @@ -183,7 +219,7 @@ export const cms = defineCms(definition, { blockTypes: [], dataDir: '.data' }) cms.collections.post.label // 'Posts' ``` -`pnpm test:definitions` (`scripts/verify-definitions.ts`) loads every `cms.definition.ts` under `app/`, `starters/`, and `examples/` in plain Node and reports any import of `react`, `react-dom`, a `.tsx` file, `@tanstack/react-start`, `@tanstack/react-router`, the `@tanstack/cms-ui-react` root, `@tanstack/cms-core/server`, or a `*.server.*` file. It runs report-only for now; `--strict` makes it fail. +`pnpm test:definitions` (`scripts/verify-definitions.ts`) loads every `cms.definition.ts` under `app/`, `starters/`, and `examples/` in plain Node and reports any import of `react`, `react-dom`, a `.tsx` file, `@tanstack/react-start`, `@tanstack/react-router`, the `@tanstack/cms-ui-react` root, `@tanstack/cms-core/server`, or a `*.server.*` file. It also scaffolds what `tanstack-cms init` and a code-mode `tanstack-cms skill add` write and checks those definitions. It fails CI on any violation; `tsx scripts/verify-definitions.ts` without `--strict` only reports. ### `getCmsConfig()` @@ -401,49 +437,65 @@ Without `i18n`, the admin hides the locale controls and `locale` is free-form, a ### Plugins ```ts -function definePlugin(plugin: CmsPlugin): CmsPlugin +function definePluginDefinition(definition: CmsPluginDefinition): CmsPluginDefinition // also in /definition +function definePlugin(plugin: { + definition: CmsPluginDefinition + runtime?: CmsPluginRuntime +}): CmsPlugin -interface CmsPlugin { +interface CmsPluginDefinition { name: string // unique within the app collections?: ReadonlyArray - blockTypes?: Array - fieldTypes?: Array // defineFieldType(), with admin input and cell - ops?: Array // defineOp(); served over HTTP, Start, OpenAPI, and as agent tools adminNav?: Array<{ label: string; to: string; permission?: Permission }> routes?: Array // read by cmsVirtualRoutes({ plugins }), not defineCms adminRoutes?: Array // same, mounted under admin.basePath +} + +interface CmsPluginRuntime { + blockTypes?: Array + fieldTypes?: Array // defineFieldType(), with admin input and cell + ops?: Array // defineOp(); served over HTTP, Start, OpenAPI, and as agent tools + eventHandlers?: Array onEvent?: (event: CmsEvent) => void // server-side, after every content change } ``` -A plugin packages a feature so an app adds it with one line. `defineCms` merges each plugin's collections, block types, field types, and ops into the config, so they behave exactly like the app's own; a name that's already taken (by the app or another plugin) throws. The returned config's type includes plugin collections, so `Register` picks them up. +A plugin packages a feature so an app adds it with one line. Like the app config, it has two halves: the **definition** (name, collections, admin nav, routes) is pure data that `cms.definition.ts` and `vite.config.ts` can load, and the **runtime** (ops, event handlers, block and field types) is server-bound. `definePlugin` throws if a key is on the wrong side, or if it gets the old flat `definePlugin({ name, … })` form; `pnpm codemod definition-split `, run from a TanStack CMS checkout, rewrites that form. + +`defineCms` merges each plugin's collections, block types, field types, and ops into the config, so they behave exactly like the app's own; a name that's already taken (by the app or another plugin) throws. The returned config's type includes plugin collections, so `Register` picks them up. + +In a two-file app, list `analytics.definition` (or the plugin itself) in `defineCmsDefinition({ plugins })` and the plugin in the runtime config's `plugins`; the runtime entry replaces the definition's entry of the same name. A plugin with only a runtime half — no collections, routes, or admin routes, like the AT Protocol connector — can sit in the runtime config alone. A one-file app lists the plugin once in `defineCms({ plugins })`. ```ts validate=type import { z } from 'zod' -import { defineCms, defineOp, definePlugin } from '@tanstack/cms-core' +import { defineCms, defineOp, definePlugin, definePluginDefinition } from '@tanstack/cms-core' export const analytics = definePlugin({ - name: 'analytics', - collections: [ - { - name: 'pageview', - label: 'Page views', - titleField: 'path', - fields: [{ name: 'path', label: 'Path', type: 'text', required: true }], + definition: definePluginDefinition({ + name: 'analytics', + collections: [ + { + name: 'pageview', + label: 'Page views', + titleField: 'path', + fields: [{ name: 'path', label: 'Path', type: 'text', required: true }], + }, + ], + adminNav: [{ label: 'Analytics', to: '/analytics' }], + }), + runtime: { + ops: [ + defineOp({ + name: 'topPages', + access: 'content.read', + description: 'The most viewed paths.', + input: z.object({ limit: z.number().int().max(50).default(10) }), + run: async () => [], + }), + ], + onEvent: (e) => { + if (e.event === 'publish') console.log(`published ${e.collection}/${e.id}`) }, - ], - ops: [ - defineOp({ - name: 'topPages', - access: 'content.read', - description: 'The most viewed paths.', - input: z.object({ limit: z.number().int().max(50).default(10) }), - run: async () => [], - }), - ], - adminNav: [{ label: 'Analytics', to: '/analytics' }], - onEvent: (e) => { - if (e.event === 'publish') console.log(`published ${e.collection}/${e.id}`) }, }) diff --git a/docs/deployment/upgrading.md b/docs/deployment/upgrading.md index e0eedf1d..e379dad9 100644 --- a/docs/deployment/upgrading.md +++ b/docs/deployment/upgrading.md @@ -242,7 +242,19 @@ onCmsEvent(({ event, collection, id }) => purge(event, collection, id)) ### 18. Plugins -New: `defineCms({ plugins: [definePlugin({ … })] })` bundles collections, block types, field types, ops, admin nav links, routes, and an `onEvent` hook. Nothing changes for apps that don't use it. See [Plugins](../api/cms-core#plugins). +New: `definePlugin({ definition, runtime })` bundles collections, admin nav links, and routes (the `definition`, built with `definePluginDefinition`) with block types, field types, ops, event handlers, and an `onEvent` hook (the `runtime`). Nothing changes for apps that don't use it. A plugin written in the flat 0.x alpha form, `definePlugin({ name, collections, ops, … })`, now throws; `pnpm codemod definition-split `, run from a TanStack CMS checkout, splits it: + +```ts +// before +definePlugin({ name: 'analytics', collections: [pageview], ops: [topPages] }) +// after +definePlugin({ + definition: definePluginDefinition({ name: 'analytics', collections: [pageview] }), + runtime: { ops: [topPages] }, +}) +``` + +`@tanstack/cms-core/definition` exports `definePluginDefinition` instead of `definePlugin`. See [Plugins](../api/cms-core#plugins). ### 19. Request hardening @@ -254,6 +266,12 @@ New: `defineCms({ plugins: [definePlugin({ … })] })` bundles collections, bloc - **Unique fields.** SQL stores enforce `unique: true` with database indexes. `tanstack-cms migrate` fails if existing documents already share a value; fix them and rerun. - **Redirects.** `redirect.to` must be a site path (`/…`) or an `http(s)` URL; other stored values are ignored. +### 20. The content model moves to `cms.definition.ts` + +Optional, and recommended. `defineCms(config)` with one config keeps working. The recommended shape splits it: `src/cms.definition.ts` holds `defineCmsDefinition({ collections, admin, plugins })` and imports only `@tanstack/cms-core/definition`, so `vite.config.ts` and client code can load it. `src/cms.config.ts` calls `defineCms(definition, runtime)` with everything else. In the runtime config, `collections` is an object keyed by collection name that attaches the server-bound `hooks`, `access`, and `storage` to the definition's collections. `Register` points at the definition: `cms: typeof definition`. + +`pnpm codemod definition-split `, run from a TanStack CMS checkout, writes `cms.definition.ts` next to each `cms.config.ts` and rewrites the config. It leaves hooks and access on the collections; move any that import server code into the runtime `collections` by hand. `tanstack-cms init` scaffolds both files. See [`defineCmsDefinition()`](../api/cms-core#the-cms-definition-definecmsdefinition). + ## Versioning policy From 1.0, TanStack CMS follows [semantic versioning](https://semver.org). The diff --git a/docs/getting-started/quick-start.md b/docs/getting-started/quick-start.md index c5e32add..4e7358b3 100644 --- a/docs/getting-started/quick-start.md +++ b/docs/getting-started/quick-start.md @@ -10,10 +10,11 @@ keywords: - "@tanstack/cms-ui-react" - tanstack-cms init - defineCms + - defineCmsDefinition - tanstack start --- -You want a schema-driven, agent-native CMS in your TanStack Start app. The TanStack CMS packages ship the store, the admin UI, the review queue, the HTTP and MCP APIs, and the routes. Your app supplies `cms.config.ts`. +You want a schema-driven, agent-native CMS in your TanStack Start app. The TanStack CMS packages ship the store, the admin UI, the review queue, the HTTP and MCP APIs, and the routes. Your app supplies its content model in `cms.definition.ts` and the runtime config in `cms.config.ts`. For a full walkthrough of the blog example, open [Build a Blog & Page CMS](../tutorials/blog-cms). @@ -55,7 +56,7 @@ npx tanstack-cms init `init` makes four changes and prints what it did: -1. **Creates `src/cms.config.ts`** (or `cms.config.ts` when there is no `src/` directory) with a starter `post` collection, one seeded `hello-world` post, and the `Register` declaration that types the rest of the CMS. An existing config is left alone unless you pass `--force`. +1. **Creates `src/cms.definition.ts` and `src/cms.config.ts`** (in the app root when there is no `src/` directory): the definition holds a starter `post` collection, and the config adds one seeded `hello-world` post and the `Register` declaration that types the rest of the CMS. If either file exists, both are left alone unless you pass `--force`. 2. **Patches `vite.config.ts`** (also `.mts` / `.js`). If the file calls `tanstackStart()` with no arguments, `init` adds the `tanstackCms()` plugin and `cmsVirtualRoutes()`. If `tanstackStart` already has options, it prints the snippet for you to add by hand. 3. **Patches `src/router.tsx`** (or `router.ts`) to import `./cms.config` for its side effect. If there is no router module, it prints the import line instead. 4. **Adds `.data/` to `.gitignore`**, where the database and uploads live in development. @@ -97,8 +98,8 @@ export default defineConfig({ // vite.config.ts virtualRouteConfig: cmsVirtualRoutes({ adminBasePath: '/admin' }) -// src/cms.config.ts -defineCms({ /* ... */ admin: { basePath: '/admin' } }) +// src/cms.definition.ts +defineCmsDefinition({ /* ... */ admin: { basePath: '/admin' } }) ``` See [Routes in a Package](../architecture/routes-in-a-package) for every route key and option. @@ -125,14 +126,17 @@ Because the router runs on both the client and the server, `cms.config.ts` is pa ## 5. Look at the content model -This is the starter config `init` writes: +`init` splits the CMS into two files. `src/cms.definition.ts` is the content model: collections, the admin base path, and plugin definitions. It imports only `@tanstack/cms-core/definition`, so `vite.config.ts` and client code can load it without pulling in the server: ```ts -import { defineCms } from '@tanstack/cms-core' +import { + defineCmsDefinition, + defineCollection, +} from '@tanstack/cms-core/definition' -export const cms = defineCms({ +export const definition = defineCmsDefinition({ collections: [ - { + defineCollection({ name: 'post', label: 'Posts', titleField: 'title', @@ -148,8 +152,18 @@ export const cms = defineCms({ { name: 'excerpt', label: 'Excerpt', type: 'textarea', required: false }, { name: 'body', label: 'Body', type: 'markdown', required: false }, ], - }, + }), ], +}) +``` + +`src/cms.config.ts` registers the CMS with everything else: block types, seed data, auth, storage, AI, ops, and the server-bound hooks and access rules of each collection, keyed by collection name (`collections: { post: { hooks, access } }`): + +```ts +import { defineCms } from '@tanstack/cms-core' +import { definition } from './cms.definition' + +export const cms = defineCms(definition, { blockTypes: [], seed: { documents: { @@ -167,7 +181,7 @@ export const cms = defineCms({ declare module '@tanstack/cms-core' { interface Register { - cms: typeof cms + cms: typeof definition } } ``` @@ -179,6 +193,8 @@ declare module '@tanstack/cms-core' { Add collections with `defineCollection()` and block types with `defineBlock()`; see [Collections & Fields](../schema/collections-and-fields). +The two-file split is recommended. A small app can keep everything in one `cms.config.ts` with `defineCms({ collections, blockTypes, … })`; that form keeps working. To split it later, run `pnpm codemod definition-split ` from a TanStack CMS checkout. + ## 6. Run the dev server ```bash @@ -203,12 +219,13 @@ In development there is nothing to log in to. With no `auth` in `defineCms()`, e To try the other roles (`viewer`, `author`, `editor`, `admin`) before wiring real auth, add `createMockAuth()`. It renders a persona switcher in the header, backed by a `cms_mock_role` cookie: -```ts validate=type +```ts +// src/cms.config.ts import { defineCms } from '@tanstack/cms-core' import { createMockAuth } from '@tanstack/cms-ui-react' +import { definition } from './cms.definition' -export const cms = defineCms({ - collections: [], +export const cms = defineCms(definition, { blockTypes: [], auth: createMockAuth(), }) @@ -224,7 +241,7 @@ TanStack CMS is fully functional without AI. AI features are opt-in: setting an ```ts // src/cms.config.ts -export const cms = defineCms({ +export const cms = defineCms(definition, { // ... ai: { textAdapter: async () => { diff --git a/docs/migration/from-payload.md b/docs/migration/from-payload.md index c2270ad5..d72e5e63 100644 --- a/docs/migration/from-payload.md +++ b/docs/migration/from-payload.md @@ -46,7 +46,7 @@ Payload v3 and TanStack CMS are both **code-first TypeScript CMSs** with schema - **No GraphQL and no deep `depth` joins.** Relations are ids resolved one level with `populate: true` / `populateRelations`. - **Field-level localization.** TanStack CMS localizes whole documents (`locale`, `translationOf`), not individual fields. - **Access rules return booleans.** Payload access functions that return `Where` queries need rewriting, and rules can only narrow a role's permissions. -- **Custom admin components don't carry over automatically.** Rebuild custom field inputs with `field.input` or `defineFieldType()`, and custom admin views or hooks with routes or `definePlugin()`. +- **Custom admin components don't carry over automatically.** Rebuild custom field inputs with `field.input` or `defineFieldType()`, and custom admin views or hooks with routes or `definePlugin({ definition, runtime })`. - **Fewer databases.** Postgres and MongoDB adapters have no built-in equivalent. ## The 1.0 Mapping diff --git a/docs/migration/overview.md b/docs/migration/overview.md index 02e976ce..f021ca97 100644 --- a/docs/migration/overview.md +++ b/docs/migration/overview.md @@ -20,7 +20,7 @@ Migrating off an existing CMS usually stalls for one of two reasons: importers c TanStack CMS keeps the app-specific part of a migration small: -- **The target is a TanStack Start app** whose app-specific code is `src/cms.config.ts` (the mapped collections, blocks, access rules, hooks, and theme). The admin, block editor, public renderer, drafts, revisions, review queue, redirects, sitemap, HTTP API, and MCP come from `@tanstack/cms-core`, `@tanstack/cms-api`, and `@tanstack/cms-ui-react`. +- **The target is a TanStack Start app** whose app-specific code is `src/cms.definition.ts` (the mapped collections) and `src/cms.config.ts` (blocks, theme, and the access rules and hooks that need server code). The admin, block editor, public renderer, drafts, revisions, review queue, redirects, sitemap, HTTP API, and MCP come from `@tanstack/cms-core`, `@tanstack/cms-api`, and `@tanstack/cms-ui-react`. - **Content moves as a CMS export** loaded with `tanstack-cms import`, so it goes straight into the configured storage. - **Each migration is an agent skill** (`.claude/skills/*-to-tanstack-cms`) with zero-dependency converter scripts, plus a worked `examples/*-before` → `examples/*-after` pair whose `MIGRATION.md` lists the mapping and the remaining gaps, and whose parity test proves the content survived. @@ -54,7 +54,9 @@ Every converter exports a `*ToMarkdown` function and a `*ToBlocks` function that Run `npx tanstack-cms init` in a TanStack Start app (from `@tanstack/cms-cli`), or copy [`examples/blog`](https://github.com/TanStack/tanstack-cms/blob/main/examples/blog). Dependencies are `@tanstack/cms-core` and `@tanstack/cms-ui-react` (which brings `@tanstack/cms-api`); `vite.config.ts` adds `tanstackCms()` from `@tanstack/cms-ui-react/vite` and passes `cmsVirtualRoutes()` to `tanstackStart({ router: { virtualRouteConfig } })`. -### 2. Map the schema (`src/cms.config.ts`) +### 2. Map the schema (`src/cms.definition.ts`) + +Write the collections in `src/cms.definition.ts` with `defineCmsDefinition`, importing only `@tanstack/cms-core/definition`, and the rest in `src/cms.config.ts` with `defineCms(definition, { blockTypes, theme, … })`. The per-CMS guides show one `defineCms({ … })` config for brevity; that form works too. - Map block-based or docs pages to a **`page`** collection with a `blocks` field, so `/p/$id`, the docs layout, and the on-page editor work. - Map articles to a **`post`** collection, so `/post/$id` and the blog home work. @@ -86,7 +88,7 @@ The migrators also write `src/seed-data.ts`. Passing it as `defineCms({ seed: { - **Users and passwords** don't migrate. Configure `auth: { getUser }` against your identity provider and map roles; without `auth`, the admin only works in development. - **Media bytes** migrate as URLs to the old host until they are uploaded into the media library and references are rewritten. - **Revision history** starts at the import. -- **Custom admin UI** (Payload components, Sanity inputs, WordPress plugins) doesn't carry over automatically; custom field inputs (`field.input`) and custom field types (`defineFieldType()`) are supported, while full view/layout overrides are rebuilt in routes or plugins (`definePlugin()`). +- **Custom admin UI** (Payload components, Sanity inputs, WordPress plugins) doesn't carry over automatically; custom field inputs (`field.input`) and custom field types (`defineFieldType()`) are supported, while full view/layout overrides are rebuilt in routes or plugins (`definePlugin({ definition, runtime })`). ## Next Steps diff --git a/examples/astro-starlight-after/MIGRATION.md b/examples/astro-starlight-after/MIGRATION.md index c4cd7979..e5798a3a 100644 --- a/examples/astro-starlight-after/MIGRATION.md +++ b/examples/astro-starlight-after/MIGRATION.md @@ -5,7 +5,9 @@ This app is [`../astro-starlight-before`](../astro-starlight-before) (an Astro 1.0 (`@tanstack/cms-core` + `@tanstack/cms-ui-react`). The migration has two halves: -- **Schema** — hand-mapped in [`src/cms.config.ts`](./src/cms.config.ts). +- **Schema** — hand-mapped in [`src/cms.definition.ts`](./src/cms.definition.ts) + (the collections) and [`src/cms.config.ts`](./src/cms.config.ts) (the block + palette). - **Data** — generated into [`src/seed-data.ts`](./src/seed-data.ts) by [`scripts/migrate-starlight.mjs`](./scripts/migrate-starlight.mjs), which reads the Starlight content **files off disk** (no server needed). diff --git a/examples/astro-starlight-after/README.md b/examples/astro-starlight-after/README.md index 205c4ede..caa0b280 100644 --- a/examples/astro-starlight-after/README.md +++ b/examples/astro-starlight-after/README.md @@ -7,9 +7,11 @@ ported to a TanStack Start app on TanStack CMS 1.0 — the same shape as All the app-specific code is: -- [`src/cms.config.ts`](./src/cms.config.ts) — the `page` collection mapped - from the Starlight frontmatter, a `redirect` collection for the old URLs, - and a Starlight-like theme. +- [`src/cms.definition.ts`](./src/cms.definition.ts) — the `page` collection + mapped from the Starlight frontmatter and a `redirect` collection for the + old URLs. +- [`src/cms.config.ts`](./src/cms.config.ts) — `defineCms(definition, …)` + with the blocks, AI adapters, seed, and a Starlight-like theme. - [`src/seed-data.ts`](./src/seed-data.ts) — every docs file as a `page` document (MDX flattened) plus the redirects, generated by [`scripts/migrate-starlight.mjs`](./scripts/migrate-starlight.mjs). diff --git a/examples/astro-starlight-after/scripts/migrate-starlight.mjs b/examples/astro-starlight-after/scripts/migrate-starlight.mjs index 4c592490..9180bce2 100644 --- a/examples/astro-starlight-after/scripts/migrate-starlight.mjs +++ b/examples/astro-starlight-after/scripts/migrate-starlight.mjs @@ -16,7 +16,7 @@ * block — there is no Lexical step. With `--export ` it also writes a * CMS export (`tanstack-cms-export` v1) to load with `tanstack-cms import`. * - * This is the data half. The schema half is the hand-written src/cms.config.ts + * This is the data half. The schema half is the hand-written src/cms.definition.ts * (see SKILL.md's frontmatter → field mapping table). */ import { readFileSync, writeFileSync, readdirSync, statSync } from 'node:fs' diff --git a/examples/astro-starlight-after/src/cms.config.ts b/examples/astro-starlight-after/src/cms.config.ts index f77f7909..ee6984c5 100644 --- a/examples/astro-starlight-after/src/cms.config.ts +++ b/examples/astro-starlight-after/src/cms.config.ts @@ -1,33 +1,11 @@ /** - * The migrated content model — the schema half of the Astro Starlight → - * TanStack CMS port. The single Starlight `docs` content collection maps to one - * core `page` collection (named `page` so the core's public renderer `/p/:id` - * and on-page agent, both wired to the page-with-blocks convention, work - * unchanged). See MIGRATION.md for the full conversion map. - * - * Starlight frontmatter → core field: - * title → title (text) - * description → description (textarea) - * (file path) → slug (text, e.g. /start/installation) - * sidebar.label → sidebarLabel (text — the docs sidebar label) - * sidebar.order → sidebarOrder (number — the docs sidebar order) - * draft: true → published:false - * body (Markdown) → blocks: [{ _type:'richText', markdown }] - * (old URL) → redirect doc (/start/installation/ → /p/start-installation) - * - * The `docs` theme variant builds the sidebar from slug groups + - * `sidebarOrder`/`sidebarLabel`, so the Starlight nav survives the move. - * - * The data half (every docs file, frontmatter + body, MDX flattened) is - * generated into ./seed-data.ts by scripts/migrate-starlight.mjs. + * The runtime half of the Astro Starlight → TanStack CMS port: the block + * palette, AI adapters, migrated seed documents, and theme. The content model + * is in ./cms.definition.ts. */ -import { - defineBlock, - defineCms, - defineCollection, - redirectsCollection, -} from '@tanstack/cms-core' +import { defineBlock, defineCms } from '@tanstack/cms-core' import { seedDocuments } from './seed-data' +import { definition } from './cms.definition' // A docs body is Markdown, so the palette needs only the `richText` block (the // UI renderer already handles it). Add more block types (+ a renderer) only @@ -40,40 +18,6 @@ const blockTypes = [ }), ] -const collections = [ - // from astro-starlight-before: the `docs` content collection - defineCollection({ - name: 'page', - label: 'Docs', - titleField: 'title', - summaryField: 'description', - path: (doc, id) => (doc.slug === '/' ? '/' : `/p/${id}`), - admin: { - columns: ['slug', 'sidebarOrder', 'published'], - defaultSort: { field: 'slug' }, - }, - fields: [ - { name: 'title', label: 'Title', type: 'text', required: true }, - { name: 'description', label: 'Description', type: 'textarea' }, - { - name: 'slug', - label: 'Slug', - type: 'text', - required: true, - unique: true, - description: 'Docs path, e.g. /start/installation', - }, - { name: 'sidebarLabel', label: 'Sidebar label', type: 'text' }, - { name: 'sidebarOrder', label: 'Sidebar order', type: 'number' }, - { name: 'blocks', label: 'Content', type: 'blocks' }, - { name: 'published', label: 'Published', type: 'boolean' }, - ], - }), - // Starlight URLs (/start/installation/) → /p/, so existing links, - // bookmarks, and the cross-page links inside the Markdown keep working. - redirectsCollection(), -] - /** * AI models: Claude for text, Gemini ("Nano Banana") for images, each enabled * by its API key. Loaded with `import()` on the server only, so the provider @@ -92,8 +36,7 @@ const ai = { }, } -export const cms = defineCms({ - collections, +export const cms = defineCms(definition, { blockTypes, ai, seed: { documents: seedDocuments }, @@ -119,6 +62,6 @@ export const cms = defineCms({ declare module '@tanstack/cms-core' { interface Register { - cms: typeof cms + cms: typeof definition } } diff --git a/examples/astro-starlight-after/src/cms.definition.ts b/examples/astro-starlight-after/src/cms.definition.ts new file mode 100644 index 00000000..24047b93 --- /dev/null +++ b/examples/astro-starlight-after/src/cms.definition.ts @@ -0,0 +1,66 @@ +/** + * The migrated content model — the schema half of the Astro Starlight → + * TanStack CMS port. The single Starlight `docs` content collection maps to one + * core `page` collection (named `page` so the core's public renderer `/p/:id` + * and on-page agent, both wired to the page-with-blocks convention, work + * unchanged). See MIGRATION.md for the full conversion map. + * + * Starlight frontmatter → core field: + * title → title (text) + * description → description (textarea) + * (file path) → slug (text, e.g. /start/installation) + * sidebar.label → sidebarLabel (text — the docs sidebar label) + * sidebar.order → sidebarOrder (number — the docs sidebar order) + * draft: true → published:false + * body (Markdown) → blocks: [{ _type:'richText', markdown }] + * (old URL) → redirect doc (/start/installation/ → /p/start-installation) + * + * The `docs` theme variant builds the sidebar from slug groups + + * `sidebarOrder`/`sidebarLabel`, so the Starlight nav survives the move. + * + * The data half (every docs file, frontmatter + body, MDX flattened) is + * generated into ./seed-data.ts by scripts/migrate-starlight.mjs. + */ +import { + defineCmsDefinition, + defineCollection, + redirectsCollection, +} from '@tanstack/cms-core/definition' + +const collections = [ + // from astro-starlight-before: the `docs` content collection + defineCollection({ + name: 'page', + label: 'Docs', + titleField: 'title', + summaryField: 'description', + path: (doc, id) => (doc.slug === '/' ? '/' : `/p/${id}`), + admin: { + columns: ['slug', 'sidebarOrder', 'published'], + defaultSort: { field: 'slug' }, + }, + fields: [ + { name: 'title', label: 'Title', type: 'text', required: true }, + { name: 'description', label: 'Description', type: 'textarea' }, + { + name: 'slug', + label: 'Slug', + type: 'text', + required: true, + unique: true, + description: 'Docs path, e.g. /start/installation', + }, + { name: 'sidebarLabel', label: 'Sidebar label', type: 'text' }, + { name: 'sidebarOrder', label: 'Sidebar order', type: 'number' }, + { name: 'blocks', label: 'Content', type: 'blocks' }, + { name: 'published', label: 'Published', type: 'boolean' }, + ], + }), + // Starlight URLs (/start/installation/) → /p/, so existing links, + // bookmarks, and the cross-page links inside the Markdown keep working. + redirectsCollection(), +] + +export const definition = defineCmsDefinition({ + collections, +}) diff --git a/examples/blog-voting/src/cms.config.ts b/examples/blog-voting/src/cms.config.ts index bc087d33..96bf2fb6 100644 --- a/examples/blog-voting/src/cms.config.ts +++ b/examples/blog-voting/src/cms.config.ts @@ -7,9 +7,10 @@ * function reads the config, so the engine always sees the blog's collections * and block palette. */ -import { defineBlock, defineCms, defineCollection } from '@tanstack/cms-core' +import { defineBlock, defineCms } from '@tanstack/cms-core' import { createMockAuth } from '@tanstack/cms-ui-react' import type { SeedStore } from '@tanstack/cms-core' +import { definition } from './cms.definition' /** The block palette for `blocks` fields. Each block is a named field group. */ const blockTypes = [ @@ -69,78 +70,6 @@ const blockTypes = [ }), ] -const collections = [ - defineCollection({ - name: 'page', - label: 'Pages', - titleField: 'title', - imageField: 'hero', - fields: [ - { name: 'title', label: 'Title', type: 'text' }, - { name: 'slug', label: 'Slug', type: 'text' }, - { name: 'hero', label: 'Featured image', type: 'image' }, - { name: 'blocks', label: 'Content', type: 'blocks' }, - { name: 'published', label: 'Published', type: 'boolean' }, - ], - }), - defineCollection({ - name: 'post', - label: 'Blog posts', - titleField: 'title', - summaryField: 'excerpt', - bylineField: 'author', - bodyField: 'body', - dateField: 'publishedDate', - schemaType: 'BlogPosting', - fields: [ - { name: 'title', label: 'Title', type: 'text' }, - { name: 'author', label: 'Author', type: 'text' }, - { - name: 'category', - label: 'Category', - type: 'select', - options: ['announcement', 'tutorial', 'architecture', 'release'], - }, - { - name: 'tags', - label: 'Tags', - type: 'multiselect', - options: ['tanstack', 'sqlite', 'mcp', 'ai', 'migrations'], - }, - { name: 'publishedDate', label: 'Published date', type: 'date' }, - { - name: 'relatedPosts', - label: 'Related posts', - type: 'relation', - collection: 'post', - many: true, - }, - { name: 'excerpt', label: 'Excerpt', type: 'textarea' }, - { name: 'body', label: 'Body', type: 'markdown' }, - { name: 'published', label: 'Published', type: 'boolean' }, - // Voting (§2 of the voting skill): cached tallies, recomputed from the - // vote collection on every vote — never written by clients directly. - { name: 'upvotes', label: 'Upvotes', type: 'number' }, - { name: 'downvotes', label: 'Downvotes', type: 'number' }, - { name: 'score', label: 'Score', type: 'number' }, - ], - }), - // Voting (§2): one document per (post, voter). The deterministic id - // `vote::` is the uniqueness constraint — the store's - // primary key (collection, id) makes double-votes overwrite instead of - // double-counting. - defineCollection({ - name: 'vote', - label: 'Votes', - titleField: 'id', - fields: [ - { name: 'post', label: 'Post', type: 'relation', collection: 'post' }, - { name: 'voter', label: 'Voter', type: 'text' }, - { name: 'value', label: 'Value', type: 'number' }, - ], - }), -] - /** Content written on first run when `.data/cms.db` does not yet exist. */ const seed: SeedStore = { documents: { @@ -218,8 +147,7 @@ const ai = { }, } -export const cms = defineCms({ - collections, +export const cms = defineCms(definition, { blockTypes, ai, seed, @@ -228,6 +156,6 @@ export const cms = defineCms({ declare module '@tanstack/cms-core' { interface Register { - cms: typeof cms + cms: typeof definition } } diff --git a/examples/blog-voting/src/cms.definition.ts b/examples/blog-voting/src/cms.definition.ts new file mode 100644 index 00000000..cdd44bb2 --- /dev/null +++ b/examples/blog-voting/src/cms.definition.ts @@ -0,0 +1,80 @@ +import { + defineCmsDefinition, + defineCollection, +} from '@tanstack/cms-core/definition' + +const collections = [ + defineCollection({ + name: 'page', + label: 'Pages', + titleField: 'title', + imageField: 'hero', + fields: [ + { name: 'title', label: 'Title', type: 'text' }, + { name: 'slug', label: 'Slug', type: 'text' }, + { name: 'hero', label: 'Featured image', type: 'image' }, + { name: 'blocks', label: 'Content', type: 'blocks' }, + { name: 'published', label: 'Published', type: 'boolean' }, + ], + }), + defineCollection({ + name: 'post', + label: 'Blog posts', + titleField: 'title', + summaryField: 'excerpt', + bylineField: 'author', + bodyField: 'body', + dateField: 'publishedDate', + schemaType: 'BlogPosting', + fields: [ + { name: 'title', label: 'Title', type: 'text' }, + { name: 'author', label: 'Author', type: 'text' }, + { + name: 'category', + label: 'Category', + type: 'select', + options: ['announcement', 'tutorial', 'architecture', 'release'], + }, + { + name: 'tags', + label: 'Tags', + type: 'multiselect', + options: ['tanstack', 'sqlite', 'mcp', 'ai', 'migrations'], + }, + { name: 'publishedDate', label: 'Published date', type: 'date' }, + { + name: 'relatedPosts', + label: 'Related posts', + type: 'relation', + collection: 'post', + many: true, + }, + { name: 'excerpt', label: 'Excerpt', type: 'textarea' }, + { name: 'body', label: 'Body', type: 'markdown' }, + { name: 'published', label: 'Published', type: 'boolean' }, + // Voting (§2 of the voting skill): cached tallies, recomputed from the + // vote collection on every vote — never written by clients directly. + { name: 'upvotes', label: 'Upvotes', type: 'number' }, + { name: 'downvotes', label: 'Downvotes', type: 'number' }, + { name: 'score', label: 'Score', type: 'number' }, + ], + }), + // Voting (§2): one document per (post, voter). The deterministic id + // `vote::` is the uniqueness constraint — the store's + // primary key (collection, id) makes double-votes overwrite instead of + // double-counting. + defineCollection({ + name: 'vote', + label: 'Votes', + titleField: 'id', + fields: [ + { name: 'post', label: 'Post', type: 'relation', collection: 'post' }, + { name: 'voter', label: 'Voter', type: 'text' }, + { name: 'value', label: 'Value', type: 'number' }, + ], + }), +] + +export const definition = defineCmsDefinition({ + collections, +}) diff --git a/examples/blog/src/cms.config.ts b/examples/blog/src/cms.config.ts index 318532dd..4e392333 100644 --- a/examples/blog/src/cms.config.ts +++ b/examples/blog/src/cms.config.ts @@ -7,15 +7,10 @@ * function reads the config, so the engine always sees the blog's collections * and block palette. */ -import { - defineBlock, - defineCms, - defineCollection, - redirectsCollection, - seoField, -} from '@tanstack/cms-core' +import { defineBlock, defineCms } from '@tanstack/cms-core' import { createMockAuth } from '@tanstack/cms-ui-react' import type { SeedStore } from '@tanstack/cms-core' +import { definition } from './cms.definition' /** The block palette for `blocks` fields. Each block is a named field group. */ const blockTypes = [ @@ -75,78 +70,6 @@ const blockTypes = [ }), ] -const collections = [ - defineCollection({ - name: 'page', - label: 'Pages', - titleField: 'title', - imageField: 'hero', - path: (doc, id) => (doc.slug === '/' ? '/' : `/p/${id}`), - fields: [ - { name: 'title', label: 'Title', type: 'text' }, - { name: 'slug', label: 'Slug', type: 'text' }, - { name: 'hero', label: 'Featured image', type: 'image' }, - { name: 'blocks', label: 'Content', type: 'blocks' }, - { name: 'published', label: 'Published', type: 'boolean' }, - seoField(), - ], - }), - defineCollection({ - name: 'post', - label: 'Blog posts', - titleField: 'title', - summaryField: 'excerpt', - bylineField: 'author', - bodyField: 'body', - dateField: 'publishedDate', - schemaType: 'BlogPosting', - path: (_doc, id) => `/post/${id}`, - admin: { columns: ['author', 'category'] }, - fields: [ - { name: 'title', label: 'Title', type: 'text' }, - { name: 'author', label: 'Author', type: 'text' }, - { - name: 'category', - label: 'Category', - type: 'select', - options: ['announcement', 'tutorial', 'architecture', 'release'], - }, - { - name: 'tags', - label: 'Tags', - type: 'multiselect', - options: ['tanstack', 'sqlite', 'mcp', 'ai', 'migrations'], - }, - { name: 'publishedDate', label: 'Published date', type: 'date' }, - { - name: 'relatedPosts', - label: 'Related posts', - type: 'relation', - collection: 'post', - many: true, - }, - { name: 'excerpt', label: 'Excerpt', type: 'textarea' }, - { name: 'body', label: 'Body', type: 'markdown' }, - { name: 'published', label: 'Published', type: 'boolean' }, - { - name: 'featured', - label: 'Featured on home', - type: 'boolean', - description: 'Only editors and admins can feature a post.', - access: { write: ['admin', 'editor'] }, - }, - { - name: 'editorNotes', - label: 'Editor notes', - type: 'text', - access: { read: ['admin', 'editor'] }, - }, - seoField(), - ], - }), - redirectsCollection(), -] - /** Content written on first run when `.data/cms.db` does not yet exist. */ const seed: SeedStore = { documents: { @@ -225,8 +148,7 @@ const ai = { }, } -export const cms = defineCms({ - collections, +export const cms = defineCms(definition, { blockTypes, ai, seed, @@ -241,6 +163,6 @@ export const cms = defineCms({ declare module '@tanstack/cms-core' { interface Register { - cms: typeof cms + cms: typeof definition } } diff --git a/examples/blog/src/cms.definition.ts b/examples/blog/src/cms.definition.ts new file mode 100644 index 00000000..a8df9d1e --- /dev/null +++ b/examples/blog/src/cms.definition.ts @@ -0,0 +1,82 @@ +import { + defineCmsDefinition, + defineCollection, + redirectsCollection, + seoField, +} from '@tanstack/cms-core/definition' + +const collections = [ + defineCollection({ + name: 'page', + label: 'Pages', + titleField: 'title', + imageField: 'hero', + path: (doc, id) => (doc.slug === '/' ? '/' : `/p/${id}`), + fields: [ + { name: 'title', label: 'Title', type: 'text' }, + { name: 'slug', label: 'Slug', type: 'text' }, + { name: 'hero', label: 'Featured image', type: 'image' }, + { name: 'blocks', label: 'Content', type: 'blocks' }, + { name: 'published', label: 'Published', type: 'boolean' }, + seoField(), + ], + }), + defineCollection({ + name: 'post', + label: 'Blog posts', + titleField: 'title', + summaryField: 'excerpt', + bylineField: 'author', + bodyField: 'body', + dateField: 'publishedDate', + schemaType: 'BlogPosting', + path: (_doc, id) => `/post/${id}`, + admin: { columns: ['author', 'category'] }, + fields: [ + { name: 'title', label: 'Title', type: 'text' }, + { name: 'author', label: 'Author', type: 'text' }, + { + name: 'category', + label: 'Category', + type: 'select', + options: ['announcement', 'tutorial', 'architecture', 'release'], + }, + { + name: 'tags', + label: 'Tags', + type: 'multiselect', + options: ['tanstack', 'sqlite', 'mcp', 'ai', 'migrations'], + }, + { name: 'publishedDate', label: 'Published date', type: 'date' }, + { + name: 'relatedPosts', + label: 'Related posts', + type: 'relation', + collection: 'post', + many: true, + }, + { name: 'excerpt', label: 'Excerpt', type: 'textarea' }, + { name: 'body', label: 'Body', type: 'markdown' }, + { name: 'published', label: 'Published', type: 'boolean' }, + { + name: 'featured', + label: 'Featured on home', + type: 'boolean', + description: 'Only editors and admins can feature a post.', + access: { write: ['admin', 'editor'] }, + }, + { + name: 'editorNotes', + label: 'Editor notes', + type: 'text', + access: { read: ['admin', 'editor'] }, + }, + seoField(), + ], + }), + redirectsCollection(), +] + +export const definition = defineCmsDefinition({ + collections, +}) diff --git a/examples/db-federated/src/cms.config.ts b/examples/db-federated/src/cms.config.ts index 9e97071c..a95bca7c 100644 --- a/examples/db-federated/src/cms.config.ts +++ b/examples/db-federated/src/cms.config.ts @@ -6,29 +6,10 @@ * parameterized live query congeals them into one coherent product model * keyed by (locale, region). */ -import { defineCms, defineCollection } from '@tanstack/cms-core' +import { defineCms } from '@tanstack/cms-core' import { createMockAuth } from '@tanstack/cms-ui-react' import type { SeedStore } from '@tanstack/cms-core' - -const collections = [ - defineCollection({ - name: 'productCopy', - label: 'Product copy', - titleField: 'title', - summaryField: 'description', - fields: [ - { name: 'productId', label: 'Product ID', type: 'text' }, - { - name: 'locale', - label: 'Locale', - type: 'select', - options: ['en', 'fr', 'de'], - }, - { name: 'title', label: 'Title', type: 'text' }, - { name: 'description', label: 'Description', type: 'textarea' }, - ], - }), -] +import { definition } from './cms.definition' const copy = ( productId: string, @@ -98,8 +79,7 @@ const seed: SeedStore = { }, } -export const cms = defineCms({ - collections, +export const cms = defineCms(definition, { blockTypes: [], seed, auth: createMockAuth(), @@ -107,6 +87,6 @@ export const cms = defineCms({ declare module '@tanstack/cms-core' { interface Register { - cms: typeof cms + cms: typeof definition } } diff --git a/examples/db-federated/src/cms.definition.ts b/examples/db-federated/src/cms.definition.ts new file mode 100644 index 00000000..7d56c356 --- /dev/null +++ b/examples/db-federated/src/cms.definition.ts @@ -0,0 +1,28 @@ +import { + defineCmsDefinition, + defineCollection, +} from '@tanstack/cms-core/definition' + +const collections = [ + defineCollection({ + name: 'productCopy', + label: 'Product copy', + titleField: 'title', + summaryField: 'description', + fields: [ + { name: 'productId', label: 'Product ID', type: 'text' }, + { + name: 'locale', + label: 'Locale', + type: 'select', + options: ['en', 'fr', 'de'], + }, + { name: 'title', label: 'Title', type: 'text' }, + { name: 'description', label: 'Description', type: 'textarea' }, + ], + }), +] + +export const definition = defineCmsDefinition({ + collections, +}) diff --git a/examples/db-markdown/src/cms.config.ts b/examples/db-markdown/src/cms.config.ts index 38eb4ea4..a5471546 100644 --- a/examples/db-markdown/src/cms.config.ts +++ b/examples/db-markdown/src/cms.config.ts @@ -2,33 +2,19 @@ * data-markdown: the "static markdown" rung. `.md` files in `content/posts` * are mounted as a read-only `post` collection via `createMarkdownStorage()`. */ -import { defineCms, defineCollection } from '@tanstack/cms-core' +import { defineCms } from '@tanstack/cms-core' import { createMarkdownStorage } from '@tanstack/cms-core/storage' +import { definition } from './cms.definition' -export const cms = defineCms({ - collections: [ - defineCollection({ - name: 'post', - label: 'Posts', - titleField: 'title', - bodyField: 'body', - dateField: 'date', - schemaType: 'BlogPosting', - storage: createMarkdownStorage({ dir: 'content/posts' }), - fields: [ - { name: 'title', label: 'Title', type: 'text' }, - { name: 'date', label: 'Date', type: 'date' }, - { name: 'tags', label: 'Tags', type: 'multiselect' }, - { name: 'body', label: 'Body', type: 'markdown' }, - { name: 'published', label: 'Published', type: 'boolean' }, - ], - }), - ], +export const cms = defineCms(definition, { + collections: { + post: { storage: createMarkdownStorage({ dir: 'content/posts' }) }, + }, blockTypes: [], }) declare module '@tanstack/cms-core' { interface Register { - cms: typeof cms + cms: typeof definition } } diff --git a/examples/db-markdown/src/cms.definition.ts b/examples/db-markdown/src/cms.definition.ts new file mode 100644 index 00000000..2f15f93a --- /dev/null +++ b/examples/db-markdown/src/cms.definition.ts @@ -0,0 +1,24 @@ +import { + defineCmsDefinition, + defineCollection, +} from '@tanstack/cms-core/definition' + +export const definition = defineCmsDefinition({ + collections: [ + defineCollection({ + name: 'post', + label: 'Posts', + titleField: 'title', + bodyField: 'body', + dateField: 'date', + schemaType: 'BlogPosting', + fields: [ + { name: 'title', label: 'Title', type: 'text' }, + { name: 'date', label: 'Date', type: 'date' }, + { name: 'tags', label: 'Tags', type: 'multiselect' }, + { name: 'body', label: 'Body', type: 'markdown' }, + { name: 'published', label: 'Published', type: 'boolean' }, + ], + }), + ], +}) diff --git a/examples/db-sqlite/src/cms.config.ts b/examples/db-sqlite/src/cms.config.ts index 285f3e1c..d2cb8bc2 100644 --- a/examples/db-sqlite/src/cms.config.ts +++ b/examples/db-sqlite/src/cms.config.ts @@ -4,23 +4,10 @@ * TanStack DB live queries (`@tanstack/cms-client/db`) instead of the * admin UI. Same collection, two editors. */ -import { defineCms, defineCollection } from '@tanstack/cms-core' +import { defineCms } from '@tanstack/cms-core' import { createMockAuth } from '@tanstack/cms-ui-react' import type { SeedStore } from '@tanstack/cms-core' - -const collections = [ - defineCollection({ - name: 'product', - label: 'Products', - titleField: 'name', - fields: [ - { name: 'name', label: 'Name', type: 'text' }, - { name: 'price', label: 'Price (USD)', type: 'number' }, - { name: 'stock', label: 'Stock', type: 'number' }, - { name: 'published', label: 'Published', type: 'boolean' }, - ], - }), -] +import { definition } from './cms.definition' const seed: SeedStore = { documents: { @@ -47,8 +34,7 @@ const seed: SeedStore = { }, } -export const cms = defineCms({ - collections, +export const cms = defineCms(definition, { blockTypes: [], seed, auth: createMockAuth(), @@ -56,6 +42,6 @@ export const cms = defineCms({ declare module '@tanstack/cms-core' { interface Register { - cms: typeof cms + cms: typeof definition } } diff --git a/examples/db-sqlite/src/cms.definition.ts b/examples/db-sqlite/src/cms.definition.ts new file mode 100644 index 00000000..523bb06c --- /dev/null +++ b/examples/db-sqlite/src/cms.definition.ts @@ -0,0 +1,22 @@ +import { + defineCmsDefinition, + defineCollection, +} from '@tanstack/cms-core/definition' + +const collections = [ + defineCollection({ + name: 'product', + label: 'Products', + titleField: 'name', + fields: [ + { name: 'name', label: 'Name', type: 'text' }, + { name: 'price', label: 'Price (USD)', type: 'number' }, + { name: 'stock', label: 'Stock', type: 'number' }, + { name: 'published', label: 'Published', type: 'boolean' }, + ], + }), +] + +export const definition = defineCmsDefinition({ + collections, +}) diff --git a/examples/emdash-after/MIGRATION.md b/examples/emdash-after/MIGRATION.md index ee33e4fd..bf569520 100644 --- a/examples/emdash-after/MIGRATION.md +++ b/examples/emdash-after/MIGRATION.md @@ -4,7 +4,9 @@ This app is [`../emdash-before`](../emdash-before) (a real EmDash blog on Astro + SQLite) ported to TanStack CMS 1.0 (`@tanstack/cms-core` + `@tanstack/cms-ui-react`). The migration has two halves: -- **Schema** — hand-mapped in [`src/cms.config.ts`](./src/cms.config.ts). +- **Schema** — hand-mapped in [`src/cms.definition.ts`](./src/cms.definition.ts) + (the collections) and [`src/cms.config.ts`](./src/cms.config.ts) (the block + palette). - **Data** — generated into [`src/seed-data.ts`](./src/seed-data.ts) by [`scripts/migrate-emdash.mjs`](./scripts/migrate-emdash.mjs), which reads EmDash's `seed/seed.json` (no running EmDash needed). @@ -38,15 +40,15 @@ covers. ### Collections -| EmDash (`seed.json`) | TanStack CMS (`cms.config.ts`) | Notes | -| ------------------------------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------ | -| `pages` | `page` | `content` → one `richText` block; `path` → `/p/` | -| `posts` | `post` | `content` → `body`; `featured_image` → `hero`; `path` → `/post/`; `admin.columns: ['categories', 'published']` | -| `bylines` | `author` | `{ name, slug, guest }`, keyed by byline slug | -| `taxonomies.category` | `post.categories` | `multiselect`; term slugs as values, labels as option labels | -| `taxonomies.tag` | `post.tags` | `multiselect` | -| `supports: drafts, revisions, scheduling, search` | built in | `publishAt`/`unpublishAt` for scheduling | -| `menus`, `widgetAreas`, `sections`, `settings` | — | Gap report | +| EmDash (`seed.json`) | TanStack CMS (`cms.definition.ts`) | Notes | +| ------------------------------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------ | +| `pages` | `page` | `content` → one `richText` block; `path` → `/p/` | +| `posts` | `post` | `content` → `body`; `featured_image` → `hero`; `path` → `/post/`; `admin.columns: ['categories', 'published']` | +| `bylines` | `author` | `{ name, slug, guest }`, keyed by byline slug | +| `taxonomies.category` | `post.categories` | `multiselect`; term slugs as values, labels as option labels | +| `taxonomies.tag` | `post.tags` | `multiselect` | +| `supports: drafts, revisions, scheduling, search` | built in | `publishAt`/`unpublishAt` for scheduling | +| `menus`, `widgetAreas`, `sections`, `settings` | — | Gap report | ### Fields diff --git a/examples/emdash-after/README.md b/examples/emdash-after/README.md index cf3ca3ea..02885783 100644 --- a/examples/emdash-after/README.md +++ b/examples/emdash-after/README.md @@ -6,9 +6,11 @@ TanStack Start app on TanStack CMS 1.0 — the same shape as [`../blog`](../blog All the app-specific code is: -- [`src/cms.config.ts`](./src/cms.config.ts) — the `page`, `post`, and - `author` collections mapped from EmDash's collections, taxonomies, and - bylines, plus an EmDash-like theme. +- [`src/cms.definition.ts`](./src/cms.definition.ts) — the `page`, `post`, + and `author` collections mapped from EmDash's collections, taxonomies, and + bylines. +- [`src/cms.config.ts`](./src/cms.config.ts) — `defineCms(definition, …)` + with the blocks, AI adapters, seed, and an EmDash-like theme. - [`src/seed-data.ts`](./src/seed-data.ts) — the EmDash entries converted (Portable Text → Markdown), generated by [`scripts/migrate-emdash.mjs`](./scripts/migrate-emdash.mjs). diff --git a/examples/emdash-after/scripts/migrate-emdash.mjs b/examples/emdash-after/scripts/migrate-emdash.mjs index bc880711..344cdfd6 100644 --- a/examples/emdash-after/scripts/migrate-emdash.mjs +++ b/examples/emdash-after/scripts/migrate-emdash.mjs @@ -16,7 +16,7 @@ * seed. With `--export ` it also writes a CMS export * (`tanstack-cms-export` v1) to load with `tanstack-cms import `. * - * This is the data half. The schema half is the hand-written src/cms.config.ts + * This is the data half. The schema half is the hand-written src/cms.definition.ts * (see SKILL.md's field/collection mapping tables). */ import { readFileSync, writeFileSync } from 'node:fs' @@ -183,7 +183,7 @@ function main() { ) } - // multiselect options for cms.config.ts: every taxonomy's terms + // multiselect options for cms.definition.ts: every taxonomy's terms for (const tax of seed.taxonomies ?? []) { const terms = (tax.terms ?? []).map((t) => `${t.slug} (${t.label})`) console.log(` taxonomy ${tax.name} options: ${terms.join(', ')}`) diff --git a/examples/emdash-after/src/cms.config.ts b/examples/emdash-after/src/cms.config.ts index 1dd613a1..04065b6e 100644 --- a/examples/emdash-after/src/cms.config.ts +++ b/examples/emdash-after/src/cms.config.ts @@ -1,25 +1,11 @@ /** - * The migrated content model — the schema half of the EmDash → TanStack CMS - * port. Each collection/field here is the hand-mapped equivalent of an EmDash - * collection in ../emdash-before/seed/seed.json. See MIGRATION.md for the - * field-by-field conversion map. - * - * EmDash field type → core field type: - * string (required) → text, required: true - * slug → slug (kebab-case, unique) - * text → textarea - * image → image (media $media.url → URL string) - * portableText → richtext (markdown) for a flat field (e.g. posts.body), - * → richText block (markdown) inside a `blocks` field (pages) - * status → boolean `published` (status === 'published') - * taxonomies → multiselect (term slugs, labels kept as option labels) - * bylines → `author` collection + `authors` relation (many) - * - * The data half (EmDash entries, Portable Text → markdown) is generated into - * ./seed-data.ts by scripts/migrate-emdash.mjs reading the EmDash seed.json. + * The runtime half of the EmDash → TanStack CMS port: the block palette, AI + * adapters, migrated seed documents, and theme. The content model is in + * ./cms.definition.ts. */ -import { defineBlock, defineCms, defineCollection } from '@tanstack/cms-core' +import { defineBlock, defineCms } from '@tanstack/cms-core' import { seedDocuments } from './seed-data' +import { definition } from './cms.definition' // A migrated EmDash blog body is Markdown, so the page palette needs only the // `richText` block (the UI renderer already handles it). Add more block types @@ -32,87 +18,6 @@ const blockTypes = [ }), ] -const collections = [ - // from emdash-before: the `pages` collection (portableText → blocks) - defineCollection({ - name: 'page', - label: 'Pages', - titleField: 'title', - path: (_doc, id) => `/p/${id}`, - fields: [ - { name: 'title', label: 'Title', type: 'text', required: true }, - { name: 'slug', label: 'Slug', type: 'slug', unique: true }, - { name: 'blocks', label: 'Content', type: 'blocks' }, - { name: 'published', label: 'Published', type: 'boolean' }, - ], - }), - // from emdash-before: the `posts` collection (featured_image → hero, - // portableText body → flat markdown, taxonomies → multiselect, bylines → - // relations to `author`) - defineCollection({ - name: 'post', - label: 'Blog posts', - titleField: 'title', - imageField: 'hero', - summaryField: 'excerpt', - bylineField: 'author', - bodyField: 'body', - schemaType: 'BlogPosting', - path: (_doc, id) => `/post/${id}`, - admin: { columns: ['categories', 'published'] }, - fields: [ - { name: 'title', label: 'Title', type: 'text', required: true }, - { name: 'slug', label: 'Slug', type: 'slug', unique: true }, - { name: 'hero', label: 'Featured image', type: 'image' }, - { name: 'excerpt', label: 'Excerpt', type: 'textarea' }, - { name: 'body', label: 'Body', type: 'richtext' }, - // The public post page shows this credit line; `authors` is the - // structured version of the same bylines. - { name: 'author', label: 'Byline', type: 'text' }, - { - name: 'authors', - label: 'Authors', - type: 'relation', - collection: 'author', - many: true, - }, - { - name: 'categories', - label: 'Categories', - type: 'multiselect', - options: [ - { value: 'development', label: 'Development' }, - { value: 'design', label: 'Design' }, - { value: 'notes', label: 'Notes' }, - ], - }, - { - name: 'tags', - label: 'Tags', - type: 'multiselect', - options: [ - { value: 'webdev', label: 'Web Development' }, - { value: 'opinion', label: 'Opinion' }, - { value: 'tools', label: 'Tools' }, - { value: 'creativity', label: 'Creativity' }, - ], - }, - { name: 'published', label: 'Published', type: 'boolean' }, - ], - }), - // from emdash-before: the site-level `bylines` (credit records) - defineCollection({ - name: 'author', - label: 'Authors', - titleField: 'name', - fields: [ - { name: 'name', label: 'Display name', type: 'text', required: true }, - { name: 'slug', label: 'Slug', type: 'slug', unique: true }, - { name: 'guest', label: 'Guest contributor', type: 'boolean' }, - ], - }), -] - /** * AI models: Claude for text, Gemini ("Nano Banana") for images, each enabled * by its API key. Loaded with `import()` on the server only, so the provider @@ -131,8 +36,7 @@ const ai = { }, } -export const cms = defineCms({ - collections, +export const cms = defineCms(definition, { blockTypes, ai, seed: { documents: seedDocuments }, @@ -163,6 +67,6 @@ export const cms = defineCms({ declare module '@tanstack/cms-core' { interface Register { - cms: typeof cms + cms: typeof definition } } diff --git a/examples/emdash-after/src/cms.definition.ts b/examples/emdash-after/src/cms.definition.ts new file mode 100644 index 00000000..692aa260 --- /dev/null +++ b/examples/emdash-after/src/cms.definition.ts @@ -0,0 +1,109 @@ +/** + * The migrated content model — the schema half of the EmDash → TanStack CMS + * port. Each collection/field here is the hand-mapped equivalent of an EmDash + * collection in ../emdash-before/seed/seed.json. See MIGRATION.md for the + * field-by-field conversion map. + * + * EmDash field type → core field type: + * string (required) → text, required: true + * slug → slug (kebab-case, unique) + * text → textarea + * image → image (media $media.url → URL string) + * portableText → richtext (markdown) for a flat field (e.g. posts.body), + * → richText block (markdown) inside a `blocks` field (pages) + * status → boolean `published` (status === 'published') + * taxonomies → multiselect (term slugs, labels kept as option labels) + * bylines → `author` collection + `authors` relation (many) + * + * The data half (EmDash entries, Portable Text → markdown) is generated into + * ./seed-data.ts by scripts/migrate-emdash.mjs reading the EmDash seed.json. + */ +import { + defineCmsDefinition, + defineCollection, +} from '@tanstack/cms-core/definition' + +const collections = [ + // from emdash-before: the `pages` collection (portableText → blocks) + defineCollection({ + name: 'page', + label: 'Pages', + titleField: 'title', + path: (_doc, id) => `/p/${id}`, + fields: [ + { name: 'title', label: 'Title', type: 'text', required: true }, + { name: 'slug', label: 'Slug', type: 'slug', unique: true }, + { name: 'blocks', label: 'Content', type: 'blocks' }, + { name: 'published', label: 'Published', type: 'boolean' }, + ], + }), + // from emdash-before: the `posts` collection (featured_image → hero, + // portableText body → flat markdown, taxonomies → multiselect, bylines → + // relations to `author`) + defineCollection({ + name: 'post', + label: 'Blog posts', + titleField: 'title', + imageField: 'hero', + summaryField: 'excerpt', + bylineField: 'author', + bodyField: 'body', + schemaType: 'BlogPosting', + path: (_doc, id) => `/post/${id}`, + admin: { columns: ['categories', 'published'] }, + fields: [ + { name: 'title', label: 'Title', type: 'text', required: true }, + { name: 'slug', label: 'Slug', type: 'slug', unique: true }, + { name: 'hero', label: 'Featured image', type: 'image' }, + { name: 'excerpt', label: 'Excerpt', type: 'textarea' }, + { name: 'body', label: 'Body', type: 'richtext' }, + // The public post page shows this credit line; `authors` is the + // structured version of the same bylines. + { name: 'author', label: 'Byline', type: 'text' }, + { + name: 'authors', + label: 'Authors', + type: 'relation', + collection: 'author', + many: true, + }, + { + name: 'categories', + label: 'Categories', + type: 'multiselect', + options: [ + { value: 'development', label: 'Development' }, + { value: 'design', label: 'Design' }, + { value: 'notes', label: 'Notes' }, + ], + }, + { + name: 'tags', + label: 'Tags', + type: 'multiselect', + options: [ + { value: 'webdev', label: 'Web Development' }, + { value: 'opinion', label: 'Opinion' }, + { value: 'tools', label: 'Tools' }, + { value: 'creativity', label: 'Creativity' }, + ], + }, + { name: 'published', label: 'Published', type: 'boolean' }, + ], + }), + // from emdash-before: the site-level `bylines` (credit records) + defineCollection({ + name: 'author', + label: 'Authors', + titleField: 'name', + fields: [ + { name: 'name', label: 'Display name', type: 'text', required: true }, + { name: 'slug', label: 'Slug', type: 'slug', unique: true }, + { name: 'guest', label: 'Guest contributor', type: 'boolean' }, + ], + }), +] + +export const definition = defineCmsDefinition({ + collections, +}) diff --git a/examples/payload-after/MIGRATION.md b/examples/payload-after/MIGRATION.md index 6a3c3689..fb8c385f 100644 --- a/examples/payload-after/MIGRATION.md +++ b/examples/payload-after/MIGRATION.md @@ -4,7 +4,9 @@ This app is [`../payload-before`](../payload-before) (Payload v3 + SQLite) ported to TanStack CMS 1.0 (`@tanstack/cms-core` + `@tanstack/cms-ui-react`). The migration has two halves: -- **Schema** — hand-mapped in [`src/cms.config.ts`](./src/cms.config.ts). +- **Schema** — hand-mapped in [`src/cms.definition.ts`](./src/cms.definition.ts) + (the collections) and [`src/cms.config.ts`](./src/cms.config.ts) (the block + palette). - **Data** — generated into [`src/seed-data.ts`](./src/seed-data.ts) by [`scripts/migrate-from-payload.mjs`](./scripts/migrate-from-payload.mjs), which reads the running Payload app's REST API and converts Lexical with @@ -33,7 +35,7 @@ Imports skip hooks and validation, which is what the parity test below covers. ### Collections -| Payload (`payload-before`) | TanStack CMS (`cms.config.ts`) | Notes | +| Payload (`payload-before`) | TanStack CMS (`cms.definition.ts`) | Notes | | -------------------------- | ------------------------------------ | ----------------------------------------------------------- | | `pages` | `page` | `useAsTitle` → `titleField`; `path` → `/` or `/p/` | | `posts` | `post` | `path` → `/post/` | diff --git a/examples/payload-after/README.md b/examples/payload-after/README.md index 2d036dad..8c6a43e8 100644 --- a/examples/payload-after/README.md +++ b/examples/payload-after/README.md @@ -7,8 +7,10 @@ ported to a TanStack Start app on TanStack CMS 1.0 — the same shape as All the app-specific code is: -- [`src/cms.config.ts`](./src/cms.config.ts) — the collections and blocks - mapped from the Payload config (the schema half of the migration). +- [`src/cms.definition.ts`](./src/cms.definition.ts) — the collections mapped + from the Payload config (the schema half of the migration). +- [`src/cms.config.ts`](./src/cms.config.ts) — `defineCms(definition, …)` + with the blocks, AI adapters, seed, and theme. - [`src/seed-data.ts`](./src/seed-data.ts) — the Payload documents converted to the core document shape, Lexical → Markdown (the data half, generated). - [`src/router.tsx`](./src/router.tsx) + [`vite.config.ts`](./vite.config.ts) diff --git a/examples/payload-after/scripts/migrate-from-payload.mjs b/examples/payload-after/scripts/migrate-from-payload.mjs index 47e76361..f348bcf5 100644 --- a/examples/payload-after/scripts/migrate-from-payload.mjs +++ b/examples/payload-after/scripts/migrate-from-payload.mjs @@ -4,7 +4,7 @@ * Reads content from a running payload-before instance over its REST API and * writes it as a TanStack CMS seed (`src/seed-data.ts`) in the core store shape. * This is the data half of the migration "skill"; the schema half is the - * hand-mapped `src/cms.config.ts`. See MIGRATION.md for the full conversion map. + * hand-mapped `src/cms.definition.ts`. See MIGRATION.md for the full conversion map. * * Usage (with payload-before running on :3010): * node scripts/migrate-from-payload.mjs [http://localhost:3010] diff --git a/examples/payload-after/src/cms.config.ts b/examples/payload-after/src/cms.config.ts index b52f3f75..497f61ce 100644 --- a/examples/payload-after/src/cms.config.ts +++ b/examples/payload-after/src/cms.config.ts @@ -1,27 +1,11 @@ /** - * The migrated content model — the schema half of the Payload → TanStack CMS - * port. Each collection/field here is the hand-mapped equivalent of a Payload - * collection in ../../payload-before/src/collections. See MIGRATION.md for the - * field-by-field conversion map. - * - * Payload field type → core field type: - * text → text (`required` / `unique` carry over) - * textarea → textarea - * checkbox → boolean (`defaultValue` carries over) - * upload (media) → image (stores a media URL string) - * richText (Lexical) → richtext (markdown) for flat fields, - * → richText block (markdown) inside `blocks` - * blocks → blocks - * admin.defaultColumns → admin.columns - * - * Payload's `access.read: () => true` is the core default (published content - * is public; drafts need `content.read`), so no `collection.access` is needed. - * - * The data half (Payload documents, Lexical → markdown) is generated into - * ./seed-data.ts by scripts/migrate-from-payload.mjs. + * The runtime half of the Payload → TanStack CMS port: the block palette, AI + * adapters, migrated seed documents, and theme. The content model is in + * ./cms.definition.ts. */ -import { defineBlock, defineCms, defineCollection } from '@tanstack/cms-core' +import { defineBlock, defineCms } from '@tanstack/cms-core' import { seedDocuments } from './seed-data' +import { definition } from './cms.definition' // Payload `pages.layout` blocks → the core block palette. Field mapping per // block: Payload `upload` image → core `image`; the richText block's Lexical @@ -67,61 +51,6 @@ const blockTypes = [ }), ] -const collections = [ - // from payload-before/src/collections/Pages.ts - defineCollection({ - name: 'page', - label: 'Pages', - titleField: 'title', - imageField: 'hero', - path: (doc, id) => (doc.slug === '/' ? '/' : `/p/${id}`), - admin: { columns: ['slug', 'published'] }, - fields: [ - { name: 'title', label: 'Title', type: 'text', required: true }, - { - name: 'slug', - label: 'Slug', - type: 'text', - required: true, - unique: true, - description: 'URL-safe path, e.g. /about', - }, - { name: 'hero', label: 'Featured image', type: 'image' }, - { name: 'blocks', label: 'Content', type: 'blocks' }, - { - name: 'published', - label: 'Published', - type: 'boolean', - defaultValue: false, - }, - ], - }), - // from payload-before/src/collections/Posts.ts - defineCollection({ - name: 'post', - label: 'Blog posts', - titleField: 'title', - summaryField: 'excerpt', - bylineField: 'author', - bodyField: 'body', - schemaType: 'BlogPosting', - path: (_doc, id) => `/post/${id}`, - admin: { columns: ['author', 'published'] }, - fields: [ - { name: 'title', label: 'Title', type: 'text', required: true }, - { name: 'author', label: 'Author', type: 'text' }, - { name: 'excerpt', label: 'Excerpt', type: 'textarea' }, - { name: 'body', label: 'Body', type: 'richtext' }, - { - name: 'published', - label: 'Published', - type: 'boolean', - defaultValue: false, - }, - ], - }), -] - /** * AI models: Claude for text, Gemini ("Nano Banana") for images, each enabled * by its API key. Loaded with `import()` on the server only, so the provider @@ -140,9 +69,7 @@ const ai = { }, } -export const cms = defineCms({ - admin: { basePath: '/admin' }, - collections, +export const cms = defineCms(definition, { blockTypes, ai, seed: { documents: seedDocuments }, @@ -170,6 +97,6 @@ export const cms = defineCms({ declare module '@tanstack/cms-core' { interface Register { - cms: typeof cms + cms: typeof definition } } diff --git a/examples/payload-after/src/cms.definition.ts b/examples/payload-after/src/cms.definition.ts new file mode 100644 index 00000000..6ad9da79 --- /dev/null +++ b/examples/payload-after/src/cms.definition.ts @@ -0,0 +1,86 @@ +/** + * The migrated content model — the schema half of the Payload → TanStack CMS + * port. Each collection/field here is the hand-mapped equivalent of a Payload + * collection in ../../payload-before/src/collections. See MIGRATION.md for the + * field-by-field conversion map. + * + * Payload field type → core field type: + * text → text (`required` / `unique` carry over) + * textarea → textarea + * checkbox → boolean (`defaultValue` carries over) + * upload (media) → image (stores a media URL string) + * richText (Lexical) → richtext (markdown) for flat fields, + * → richText block (markdown) inside `blocks` + * blocks → blocks + * admin.defaultColumns → admin.columns + * + * Payload's `access.read: () => true` is the core default (published content + * is public; drafts need `content.read`), so no `collection.access` is needed. + * + * The data half (Payload documents, Lexical → markdown) is generated into + * ./seed-data.ts by scripts/migrate-from-payload.mjs. + */ +import { + defineCmsDefinition, + defineCollection, +} from '@tanstack/cms-core/definition' + +const collections = [ + // from payload-before/src/collections/Pages.ts + defineCollection({ + name: 'page', + label: 'Pages', + titleField: 'title', + imageField: 'hero', + path: (doc, id) => (doc.slug === '/' ? '/' : `/p/${id}`), + admin: { columns: ['slug', 'published'] }, + fields: [ + { name: 'title', label: 'Title', type: 'text', required: true }, + { + name: 'slug', + label: 'Slug', + type: 'text', + required: true, + unique: true, + description: 'URL-safe path, e.g. /about', + }, + { name: 'hero', label: 'Featured image', type: 'image' }, + { name: 'blocks', label: 'Content', type: 'blocks' }, + { + name: 'published', + label: 'Published', + type: 'boolean', + defaultValue: false, + }, + ], + }), + // from payload-before/src/collections/Posts.ts + defineCollection({ + name: 'post', + label: 'Blog posts', + titleField: 'title', + summaryField: 'excerpt', + bylineField: 'author', + bodyField: 'body', + schemaType: 'BlogPosting', + path: (_doc, id) => `/post/${id}`, + admin: { columns: ['author', 'published'] }, + fields: [ + { name: 'title', label: 'Title', type: 'text', required: true }, + { name: 'author', label: 'Author', type: 'text' }, + { name: 'excerpt', label: 'Excerpt', type: 'textarea' }, + { name: 'body', label: 'Body', type: 'richtext' }, + { + name: 'published', + label: 'Published', + type: 'boolean', + defaultValue: false, + }, + ], + }), +] + +export const definition = defineCmsDefinition({ + admin: { basePath: '/admin' }, + collections, +}) diff --git a/examples/picks/src/cms.config.ts b/examples/picks/src/cms.config.ts index 6c50900a..bf233bfd 100644 --- a/examples/picks/src/cms.config.ts +++ b/examples/picks/src/cms.config.ts @@ -1,9 +1,8 @@ import { defineCms } from '@tanstack/cms-core' import { createMockAuth } from '@tanstack/cms-ui-react' -import { picks } from './collection' import { pickDocuments } from './seed' -export const cms = defineCms({ - collections: [picks], +import { definition } from './cms.definition' +export const cms = defineCms(definition, { blockTypes: [], seed: { documents: { picks: pickDocuments } }, auth: createMockAuth({ defaultRole: 'unauthenticated' }), diff --git a/examples/picks/src/cms.definition.ts b/examples/picks/src/cms.definition.ts new file mode 100644 index 00000000..fe2e12bf --- /dev/null +++ b/examples/picks/src/cms.definition.ts @@ -0,0 +1,6 @@ +import { defineCmsDefinition } from '@tanstack/cms-core/definition' +import { picks } from './collection' + +export const definition = defineCmsDefinition({ + collections: [picks], +}) diff --git a/examples/wordpress-after/MIGRATION.md b/examples/wordpress-after/MIGRATION.md index 3cb347d8..8fba08c8 100644 --- a/examples/wordpress-after/MIGRATION.md +++ b/examples/wordpress-after/MIGRATION.md @@ -4,7 +4,9 @@ This app is [`../wordpress-before/export.wxr.xml`](../wordpress-before/export.wx (a WordPress WXR export) ported to TanStack CMS 1.0 (`@tanstack/cms-core` + `@tanstack/cms-ui-react`). The migration has two halves: -- **Schema** — hand-mapped in [`src/cms.config.ts`](./src/cms.config.ts). +- **Schema** — hand-mapped in [`src/cms.definition.ts`](./src/cms.definition.ts) + (the collections) and [`src/cms.config.ts`](./src/cms.config.ts) (the block + palette). - **Data** — generated into [`src/seed-data.ts`](./src/seed-data.ts) by [`scripts/migrate-wordpress.mjs`](./scripts/migrate-wordpress.mjs), which parses the WXR (no running WordPress needed). @@ -38,7 +40,7 @@ handles both Gutenberg and classic-editor bodies. ### Post types → collections -| WordPress (`export.wxr.xml`) | TanStack CMS (`cms.config.ts`) | Notes | +| WordPress (`export.wxr.xml`) | TanStack CMS (`cms.definition.ts`) | Notes | | ---------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------------- | | `page` post type | `page` | Body → one `richText` block; `path` → `/p/` | | `post` post type | `post` | Body → `body`; `path` → `/post/`; `admin.columns: ['author', 'categories', 'published']` | diff --git a/examples/wordpress-after/README.md b/examples/wordpress-after/README.md index 787e0bb8..4ee4a0b1 100644 --- a/examples/wordpress-after/README.md +++ b/examples/wordpress-after/README.md @@ -6,10 +6,11 @@ TanStack CMS 1.0 — the same shape as [`../blog`](../blog). All the app-specific code is: -- [`src/cms.config.ts`](./src/cms.config.ts) — the `page` and `post` +- [`src/cms.definition.ts`](./src/cms.definition.ts) — the `page` and `post` collections mapped from the WordPress post types, categories and tags as - `multiselect` fields, a `redirect` collection for the old permalinks, and a - classic WordPress theme. + `multiselect` fields, and a `redirect` collection for the old permalinks. +- [`src/cms.config.ts`](./src/cms.config.ts) — `defineCms(definition, …)` + with the blocks, AI adapters, seed, and a classic WordPress theme. - [`src/seed-data.ts`](./src/seed-data.ts) — the posts and pages converted (Gutenberg/HTML → Markdown), generated by [`scripts/migrate-wordpress.mjs`](./scripts/migrate-wordpress.mjs). diff --git a/examples/wordpress-after/scripts/migrate-wordpress.mjs b/examples/wordpress-after/scripts/migrate-wordpress.mjs index ef1c06fd..d13f85f4 100644 --- a/examples/wordpress-after/scripts/migrate-wordpress.mjs +++ b/examples/wordpress-after/scripts/migrate-wordpress.mjs @@ -16,7 +16,7 @@ * `--export ` it also writes a CMS export (`tanstack-cms-export` v1) to * load with `tanstack-cms import `. * - * This is the data half. The schema half is the hand-written src/cms.config.ts + * This is the data half. The schema half is the hand-written src/cms.definition.ts * (see SKILL.md's field/collection mapping tables). */ import { readFileSync, writeFileSync } from 'node:fs' @@ -71,7 +71,7 @@ const CONFIG = { }), }, } -const REDIRECTS = 'redirect' // the redirectsCollection() name in cms.config.ts +const REDIRECTS = 'redirect' // the redirectsCollection() name in cms.definition.ts // =========================================================================== /** Path of a WordPress permalink (`https://site/a-post/` → `/a-post/`), or null. */ diff --git a/examples/wordpress-after/src/cms.config.ts b/examples/wordpress-after/src/cms.config.ts index 199c789c..689eeb47 100644 --- a/examples/wordpress-after/src/cms.config.ts +++ b/examples/wordpress-after/src/cms.config.ts @@ -1,31 +1,11 @@ /** - * The migrated content model — the schema half of the WordPress → TanStack CMS - * port. Each collection/field here is the hand-mapped equivalent of a WordPress - * post type in ../wordpress-before/export.wxr.xml. See MIGRATION.md for the - * field-by-field conversion map. - * - * WordPress → core field type: - * post_title → title (text) - * post_name (slug) → slug (text) - * featured image → hero (image) (_thumbnail_id → attachment URL) - * dc:creator → author (text) (login resolved to display name) - * excerpt → excerpt (textarea, markdown) - * content (HTML / Gutenberg) → body (textarea markdown) for posts, - * → richText block (markdown) inside `blocks` for pages - * status=publish → published:true (draft → false) - * categories/tags → multiselect (term nicenames; labels as option labels) - * permalinks → redirect docs (old / URL → /post/, /p/) - * - * The data half (WXR entries, Gutenberg/HTML → markdown) is generated into - * ./seed-data.ts by scripts/migrate-wordpress.mjs. + * The runtime half of the WordPress → TanStack CMS port: the block palette, AI + * adapters, migrated seed documents, and theme. The content model is in + * ./cms.definition.ts. */ -import { - defineBlock, - defineCms, - defineCollection, - redirectsCollection, -} from '@tanstack/cms-core' +import { defineBlock, defineCms } from '@tanstack/cms-core' import { seedDocuments } from './seed-data' +import { definition } from './cms.definition' // WordPress bodies become Markdown, so the page palette needs only the // `richText` block (the UI renderer already handles it). @@ -37,65 +17,6 @@ const blockTypes = [ }), ] -const collections = [ - // from wordpress-before: `page` post type (Gutenberg → blocks) - defineCollection({ - name: 'page', - label: 'Pages', - titleField: 'title', - path: (_doc, id) => `/p/${id}`, - fields: [ - { name: 'title', label: 'Title', type: 'text', required: true }, - { name: 'slug', label: 'Slug', type: 'text', unique: true }, - { name: 'blocks', label: 'Content', type: 'blocks' }, - { name: 'published', label: 'Published', type: 'boolean' }, - ], - }), - // from wordpress-before: `post` post type (Gutenberg/classic HTML → markdown) - defineCollection({ - name: 'post', - label: 'Blog posts', - titleField: 'title', - imageField: 'hero', - summaryField: 'excerpt', - bylineField: 'author', - bodyField: 'body', - schemaType: 'BlogPosting', - path: (_doc, id) => `/post/${id}`, - admin: { columns: ['author', 'categories', 'published'] }, - fields: [ - { name: 'title', label: 'Title', type: 'text', required: true }, - { name: 'slug', label: 'Slug', type: 'text', unique: true }, - { name: 'hero', label: 'Featured image', type: 'image' }, - { name: 'author', label: 'Author', type: 'text' }, - { name: 'excerpt', label: 'Excerpt', type: 'textarea' }, - { name: 'body', label: 'Body', type: 'richtext' }, - { - name: 'categories', - label: 'Categories', - type: 'multiselect', - options: [ - { value: 'growing', label: 'Growing' }, - { value: 'soil', label: 'Soil' }, - ], - }, - { - name: 'tags', - label: 'Tags', - type: 'multiselect', - options: [ - { value: 'beginner', label: 'Beginner' }, - { value: 'tomatoes', label: 'Tomatoes' }, - ], - }, - { name: 'published', label: 'Published', type: 'boolean' }, - ], - }), - // Old WordPress permalinks (/) → the new public URLs. The - // catch-all route follows these with a 301. - redirectsCollection(), -] - /** * AI models: Claude for text, Gemini ("Nano Banana") for images, each enabled * by its API key. Loaded with `import()` on the server only, so the provider @@ -114,8 +35,7 @@ const ai = { }, } -export const cms = defineCms({ - collections, +export const cms = defineCms(definition, { blockTypes, ai, seed: { documents: seedDocuments }, @@ -147,6 +67,6 @@ export const cms = defineCms({ declare module '@tanstack/cms-core' { interface Register { - cms: typeof cms + cms: typeof definition } } diff --git a/examples/wordpress-after/src/cms.definition.ts b/examples/wordpress-after/src/cms.definition.ts new file mode 100644 index 00000000..350fe193 --- /dev/null +++ b/examples/wordpress-after/src/cms.definition.ts @@ -0,0 +1,89 @@ +/** + * The migrated content model — the schema half of the WordPress → TanStack CMS + * port. Each collection/field here is the hand-mapped equivalent of a WordPress + * post type in ../wordpress-before/export.wxr.xml. See MIGRATION.md for the + * field-by-field conversion map. + * + * WordPress → core field type: + * post_title → title (text) + * post_name (slug) → slug (text) + * featured image → hero (image) (_thumbnail_id → attachment URL) + * dc:creator → author (text) (login resolved to display name) + * excerpt → excerpt (textarea, markdown) + * content (HTML / Gutenberg) → body (textarea markdown) for posts, + * → richText block (markdown) inside `blocks` for pages + * status=publish → published:true (draft → false) + * categories/tags → multiselect (term nicenames; labels as option labels) + * permalinks → redirect docs (old / URL → /post/, /p/) + * + * The data half (WXR entries, Gutenberg/HTML → markdown) is generated into + * ./seed-data.ts by scripts/migrate-wordpress.mjs. + */ +import { + defineCmsDefinition, + defineCollection, + redirectsCollection, +} from '@tanstack/cms-core/definition' + +const collections = [ + // from wordpress-before: `page` post type (Gutenberg → blocks) + defineCollection({ + name: 'page', + label: 'Pages', + titleField: 'title', + path: (_doc, id) => `/p/${id}`, + fields: [ + { name: 'title', label: 'Title', type: 'text', required: true }, + { name: 'slug', label: 'Slug', type: 'text', unique: true }, + { name: 'blocks', label: 'Content', type: 'blocks' }, + { name: 'published', label: 'Published', type: 'boolean' }, + ], + }), + // from wordpress-before: `post` post type (Gutenberg/classic HTML → markdown) + defineCollection({ + name: 'post', + label: 'Blog posts', + titleField: 'title', + imageField: 'hero', + summaryField: 'excerpt', + bylineField: 'author', + bodyField: 'body', + schemaType: 'BlogPosting', + path: (_doc, id) => `/post/${id}`, + admin: { columns: ['author', 'categories', 'published'] }, + fields: [ + { name: 'title', label: 'Title', type: 'text', required: true }, + { name: 'slug', label: 'Slug', type: 'text', unique: true }, + { name: 'hero', label: 'Featured image', type: 'image' }, + { name: 'author', label: 'Author', type: 'text' }, + { name: 'excerpt', label: 'Excerpt', type: 'textarea' }, + { name: 'body', label: 'Body', type: 'richtext' }, + { + name: 'categories', + label: 'Categories', + type: 'multiselect', + options: [ + { value: 'growing', label: 'Growing' }, + { value: 'soil', label: 'Soil' }, + ], + }, + { + name: 'tags', + label: 'Tags', + type: 'multiselect', + options: [ + { value: 'beginner', label: 'Beginner' }, + { value: 'tomatoes', label: 'Tomatoes' }, + ], + }, + { name: 'published', label: 'Published', type: 'boolean' }, + ], + }), + // Old WordPress permalinks (/) → the new public URLs. The + // catch-all route follows these with a 301. + redirectsCollection(), +] + +export const definition = defineCmsDefinition({ + collections, +}) diff --git a/package.json b/package.json index 8d185e3d..0591e78f 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,7 @@ "test:docs": "tsx scripts/verify-links.ts", "test:starters": "tsx scripts/verify-starters.ts", "test:dialects": "tsx scripts/dialect-inventory.ts --check", - "test:definitions": "tsx scripts/verify-definitions.ts", + "test:definitions": "tsx scripts/verify-definitions.ts --strict", "test:scripts": "vitest run scripts/codemods scripts/dialect-inventory.test.ts scripts/seo-snapshots scripts/verify-definitions.test.ts", "test:dts": "node scripts/scan-dangling-dts.mjs", "test:kiira": "kiira check", diff --git a/packages/cli/README.md b/packages/cli/README.md index 8e7c7a7b..af5c7467 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -15,7 +15,7 @@ local SQLite, libsql/Turso, local disk, or S3/R2. | Command | What it does | | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `tanstack-cms init [--dir app] [--force]` | Creates `src/cms.config.ts`, adds `tanstackCms()` and `cmsVirtualRoutes()` to `vite.config.ts`, imports the config from `src/router.tsx`, and ignores `.data/`. Prints instructions for files it can't patch. `--dir` targets another app directory; `--force` overwrites an existing `cms.config.ts`. | +| `tanstack-cms init [--dir app] [--force]` | Creates `src/cms.definition.ts` and `src/cms.config.ts`, adds `tanstackCms()` and `cmsVirtualRoutes()` to `vite.config.ts`, imports the config from `src/router.tsx`, and ignores `.data/`. Prints instructions for files it can't patch. `--dir` targets another app directory; `--force` overwrites existing `cms.definition.ts` and `cms.config.ts` files. | | `tanstack-cms migrate [--status] [--dry-run] [--collections a,b]` | Applies pending storage schema migrations, field indexes, and per-collection content migrations (`collection.migrations`). `--status` reports storage and content migration versions; `--dry-run` previews content migrations without writing; `--collections` restricts content migrations to the named collections. Run in deploy pipelines before starting the server. | | `tanstack-cms seed [--force]` | Writes the `defineCms({ seed })` documents. Without `--force` it does nothing once the store has content. | | `tanstack-cms export [--out file] [--collections a,b] [--revisions]` | Writes committed documents (and media metadata, plus revision history with `--revisions`) as JSON, to stdout by default. | diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts index a7aaad3f..f4649c3c 100644 --- a/packages/cli/src/commands/init.ts +++ b/packages/cli/src/commands/init.ts @@ -1,17 +1,22 @@ /** * `tanstack-cms init` — add TanStack CMS to an existing TanStack Start app: - * a starter `src/cms.config.ts`, the Vite plugins, the router import, and + * a starter `src/cms.definition.ts` (the content model, safe to import from + * client code) and `src/cms.config.ts` (`defineCms(definition, runtime)`), + * the Vite plugins, the router import, and * `.gitignore` entries. Files it can't patch safely get printed instructions. */ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' import path from 'node:path' import type { Io } from '../io' -export const CONFIG_TEMPLATE = `import { defineCms } from '@tanstack/cms-core' +export const DEFINITION_TEMPLATE = `import { + defineCmsDefinition, + defineCollection, +} from '@tanstack/cms-core/definition' -export const cms = defineCms({ +export const definition = defineCmsDefinition({ collections: [ - { + defineCollection({ name: 'post', label: 'Posts', titleField: 'title', @@ -28,8 +33,15 @@ export const cms = defineCms({ { name: 'excerpt', label: 'Excerpt', type: 'textarea', required: false }, { name: 'body', label: 'Body', type: 'markdown', required: false }, ], - }, + }), ], +}) +` + +export const CONFIG_TEMPLATE = `import { defineCms } from '@tanstack/cms-core' +import { definition } from './cms.definition' + +export const cms = defineCms(definition, { blockTypes: [], seed: { documents: { @@ -47,7 +59,7 @@ export const cms = defineCms({ declare module '@tanstack/cms-core' { interface Register { - cms: typeof cms + cms: typeof definition } } ` @@ -129,13 +141,20 @@ export function init(options: InitOptions, io: Io): InitResult { const rel = (f: string) => path.relative(dir, f) || f const srcDir = existsSync(path.join(dir, 'src')) ? 'src' : '' - const configFile = path.join(dir, srcDir, 'cms.config.ts') - if (existsSync(configFile) && !options.force) { - io.log(`• ${rel(configFile)} already exists (use --force to overwrite)`) + const scaffold = [ + [path.join(dir, srcDir, 'cms.definition.ts'), DEFINITION_TEMPLATE], + [path.join(dir, srcDir, 'cms.config.ts'), CONFIG_TEMPLATE], + ] as const + const existing = scaffold.filter(([file]) => existsSync(file)) + if (existing.length && !options.force) { + for (const [file] of existing) + io.log(`• ${rel(file)} already exists (use --force to overwrite)`) } else { - mkdirSync(path.dirname(configFile), { recursive: true }) - writeFileSync(configFile, CONFIG_TEMPLATE) - result.created.push(rel(configFile)) + mkdirSync(path.join(dir, srcDir), { recursive: true }) + for (const [file, template] of scaffold) { + writeFileSync(file, template) + result.created.push(rel(file)) + } } const viteFile = ['vite.config.ts', 'vite.config.mts', 'vite.config.js'] diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 54905ac9..d24061be 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -41,7 +41,7 @@ export type { Io } from './io' const HELP = `tanstack-cms [options] Commands: - init Add TanStack CMS to this TanStack Start app (--dir , --force to overwrite cms.config.ts) + init Add TanStack CMS to this TanStack Start app (--dir , --force to overwrite cms.definition.ts and cms.config.ts) migrate Apply storage and content migrations (--status, --dry-run, --collections) migrate-wp Evacuate a WordPress site via live REST API (--url) or WXR archive (--wxr, --uploads, --target code|base, --install-skills) skill List or install TanStack CMS Integration Skills (skill list, skill add ) diff --git a/packages/cli/tests/cli.test.ts b/packages/cli/tests/cli.test.ts index a5570c26..97445de2 100644 --- a/packages/cli/tests/cli.test.ts +++ b/packages/cli/tests/cli.test.ts @@ -189,8 +189,11 @@ describe('tanstack-cms init', () => { const io = capture() expect(await main(['init', '--cwd', dir], io)).toBe(0) expect(readFileSync(path.join(dir, 'src/cms.config.ts'), 'utf8')).toMatch( - /defineCms\(/, + /defineCms\(definition, \{/, ) + expect( + readFileSync(path.join(dir, 'src/cms.definition.ts'), 'utf8'), + ).toMatch(/from '@tanstack\/cms-core\/definition'/) const vite = readFileSync(path.join(dir, 'vite.config.ts'), 'utf8') expect(vite).toMatch(/tanstackCms\(\),/) expect(vite).toMatch(/virtualRouteConfig: cmsVirtualRoutes\(\)/) @@ -203,6 +206,18 @@ describe('tanstack-cms init', () => { const again = capture() await main(['init', '--cwd', dir], again) expect(again.out.join('\n')).toMatch(/already exists/) + + rmSync(path.join(dir, 'src/cms.config.ts')) + const partial = capture() + await main(['init', '--cwd', dir], partial) + expect(partial.out.join('\n')).toMatch( + /src\/cms\.definition\.ts already exists/, + ) + expect(existsSync(path.join(dir, 'src/cms.config.ts'))).toBe(false) + + const forced = capture() + await main(['init', '--cwd', dir, '--force'], forced) + expect(forced.out.join('\n')).toMatch(/created src\/cms\.config\.ts/) }) it('leaves vite configs it cannot patch for manual edits', () => { diff --git a/packages/cms-connect-atproto/src/connector.ts b/packages/cms-connect-atproto/src/connector.ts index d5c541ca..9ce6047f 100644 --- a/packages/cms-connect-atproto/src/connector.ts +++ b/packages/cms-connect-atproto/src/connector.ts @@ -11,7 +11,11 @@ * factory (and building a config with it) never pulls the optional peer into * the type graph or the bundle. */ -import { definePlugin, defineEventHandler } from '@tanstack/cms-core' +import { + defineEventHandler, + definePlugin, + definePluginDefinition, +} from '@tanstack/cms-core' import { createAtpClient } from './client' import { isPublishEnabled, publishMappingFor } from './config' import { publishDocument } from './publish/publisher' @@ -57,9 +61,11 @@ export function createAtprotoConnector( eventHandlers.push(syncHandler(config)) } + // No collections or routes, so apps list it in the runtime config's + // `plugins` only; `cms.definition.ts` doesn't need it. return definePlugin({ - name: config.name ?? 'atproto', - eventHandlers, + definition: definePluginDefinition({ name: config.name ?? 'atproto' }), + runtime: { eventHandlers }, }) } diff --git a/packages/cms-connect-atproto/src/index.ts b/packages/cms-connect-atproto/src/index.ts index 3487a500..a9d759b5 100644 --- a/packages/cms-connect-atproto/src/index.ts +++ b/packages/cms-connect-atproto/src/index.ts @@ -10,13 +10,15 @@ * ## Recommended: one-call setup * * Pass `createAtprotoConnector(config)` as a plugin and the publish/sync event - * handlers are wired for you — no `defineEventHandler` by hand: + * handlers are wired for you — no `defineEventHandler` by hand. It has no + * collections or routes, so it goes in the runtime config only: * * ```ts * import { defineCms } from '@tanstack/cms-core' * import { createAtprotoConnector } from '@tanstack/cms-connect-atproto' + * import { definition } from './cms.definition' * - * export default defineCms({ + * export const cms = defineCms(definition, { * plugins: [ * createAtprotoConnector({ * publish: { post: { enabled: true, linkBase: 'https://site.com/blog' } }, diff --git a/packages/cms-connect-atproto/tests/connector.test.ts b/packages/cms-connect-atproto/tests/connector.test.ts index 40ca873c..af8556b1 100644 --- a/packages/cms-connect-atproto/tests/connector.test.ts +++ b/packages/cms-connect-atproto/tests/connector.test.ts @@ -1,6 +1,11 @@ import { describe, expect, it } from 'vitest' +import { createCms } from '@tanstack/cms-core' +import { defineCmsDefinition } from '@tanstack/cms-core/definition' import { createAtprotoConnector } from '../src/connector' -import type { EventHandlerDefinition } from '@tanstack/cms-core' +import type { + EventHandlerDefinition, + ResolvedCmsConfig, +} from '@tanstack/cms-core' function handlerById( handlers: ReadonlyArray | undefined, @@ -16,6 +21,18 @@ describe('createAtprotoConnector', () => { expect(plugin.eventHandlers ?? []).toHaveLength(0) }) + it('goes in the runtime config without a definition entry', () => { + const plugin = createAtprotoConnector({ + publish: { post: { enabled: true } }, + }) + const cms = createCms(defineCmsDefinition({ collections: [] }), { + blockTypes: [], + plugins: [plugin], + }) + const { eventHandlers } = cms.config as ResolvedCmsConfig + expect(eventHandlers?.map((h) => h.id)).toEqual(['atproto:publish:post']) + }) + it('honors a custom plugin name', () => { const plugin = createAtprotoConnector({ name: 'bsky' }) expect(plugin.name).toBe('bsky') diff --git a/packages/cms-skills/src/engine/engine.ts b/packages/cms-skills/src/engine/engine.ts index 49d0c150..62efc09b 100644 --- a/packages/cms-skills/src/engine/engine.ts +++ b/packages/cms-skills/src/engine/engine.ts @@ -17,6 +17,19 @@ import type { JsonValue } from '@tanstack/cms-core' const PROTECTED_COLLECTIONS = new Set(['shop', 'reports', 'interfaces']) +const DEFINITION_SCAFFOLD = `import { defineCmsDefinition } from '@tanstack/cms-core/definition' + +export const definition = defineCmsDefinition({ + collections: [], +}) +` + +const RUNTIME_SCAFFOLD = `import { defineCms } from '@tanstack/cms-core' +import { definition } from './cms.definition' + +export const cms = defineCms(definition, {}) +` + export class SkillEngine { private readonly skills: Map = new Map() @@ -289,10 +302,16 @@ export class SkillEngine { ? path.join(projectRoot, 'src') : projectRoot - // 1. Update cms.config.ts - const configPath = existsSync(path.join(srcDir, 'cms.config.ts')) - ? path.join(srcDir, 'cms.config.ts') - : path.join(projectRoot, 'cms.config.ts') + // 1. Add the collections to the content model: `cms.definition.ts`, or + // `cms.config.ts` in a one-file app. A new app gets both files. + const hasModel = (dir: string) => + existsSync(path.join(dir, 'cms.definition.ts')) || + existsSync(path.join(dir, 'cms.config.ts')) + const modelDir = [srcDir, projectRoot].find(hasModel) ?? srcDir + const definitionPath = path.join(modelDir, 'cms.definition.ts') + const runtimePath = path.join(modelDir, 'cms.config.ts') + const oneFile = existsSync(runtimePath) && !existsSync(definitionPath) + const configPath = oneFile ? runtimePath : definitionPath const collectionSnippets = skill.collections .map((col) => { @@ -328,7 +347,11 @@ export const ${colName}Collection = ${JSON.stringify( mkdirSync(path.dirname(configPath), { recursive: true }) const existingConfig = existsSync(configPath) ? readFileSync(configPath, 'utf8') - : `import { defineCms } from '@tanstack/cms-core'\n\nexport const cms = defineCms({\n collections: [],\n})\n` + : DEFINITION_SCAFFOLD + if (!existsSync(runtimePath)) { + writeFileSync(runtimePath, RUNTIME_SCAFFOLD, 'utf8') + filesWritten.push(runtimePath) + } if (!existingConfig.includes(skill.id)) { const appended = [ existingConfig.trimEnd(), @@ -345,6 +368,7 @@ export const ${colName}Collection = ${JSON.stringify( } } else { cmsConfigUpdated = true + if (!existsSync(runtimePath)) filesWritten.push(runtimePath) filesWritten.push(configPath) } diff --git a/packages/cms-skills/src/engine/types.ts b/packages/cms-skills/src/engine/types.ts index 524f6603..efff3a9e 100644 --- a/packages/cms-skills/src/engine/types.ts +++ b/packages/cms-skills/src/engine/types.ts @@ -166,6 +166,10 @@ export interface ApplySkillToCodeResult { skillId: string skillSlug: string filesWritten: Array + /** + * The skill's collections were added to the content model: + * `cms.definition.ts`, or `cms.config.ts` in a one-file app. + */ cmsConfigUpdated: boolean operationsUpdated: boolean blockComponentsWritten: Array diff --git a/packages/cms-skills/tests/skills.test.ts b/packages/cms-skills/tests/skills.test.ts index 672bd80b..657e8d27 100644 --- a/packages/cms-skills/tests/skills.test.ts +++ b/packages/cms-skills/tests/skills.test.ts @@ -1,4 +1,11 @@ -import { mkdtempSync, readFileSync, rmSync, existsSync } from 'node:fs' +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs' import { tmpdir } from 'node:os' import path from 'node:path' import { afterEach, describe, expect, it } from 'vitest' @@ -137,9 +144,16 @@ describe('@tanstack/cms-skills engine & registry', () => { expect(codeResult.operationsUpdated).toBe(true) expect(codeResult.blockComponentsWritten).toHaveLength(1) - const configContent = readFileSync(path.join(root, 'cms.config.ts'), 'utf8') - expect(configContent).toContain('@tanstack/skill-forms-lead-capture') - expect(configContent).toContain('form_submissionsCollection') + const definitionContent = readFileSync( + path.join(root, 'cms.definition.ts'), + 'utf8', + ) + expect(definitionContent).toContain('defineCmsDefinition(') + expect(definitionContent).toContain('@tanstack/skill-forms-lead-capture') + expect(definitionContent).toContain('form_submissionsCollection') + expect(readFileSync(path.join(root, 'cms.config.ts'), 'utf8')).toContain( + 'defineCms(definition, {})', + ) const opsContent = readFileSync(path.join(root, 'operations.ts'), 'utf8') expect(opsContent).toContain('skill.forms_lead_capture.afterCreate') @@ -160,6 +174,34 @@ describe('@tanstack/cms-skills engine & registry', () => { expect(existsSync(manifestFile)).toBe(true) }) + it('adds code-mode collections to cms.definition.ts beside an existing config, or to a one-file cms.config.ts', async () => { + const split = mkdtempSync(path.join(tmpdir(), 'cms-skill-split-')) + tempDirs.push(split) + mkdirSync(path.join(split, 'src')) + const runtime = "import { defineCms } from '@tanstack/cms-core'\n" + writeFileSync(path.join(split, 'src/cms.config.ts'), runtime) + writeFileSync( + path.join(split, 'src/cms.definition.ts'), + 'export const definition = {}\n', + ) + await applySkillToCode('forms-lead-capture', split) + expect( + readFileSync(path.join(split, 'src/cms.definition.ts'), 'utf8'), + ).toContain('form_submissionsCollection') + expect(readFileSync(path.join(split, 'src/cms.config.ts'), 'utf8')).toBe( + runtime, + ) + + const oneFile = mkdtempSync(path.join(tmpdir(), 'cms-skill-one-file-')) + tempDirs.push(oneFile) + writeFileSync(path.join(oneFile, 'cms.config.ts'), runtime) + await applySkillToCode('forms-lead-capture', oneFile) + expect(readFileSync(path.join(oneFile, 'cms.config.ts'), 'utf8')).toContain( + 'form_submissionsCollection', + ) + expect(existsSync(path.join(oneFile, 'cms.definition.ts'))).toBe(false) + }) + it('exposes listSkills and proposeSkillInstall tools from @tanstack/cms-core/server', async () => { const cf7Skills = listCoreSkills({ wpPlugin: 'contact-form-7' }) expect(cf7Skills).toHaveLength(1) diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts index 4a2fdbaa..570cfa4c 100644 --- a/packages/core/src/config.ts +++ b/packages/core/src/config.ts @@ -15,15 +15,20 @@ */ import { DEFAULT_ASSET_COLLECTION, buildAssetCollection } from './assets' import { - DEFINITION_KEYS, collectionsByName, isCmsDefinition, normalizeAdminBasePath, } from './lib/definition' -import type { CmsDefinition, CmsDefinitionConfig } from './lib/definition' +import type { + CmsDefinition, + CmsDefinitionConfig, + DEFINITION_KEYS, +} from './lib/definition' +import { PLUGIN_DEFINITION_KEYS, PLUGIN_RUNTIME_KEYS } from './lib/authoring' import type { BlockType, Collection, + CollectionHooks, Doc, FieldTypeDefinition, InferDoc, @@ -33,7 +38,7 @@ import type { CmsAuthConfig, CmsSession } from './lib/auth' import type { StorageAdapter } from './storage/types' import type { MediaAdapter } from './media/types' import type { MediaKind } from './media/sniff' -import type { Permission } from './lib/access' +import type { CollectionAccess, Permission } from './lib/access' import type { CmsOpDefinition, CmsOpContext, @@ -42,8 +47,6 @@ import type { } from './ops' import type { CmsEventsConfig, EventHandlerDefinition } from './events' -export { definePlugin } from './lib/authoring' - /** The seed store an app ships so a fresh install isn't empty. */ export interface SeedStore { documents: Record> @@ -360,20 +363,15 @@ export interface CmsAdminNavItem { } /** - * A reusable slice of CMS configuration. Everything is optional; contribute - * only what the plugin needs. + * The definition part of a plugin (`definePluginDefinition`): pure data that + * routing and the admin read. Everything but `name` is optional. */ -export interface CmsPlugin< +export interface CmsPluginDefinition< TCollections extends ReadonlyArray = ReadonlyArray, > { /** Unique within the app; shown in error messages. */ name: string collections?: TCollections - blockTypes?: ReadonlyArray - fieldTypes?: ReadonlyArray - ops?: ReadonlyArray - /** Durable async event handlers contributed by the plugin. */ - eventHandlers?: ReadonlyArray adminNav?: ReadonlyArray /** * Route nodes from `@tanstack/virtual-file-routes` (`route()`, @@ -388,10 +386,79 @@ export interface CmsPlugin< * when `admin.basePath` is `/admin`. */ adminRoutes?: ReadonlyArray +} + +/** The runtime part of a plugin: what runs on the server or renders. */ +export interface CmsPluginRuntime { + blockTypes?: ReadonlyArray + fieldTypes?: ReadonlyArray + ops?: ReadonlyArray + /** Durable async event handlers contributed by the plugin. */ + eventHandlers?: ReadonlyArray /** Called on the server for every content event (see `onCmsEvent`). Errors are ignored. */ onEvent?: (event: CmsEvent) => void } +/** + * A reusable slice of CMS configuration: a plugin definition plus its + * runtime (see `definePlugin`). + */ +export interface CmsPlugin< + TCollections extends ReadonlyArray = ReadonlyArray, +> + extends CmsPluginDefinition, CmsPluginRuntime { + /** The definition `definePlugin` was given; set by `definePlugin`. */ + readonly definition?: CmsPluginDefinition +} + +/** + * A plugin: its definition (`definePluginDefinition`, pure data that + * `cms.definition.ts` lists) and its runtime (ops, event handlers, block and + * field types). Register the definition with `defineCmsDefinition({ plugins })` + * and the plugin with the runtime config's `plugins`; a single + * `defineCms(config)` takes the plugin alone. + * + * ```ts + * export const analytics = definePlugin({ + * definition: analyticsDefinition, + * runtime: { ops: [trackOp], eventHandlers: [rollup] }, + * }) + * ``` + */ +export function definePlugin< + const TCollections extends ReadonlyArray = readonly [], +>(plugin: { + definition: CmsPluginDefinition + runtime?: CmsPluginRuntime +}): CmsPlugin { + const { definition, runtime = {} } = (plugin ?? {}) as Partial + if (typeof definition !== 'object' || definition === null) { + throw new TypeError( + 'definePlugin({ definition, runtime }): move `name`, `collections`, ' + + '`adminNav`, `routes`, and `adminRoutes` into ' + + '`definition: definePluginDefinition({ … })` and the rest into ' + + '`runtime` (`pnpm codemod definition-split` does this).', + ) + } + for (const key of PLUGIN_DEFINITION_KEYS) { + if (Reflect.get(runtime, key) !== undefined) { + throw new TypeError( + `Plugin "${definition.name}": \`${key}\` belongs to the plugin's ` + + 'definition, not its runtime.', + ) + } + } + for (const key of PLUGIN_RUNTIME_KEYS) { + if (Reflect.get(definition, key) !== undefined) { + throw new TypeError( + `Plugin "${definition.name}": \`${key}\` belongs to the plugin's ` + + 'runtime, not its definition.', + ) + } + } + return { ...definition, ...runtime, definition } +} + export interface CmsAdminConfig { /** * URL prefix the admin routes are mounted under (e.g. `/admin`). Must @@ -991,9 +1058,7 @@ function setCurrentCmsConfig( * `createStore`); `defineCms` is a thin convenience layer that constructs one * and registers it as the global. */ -export interface Cms< - TConfigResolved extends ResolvedCmsConfig = ResolvedCmsConfig, -> { +export interface Cms { /** The resolved config (plugins applied, i18n validated). */ readonly config: TConfigResolved /** @@ -1025,7 +1090,7 @@ export interface Cms< */ export function createCms< const TDefinition extends CmsDefinitionConfig, - const TRuntime extends CmsRuntimeConfig, + const TRuntime extends CmsRuntimeConfig, >( definition: CmsDefinition, runtime: TRuntime, @@ -1064,12 +1129,21 @@ export function defineCmsConfig( * * Takes a light definition (`defineCmsDefinition`) and the runtime config * that extends it. The runtime config holds everything the definition doesn't - * (`auth`, `storage`, `ai`, `ops`, `eventHandlers`, `seed`, …) and can't - * repeat `collections`, `admin`, or `plugins`. + * (`auth`, `storage`, `ai`, `ops`, `eventHandlers`, `seed`, …), plus the + * server-bound hooks and access of its collections, keyed by name, and the + * runtime of its plugins: + * + * ```ts + * defineCms(definition, { + * auth, + * collections: { post: { hooks: { afterChange: audit } } }, + * plugins: [analytics], + * }) + * ``` */ export function defineCms< const TDefinition extends CmsDefinitionConfig, - const TRuntime extends CmsRuntimeConfig, + const TRuntime extends CmsRuntimeConfig, >( definition: CmsDefinition, runtime: TRuntime, @@ -1090,19 +1164,53 @@ export function defineCms( type DefinitionKey = (typeof DEFINITION_KEYS)[number] +/** + * The server-bound half of a collection, attached by name in the runtime + * config: hooks, access rules, and a storage adapter that import server + * code, so they can't sit in `cms.definition.ts`. Pure hooks and role lists + * can stay on the collection; a hook, access action, or `storage` set in + * both places throws. + */ +export interface CmsCollectionRuntime { + hooks?: CollectionHooks + access?: CollectionAccess + /** Per-collection storage (see `Collection.storage`). */ + storage?: StorageAdapter +} + +/** The runtime `collections` map for a definition: its collection names to their runtime halves. */ +export type CmsRuntimeCollections< + TDefinition extends CmsDefinitionConfig = CmsDefinitionConfig, +> = { + [ + K in keyof ResolvedDefinitionConfig['collections'] + ]?: CmsCollectionRuntime< + ResolvedDefinitionConfig['collections'][K] extends Collection + ? InferDoc['collections'][K]> + : Doc + > +} + /** * The runtime part of a CMS config, passed next to a definition to - * `defineCms(definition, runtime)`: everything but the keys the definition - * owns (`collections`, `admin`, `plugins`). + * `defineCms(definition, runtime)`: everything the definition doesn't hold. + * `collections` attaches server-bound hooks and access by collection name. + * `plugins` takes `definePlugin` results: each replaces the definition's + * plugin of the same name, and a plugin without collections or routes may + * appear here alone. `admin` stays in the definition. */ -export type CmsRuntimeConfig = Omit & { - [K in DefinitionKey]?: never +export type CmsRuntimeConfig< + TDefinition extends CmsDefinitionConfig = CmsDefinitionConfig, +> = Omit & { + admin?: never + collections?: CmsRuntimeCollections + plugins?: ReadonlyArray } /** The full config `defineCms(definition, runtime)` builds from its two halves. */ export type DefinedCmsConfig< TDefinition extends CmsDefinitionConfig, - TRuntime extends CmsRuntimeConfig, + TRuntime extends object, > = Extract, CmsConfig> /** The single config behind `defineCms(config)` or `defineCms(definition, runtime)`. */ @@ -1126,15 +1234,184 @@ function extendDefinition( '`storage`, `blockTypes`, …) as the second argument.', ) } - for (const key of DEFINITION_KEYS) { - if ((runtime as Record)[key] !== undefined) { + const { + admin, + collections: collectionRuntimes, + plugins: pluginRuntimes, + ...rest + } = runtime as CmsRuntimeConfig & { admin?: unknown } + const where = `${owner}(definition, runtime)` + if (admin !== undefined) { + throw new TypeError( + `${where}: \`admin\` belongs to the definition; set it in ` + + '`defineCmsDefinition`, not the runtime config.', + ) + } + const plugins = withPluginRuntimes( + input.config.plugins ?? [], + pluginRuntimes, + where, + ) + const { collections, plugins: withRuntimes } = withCollectionRuntimes( + input.config.collections, + plugins, + collectionRuntimes, + where, + ) + return { + ...rest, + ...input.config, + collections, + ...(input.config.plugins || pluginRuntimes + ? { plugins: withRuntimes } + : {}), + } as CmsConfig +} + +/** The definition's plugins, each replaced by its runtime plugin when given. */ +function withPluginRuntimes( + definitions: ReadonlyArray, + runtimes: unknown, + where: string, +): Array { + if (runtimes === undefined) return [...definitions] + if (!Array.isArray(runtimes)) { + throw new TypeError( + `${where}: \`plugins\` must be an array of \`definePlugin\` results.`, + ) + } + const byName = new Map() + const runtimeOnly: Array = [] + for (const plugin of runtimes as ReadonlyArray) { + const name = plugin?.name + if (byName.has(name) || runtimeOnly.some((p) => p.name === name)) { + throw new Error(`Plugin "${name}" is registered twice.`) + } + const declared = definitions.find((d) => d.name === name) + if (!declared) { + // Routing reads only collections and routes, so a plugin without them + // needs no definition entry. + if ( + plugin.collections?.length || + plugin.routes?.length || + plugin.adminRoutes?.length + ) { + throw new Error( + `${where}: plugin "${name}" has collections or routes but is not ` + + 'in the definition; add its definition to ' + + '`defineCmsDefinition({ plugins })`.', + ) + } + runtimeOnly.push(plugin) + continue + } + const own = (p: CmsPluginDefinition) => (p as CmsPlugin).definition ?? p + if (own(plugin) !== own(declared)) { + throw new Error( + `${where}: plugin "${name}" was built from a different definition ` + + 'than the one in `defineCmsDefinition({ plugins })`.', + ) + } + byName.set(name, plugin) + } + return [...definitions.map((d) => byName.get(d.name) ?? d), ...runtimeOnly] +} + +const COLLECTION_RUNTIME_KEYS = ['hooks', 'access', 'storage'] as const + +/** + * Attach the runtime config's `collections` (hooks and access by name) to the + * definition's and its plugins' collections. Untouched collections and + * plugins keep their identity. + */ +function withCollectionRuntimes( + collections: ReadonlyArray, + plugins: Array, + runtimes: unknown, + where: string, +): { collections: ReadonlyArray; plugins: Array } { + if (runtimes === undefined) return { collections, plugins } + if (typeof runtimes !== 'object' || runtimes === null) { + throw new TypeError( + `${where}: \`collections\` must map collection names to ` + + '`{ hooks, access, storage }`.', + ) + } + if (Array.isArray(runtimes)) { + throw new TypeError( + `${where}: the collections themselves belong to the definition; the ` + + "runtime config's `collections` maps a collection name to its " + + 'server-bound `{ hooks, access }`, e.g. `collections: { post: { hooks } }`.', + ) + } + const pending = new Map( + Object.entries(runtimes as Record), + ) + const attach = (collection: Collection): Collection => { + const extra = pending.get(collection.name) + if (extra === undefined) return collection + pending.delete(collection.name) + return attachCollectionRuntime(collection, extra, where) + } + const outCollections = collections.map(attach) + const outPlugins = plugins.map((plugin) => { + if (!plugin.collections?.some((c) => pending.has(c.name))) return plugin + return { ...plugin, collections: plugin.collections.map(attach) } + }) + const [unknown] = pending.keys() + if (unknown !== undefined) { + throw new Error( + `${where}: \`collections.${unknown}\` is not a collection in the definition.`, + ) + } + return { collections: outCollections, plugins: outPlugins } +} + +function attachCollectionRuntime( + collection: Collection, + extra: CmsCollectionRuntime, + where: string, +): Collection { + if (typeof extra !== 'object' || extra === null) { + throw new TypeError( + `${where}: \`collections.${collection.name}\` must be ` + + '`{ hooks, access, storage }`.', + ) + } + for (const key of Object.keys(extra)) { + if (!(COLLECTION_RUNTIME_KEYS as ReadonlyArray).includes(key)) { throw new TypeError( - `${owner}(definition, runtime): \`${key}\` belongs to the ` + - 'definition; set it in `defineCmsDefinition`, not the runtime config.', + `${where}: \`collections.${collection.name}.${key}\` belongs to the ` + + 'definition; only `hooks`, `access`, and `storage` can be attached ' + + 'at runtime.', ) } } - return { ...runtime, ...input.config } as CmsConfig + const out: Collection = { ...collection } + if (extra.storage !== undefined) { + if (collection.storage !== undefined) { + throw new Error( + `${where}: \`collections.${collection.name}.storage\` is already ` + + 'set on the collection in the definition.', + ) + } + out.storage = extra.storage + } + for (const key of ['hooks', 'access'] as const) { + const add = extra[key] as Record | undefined + if (add === undefined) continue + const base = (collection[key] ?? {}) as Record + for (const name of Object.keys(add)) { + if (add[name] !== undefined && base[name] !== undefined) { + throw new Error( + `${where}: \`collections.${collection.name}.${key}.${name}\` is ` + + 'already set on the collection in the definition.', + ) + } + } + Object.assign(out, { [key]: { ...base, ...add } }) + } + return out } /** Normalized admin base path: `''` or `/segment(s)` without a trailing slash. */ diff --git a/packages/core/src/definition.ts b/packages/core/src/definition.ts index 433e3cde..7469916f 100644 --- a/packages/core/src/definition.ts +++ b/packages/core/src/definition.ts @@ -28,12 +28,13 @@ export { defineBlock, defineCollection, defineFieldType, - definePlugin, + definePluginDefinition, isBuiltInFieldType, isSafeRedirectTarget, redirectsCollection, seoField, } from './lib/authoring.ts' +export { defineInterfaceCollection } from './interfaces.ts' export type { AssetMediaKind, Block, @@ -74,4 +75,8 @@ export type { FieldAccess, Permission, } from './lib/access.ts' -export type { CmsAdminConfig, CmsAdminNavItem, CmsPlugin } from './config.ts' +export type { + CmsAdminConfig, + CmsAdminNavItem, + CmsPluginDefinition, +} from './config.ts' diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index cb074103..fb4b99ac 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -23,6 +23,7 @@ export { pluginAdminNav, runWithCmsConfig, } from './config' +export { definePluginDefinition } from './lib/authoring' export type { Cms, CmsConfig, @@ -48,10 +49,14 @@ export type { CmsWebhookEvent, CmsEvent, CmsPlugin, + CmsPluginDefinition, + CmsPluginRuntime, CmsAdminNavItem, WithPlugins, ResolvedCmsConfig, CmsRuntimeConfig, + CmsRuntimeCollections, + CmsCollectionRuntime, DefinedCmsConfig, CollectionsByName, CmsRateLimit, diff --git a/packages/core/src/interfaces.ts b/packages/core/src/interfaces.ts index 318a7695..5f3183b0 100644 --- a/packages/core/src/interfaces.ts +++ b/packages/core/src/interfaces.ts @@ -1,7 +1,7 @@ import { z } from 'zod' -import { defineCollection } from './schema' +import { defineCollection } from './lib/authoring.ts' import type { JsonValue } from './schema' -import { parseCron } from './lib/cron' +import { parseCron } from './lib/cron.ts' import type { EventHandlerContext, EventHandlerDefinition } from './events' export const interfaceScheduleSchema = z diff --git a/packages/core/src/lib/authoring.ts b/packages/core/src/lib/authoring.ts index e7b424ca..2468cb3b 100644 --- a/packages/core/src/lib/authoring.ts +++ b/packages/core/src/lib/authoring.ts @@ -16,7 +16,7 @@ import type { FieldTypeDefinition, } from '../schema' import type { AssetFieldOptions } from '../assets' -import type { CmsPlugin } from '../config' +import type { CmsPluginDefinition } from '../config' /** Type-safe identity helper for a custom field type. */ export function defineFieldType( @@ -226,9 +226,53 @@ export function assetField(options: AssetFieldOptions): Field { } } -/** Type-safe identity helper for a plugin (`defineCms({ plugins })`). */ -export function definePlugin< +/** The keys of a plugin's definition part. */ +export const PLUGIN_DEFINITION_KEYS = [ + 'name', + 'collections', + 'adminNav', + 'routes', + 'adminRoutes', +] as const + +/** The keys of a plugin's runtime part. */ +export const PLUGIN_RUNTIME_KEYS = [ + 'blockTypes', + 'fieldTypes', + 'ops', + 'eventHandlers', + 'onEvent', +] as const + +/** + * The definition part of a plugin: its name, collections, admin nav, and + * routes. Pure data, so it can sit in `cms.definition.ts` + * (`defineCmsDefinition({ plugins })`). Pair it with its ops and event + * handlers in `definePlugin({ definition, runtime })`. + * + * ```ts + * // analytics.definition.ts + * export const analyticsDefinition = definePluginDefinition({ + * name: 'analytics', + * collections: [pageView], + * adminNav: [{ label: 'Analytics', to: '/analytics' }], + * }) + * ``` + */ +export function definePluginDefinition< const TCollections extends ReadonlyArray = readonly [], ->(plugin: CmsPlugin): CmsPlugin { - return plugin +>( + definition: CmsPluginDefinition, +): CmsPluginDefinition { + for (const key of PLUGIN_RUNTIME_KEYS) { + if (Reflect.get(definition, key) !== undefined) { + throw new TypeError( + `definePluginDefinition: \`${key}\` belongs to the plugin's runtime; ` + + 'pass it as `definePlugin({ definition, runtime: { ' + + key + + ' } })`.', + ) + } + } + return definition } diff --git a/packages/core/src/lib/definition.ts b/packages/core/src/lib/definition.ts index 502338be..e1e2c5ae 100644 --- a/packages/core/src/lib/definition.ts +++ b/packages/core/src/lib/definition.ts @@ -14,7 +14,7 @@ * re-exported from `@tanstack/cms-core/definition` (`src/definition.ts`). */ import type { Collection } from '../schema' -import type { CmsAdminConfig, CmsPlugin } from '../config' +import type { CmsAdminConfig, CmsPluginDefinition } from '../config' /** * Every route the CMS UI can mount, by stable key and surface. The one source @@ -44,11 +44,15 @@ export interface CmsDefinitionConfig { collections: ReadonlyArray /** Admin mount point and translations. */ admin?: CmsAdminConfig - /** Plugins; their collections and routes are part of the definition. */ - plugins?: ReadonlyArray + /** + * Plugin definitions (`definePluginDefinition`): their collections, admin + * nav, and routes. The runtime config's `plugins` adds their ops and event + * handlers. + */ + plugins?: ReadonlyArray } -/** The keys a definition owns; a runtime config passed next to it can't repeat them. */ +/** The keys a definition owns. */ export const DEFINITION_KEYS = ['collections', 'admin', 'plugins'] as const /** A collection as routing sees it. */ diff --git a/packages/core/tests/collections-array.test.ts b/packages/core/tests/collections-array.test.ts index 6dc99fab..52d8a68c 100644 --- a/packages/core/tests/collections-array.test.ts +++ b/packages/core/tests/collections-array.test.ts @@ -3,6 +3,7 @@ import { defineCms, defineCollection, definePlugin, + definePluginDefinition, getCmsConfig, runWithCmsConfig, } from '../src/index' @@ -61,7 +62,10 @@ describe('defineCms({ collections: [...] })', () => { collections: [], blockTypes: [], plugins: [ - definePlugin({ name: 'twice', collections: [pageview, pageview] }), + definePluginDefinition({ + name: 'twice', + collections: [pageview, pageview], + }), ], }), ).toThrow('Plugin "twice": collection "pageview" is defined twice.') @@ -72,7 +76,9 @@ describe('defineCms({ collections: [...] })', () => { defineCms({ collections: [post], blockTypes: [], - plugins: [definePlugin({ name: 'clash', collections: [post] })], + plugins: [ + definePluginDefinition({ name: 'clash', collections: [post] }), + ], }), ).toThrow('Plugin "clash": collection "post" is already defined.') }) @@ -132,8 +138,10 @@ describe('collection types', () => { it('types defineCms results by name, including plugin collections', () => { const analytics = definePlugin({ - name: 'analytics', - collections: [pageview], + definition: definePluginDefinition({ + name: 'analytics', + collections: [pageview], + }), }) expectTypeOf(() => { const cms = defineCms({ diff --git a/packages/core/tests/definition.test.ts b/packages/core/tests/definition.test.ts index 3b19283b..b97c85d9 100644 --- a/packages/core/tests/definition.test.ts +++ b/packages/core/tests/definition.test.ts @@ -12,9 +12,16 @@ import { import { CMS_ROUTE_KEYS, defineCmsDefinition, + definePluginDefinition, isCmsDefinition, } from '../src/definition' -import type { CmsConfig, CmsRuntimeConfig } from '../src/index' +import type { + CmsConfig, + Collection, + CmsRuntimeConfig, + ResolvedCmsConfig, +} from '../src/index' +import type { StorageAdapter } from '../src/storage' import type { CmsRouteKey } from '../src/definition' import * as rootEntry from '../src/index' import * as definitionEntry from '../src/definition' @@ -52,7 +59,7 @@ const dashboardRoute = { file: 'analytics.tsx', } -const analytics = definePlugin({ +const analytics = definePluginDefinition({ name: 'analytics', collections: [pageview], routes: [statsRoute], @@ -101,7 +108,9 @@ describe('defineCmsDefinition', () => { expect(() => defineCmsDefinition({ collections: [post], - plugins: [definePlugin({ name: 'clash', collections: [post] })], + plugins: [ + definePluginDefinition({ name: 'clash', collections: [post] }), + ], }), ).toThrow('Plugin "clash": collection "post" is already defined.') expect(() => @@ -140,9 +149,9 @@ describe('the definition entry source', { timeout: 30_000 }, () => { ], }) const d = m.defineCmsDefinition({ - collections: [page, m.redirectsCollection()], + collections: [page, m.redirectsCollection(), m.defineInterfaceCollection()], admin: { basePath: '/cms' }, - plugins: [m.definePlugin({ name: 'p' })], + plugins: [m.definePluginDefinition({ name: 'p' })], }) process.stdout.write([d.adminBasePath(), d.routeKeys().length, d.collections().map((c) => c.name).join()].join(' '))`, ], @@ -150,7 +159,7 @@ describe('the definition entry source', { timeout: 30_000 }, () => { ) expect(child.stderr).toBe('') expect(child.stdout.trim()).toBe( - `/cms ${expectedRouteKeyCount} page,redirect`, + `/cms ${expectedRouteKeyCount} page,redirect,interfaces`, ) }) @@ -160,7 +169,8 @@ describe('the definition entry source', { timeout: 30_000 }, () => { 'defineBlock', 'defineCollection', 'defineFieldType', - 'definePlugin', + 'defineInterfaceCollection', + 'definePluginDefinition', 'isBuiltInFieldType', 'isSafeRedirectTarget', 'redirectsCollection', @@ -208,16 +218,20 @@ describe('defineCms(definition, runtime)', () => { input: z.object({}), run: async () => 'pong', }) - const withOp = definePlugin({ name: 'ops', ops: [op] }) + const opsDefinition = definePluginDefinition({ name: 'ops' }) + const withOp = definePlugin({ + definition: opsDefinition, + runtime: { ops: [op] }, + }) const definition = defineCmsDefinition({ collections: [post], - plugins: [withOp], + plugins: [opsDefinition], }) - defineCms(definition, { blockTypes: [] }) + defineCms(definition, { blockTypes: [], plugins: [withOp] }) expect(getCmsConfig().ops?.map((o) => o.name)).toEqual(['ping']) - expect(() => defineCms(definition, { blockTypes: [], ops: [op] })).toThrow( - 'Plugin "ops": op "ping" is already defined.', - ) + expect(() => + defineCms(definition, { blockTypes: [], plugins: [withOp], ops: [op] }), + ).toThrow('Plugin "ops": op "ping" is already defined.') }) it('validates i18n like the single-argument form', () => { @@ -233,9 +247,9 @@ describe('defineCms(definition, runtime)', () => { it('rejects a runtime config that repeats a definition key', () => { const definition = defineCmsDefinition({ collections: [post] }) expect(() => - // @ts-expect-error `collections` belongs to the definition + // @ts-expect-error the collections themselves belong to the definition defineCms(definition, { blockTypes: [], collections: [author] }), - ).toThrow(/`collections` belongs to the definition/) + ).toThrow(/the collections themselves belong to the definition/) expect(() => // @ts-expect-error `admin` belongs to the definition defineCms(definition, { blockTypes: [], admin: { basePath: '/x' } }), @@ -291,9 +305,224 @@ describe('definition types', () => { }) it('keeps definition keys out of the runtime config', () => { - expectTypeOf().toEqualTypeOf() + expectTypeOf().toEqualTypeOf() expectTypeOf().toEqualTypeOf< CmsConfig['blockTypes'] >() }) }) + +describe('runtime collections: { name: { hooks, access } }', () => { + const audit = async () => {} + const stamp = () => {} + const auditedPost = defineCollection({ + name: 'post', + label: 'Posts', + titleField: 'title', + fields: [{ name: 'title', label: 'Title', type: 'text' }], + hooks: { preValidate: stamp }, + access: { read: ['admin', 'editor'] }, + }) + + it('attaches server-bound hooks and access to the named collection', () => { + const definition = defineCmsDefinition({ collections: [auditedPost] }) + const reportRead = () => true + const cms = defineCms(definition, { + blockTypes: [], + collections: { + post: { + hooks: { afterChange: audit }, + access: { publish: reportRead }, + }, + }, + }) + expect(cms.collections.post.hooks).toEqual({ + preValidate: stamp, + afterChange: audit, + }) + expect(cms.collections.post.access).toEqual({ + read: ['admin', 'editor'], + publish: reportRead, + }) + expect(auditedPost.hooks).toEqual({ preValidate: stamp }) + expect(definition.config.collections[0]).toBe(auditedPost) + }) + + it('reaches plugin collections, leaving untouched plugins as they are', () => { + const other = definePluginDefinition({ name: 'other' }) + const definition = defineCmsDefinition({ + collections: [post], + plugins: [analytics, other], + }) + const cms = defineCms(definition, { + blockTypes: [], + collections: { pageview: { hooks: { afterDelete: audit } } }, + }) + expect(cms.collections.pageview.hooks).toEqual({ afterDelete: audit }) + expect(cms.collections.post).toBe(post) + expect(cms.plugins?.[1]).toBe(other) + expect(pageview.hooks).toBeUndefined() + }) + + it('throws when a hook or access action is set in both places', () => { + const definition = defineCmsDefinition({ collections: [auditedPost] }) + expect(() => + defineCms(definition, { + blockTypes: [], + collections: { post: { hooks: { preValidate: stamp } } }, + }), + ).toThrow( + '`collections.post.hooks.preValidate` is already set on the collection in the definition.', + ) + expect(() => + defineCms(definition, { + blockTypes: [], + collections: { post: { access: { read: ['admin'] } } }, + }), + ).toThrow('`collections.post.access.read` is already set') + }) + + it('throws on an unknown name or a key other than hooks and access', () => { + const definition = defineCmsDefinition({ collections: [post] }) + expect(() => + defineCms(definition, { + blockTypes: [], + // @ts-expect-error not a collection of the definition + collections: { nope: { hooks: {} } }, + }), + ).toThrow('`collections.nope` is not a collection in the definition.') + expect(() => + defineCms(definition, { + blockTypes: [], + // @ts-expect-error only hooks and access are runtime + collections: { post: { fields: [] } }, + }), + ).toThrow('`collections.post.fields` belongs to the definition') + }) + + it('attaches a storage adapter, once', () => { + const storage = { readOnly: true } as unknown as StorageAdapter + const definition = defineCmsDefinition({ collections: [post] }) + const cms = defineCms(definition, { + blockTypes: [], + collections: { post: { storage } }, + }) + expect((cms.collections.post as Collection).storage).toBe(storage) + const stored = defineCmsDefinition({ + collections: [{ ...pageview, storage }], + }) + expect(() => + defineCms(stored, { + blockTypes: [], + collections: { pageview: { storage } }, + }), + ).toThrow('`collections.pageview.storage` is already set') + }) + + it('types hooks against the definition collection', () => { + expectTypeOf(() => { + const definition = defineCmsDefinition({ collections: [post] }) + defineCms(definition, { + blockTypes: [], + collections: { + post: { + hooks: { + preValidate: ({ doc }) => { + expectTypeOf(doc.views).toEqualTypeOf() + expectTypeOf(doc.title).toEqualTypeOf() + }, + }, + }, + }, + }) + }).toBeFunction() + }) +}) + +describe('runtime plugins', () => { + const trackDefinition = definePluginDefinition({ + name: 'track', + collections: [pageview], + }) + const ping = defineOp({ + name: 'trackPing', + access: 'public', + description: 'Ping.', + input: z.object({}), + run: async () => 'pong', + }) + const track = definePlugin({ + definition: trackDefinition, + runtime: { ops: [ping] }, + }) + const opNames = (config: object) => + (config as ResolvedCmsConfig).ops?.map((o) => o.name) + + it('matches each runtime plugin to its definition by name', () => { + const definition = defineCmsDefinition({ + collections: [post], + plugins: [trackDefinition], + }) + const withoutRuntime = createCms(definition, { blockTypes: [] }) + expect(opNames(withoutRuntime.config)).toEqual([]) + const cms = createCms(definition, { blockTypes: [], plugins: [track] }) + expect(opNames(cms.config)).toEqual(['trackPing']) + expect(cms.config.plugins).toEqual([track]) + expect(Object.keys(cms.config.collections)).toEqual([ + 'post', + 'asset', + 'pageview', + ]) + }) + + it('takes a plugin without collections or routes at runtime alone', () => { + const notify = definePlugin({ + definition: definePluginDefinition({ name: 'notify' }), + runtime: { ops: [ping] }, + }) + const definition = defineCmsDefinition({ + collections: [post], + plugins: [trackDefinition], + }) + const cms = createCms(definition, { blockTypes: [], plugins: [notify] }) + expect(cms.config.plugins?.map((p) => p.name)).toEqual(['track', 'notify']) + expect(opNames(cms.config)).toEqual(['trackPing']) + const bare = createCms(defineCmsDefinition({ collections: [post] }), { + blockTypes: [], + plugins: [notify], + }) + expect((bare.config as ResolvedCmsConfig).plugins).toEqual([notify]) + }) + + it('accepts the combined plugin in the definition too', () => { + const definition = defineCmsDefinition({ + collections: [post], + plugins: [track], + }) + const cms = createCms(definition, { blockTypes: [], plugins: [track] }) + expect(opNames(cms.config)).toEqual(['trackPing']) + }) + + it('throws on a runtime plugin the definition lacks or defines differently', () => { + const definition = defineCmsDefinition({ collections: [post] }) + expect(() => + createCms(definition, { blockTypes: [], plugins: [track] }), + ).toThrow( + 'plugin "track" has collections or routes but is not in the definition', + ) + const lookalike = defineCmsDefinition({ + collections: [post], + plugins: [definePluginDefinition({ name: 'track' })], + }) + expect(() => + createCms(lookalike, { blockTypes: [], plugins: [track] }), + ).toThrow('plugin "track" was built from a different definition') + const listed = defineCmsDefinition({ + collections: [post], + plugins: [trackDefinition], + }) + expect(() => + createCms(listed, { blockTypes: [], plugins: [track, track] }), + ).toThrow('Plugin "track" is registered twice.') + }) +}) diff --git a/packages/core/tests/plugins.test.ts b/packages/core/tests/plugins.test.ts index 16db19d8..1c4028d4 100644 --- a/packages/core/tests/plugins.test.ts +++ b/packages/core/tests/plugins.test.ts @@ -9,6 +9,7 @@ import { defineFieldType, defineOp, definePlugin, + definePluginDefinition, fieldTypeDefinitions, getCmsConfig, pluginAdminNav, @@ -39,7 +40,7 @@ const post: Collection = { const events: Array = [] -const analytics = definePlugin({ +const analyticsDefinition = definePluginDefinition({ name: 'analytics', collections: [ { @@ -49,6 +50,10 @@ const analytics = definePlugin({ fields: [{ name: 'path', label: 'Path', type: 'text' }], }, ], + adminNav: [{ label: 'Analytics', to: '/analytics' }], +}) + +const analyticsRuntime = { blockTypes: [ { type: 'chart', @@ -71,8 +76,12 @@ const analytics = definePlugin({ run: async () => [], }), ], - adminNav: [{ label: 'Analytics', to: '/analytics' }], - onEvent: (e) => events.push(e), + onEvent: (e: CmsEvent) => events.push(e), +} + +const analytics = definePlugin({ + definition: analyticsDefinition, + runtime: analyticsRuntime, }) describe('defineCms({ plugins })', () => { @@ -115,7 +124,10 @@ describe('defineCms({ plugins })', () => { blockTypes: [], plugins: [ analytics, - definePlugin({ name: 'other', ops: analytics.ops }), + definePlugin({ + definition: definePluginDefinition({ name: 'other' }), + runtime: { ops: analytics.ops }, + }), ], }), ).toThrow(/op "topPages"/) @@ -145,3 +157,45 @@ describe('defineCms({ plugins })', () => { expect(runWithCmsConfig(raw, () => getCmsConfig())).toBe(seen) }) }) + +describe('definePlugin({ definition, runtime })', () => { + it('flattens both halves and keeps the definition', () => { + expect(analytics.name).toBe('analytics') + expect(analytics.collections).toBe(analyticsDefinition.collections) + expect(analytics.ops).toBe(analyticsRuntime.ops) + expect(analytics.definition).toBe(analyticsDefinition) + expectTypeOf(analytics.collections).toEqualTypeOf( + analyticsDefinition.collections, + ) + }) + + it('takes a definition alone', () => { + const plugin = definePlugin({ definition: analyticsDefinition }) + expect(plugin.ops).toBeUndefined() + expect(plugin.adminNav).toEqual(analyticsDefinition.adminNav) + }) + + it('rejects the flat form and keys on the wrong side', () => { + expect(() => + // @ts-expect-error the flat form was split into definition and runtime + definePlugin({ name: 'flat', ops: [] }), + ).toThrow(/definePlugin\(\{ definition, runtime \}\)/) + expect(() => + definePlugin({ + definition: analyticsDefinition, + // @ts-expect-error collections belong to the definition + runtime: { collections: [] }, + }), + ).toThrow(/`collections` belongs to the plugin's definition/) + expect(() => + definePlugin({ + // @ts-expect-error ops belong to the runtime + definition: { name: 'x', ops: [] }, + }), + ).toThrow(/`ops` belongs to the plugin's runtime/) + expect(() => + // @ts-expect-error ops belong to the runtime + definePluginDefinition({ name: 'x', ops: [] }), + ).toThrow(/definePluginDefinition: `ops` belongs to the plugin's runtime/) + }) +}) diff --git a/packages/core/tests/register-definition/register.ts b/packages/core/tests/register-definition/register.ts index 12ca03a0..46c9010a 100644 --- a/packages/core/tests/register-definition/register.ts +++ b/packages/core/tests/register-definition/register.ts @@ -4,7 +4,11 @@ * program and the other core tests run unregistered. */ import { expectTypeOf } from 'vitest' -import { adminPath, defineCollection, definePlugin } from '../../src/index' +import { + adminPath, + defineCollection, + definePluginDefinition, +} from '../../src/index' import { defineCmsDefinition } from '../../src/definition' import type { RegisteredAdminBasePath, @@ -24,7 +28,7 @@ const post = defineCollection({ ], }) -const analytics = definePlugin({ +const analytics = definePluginDefinition({ name: 'analytics', collections: [ defineCollection({ diff --git a/scripts/__fixtures__/definitions/definition-only/cms.definition.ts b/scripts/__fixtures__/definitions/definition-only/cms.definition.ts index 70c24390..5e65ba49 100644 --- a/scripts/__fixtures__/definitions/definition-only/cms.definition.ts +++ b/scripts/__fixtures__/definitions/definition-only/cms.definition.ts @@ -1,11 +1,11 @@ import { defineCmsDefinition, - definePlugin, + definePluginDefinition, } from '../../../../packages/core/src/definition.ts' import { page, redirect } from './collections.ts' export const definition = defineCmsDefinition({ collections: [page, redirect], admin: { basePath: '/admin' }, - plugins: [definePlugin({ name: 'empty' })], + plugins: [definePluginDefinition({ name: 'empty' })], }) diff --git a/scripts/codemods/__fixtures__/definition-split/already-split/cms.config.input.ts b/scripts/codemods/__fixtures__/definition-split/already-split/cms.config.input.ts new file mode 100644 index 00000000..eea7369f --- /dev/null +++ b/scripts/codemods/__fixtures__/definition-split/already-split/cms.config.input.ts @@ -0,0 +1,4 @@ +import { defineCms } from '@tanstack/cms-core' +import { definition } from './cms.definition' + +export const cms = defineCms(definition, { blockTypes: [] }) diff --git a/scripts/codemods/__fixtures__/definition-split/docs.input.md b/scripts/codemods/__fixtures__/definition-split/docs.input.md new file mode 100644 index 00000000..7e67649b --- /dev/null +++ b/scripts/codemods/__fixtures__/definition-split/docs.input.md @@ -0,0 +1,17 @@ +# Plugins + +```ts +import { definePlugin } from '@tanstack/cms-core' + +export const analytics = definePlugin({ + name: 'analytics', + collections: [pageview], + ops: [topPages], +}) +``` + +Configs in docs aren't split; only `cms.config.*` files are: + +```ts +export const cms = defineCms({ collections: [post], blockTypes: [] }) +``` diff --git a/scripts/codemods/__fixtures__/definition-split/docs.output.md b/scripts/codemods/__fixtures__/definition-split/docs.output.md new file mode 100644 index 00000000..e2ef881e --- /dev/null +++ b/scripts/codemods/__fixtures__/definition-split/docs.output.md @@ -0,0 +1,21 @@ +# Plugins + +```ts +import { definePlugin, definePluginDefinition } from '@tanstack/cms-core' + +export const analytics = definePlugin({ + definition: definePluginDefinition({ + name: 'analytics', + collections: [pageview], + }), + runtime: { + ops: [topPages], + }, +}) +``` + +Configs in docs aren't split; only `cms.config.*` files are: + +```ts +export const cms = defineCms({ collections: [post], blockTypes: [] }) +``` diff --git a/scripts/codemods/__fixtures__/definition-split/function/cms.config.input.ts b/scripts/codemods/__fixtures__/definition-split/function/cms.config.input.ts new file mode 100644 index 00000000..bf6d47b4 --- /dev/null +++ b/scripts/codemods/__fixtures__/definition-split/function/cms.config.input.ts @@ -0,0 +1,22 @@ +import { defineCms, defineCollection } from '@tanstack/cms-core' +import type { CmsConfig } from '@tanstack/cms-core' + +export function registerStarterCms(options: { dataDir?: string } = {}) { + const auth: NonNullable = { + getUser: () => null, + } + + return defineCms({ + ...(options.dataDir ? { dataDir: options.dataDir } : {}), + collections: [ + defineCollection({ + name: 'item', + label: 'Items', + titleField: 'title', + fields: [{ name: 'title', label: 'Title', type: 'text' }], + }), + ], + blockTypes: [], + auth, + }) +} diff --git a/scripts/codemods/__fixtures__/definition-split/function/cms.config.output.ts b/scripts/codemods/__fixtures__/definition-split/function/cms.config.output.ts new file mode 100644 index 00000000..94cd97e4 --- /dev/null +++ b/scripts/codemods/__fixtures__/definition-split/function/cms.config.output.ts @@ -0,0 +1,15 @@ +import { defineCms } from '@tanstack/cms-core' +import type { CmsConfig } from '@tanstack/cms-core' +import { definition } from './cms.definition' + +export function registerStarterCms(options: { dataDir?: string } = {}) { + const auth: NonNullable = { + getUser: () => null, + } + + return defineCms(definition, { + ...(options.dataDir ? { dataDir: options.dataDir } : {}), + blockTypes: [], + auth, + }) +} diff --git a/scripts/codemods/__fixtures__/definition-split/function/cms.definition.created.ts b/scripts/codemods/__fixtures__/definition-split/function/cms.definition.created.ts new file mode 100644 index 00000000..7a265f26 --- /dev/null +++ b/scripts/codemods/__fixtures__/definition-split/function/cms.definition.created.ts @@ -0,0 +1,12 @@ +import { defineCmsDefinition, defineCollection } from '@tanstack/cms-core/definition' + +export const definition = defineCmsDefinition({ + collections: [ + defineCollection({ + name: 'item', + label: 'Items', + titleField: 'title', + fields: [{ name: 'title', label: 'Title', type: 'text' }], + }), + ], +}) diff --git a/scripts/codemods/__fixtures__/definition-split/local/cms.config.input.ts b/scripts/codemods/__fixtures__/definition-split/local/cms.config.input.ts new file mode 100644 index 00000000..9869b3c9 --- /dev/null +++ b/scripts/codemods/__fixtures__/definition-split/local/cms.config.input.ts @@ -0,0 +1,9 @@ +import { defineCms } from '@tanstack/cms-core' +import type { Collection } from '@tanstack/cms-core' + +export function registerTablesCms(options: { tables: Array }) { + return defineCms({ + collections: options.tables, + blockTypes: [], + }) +} diff --git a/scripts/codemods/__fixtures__/definition-split/local/cms.config.warnings.json b/scripts/codemods/__fixtures__/definition-split/local/cms.config.warnings.json new file mode 100644 index 00000000..ddf412a7 --- /dev/null +++ b/scripts/codemods/__fixtures__/definition-split/local/cms.config.warnings.json @@ -0,0 +1,3 @@ +[ + "cms.config.ts:6:18: `options` is local to the code around defineCms, so the definition can't import it; split the config by hand" +] diff --git a/scripts/codemods/__fixtures__/definition-split/plugin.input.ts b/scripts/codemods/__fixtures__/definition-split/plugin.input.ts new file mode 100644 index 00000000..96717e01 --- /dev/null +++ b/scripts/codemods/__fixtures__/definition-split/plugin.input.ts @@ -0,0 +1,26 @@ +import { defineEventHandler, definePlugin } from '@tanstack/cms-core' +import { definePlugin as defineNitroPlugin } from 'nitro' +import { pageview } from './pageview' + +export const analytics = definePlugin({ + name: 'analytics', + collections: [pageview], + adminNav: [{ label: 'Analytics', to: '/analytics' }], + eventHandlers: [ + defineEventHandler({ + id: 'rollup', + on: 'document.published', + run: async () => {}, + }), + ], + onEvent: (event) => console.log(event.id), +}) + +export const pure = definePlugin({ name: 'pure', collections: [pageview] }) + +export const wired = definePlugin({ definition: pure }) + +// @ts-expect-error the flat form is rejected +export const rejected = definePlugin({ name: 'flat' }) + +export default defineNitroPlugin(() => {}) diff --git a/scripts/codemods/__fixtures__/definition-split/plugin.output.ts b/scripts/codemods/__fixtures__/definition-split/plugin.output.ts new file mode 100644 index 00000000..7200acab --- /dev/null +++ b/scripts/codemods/__fixtures__/definition-split/plugin.output.ts @@ -0,0 +1,35 @@ +import { defineEventHandler, definePlugin, definePluginDefinition } from '@tanstack/cms-core' +import { definePlugin as defineNitroPlugin } from 'nitro' +import { pageview } from './pageview' + +export const analytics = definePlugin({ + definition: definePluginDefinition({ + name: 'analytics', + collections: [pageview], + adminNav: [{ label: 'Analytics', to: '/analytics' }], + }), + runtime: { + eventHandlers: [ + defineEventHandler({ + id: 'rollup', + on: 'document.published', + run: async () => {}, + }), + ], + onEvent: (event) => console.log(event.id), + }, +}) + +export const pure = definePlugin({ + definition: definePluginDefinition({ + name: 'pure', + collections: [pageview], + }), +}) + +export const wired = definePlugin({ definition: pure }) + +// @ts-expect-error the flat form is rejected +export const rejected = definePlugin({ name: 'flat' }) + +export default defineNitroPlugin(() => {}) diff --git a/scripts/codemods/__fixtures__/definition-split/root-import/cms.config.input.ts b/scripts/codemods/__fixtures__/definition-split/root-import/cms.config.input.ts new file mode 100644 index 00000000..afaf2821 --- /dev/null +++ b/scripts/codemods/__fixtures__/definition-split/root-import/cms.config.input.ts @@ -0,0 +1,16 @@ +import { defineCms, defineCollection, slugify } from '@tanstack/cms-core' + +export const cms = defineCms({ + collections: [ + defineCollection({ + name: 'post', + label: 'Posts', + titleField: 'title', + fields: [{ name: 'title', label: 'Title', type: 'text' }], + hooks: { + preValidate: ({ doc }) => ({ ...doc, slug: slugify(doc.title) }), + }, + }), + ], + blockTypes: [], +}) diff --git a/scripts/codemods/__fixtures__/definition-split/root-import/cms.config.output.ts b/scripts/codemods/__fixtures__/definition-split/root-import/cms.config.output.ts new file mode 100644 index 00000000..d1d8e1e3 --- /dev/null +++ b/scripts/codemods/__fixtures__/definition-split/root-import/cms.config.output.ts @@ -0,0 +1,6 @@ +import { defineCms } from '@tanstack/cms-core' +import { definition } from './cms.definition' + +export const cms = defineCms(definition, { + blockTypes: [], +}) diff --git a/scripts/codemods/__fixtures__/definition-split/root-import/cms.config.warnings.json b/scripts/codemods/__fixtures__/definition-split/root-import/cms.config.warnings.json new file mode 100644 index 00000000..afbd133a --- /dev/null +++ b/scripts/codemods/__fixtures__/definition-split/root-import/cms.config.warnings.json @@ -0,0 +1,3 @@ +[ + "cms.config.ts:1:39: `slugify` comes from the @tanstack/cms-core root, which cms.definition.ts shouldn't load; move what uses it to the runtime config" +] diff --git a/scripts/codemods/__fixtures__/definition-split/root-import/cms.definition.created.ts b/scripts/codemods/__fixtures__/definition-split/root-import/cms.definition.created.ts new file mode 100644 index 00000000..ebd7f9ab --- /dev/null +++ b/scripts/codemods/__fixtures__/definition-split/root-import/cms.definition.created.ts @@ -0,0 +1,16 @@ +import { defineCmsDefinition, defineCollection } from '@tanstack/cms-core/definition' +import { slugify } from '@tanstack/cms-core' + +export const definition = defineCmsDefinition({ + collections: [ + defineCollection({ + name: 'post', + label: 'Posts', + titleField: 'title', + fields: [{ name: 'title', label: 'Title', type: 'text' }], + hooks: { + preValidate: ({ doc }) => ({ ...doc, slug: slugify(doc.title) }), + }, + }), + ], +}) diff --git a/scripts/codemods/__fixtures__/definition-split/shared/cms.config.input.ts b/scripts/codemods/__fixtures__/definition-split/shared/cms.config.input.ts new file mode 100644 index 00000000..87b6cf64 --- /dev/null +++ b/scripts/codemods/__fixtures__/definition-split/shared/cms.config.input.ts @@ -0,0 +1,17 @@ +import { defineCms, defineCollection } from '@tanstack/cms-core' + +export const ROUTES = { adminBasePath: '/cms-admin' } as const + +const page = defineCollection({ + name: 'page', + label: 'Pages', + titleField: 'title', + fields: [{ name: 'title', label: 'Title', type: 'text' }], +}) + +export const cms = defineCms({ + admin: { basePath: ROUTES.adminBasePath }, + collections: [page], + blockTypes: [], + seed: { documents: { [page.name]: {} } }, +}) diff --git a/scripts/codemods/__fixtures__/definition-split/shared/cms.config.output.ts b/scripts/codemods/__fixtures__/definition-split/shared/cms.config.output.ts new file mode 100644 index 00000000..054dae99 --- /dev/null +++ b/scripts/codemods/__fixtures__/definition-split/shared/cms.config.output.ts @@ -0,0 +1,8 @@ +import { defineCms } from '@tanstack/cms-core' +import { definition, page } from './cms.definition' +export { ROUTES } from './cms.definition' + +export const cms = defineCms(definition, { + blockTypes: [], + seed: { documents: { [page.name]: {} } }, +}) diff --git a/scripts/codemods/__fixtures__/definition-split/shared/cms.definition.created.ts b/scripts/codemods/__fixtures__/definition-split/shared/cms.definition.created.ts new file mode 100644 index 00000000..bfcd9db1 --- /dev/null +++ b/scripts/codemods/__fixtures__/definition-split/shared/cms.definition.created.ts @@ -0,0 +1,15 @@ +import { defineCmsDefinition, defineCollection } from '@tanstack/cms-core/definition' + +export const ROUTES = { adminBasePath: '/cms-admin' } as const + +export const page = defineCollection({ + name: 'page', + label: 'Pages', + titleField: 'title', + fields: [{ name: 'title', label: 'Title', type: 'text' }], +}) + +export const definition = defineCmsDefinition({ + admin: { basePath: ROUTES.adminBasePath }, + collections: [page], +}) diff --git a/scripts/codemods/__fixtures__/definition-split/variable/cms.config.input.ts b/scripts/codemods/__fixtures__/definition-split/variable/cms.config.input.ts new file mode 100644 index 00000000..685a5cc8 --- /dev/null +++ b/scripts/codemods/__fixtures__/definition-split/variable/cms.config.input.ts @@ -0,0 +1,39 @@ +/** The blog's CMS. */ +import { defineBlock, defineCms, defineCollection } from '@tanstack/cms-core' +import { createMockAuth } from '@tanstack/cms-ui-react' +import type { Field, SeedStore } from '@tanstack/cms-core' +import { author } from './collections/author' + +const blockTypes = [ + defineBlock({ type: 'hero', label: 'Hero', fields: [] }), +] + +const titleField: Field = { name: 'title', label: 'Title', type: 'text' } + +/** Posts and their authors. */ +const collections = [ + defineCollection({ + name: 'post', + label: 'Posts', + titleField: 'title', + fields: [titleField], + }), + author, +] + +const seed: SeedStore = { documents: {} } + +export const cms = defineCms({ + // Mounted under /admin. + admin: { basePath: '/admin' }, + collections, + blockTypes, + seed, + auth: createMockAuth(), +}) + +declare module '@tanstack/cms-core' { + interface Register { + cms: typeof cms + } +} diff --git a/scripts/codemods/__fixtures__/definition-split/variable/cms.config.output.ts b/scripts/codemods/__fixtures__/definition-split/variable/cms.config.output.ts new file mode 100644 index 00000000..62ef2fe6 --- /dev/null +++ b/scripts/codemods/__fixtures__/definition-split/variable/cms.config.output.ts @@ -0,0 +1,23 @@ +/** The blog's CMS. */ +import { defineBlock, defineCms } from '@tanstack/cms-core' +import { createMockAuth } from '@tanstack/cms-ui-react' +import type { SeedStore } from '@tanstack/cms-core' +import { definition } from './cms.definition' + +const blockTypes = [ + defineBlock({ type: 'hero', label: 'Hero', fields: [] }), +] + +const seed: SeedStore = { documents: {} } + +export const cms = defineCms(definition, { + blockTypes, + seed, + auth: createMockAuth(), +}) + +declare module '@tanstack/cms-core' { + interface Register { + cms: typeof definition + } +} diff --git a/scripts/codemods/__fixtures__/definition-split/variable/cms.definition.created.ts b/scripts/codemods/__fixtures__/definition-split/variable/cms.definition.created.ts new file mode 100644 index 00000000..1e915b19 --- /dev/null +++ b/scripts/codemods/__fixtures__/definition-split/variable/cms.definition.created.ts @@ -0,0 +1,22 @@ +import { defineCmsDefinition, defineCollection } from '@tanstack/cms-core/definition' +import type { Field } from '@tanstack/cms-core/definition' +import { author } from './collections/author' + +const titleField: Field = { name: 'title', label: 'Title', type: 'text' } + +/** Posts and their authors. */ +const collections = [ + defineCollection({ + name: 'post', + label: 'Posts', + titleField: 'title', + fields: [titleField], + }), + author, +] + +export const definition = defineCmsDefinition({ + // Mounted under /admin. + admin: { basePath: '/admin' }, + collections, +}) diff --git a/scripts/codemods/definition-split.test.ts b/scripts/codemods/definition-split.test.ts new file mode 100644 index 00000000..74751a39 --- /dev/null +++ b/scripts/codemods/definition-split.test.ts @@ -0,0 +1,18 @@ +import { join } from 'node:path' +import { Project } from 'ts-morph' +import { expect, it } from 'vitest' +import * as entry from '../../packages/core/src/definition' +import { DEFINITION_TYPES, DEFINITION_VALUES } from './definition-split' + +it('knows every export of @tanstack/cms-core/definition', () => { + expect([...DEFINITION_VALUES].sort()).toEqual(Object.keys(entry).sort()) + const file = new Project({ + skipAddingFilesFromTsConfig: true, + }).addSourceFileAtPath( + join(import.meta.dirname, '../../packages/core/src/definition.ts'), + ) + const all = [...file.getExportedDeclarations().keys()] + expect([...DEFINITION_TYPES].sort()).toEqual( + all.filter((name) => !DEFINITION_VALUES.has(name)).sort(), + ) +}) diff --git a/scripts/codemods/definition-split.ts b/scripts/codemods/definition-split.ts new file mode 100644 index 00000000..219b3ff3 --- /dev/null +++ b/scripts/codemods/definition-split.ts @@ -0,0 +1,680 @@ +/** + * Split an app's CMS config into a light definition and the runtime config + * that extends it, and plugins into their definition and runtime parts. + * + * - `cms.config.*`: the `defineCms({ … })` call's `collections`, `admin`, and + * `plugins` move to a new `cms.definition.*` beside it, as + * `defineCmsDefinition({ … })`, together with the same-file declarations + * and imports they use (core helpers come from + * `@tanstack/cms-core/definition`). The call becomes + * `defineCms(definition, { …rest })`, and `Register`'s `cms: typeof cms` + * becomes `typeof definition`. + * - Anywhere: a flat `definePlugin({ name, collections, ops, … })` becomes + * `definePlugin({ definition: definePluginDefinition({ name, collections }), + * runtime: { ops } })`. Calls under `@ts-expect-error` are left alone. + * + * It doesn't follow imports: a collection module that imports server code + * still fails `pnpm test:definitions`, and its server-bound hooks and access + * move to the runtime config's `collections: { name: { hooks, access } }` by + * hand. Code it can't move safely (a definition key that reads a local of the + * function around `defineCms`, a spread argument) is reported instead. + */ +import { basename, dirname, join } from 'node:path' +import { Node, SyntaxKind } from 'ts-morph' +import { applyEdits } from './lib/harness' +import type { + CallExpression, + Identifier, + ImportDeclaration, + ObjectLiteralElementLike, + SourceFile, + Statement, + Symbol as MorphSymbol, +} from 'ts-morph' +import type { Codemod, CodemodContext, TextEdit } from './lib/harness' + +const CORE = '@tanstack/cms-core' +const DEFINITION_ENTRY = '@tanstack/cms-core/definition' + +/** Values `@tanstack/cms-core/definition` exports (kept in sync by a test). */ +export const DEFINITION_VALUES: ReadonlySet = new Set([ + 'CMS_ROUTE_KEYS', + 'assetField', + 'defineBlock', + 'defineCmsDefinition', + 'defineCollection', + 'defineFieldType', + 'defineInterfaceCollection', + 'definePluginDefinition', + 'isBuiltInFieldType', + 'isCmsDefinition', + 'isSafeRedirectTarget', + 'redirectsCollection', + 'seoField', +]) + +/** Types `@tanstack/cms-core/definition` exports (kept in sync by a test). */ +export const DEFINITION_TYPES: ReadonlySet = new Set([ + 'AccessRule', + 'AccessRuleContext', + 'AssetFieldOptions', + 'AssetMediaKind', + 'Block', + 'BlockType', + 'BuiltInFieldType', + 'ChangeHookArgs', + 'CmsAdminConfig', + 'CmsAdminNavItem', + 'CmsDefinition', + 'CmsDefinitionCollection', + 'CmsDefinitionConfig', + 'CmsPluginDefinition', + 'CmsPluginRoute', + 'CmsRouteKey', + 'CmsRouteSurface', + 'Collection', + 'CollectionAccess', + 'CollectionAction', + 'CollectionAdmin', + 'CollectionHooks', + 'ContentMigration', + 'CustomFieldTypes', + 'DefineCollectionInput', + 'Doc', + 'Field', + 'FieldAccess', + 'FieldCellProps', + 'FieldCondition', + 'FieldFacet', + 'FieldInputProps', + 'FieldOption', + 'FieldType', + 'FieldTypeDefinition', + 'FieldValidator', + 'FieldValidatorFn', + 'InferBlock', + 'InferDoc', + 'InferDocFromFields', + 'InferFieldValue', + 'JsonValue', + 'Permission', + 'StandardSchemaV1', + 'SystemMetadata', +]) + +const CONFIG_FILE = /^cms\.config\.([cm]?[jt]sx?)$/ +const DEFINITION_KEYS = ['collections', 'admin', 'plugins'] +const PLUGIN_DEFINITION_KEYS = [ + 'name', + 'collections', + 'adminNav', + 'routes', + 'adminRoutes', +] + +/** The core export `id` names, when it's imported from `@tanstack/cms-core`. */ +function coreImportName(id: Node): string | undefined { + if (!Node.isIdentifier(id)) return undefined + for (const decl of id.getSymbol()?.getDeclarations() ?? []) { + if (!Node.isImportSpecifier(decl)) continue + if (decl.getImportDeclaration().getModuleSpecifierValue() !== CORE) continue + return decl.getName() + } + return undefined +} + +function isCoreCall(call: CallExpression, name: string): boolean { + return coreImportName(call.getExpression()) === name +} + +function underTsExpectError(node: Node): boolean { + const text = node.getSourceFile().getFullText() + const lineStart = text.lastIndexOf('\n', node.getStart() - 1) + const prevStart = text.lastIndexOf('\n', lineStart - 1) + return /@ts-(expect-error|ignore)/.test(text.slice(prevStart + 1, lineStart)) +} + +function propName(p: ObjectLiteralElementLike): string | undefined { + if ( + Node.isPropertyAssignment(p) || + Node.isShorthandPropertyAssignment(p) || + Node.isMethodDeclaration(p) + ) { + return p.getName() + } + return undefined +} + +function lineIndent(node: Node): string { + const text = node.getSourceFile().getFullText() + const start = node.getStartLinePos() + return /^[ \t]*/.exec(text.slice(start))![0] +} + +/** `text` (a node starting at `from` indentation) re-indented to `to`. */ +function reindent(text: string, from: string, to: string): string { + return text + .split('\n') + .map((line, i) => { + if (i === 0) return to + line + if (!line.trim()) return '' + return to + (line.startsWith(from) ? line.slice(from.length) : line) + }) + .join('\n') +} + +/** Properties re-indented to `indent`, with the comments above each. */ +function block( + props: ReadonlyArray, + indent: string, +): string { + return props + .map((p) => { + const text = p + .getSourceFile() + .getFullText() + .slice(p.getPos(), p.getEnd()) + .trimStart() + return `${reindent(text, lineIndent(p), indent)},` + }) + .join('\n') +} + +// --- definePlugin({ name, … }) → definePlugin({ definition, runtime }) ----- + +function splitPlugins(file: SourceFile, ctx: CodemodContext): void { + const edits: Array = [] + let importFrom: ImportDeclaration | undefined + for (const call of file.getDescendantsOfKind(SyntaxKind.CallExpression)) { + if (!isCoreCall(call, 'definePlugin') || underTsExpectError(call)) continue + const arg = call.getArguments()[0] + if (!arg) continue + if (!Node.isObjectLiteralExpression(arg)) { + if (!Node.isIdentifier(arg)) { + ctx.warn( + "definePlugin's argument isn't an object literal; split it into { definition, runtime } by hand", + arg, + ) + } + continue + } + if (arg.getProperty('definition')) continue + const props = arg.getProperties() + if (props.some((p) => propName(p) === undefined)) { + ctx.warn( + 'definePlugin spreads an object; split it into { definition, runtime } by hand', + arg, + ) + continue + } + const definition = props.filter((p) => + PLUGIN_DEFINITION_KEYS.includes(propName(p)!), + ) + const runtime = props.filter( + (p) => !PLUGIN_DEFINITION_KEYS.includes(propName(p)!), + ) + const base = lineIndent(call) + const inner = `${base} ` + const parts = [ + `${base} definition: definePluginDefinition({\n${block(definition, inner)}\n${base} }),`, + ] + if (runtime.length) { + parts.push(`${base} runtime: {\n${block(runtime, inner)}\n${base} },`) + } + edits.push({ + start: arg.getStart(), + end: arg.getEnd(), + text: `{\n${parts.join('\n')}\n${base}}`, + }) + importFrom ??= (call.getExpression() as Identifier) + .getSymbol() + ?.getDeclarations() + .find((d) => Node.isImportSpecifier(d)) + ?.getFirstAncestorByKind(SyntaxKind.ImportDeclaration) + } + if (!edits.length) return + if ( + importFrom && + !importFrom + .getNamedImports() + .some((s) => s.getName() === 'definePluginDefinition') + ) { + const named = importFrom.getNamedImports() + const last = named[named.length - 1]! + edits.push({ + start: last.getEnd(), + end: last.getEnd(), + text: ', definePluginDefinition', + }) + } + applyEdits(file, edits) +} + +// --- cms.config.* → cms.definition.* + defineCms(definition, runtime) ------- + +interface ImportUse { + decl: ImportDeclaration + /** Local names this file's moved code uses from `decl`. */ + names: Set +} + +const MOVABLE = new Set([ + SyntaxKind.VariableStatement, + SyntaxKind.FunctionDeclaration, + SyntaxKind.ClassDeclaration, + SyntaxKind.EnumDeclaration, + SyntaxKind.TypeAliasDeclaration, + SyntaxKind.InterfaceDeclaration, +]) + +function topLevel(node: Node): Statement | undefined { + let at: Node | undefined = node + while (at && !Node.isSourceFile(at.getParent())) at = at.getParent() + return at as Statement | undefined +} + +function within(node: Node, outer: Node): boolean { + return node.getStart() >= outer.getPos() && node.getEnd() <= outer.getEnd() +} + +/** The symbol an identifier (or a shorthand property's value) refers to. */ +function referenced(node: Node): MorphSymbol | undefined { + if (Node.isShorthandPropertyAssignment(node)) return node.getValueSymbol() + if (!Node.isIdentifier(node)) return undefined + if (Node.isShorthandPropertyAssignment(node.getParent())) return undefined + return node.getSymbol() +} + +function declaredNames(stmt: Statement): Array { + if (Node.isVariableStatement(stmt)) { + return stmt + .getDeclarations() + .flatMap((d) => + Node.isIdentifier(d.getNameNode()) + ? [d.getNameNode() as Identifier] + : d.getNameNode().getDescendantsOfKind(SyntaxKind.Identifier), + ) + } + const name = ( + stmt as Statement & { getNameNode?: () => Node | undefined } + ).getNameNode?.() + return name && Node.isIdentifier(name) ? [name] : [] +} + +function importLocalNames(decl: ImportDeclaration): Array { + return [ + ...(decl.getDefaultImport() ? [decl.getDefaultImport()!.getText()] : []), + ...(decl.getNamespaceImport() + ? [decl.getNamespaceImport()!.getText()] + : []), + ...decl + .getNamedImports() + .map((s) => s.getAliasNode()?.getText() ?? s.getName()), + ] +} + +interface Style { + quote: string + semi: string +} + +function styleOf(file: SourceFile): Style { + const first = file.getImportDeclarations()[0] + return { + quote: first?.getModuleSpecifier().getText().startsWith('"') ? '"' : "'", + semi: first?.getText().trimEnd().endsWith(';') ? ';' : '', + } +} + +/** An import declaration's text keeping only `keep` (by local name). */ +function printImport( + decl: ImportDeclaration, + keep: (local: string) => boolean, + style: Style, + moduleOverride?: string, +): string | undefined { + const typeOnly = decl.isTypeOnly() + const parts: Array = [] + const def = decl.getDefaultImport()?.getText() + if (def && keep(def)) parts.push(def) + const ns = decl.getNamespaceImport()?.getText() + if (ns && keep(ns)) parts.push(`* as ${ns}`) + const named = decl + .getNamedImports() + .filter((s) => keep(s.getAliasNode()?.getText() ?? s.getName())) + .map((s) => s.getText()) + if (named.length) parts.push(`{ ${named.join(', ')} }`) + if (!parts.length) return undefined + const from = moduleOverride ?? decl.getModuleSpecifierValue() + return `import ${typeOnly ? 'type ' : ''}${parts.join(', ')} from ${style.quote}${from}${style.quote}${style.semi}` +} + +/** Whether a spread could hold `collections`, `admin`, or `plugins`. */ +function mayCarryDefinitionKeys(expr: Node): boolean { + if (Node.isParenthesizedExpression(expr)) { + return mayCarryDefinitionKeys(expr.getExpression()) + } + if (Node.isConditionalExpression(expr)) { + return ( + mayCarryDefinitionKeys(expr.getWhenTrue()) || + mayCarryDefinitionKeys(expr.getWhenFalse()) + ) + } + if (Node.isObjectLiteralExpression(expr)) { + return expr + .getProperties() + .some( + (p) => + DEFINITION_KEYS.includes(propName(p) ?? '') || + (Node.isSpreadAssignment(p) && + mayCarryDefinitionKeys(p.getExpression())), + ) + } + return true +} + +function splitConfig(file: SourceFile, ctx: CodemodContext): void { + const match = CONFIG_FILE.exec(file.getBaseName()) + if (!match) return + const calls = file + .getDescendantsOfKind(SyntaxKind.CallExpression) + .filter((c) => isCoreCall(c, 'defineCms')) + if (!calls.length) return + if (calls.length > 1) { + ctx.warn('more than one defineCms call; split the config by hand', calls[1]) + return + } + const call = calls[0]! + const args = call.getArguments() + if (args.length !== 1) return + const obj = args[0]! + if (!Node.isObjectLiteralExpression(obj)) { + ctx.warn( + "defineCms's argument isn't an object literal; split it into cms.definition.ts by hand", + obj, + ) + return + } + const moved = obj + .getProperties() + .filter((p) => DEFINITION_KEYS.includes(propName(p) ?? '')) + if (!moved.some((p) => propName(p) === 'collections')) { + ctx.warn( + 'defineCms has no `collections` of its own; split the config by hand', + obj, + ) + return + } + if ( + file + .getImportDeclarations() + .some((d) => importLocalNames(d).includes('definition')) || + file + .getStatements() + .some((s) => declaredNames(s).some((n) => n.getText() === 'definition')) + ) { + ctx.warn('the config already declares `definition`; split it by hand', call) + return + } + if ( + obj + .getProperties() + .some( + (p) => + Node.isSpreadAssignment(p) && + mayCarryDefinitionKeys(p.getExpression()), + ) + ) { + ctx.warn( + "defineCms spreads an object; check it doesn't carry collections, admin, or plugins", + obj, + ) + } + + const callStatement = topLevel(call) + const fn = call.getFirstAncestor((n) => Node.isFunctionLikeDeclaration(n)) + const statements = new Set() + const imports = new Map() + let blocked: { name: string; node: Node } | undefined + + const visit = (root: Node, own: Node) => { + const check = (node: Node) => { + const symbol = referenced(node) + if (!symbol) return + for (const decl of symbol.getDeclarations()) { + if (decl.getSourceFile() !== file || within(decl, own)) continue + const importDecl = decl.getFirstAncestorByKind( + SyntaxKind.ImportDeclaration, + ) + if (importDecl) { + const use = imports.get(importDecl) ?? { + decl: importDecl, + names: new Set(), + } + use.names.add(symbol.getName()) + imports.set(importDecl, use) + continue + } + const stmt = topLevel(decl) + if ( + !stmt || + stmt === callStatement || + (fn && within(decl, fn)) || + !MOVABLE.has(stmt.getKind()) + ) { + blocked ??= { name: symbol.getName(), node } + continue + } + if (!statements.has(stmt)) { + statements.add(stmt) + visit(stmt, stmt) + } + } + } + check(root) + root.forEachDescendant(check) + } + for (const p of moved) visit(p, p) + if (blocked) { + ctx.warn( + `\`${blocked.name}\` is local to the code around defineCms, so the definition can't import it; split the config by hand`, + blocked.node, + ) + return + } + + const movedRanges: Array = [...moved, ...statements] + const outside = (node: Node) => !movedRanges.some((r) => within(node, r)) + const usedOutside = (symbol: MorphSymbol | undefined) => + symbol !== undefined && + file + .getDescendants() + .some( + (node) => + (Node.isIdentifier(node) || + Node.isShorthandPropertyAssignment(node)) && + !Node.isImportSpecifier(node.getParent()) && + referenced(node) === symbol && + outside(node), + ) + + const ordered = file.getStatements().filter((s) => statements.has(s)) + const shared: Array = [] + const reexported: Array = [] + const stmtTexts = ordered.map((stmt) => { + const names = declaredNames(stmt) + const exported = Node.isExportable(stmt) && stmt.isExported() + const needed = names.filter((n) => usedOutside(n.getSymbol())) + shared.push(...needed.map((n) => n.getText())) + if (exported) reexported.push(...names.map((n) => n.getText())) + const full = file.getFullText() + const lead = full + .slice(stmt.getPos(), stmt.getStart()) + .replace(/^\s*\n/, '') + const body = full.slice(stmt.getStart(), stmt.getEnd()) + return lead + (needed.length && !exported ? `export ${body}` : body) + }) + + const style = styleOf(file) + const ext = match[1]! + const definitionPath = join( + dirname(file.getFilePath()), + `cms.definition.${ext}`, + ) + const importPath = `./${basename(definitionPath).replace(/\.[cm]?[jt]sx?$/, '')}` + + const definitionImports: Array = [] + const entryValues = new Set(['defineCmsDefinition']) + const entryTypes = new Set() + for (const use of [...imports.values()].sort( + (a, b) => a.decl.getStart() - b.decl.getStart(), + )) { + if (use.decl.getModuleSpecifierValue() !== CORE) { + const text = printImport(use.decl, (l) => use.names.has(l), style) + if (text) definitionImports.push(text) + continue + } + const rootOnly = new Set() + for (const spec of use.decl.getNamedImports()) { + const local = spec.getAliasNode()?.getText() ?? spec.getName() + if (!use.names.has(local)) continue + const name = spec.getName() + const isType = + use.decl.isTypeOnly() || spec.isTypeOnly() || DEFINITION_TYPES.has(name) + if ( + local === name && + (DEFINITION_VALUES.has(name) || DEFINITION_TYPES.has(name)) + ) { + ;(isType ? entryTypes : entryValues).add(local) + continue + } + rootOnly.add(local) + if (!isType) { + ctx.warn( + `\`${spec.getName()}\` comes from the @tanstack/cms-core root, which cms.definition.${ext} shouldn't load; move what uses it to the runtime config`, + spec, + ) + } + } + const text = printImport(use.decl, (l) => rootOnly.has(l), style) + if (text) definitionImports.push(text) + } + const q = style.quote + const entryImports = [ + `import { ${[...entryValues].sort().join(', ')} } from ${q}${DEFINITION_ENTRY}${q}${style.semi}`, + ...(entryTypes.size + ? [ + `import type { ${[...entryTypes].sort().join(', ')} } from ${q}${DEFINITION_ENTRY}${q}${style.semi}`, + ] + : []), + ] + if (moved.some((p) => propName(p) === 'plugins')) { + ctx.warn( + "`plugins` moved to the definition: list each plugin's definition there and pass plugins with ops or event handlers to the runtime config's `plugins`", + moved.find((p) => propName(p) === 'plugins'), + ) + } + + const definitionText = [ + [...entryImports, ...definitionImports].join('\n'), + ...stmtTexts, + `export const definition = defineCmsDefinition({\n${block(moved, ' ')}\n})${style.semi}`, + ].join('\n\n') + if (!ctx.createFile(definitionPath, `${definitionText}\n`)) return + + // The config: drop what moved, import the definition, pass it first. + const edits: Array = [] + const full = file.getFullText() + for (const p of moved) { + const comma = /^\s*,/.exec(full.slice(p.getEnd())) + edits.push({ + start: p.getPos(), + end: p.getEnd() + (comma ? comma[0].length : 0), + text: '', + }) + } + edits.push({ + start: obj.getStart(), + end: obj.getStart(), + text: 'definition, ', + }) + for (const stmt of ordered) { + edits.push({ start: stmt.getPos(), end: stmt.getEnd(), text: '' }) + } + for (const use of imports.values()) { + const locals = importLocalNames(use.decl) + const keep = new Set( + locals.filter((l) => { + if (!use.names.has(l)) return true + const spec = use.decl + .getNamedImports() + .find((s) => (s.getAliasNode()?.getText() ?? s.getName()) === l) + const id = + spec?.getAliasNode() ?? + spec?.getNameNode() ?? + (use.decl.getDefaultImport()?.getText() === l + ? use.decl.getDefaultImport() + : use.decl.getNamespaceImport()) + return usedOutside(id?.getSymbol()) + }), + ) + if (keep.size === locals.length) continue + const text = printImport(use.decl, (l) => keep.has(l), style) + edits.push( + text + ? { start: use.decl.getStart(), end: use.decl.getEnd(), text } + : { start: use.decl.getPos(), end: use.decl.getEnd(), text: '' }, + ) + } + const fromDefinition = [ + `import { ${['definition', ...shared].join(', ')} } from ${q}${importPath}${q}${style.semi}`, + ...(reexported.length + ? [ + `export { ${reexported.join(', ')} } from ${q}${importPath}${q}${style.semi}`, + ] + : []), + ].join('\n') + const lastImport = file.getImportDeclarations().at(-1) + if (lastImport) { + edits.push({ + start: lastImport.getEnd(), + end: lastImport.getEnd(), + text: `\n${fromDefinition}`, + }) + } else { + edits.push({ start: 0, end: 0, text: `${fromDefinition}\n\n` }) + } + + const cmsVar = call.getParentIfKind(SyntaxKind.VariableDeclaration) + if (cmsVar) { + for (const mod of file.getDescendantsOfKind(SyntaxKind.ModuleDeclaration)) { + if (mod.getName().replace(/['"]/g, '') !== CORE) continue + const register = mod.getInterface('Register') + const type = register?.getProperty('cms')?.getTypeNode() + if ( + type && + Node.isTypeQuery(type) && + type.getExprName().getText() === cmsVar.getName() + ) { + edits.push({ + start: type.getStart(), + end: type.getEnd(), + text: 'typeof definition', + }) + } + } + } + applyEdits(file, edits) +} + +export const definitionSplit: Codemod = { + name: 'definition-split', + description: + 'Move collections, admin, and plugins into cms.definition.ts (defineCmsDefinition) and split definePlugin into { definition, runtime }', + mightApply: (text) => + text.includes('defineCms(') || text.includes('definePlugin('), + transform(file, ctx) { + splitPlugins(file, ctx) + splitConfig(file, ctx) + }, +} diff --git a/scripts/codemods/fixtures.test.ts b/scripts/codemods/fixtures.test.ts index 31fdb8ed..66f33be1 100644 --- a/scripts/codemods/fixtures.test.ts +++ b/scripts/codemods/fixtures.test.ts @@ -7,6 +7,16 @@ * `.md` fixtures run through the Markdown code-block path. A case with no * `.output` file must come through unchanged. An optional * `.warnings.json` lists the expected warnings. + * + * A codemod that keys on the file name or creates files gets one case per + * directory, so the input keeps its real name: + * + * __fixtures__///cms.config.input.ts + * __fixtures__///cms.config.output.ts + * __fixtures__///cms.definition.created.ts + * + * Every file the transform creates must match a `.created.` + * there, and nothing else may be created. */ import { existsSync, readFileSync, readdirSync } from 'node:fs' import { join } from 'node:path' @@ -16,15 +26,41 @@ import { transformMarkdown, transformSource } from './lib/harness' const FIXTURES = join(import.meta.dirname, '__fixtures__') -function casesFor( - name: string, -): Array<{ id: string; input: string; ext: string }> { - const dir = join(FIXTURES, name) - if (!existsSync(dir)) return [] +interface Case { + id: string + dir: string + /** The input's name without `.input.`. */ + base: string + ext: string + input: string + /** One case per directory: created files are checked. */ + own: boolean +} + +const INPUT = /^(.+)\.input\.(\w+)$/ +const CREATED = /^(.+)\.created\.(\w+)$/ + +function casesIn(dir: string, prefix: string, own: boolean): Array { return readdirSync(dir) - .map((f) => /^(.+)\.input\.(\w+)$/.exec(f)) + .map((f) => INPUT.exec(f)) .filter((m): m is RegExpExecArray => m !== null) - .map(([file, id, ext]) => ({ id: id!, ext: ext!, input: join(dir, file!) })) + .map(([file, base, ext]) => ({ + id: prefix + base!, + dir, + base: base!, + ext: ext!, + input: join(dir, file!), + own, + })) +} + +function casesFor(name: string): Array { + const root = join(FIXTURES, name) + if (!existsSync(root)) return [] + const nested = readdirSync(root, { withFileTypes: true }) + .filter((e) => e.isDirectory()) + .flatMap((e) => casesIn(join(root, e.name), `${e.name}/`, true)) + return [...casesIn(root, '', false), ...nested] } it('every registered codemod has fixtures', () => { @@ -32,28 +68,52 @@ it('every registered codemod has fixtures', () => { expect(missing).toEqual([]) }) +it('keeps one case per fixture directory', () => { + for (const name of Object.keys(CODEMODS)) { + const perDir = new Map() + for (const c of casesFor(name).filter((c) => c.own)) { + perDir.set(c.dir, (perDir.get(c.dir) ?? 0) + 1) + } + expect( + [...perDir.values()].every((n) => n === 1), + name, + ).toBe(true) + } +}) + for (const codemod of Object.values(CODEMODS)) { describe(codemod.name, () => { for (const c of casesFor(codemod.name)) { it(c.id, () => { - const dir = join(FIXTURES, codemod.name) const input = readFileSync(c.input, 'utf8') - const outputPath = join(dir, `${c.id}.output.${c.ext}`) + const outputPath = join(c.dir, `${c.base}.output.${c.ext}`) const expected = existsSync(outputPath) ? readFileSync(outputPath, 'utf8') : input - const fileName = `${c.id}.${c.ext}` + const fileName = `${c.base}.${c.ext}` const result = c.ext === 'md' || c.ext === 'mdx' - ? transformMarkdown(codemod, input, fileName) + ? { ...transformMarkdown(codemod, input, fileName), created: {} } : transformSource(codemod, input, fileName) expect(result.text).toBe(expected) - const warningsPath = join(dir, `${c.id}.warnings.json`) + const warningsPath = join(c.dir, `${c.base}.warnings.json`) expect(result.warnings).toEqual( existsSync(warningsPath) ? JSON.parse(readFileSync(warningsPath, 'utf8')) : [], ) + const expectedCreated = c.own + ? Object.fromEntries( + readdirSync(c.dir) + .map((f) => CREATED.exec(f)) + .filter((m): m is RegExpExecArray => m !== null) + .map(([file, name, ext]) => [ + `${name}.${ext}`, + readFileSync(join(c.dir, file!), 'utf8'), + ]), + ) + : {} + expect(result.created).toEqual(expectedCreated) }) } }) diff --git a/scripts/codemods/harness.test.ts b/scripts/codemods/harness.test.ts index b72ff78a..f64e3266 100644 --- a/scripts/codemods/harness.test.ts +++ b/scripts/codemods/harness.test.ts @@ -174,6 +174,44 @@ describe('runCodemod', () => { expect(result.changed).toEqual(['docs/page.md']) }) + const createSibling: Codemod = { + name: 'create-sibling', + description: '', + mightApply: (text) => text.includes('sibling'), + transform(file, ctx) { + ctx.createFile( + join(dirname(file.getFilePath()), 'sibling.ts'), + 'export const sibling = 1\n', + ) + }, + } + + it('writes files a transform creates, and never overwrites one', async () => { + const cwd = repo({ + 'app/a/src/main.ts': '// sibling\n', + 'app/b/src/main.ts': '// sibling\n', + 'app/b/src/sibling.ts': 'keep\n', + }) + const dry = await runCodemod(createSibling, { cwd, dry: true }) + expect(dry.changed).toEqual(['app/a/src/sibling.ts']) + expect(dry.warnings).toEqual([ + 'app/b/src/main.ts: app/b/src/sibling.ts already exists; not overwritten', + ]) + await runCodemod(createSibling, { cwd }) + expect(readFileSync(join(cwd, 'app/a/src/sibling.ts'), 'utf8')).toBe( + 'export const sibling = 1\n', + ) + expect(readFileSync(join(cwd, 'app/b/src/sibling.ts'), 'utf8')).toBe( + 'keep\n', + ) + }) + + it('returns created files from transformSource, relative to the input', () => { + expect( + transformSource(createSibling, '// sibling\n', 'main.ts').created, + ).toEqual({ 'sibling.ts': 'export const sibling = 1\n' }) + }) + it('writes files a transform reaches through an import', async () => { const followImport: Codemod = { name: 'follow-import', diff --git a/scripts/codemods/index.ts b/scripts/codemods/index.ts index b0d976a7..a867dee9 100644 --- a/scripts/codemods/index.ts +++ b/scripts/codemods/index.ts @@ -1,9 +1,11 @@ import { collectionsArray } from './collections-array' +import { definitionSplit } from './definition-split' import { explicitRoles } from './explicit-roles' import type { Codemod } from './lib/harness' /** Every codemod `pnpm codemod ` can run, keyed by name. */ export const CODEMODS: Record = { [collectionsArray.name]: collectionsArray, + [definitionSplit.name]: definitionSplit, [explicitRoles.name]: explicitRoles, } diff --git a/scripts/codemods/lib/harness.ts b/scripts/codemods/lib/harness.ts index 81e138f3..2fe99f9b 100644 --- a/scripts/codemods/lib/harness.ts +++ b/scripts/codemods/lib/harness.ts @@ -1,5 +1,5 @@ -import { readFileSync, writeFileSync } from 'node:fs' -import { extname, isAbsolute, relative, resolve } from 'node:path' +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import { dirname, extname, isAbsolute, relative, resolve } from 'node:path' import { Project, ts } from 'ts-morph' import type { Node, SourceFile } from 'ts-morph' import { SURFACES, listWorkspaceFiles } from '../../lib/workspace-files' @@ -7,6 +7,11 @@ import { SURFACES, listWorkspaceFiles } from '../../lib/workspace-files' export interface CodemodContext { /** Flag something the codemod saw but could not rewrite safely. */ warn: (message: string, node?: Node) => void + /** + * Create a new file at `path` (absolute, usually beside the file being + * transformed). Returns false, with a warning, when it already exists. + */ + createFile: (path: string, text: string) => boolean } export interface Codemod { @@ -87,9 +92,25 @@ function contextFor( file: SourceFile, label: string, warnings: Array, + created: Map, options: { cwd?: string; lineOffset?: number } = {}, ): CodemodContext { return { + createFile: (path, text) => { + const project = file.getProject() + if ( + created.has(path) || + project.getSourceFile(path) || + (options.cwd !== undefined && existsSync(path)) + ) { + const where = options.cwd ? relative(options.cwd, path) : path + warnings.push(`${label}: ${where} already exists; not overwritten`) + return false + } + project.createSourceFile(path, text) + created.set(path, text) + return true + }, warn: (message, node) => { if (!node) { warnings.push(`${label}: ${message}`) @@ -107,21 +128,39 @@ function contextFor( } } +export interface TransformResult { + text: string + warnings: Array + /** Files the transform created, by path relative to the input's directory. */ + created: Record +} + /** Run a codemod over one in-memory source text (tests, Markdown code blocks). */ export function transformSource( codemod: Codemod, text: string, fileName = 'input.tsx', lineOffset = 0, -): { text: string; warnings: Array } { +): TransformResult { const warnings: Array = [] + const created = new Map() if (codemod.mightApply && !codemod.mightApply(text)) { - return { text, warnings } + return { text, warnings, created: {} } } const project = createProject(true) const file = project.createSourceFile(fileName, text, { overwrite: true }) - codemod.transform(file, contextFor(file, fileName, warnings, { lineOffset })) - return { text: file.getFullText(), warnings } + codemod.transform( + file, + contextFor(file, fileName, warnings, created, { lineOffset }), + ) + const dir = dirname(file.getFilePath()) + return { + text: file.getFullText(), + warnings, + created: Object.fromEntries( + [...created].map(([path, body]) => [relative(dir, path), body]), + ), + } } const FENCE = @@ -221,6 +260,7 @@ export async function runCodemod( const changed = new Map() const project = createProject(false) + const created = new Map() const original = new Map() const targets: Array = [] for (const rel of files) { @@ -241,7 +281,7 @@ export async function runCodemod( for (const file of targets) { const rel = relative(cwd, file.getFilePath()) - codemod.transform(file, contextFor(file, rel, warnings, { cwd })) + codemod.transform(file, contextFor(file, rel, warnings, created, { cwd })) } // A transform that follows an import edits a file ts-morph loaded on demand, @@ -254,8 +294,13 @@ export async function runCodemod( } } + for (const [abs, text] of created) changed.set(relative(cwd, abs), text) + if (!options.dry) { - for (const [rel, text] of changed) writeFileSync(resolve(cwd, rel), text) + for (const [rel, text] of changed) { + mkdirSync(dirname(resolve(cwd, rel)), { recursive: true }) + writeFileSync(resolve(cwd, rel), text) + } } return { changed: [...changed.keys()].sort(), warnings } } diff --git a/scripts/dialect-inventory.test.ts b/scripts/dialect-inventory.test.ts index 16ea36ee..90c5c9a7 100644 --- a/scripts/dialect-inventory.test.ts +++ b/scripts/dialect-inventory.test.ts @@ -97,13 +97,20 @@ describe('markers', () => { ).toBe(3) }) - it('count Record-form collections, not CLI option specs', () => { + it('count Record-form collections, not CLI option specs or runtime collections', () => { expect( count( 'collectionsRecord', - "defineCms({ collections: { post } })\nparseArgs({ options: { collections: { type: 'string' } } })", + [ + 'defineCms({ collections: { post } })', + "defineCms({ collections: { post: { name: 'post', fields: [] } } })", + "parseArgs({ options: { collections: { type: 'string' } } })", + 'defineCms(definition, { collections: { post: { hooks } } })', + "defineCms(definition, { collections: { 'my-post': { access } } })", + 'defineCms(definition, {\n collections: {\n post: {\n // why\n storage,\n },\n },\n})', + ].join('\n'), ), - ).toBe(1) + ).toBe(2) }) it('count the field names in the SEO cascade lists', () => { diff --git a/scripts/dialect-inventory.ts b/scripts/dialect-inventory.ts index f95bb324..d9b5fc08 100644 --- a/scripts/dialect-inventory.ts +++ b/scripts/dialect-inventory.ts @@ -82,8 +82,11 @@ export const MARKERS: ReadonlyArray = [ { id: 'collectionsRecord', label: 'Record-form `collections: {`', - // `parseArgs` options (`collections: { type: 'string' }`) aren't configs. - pattern: /\bcollections:\s*\{(?!\s*type:)/g, + // `parseArgs` options (`collections: { type: 'string' }`) aren't configs, + // and the runtime config's `collections: { post: { hooks, access, + // storage } }` attaches to the definition's collections by name. + pattern: + /\bcollections:\s*\{(?!\s*type:)(?![\s,]*[\w$'"-]+\s*:\s*\{(?:\s|\/\/[^\n]*\n)*(?:hooks|access|storage)\b)/g, }, { id: 'uiReactToolsImport', diff --git a/scripts/verify-definitions.test.ts b/scripts/verify-definitions.test.ts index c85a5d45..ca339780 100644 --- a/scripts/verify-definitions.test.ts +++ b/scripts/verify-definitions.test.ts @@ -1,10 +1,20 @@ import { spawnSync } from 'node:child_process' -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { + existsSync, + mkdirSync, + mkdtempSync, + rmSync, + writeFileSync, +} from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join, resolve } from 'node:path' import { pathToFileURL } from 'node:url' import { afterAll, describe, expect, it } from 'vitest' -import { findDefinitions, verifyDefinition } from './verify-definitions' +import { + findDefinitions, + scaffoldGenerated, + verifyDefinition, +} from './verify-definitions' const FIXTURES = 'scripts/__fixtures__/definitions' const fixture = (name: string) => `${FIXTURES}/${name}/cms.definition.ts` @@ -95,6 +105,27 @@ describe('verify-definitions CLI', { timeout: 30_000 }, () => { }) }) +describe('scaffoldGenerated', { timeout: 60_000 }, () => { + it('checks the definitions tanstack-cms init and a code-mode skill write', async () => { + const generated = await scaffoldGenerated() + try { + expect(generated.files.map((g) => g.label)).toEqual([ + 'tanstack-cms init', + 'tanstack-cms skill add forms-lead-capture --target code', + ]) + const results = generated.files.map(({ file }) => verifyDefinition(file)) + for (const result of results) { + expect(result.error).toBeUndefined() + expect(result.violations).toEqual([]) + } + expect(results[0]?.accessors?.collections).toBe('1 collection(s)') + } finally { + generated.dispose() + } + for (const { file } of generated.files) expect(existsSync(file)).toBe(false) + }) +}) + describe('findDefinitions', () => { const root = mkdtempSync(join(tmpdir(), 'verify-definitions-')) afterAll(() => rmSync(root, { recursive: true, force: true })) diff --git a/scripts/verify-definitions.ts b/scripts/verify-definitions.ts index b62f897d..b70a6690 100644 --- a/scripts/verify-definitions.ts +++ b/scripts/verify-definitions.ts @@ -7,15 +7,20 @@ * `@tanstack/cms-ui-react` root, `@tanstack/cms-core/server`, and `*.server.*` * files (see `lib/definition-guard.mjs`). Then it checks that the accessors * (`adminBasePath()`, `collections()`, `pluginRoutes()`, `routeKeys()`) - * return values. + * return values. It also scaffolds what the generators write — the + * `tanstack-cms init` template and a code-mode Integration Skill — and checks + * those definitions the same way. (The migration skills' generated apps are + * the `examples/*-after` apps, which the glob already covers.) * - * pnpm test:definitions report only: print, exit 0 - * pnpm test:definitions --strict exit 1 on any violation + * pnpm test:definitions CI: exit 1 on any violation + * tsx scripts/verify-definitions.ts report only: print, exit 0 + * tsx scripts/verify-definitions.ts --strict exit 1 on any violation * CMS_VERIFY_DEFINITIONS_STRICT=1 pnpm … same as --strict * pnpm test:definitions path/to/cms.definition.ts … check these files only */ import { spawnSync } from 'node:child_process' -import { relative, resolve } from 'node:path' +import { mkdirSync, mkdtempSync, rmSync } from 'node:fs' +import { join, relative, resolve } from 'node:path' import { fileURLToPath } from 'node:url' import { glob } from 'tinyglobby' import { IGNORE } from './lib/workspace-files' @@ -51,6 +56,47 @@ export async function findDefinitions(cwd = ROOT): Promise> { return files.sort() } +/** + * The scratch app lives under `packages/cli` so `@tanstack/cms-core` resolves + * from the generated files the way it does in a real app. + */ +const SCRATCH_PARENT = join(ROOT, 'packages/cli') + +export interface GeneratedDefinitions { + /** Label → repo-relative path of the generated `cms.definition.ts`. */ + files: Array<{ label: string; file: string }> + dispose: () => void +} + +/** Run the generators into scratch apps and return their definitions. */ +export async function scaffoldGenerated(): Promise { + const { init } = await import('../packages/cli/src/commands/init') + const { applySkillToCode } = await import('../packages/cms-skills/src/index') + const scratch = mkdtempSync(join(SCRATCH_PARENT, '.verify-definitions-')) + const quiet = { log: () => {}, error: () => {} } + const app = (name: string) => { + const dir = join(scratch, name) + mkdirSync(join(dir, 'src'), { recursive: true }) + return dir + } + const initApp = app('init') + init({ dir: initApp }, quiet) + const skillApp = app('skill') + await applySkillToCode('forms-lead-capture', skillApp) + const file = (dir: string) => + relative(ROOT, join(dir, 'src/cms.definition.ts')) + return { + files: [ + { label: 'tanstack-cms init', file: file(initApp) }, + { + label: 'tanstack-cms skill add forms-lead-capture --target code', + file: file(skillApp), + }, + ], + dispose: () => rmSync(scratch, { recursive: true, force: true }), + } +} + /** Load one definition in its own Node process and report what it broke. */ export function verifyDefinition(file: string, cwd = ROOT): DefinitionResult { const absolute = resolve(cwd, file) @@ -115,6 +161,16 @@ async function main(): Promise { return } const results = files.map((file) => verifyDefinition(file)) + if (!explicit.length) { + const generated = await scaffoldGenerated() + try { + for (const { label, file } of generated.files) { + results.push({ ...verifyDefinition(file), file: `${label} → ${file}` }) + } + } finally { + generated.dispose() + } + } for (const result of results) console.log(report(result, ROOT)) const bad = results.filter(failed) console.log( diff --git a/starters/admin-only/CMS-INTEGRATION.md b/starters/admin-only/CMS-INTEGRATION.md index 04b00dcd..a76a0c5a 100644 --- a/starters/admin-only/CMS-INTEGRATION.md +++ b/starters/admin-only/CMS-INTEGRATION.md @@ -10,6 +10,7 @@ A schema meant to be run entirely from the canned admin. It defines two related ## Files +- [`starters/admin-only/src/cms.definition.ts`](./src/cms.definition.ts): the collections (`definition`). It imports only `@tanstack/cms-core/definition`, so client code and Vite config can load it. - [`starters/admin-only/src/cms.config.ts`](./src/cms.config.ts): `registerAdminOnlyCms()` and `ADMIN_ONLY_ROUTES_CONFIG`. - [`starters/admin-only/tests/seam.test.ts`](./tests/seam.test.ts): the S1/S2/S3 suite. diff --git a/starters/admin-only/src/cms.config.ts b/starters/admin-only/src/cms.config.ts index 92879824..ee13e2e3 100644 --- a/starters/admin-only/src/cms.config.ts +++ b/starters/admin-only/src/cms.config.ts @@ -1,5 +1,6 @@ -import { defineCms, defineCollection } from '@tanstack/cms-core' +import { defineCms } from '@tanstack/cms-core' import type { CmsConfig } from '@tanstack/cms-core' +import { definition } from './cms.definition' /** * Mode #2 Starter: Admin-only CMS (`admin-only`). @@ -22,50 +23,8 @@ export function registerAdminOnlyCms(options: { dataDir?: string } = {}) { getUser: () => ({ id: 'ops-1', name: 'Ops Editor', role: 'admin' }), } - return defineCms({ + return defineCms(definition, { ...(options.dataDir ? { dataDir: options.dataDir } : {}), - collections: [ - defineCollection({ - name: 'vendor', - label: 'Vendors', - titleField: 'name', - fields: [ - { name: 'name', label: 'Vendor Name', type: 'text', required: true }, - { - name: 'tier', - label: 'Vendor Tier', - type: 'select', - options: ['preferred', 'standard'], - defaultValue: 'standard', - }, - ], - }), - defineCollection({ - name: 'assetRecord', - label: 'Equipment Records', - titleField: 'serialNumber', - fields: [ - { - name: 'serialNumber', - label: 'Serial Number', - type: 'text', - required: true, - }, - { - name: 'vendor', - label: 'Vendor', - type: 'relation', - collection: 'vendor', - }, - { - name: 'active', - label: 'Active', - type: 'boolean', - defaultValue: true, - }, - ], - }), - ], blockTypes: [], auth, }) diff --git a/starters/admin-only/src/cms.definition.ts b/starters/admin-only/src/cms.definition.ts new file mode 100644 index 00000000..a16c297c --- /dev/null +++ b/starters/admin-only/src/cms.definition.ts @@ -0,0 +1,49 @@ +import { + defineCmsDefinition, + defineCollection, +} from '@tanstack/cms-core/definition' + +export const definition = defineCmsDefinition({ + collections: [ + defineCollection({ + name: 'vendor', + label: 'Vendors', + titleField: 'name', + fields: [ + { name: 'name', label: 'Vendor Name', type: 'text', required: true }, + { + name: 'tier', + label: 'Vendor Tier', + type: 'select', + options: ['preferred', 'standard'], + defaultValue: 'standard', + }, + ], + }), + defineCollection({ + name: 'assetRecord', + label: 'Equipment Records', + titleField: 'serialNumber', + fields: [ + { + name: 'serialNumber', + label: 'Serial Number', + type: 'text', + required: true, + }, + { + name: 'vendor', + label: 'Vendor', + type: 'relation', + collection: 'vendor', + }, + { + name: 'active', + label: 'Active', + type: 'boolean', + defaultValue: true, + }, + ], + }), + ], +}) diff --git a/starters/contact-cards/CMS-INTEGRATION.md b/starters/contact-cards/CMS-INTEGRATION.md index 55e41762..7a657427 100644 --- a/starters/contact-cards/CMS-INTEGRATION.md +++ b/starters/contact-cards/CMS-INTEGRATION.md @@ -10,6 +10,7 @@ A bespoke people-and-relationships app on the CMS database. It has custom card, ## Files +- [`starters/contact-cards/src/cms.definition.ts`](./src/cms.definition.ts): the collections (`definition`). It imports only `@tanstack/cms-core/definition`, so client code and Vite config can load it. - [`starters/contact-cards/src/cms.config.ts`](./src/cms.config.ts): `registerContactCardsCms()`, the `askContacts` op, `REVIEW_ONLY_ROUTES_CONFIG`, and `SEED_PEOPLE`. - [`starters/contact-cards/src/views.tsx`](./src/views.tsx): `PersonCardView`, `RelationshipTimelineView`, and `ContactCardsReviewScreen`. - [`starters/contact-cards/tests/seam.test.ts`](./tests/seam.test.ts): the S1/S3/S5/S6 suite, which also checks that `views.tsx` imports only `/primitives`. diff --git a/starters/contact-cards/src/cms.config.ts b/starters/contact-cards/src/cms.config.ts index 516edc81..5b682d99 100644 --- a/starters/contact-cards/src/cms.config.ts +++ b/starters/contact-cards/src/cms.config.ts @@ -1,7 +1,8 @@ import { z } from 'zod' -import { defineCms, defineCollection, defineOp } from '@tanstack/cms-core' +import { defineCms, defineOp } from '@tanstack/cms-core' import { queryDocumentSummaries } from '@tanstack/cms-core/server' import type { CmsConfig } from '@tanstack/cms-core' +import { definition } from './cms.definition' /** * Class #10 Starter: Contact Cards (`contact-cards`). @@ -72,55 +73,11 @@ export function registerContactCardsCms(options: { dataDir?: string } = {}) { }, } - return defineCms({ + return defineCms(definition, { ...(options.dataDir ? { dataDir: options.dataDir } : {}), roles: { 'agent-actor': ['content.read', 'content.write', 'agent.use'], }, - collections: [ - defineCollection({ - name: 'person', - label: 'People', - titleField: 'name', - fields: [ - { name: 'name', label: 'Full Name', type: 'text', required: true }, - { - name: 'whatTheyDo', - label: 'What They Do', - type: 'text', - required: true, - }, - { - name: 'specialty', - label: 'Specialty Facet', - type: 'select', - options: ['compilers', 'systems', 'design', 'product'], - defaultValue: 'systems', - }, - { name: 'organization', label: 'Organization', type: 'text' }, - ], - }), - defineCollection({ - name: 'relationship', - label: 'Relationships & Interactions', - titleField: 'summary', - summaryField: 'summary', - fields: [ - { name: 'summary', label: 'Summary', type: 'text', required: true }, - { - name: 'person', - label: 'Person', - type: 'relation', - collection: 'person', - }, - { - name: 'occurredAt', - label: 'Occurred At', - type: 'date', - }, - ], - }), - ], ops: [ // Read-only `/ask` contract: answers over the data with citations; can never write. defineOp({ diff --git a/starters/contact-cards/src/cms.definition.ts b/starters/contact-cards/src/cms.definition.ts new file mode 100644 index 00000000..1bdce3c5 --- /dev/null +++ b/starters/contact-cards/src/cms.definition.ts @@ -0,0 +1,51 @@ +import { + defineCmsDefinition, + defineCollection, +} from '@tanstack/cms-core/definition' + +export const definition = defineCmsDefinition({ + collections: [ + defineCollection({ + name: 'person', + label: 'People', + titleField: 'name', + fields: [ + { name: 'name', label: 'Full Name', type: 'text', required: true }, + { + name: 'whatTheyDo', + label: 'What They Do', + type: 'text', + required: true, + }, + { + name: 'specialty', + label: 'Specialty Facet', + type: 'select', + options: ['compilers', 'systems', 'design', 'product'], + defaultValue: 'systems', + }, + { name: 'organization', label: 'Organization', type: 'text' }, + ], + }), + defineCollection({ + name: 'relationship', + label: 'Relationships & Interactions', + titleField: 'summary', + summaryField: 'summary', + fields: [ + { name: 'summary', label: 'Summary', type: 'text', required: true }, + { + name: 'person', + label: 'Person', + type: 'relation', + collection: 'person', + }, + { + name: 'occurredAt', + label: 'Occurred At', + type: 'date', + }, + ], + }), + ], +}) diff --git a/starters/directory-listings/CMS-INTEGRATION.md b/starters/directory-listings/CMS-INTEGRATION.md index 260527db..680ba0d2 100644 --- a/starters/directory-listings/CMS-INTEGRATION.md +++ b/starters/directory-listings/CMS-INTEGRATION.md @@ -10,6 +10,7 @@ A moderated directory. Strangers submit listings and claims through public ops, ## Files +- [`starters/directory-listings/src/cms.definition.ts`](./src/cms.definition.ts): the collections (`definition`). It imports only `@tanstack/cms-core/definition`, so client code and Vite config can load it. - [`starters/directory-listings/src/cms.config.ts`](./src/cms.config.ts): `registerDirectoryListingsCms()` and the `submitPublicListing`, `claimListing`, and `searchDirectoryListings` ops. - [`starters/directory-listings/tests/seam.test.ts`](./tests/seam.test.ts): the S3/S4/S6 suite. diff --git a/starters/directory-listings/src/cms.config.ts b/starters/directory-listings/src/cms.config.ts index ba78edaf..4a56d020 100644 --- a/starters/directory-listings/src/cms.config.ts +++ b/starters/directory-listings/src/cms.config.ts @@ -1,16 +1,12 @@ import { z } from 'zod' -import { - CmsError, - defineCms, - defineCollection, - defineOp, -} from '@tanstack/cms-core' +import { CmsError, defineCms, defineOp } from '@tanstack/cms-core' import { queryDocumentSummaries, readDocument, stageWrite, } from '@tanstack/cms-core/server' import type { CmsConfig } from '@tanstack/cms-core' +import { definition } from './cms.definition' export function registerDirectoryListingsCms( options: { dataDir?: string } = {}, @@ -30,43 +26,8 @@ export function registerDirectoryListingsCms( }, } - return defineCms({ + return defineCms(definition, { ...(options.dataDir ? { dataDir: options.dataDir } : {}), - collections: [ - defineCollection({ - name: 'listing', - label: 'Directory Listings', - titleField: 'businessName', - summaryField: 'description', - fields: [ - { - name: 'businessName', - label: 'Business Name', - type: 'text', - required: true, - }, - { - name: 'category', - label: 'Category Facet', - type: 'select', - options: ['bakery', 'plumber', 'clinic', 'roaster'], - defaultValue: 'roaster', - }, - { - name: 'city', - label: 'City / Location', - type: 'text', - required: true, - }, - { - name: 'claimedByEmail', - label: 'Claimed By Email', - type: 'email', - }, - { name: 'description', label: 'Description', type: 'textarea' }, - ], - }), - ], ops: [ defineOp({ name: 'submitPublicListing', diff --git a/starters/directory-listings/src/cms.definition.ts b/starters/directory-listings/src/cms.definition.ts new file mode 100644 index 00000000..dc06a048 --- /dev/null +++ b/starters/directory-listings/src/cms.definition.ts @@ -0,0 +1,42 @@ +import { + defineCmsDefinition, + defineCollection, +} from '@tanstack/cms-core/definition' + +export const definition = defineCmsDefinition({ + collections: [ + defineCollection({ + name: 'listing', + label: 'Directory Listings', + titleField: 'businessName', + summaryField: 'description', + fields: [ + { + name: 'businessName', + label: 'Business Name', + type: 'text', + required: true, + }, + { + name: 'category', + label: 'Category Facet', + type: 'select', + options: ['bakery', 'plumber', 'clinic', 'roaster'], + defaultValue: 'roaster', + }, + { + name: 'city', + label: 'City / Location', + type: 'text', + required: true, + }, + { + name: 'claimedByEmail', + label: 'Claimed By Email', + type: 'email', + }, + { name: 'description', label: 'Description', type: 'textarea' }, + ], + }), + ], +}) diff --git a/starters/documentation-kb/CMS-INTEGRATION.md b/starters/documentation-kb/CMS-INTEGRATION.md index c8ca4698..a7caa99d 100644 --- a/starters/documentation-kb/CMS-INTEGRATION.md +++ b/starters/documentation-kb/CMS-INTEGRATION.md @@ -10,7 +10,8 @@ Two product versions of one small docs set. Version, section, and order are fiel ## Files -- [`starters/documentation-kb/src/cms.config.ts`](./src/cms.config.ts): `registerDocumentationKbCms()`, the schema, and the `getDocsNavTree` and `searchVersionedDocs` ops. +- [`starters/documentation-kb/src/cms.definition.ts`](./src/cms.definition.ts): the collections (`definition`). It imports only `@tanstack/cms-core/definition`, so client code and Vite config can load it. +- [`starters/documentation-kb/src/cms.config.ts`](./src/cms.config.ts): `registerDocumentationKbCms()` and the `getDocsNavTree` and `searchVersionedDocs` ops. - [`starters/documentation-kb/tests/seam.test.ts`](./tests/seam.test.ts): the S2/S6 suite. ## Features used diff --git a/starters/documentation-kb/src/cms.config.ts b/starters/documentation-kb/src/cms.config.ts index e2438ced..67266084 100644 --- a/starters/documentation-kb/src/cms.config.ts +++ b/starters/documentation-kb/src/cms.config.ts @@ -1,68 +1,23 @@ import { z } from 'zod' -import { defineCms, defineCollection, defineOp } from '@tanstack/cms-core' +import { defineCms, defineOp } from '@tanstack/cms-core' import { queryDocumentSummaries, queryDocuments, } from '@tanstack/cms-core/server' import type { CmsConfig } from '@tanstack/cms-core' +import { definition } from './cms.definition' export function registerDocumentationKbCms(options: { dataDir?: string } = {}) { const auth: NonNullable = { getUser: () => ({ id: 'docs-editor', name: 'Docs Editor', role: 'admin' }), } - return defineCms({ + return defineCms(definition, { ...(options.dataDir ? { dataDir: options.dataDir } : {}), theme: { name: 'Acme SDK Docs', variant: 'docs', }, - collections: [ - defineCollection({ - name: 'docPage', - label: 'Documentation Pages', - titleField: 'title', - bodyField: 'body', - path: (doc, id) => - `/docs/${String(doc.version ?? 'v2')}/${String(doc.slug ?? id)}`, - fields: [ - { name: 'title', label: 'Page Title', type: 'text', required: true }, - { name: 'slug', label: 'Slug', type: 'slug', from: 'title' }, - { - name: 'version', - label: 'Product Release Version', - type: 'select', - options: ['v1', 'v2'], - defaultValue: 'v2', - }, - { - name: 'section', - label: 'Sidebar Section', - type: 'select', - options: ['getting-started', 'guides', 'api-reference'], - defaultValue: 'getting-started', - }, - { - name: 'order', - label: 'Sidebar Order', - type: 'number', - defaultValue: 1, - }, - { - name: 'deprecatedInV2', - label: 'Deprecated in v2', - type: 'boolean', - defaultValue: false, - }, - { - name: 'body', - label: 'Markdown Body', - type: 'richtext', - required: true, - }, - ], - }), - ], ops: [ defineOp({ name: 'getDocsNavTree', diff --git a/starters/documentation-kb/src/cms.definition.ts b/starters/documentation-kb/src/cms.definition.ts new file mode 100644 index 00000000..e8593a9b --- /dev/null +++ b/starters/documentation-kb/src/cms.definition.ts @@ -0,0 +1,53 @@ +import { + defineCmsDefinition, + defineCollection, +} from '@tanstack/cms-core/definition' + +export const definition = defineCmsDefinition({ + collections: [ + defineCollection({ + name: 'docPage', + label: 'Documentation Pages', + titleField: 'title', + bodyField: 'body', + path: (doc, id) => + `/docs/${String(doc.version ?? 'v2')}/${String(doc.slug ?? id)}`, + fields: [ + { name: 'title', label: 'Page Title', type: 'text', required: true }, + { name: 'slug', label: 'Slug', type: 'slug', from: 'title' }, + { + name: 'version', + label: 'Product Release Version', + type: 'select', + options: ['v1', 'v2'], + defaultValue: 'v2', + }, + { + name: 'section', + label: 'Sidebar Section', + type: 'select', + options: ['getting-started', 'guides', 'api-reference'], + defaultValue: 'getting-started', + }, + { + name: 'order', + label: 'Sidebar Order', + type: 'number', + defaultValue: 1, + }, + { + name: 'deprecatedInV2', + label: 'Deprecated in v2', + type: 'boolean', + defaultValue: false, + }, + { + name: 'body', + label: 'Markdown Body', + type: 'richtext', + required: true, + }, + ], + }), + ], +}) diff --git a/starters/ecommerce-storefront/CMS-INTEGRATION.md b/starters/ecommerce-storefront/CMS-INTEGRATION.md index fe8d050d..24ba2b7d 100644 --- a/starters/ecommerce-storefront/CMS-INTEGRATION.md +++ b/starters/ecommerce-storefront/CMS-INTEGRATION.md @@ -10,7 +10,8 @@ Native commerce built on CMS collections: products, variants with prices and inv ## Files -- [`starters/ecommerce-storefront/src/cms.config.ts`](./src/cms.config.ts): `registerEcommerceStorefrontCms()`, the schema, the ops, and `PaymentAdapter`/`defaultPaymentAdapter`. +- [`starters/ecommerce-storefront/src/cms.definition.ts`](./src/cms.definition.ts): the collections (`definition`). It imports only `@tanstack/cms-core/definition`, so client code and Vite config can load it. +- [`starters/ecommerce-storefront/src/cms.config.ts`](./src/cms.config.ts): `registerEcommerceStorefrontCms()`, the ops, and `PaymentAdapter`/`defaultPaymentAdapter`. - [`starters/ecommerce-storefront/tests/seam.test.ts`](./tests/seam.test.ts): the S1/S4/S5/S6 suite. ## Features used diff --git a/starters/ecommerce-storefront/src/cms.config.ts b/starters/ecommerce-storefront/src/cms.config.ts index 2d8a55ba..3a5cba8a 100644 --- a/starters/ecommerce-storefront/src/cms.config.ts +++ b/starters/ecommerce-storefront/src/cms.config.ts @@ -1,12 +1,8 @@ import { z } from 'zod' -import { - CmsError, - defineCms, - defineCollection, - defineOp, -} from '@tanstack/cms-core' +import { CmsError, defineCms, defineOp } from '@tanstack/cms-core' import { commitDocument, readDocument } from '@tanstack/cms-core/server' import type { CmsConfig } from '@tanstack/cms-core' +import { definition } from './cms.definition' export interface PaymentAdapter { charge: (input: { @@ -49,111 +45,8 @@ export function registerEcommerceStorefrontCms( }, } - return defineCms({ + return defineCms(definition, { ...(options.dataDir ? { dataDir: options.dataDir } : {}), - collections: [ - defineCollection({ - name: 'product', - label: 'Products', - titleField: 'title', - summaryField: 'description', - fields: [ - { - name: 'title', - label: 'Product Title', - type: 'text', - required: true, - }, - { name: 'slug', label: 'Slug', type: 'slug', from: 'title' }, - { name: 'description', label: 'Description', type: 'textarea' }, - ], - }), - defineCollection({ - name: 'variant', - label: 'Product Variants', - titleField: 'sku', - fields: [ - { name: 'sku', label: 'SKU', type: 'text', required: true }, - { - name: 'product', - label: 'Product', - type: 'relation', - collection: 'product', - }, - { - name: 'priceCents', - label: 'Price (cents)', - type: 'number', - required: true, - }, - { - name: 'currency', - label: 'Currency', - type: 'select', - options: ['USD', 'EUR'], - defaultValue: 'USD', - }, - { - name: 'inventory', - label: 'Inventory Count', - type: 'number', - defaultValue: 0, - }, - ], - }), - defineCollection({ - name: 'cart', - label: 'Persisted Carts', - titleField: 'customerEmail', - fields: [ - { - name: 'customerEmail', - label: 'Customer Email', - type: 'email', - required: true, - }, - { name: 'itemsJson', label: 'Cart Items JSON', type: 'textarea' }, - ], - }), - defineCollection({ - name: 'order', - label: 'Orders', - titleField: 'orderNumber', - fields: [ - { - name: 'orderNumber', - label: 'Order Number', - type: 'text', - required: true, - }, - { - name: 'customerEmail', - label: 'Customer Email', - type: 'email', - required: true, - }, - { - name: 'totalCents', - label: 'Total (cents)', - type: 'number', - required: true, - }, - { - name: 'transactionId', - label: 'Payment Transaction ID', - type: 'text', - required: true, - }, - { - name: 'status', - label: 'Order Status', - type: 'select', - options: ['paid', 'cancelled'], - defaultValue: 'paid', - }, - ], - }), - ], ops: [ defineOp({ name: 'addToCart', diff --git a/starters/ecommerce-storefront/src/cms.definition.ts b/starters/ecommerce-storefront/src/cms.definition.ts new file mode 100644 index 00000000..9aab3772 --- /dev/null +++ b/starters/ecommerce-storefront/src/cms.definition.ts @@ -0,0 +1,110 @@ +import { + defineCmsDefinition, + defineCollection, +} from '@tanstack/cms-core/definition' + +export const definition = defineCmsDefinition({ + collections: [ + defineCollection({ + name: 'product', + label: 'Products', + titleField: 'title', + summaryField: 'description', + fields: [ + { + name: 'title', + label: 'Product Title', + type: 'text', + required: true, + }, + { name: 'slug', label: 'Slug', type: 'slug', from: 'title' }, + { name: 'description', label: 'Description', type: 'textarea' }, + ], + }), + defineCollection({ + name: 'variant', + label: 'Product Variants', + titleField: 'sku', + fields: [ + { name: 'sku', label: 'SKU', type: 'text', required: true }, + { + name: 'product', + label: 'Product', + type: 'relation', + collection: 'product', + }, + { + name: 'priceCents', + label: 'Price (cents)', + type: 'number', + required: true, + }, + { + name: 'currency', + label: 'Currency', + type: 'select', + options: ['USD', 'EUR'], + defaultValue: 'USD', + }, + { + name: 'inventory', + label: 'Inventory Count', + type: 'number', + defaultValue: 0, + }, + ], + }), + defineCollection({ + name: 'cart', + label: 'Persisted Carts', + titleField: 'customerEmail', + fields: [ + { + name: 'customerEmail', + label: 'Customer Email', + type: 'email', + required: true, + }, + { name: 'itemsJson', label: 'Cart Items JSON', type: 'textarea' }, + ], + }), + defineCollection({ + name: 'order', + label: 'Orders', + titleField: 'orderNumber', + fields: [ + { + name: 'orderNumber', + label: 'Order Number', + type: 'text', + required: true, + }, + { + name: 'customerEmail', + label: 'Customer Email', + type: 'email', + required: true, + }, + { + name: 'totalCents', + label: 'Total (cents)', + type: 'number', + required: true, + }, + { + name: 'transactionId', + label: 'Payment Transaction ID', + type: 'text', + required: true, + }, + { + name: 'status', + label: 'Order Status', + type: 'select', + options: ['paid', 'cancelled'], + defaultValue: 'paid', + }, + ], + }), + ], +}) diff --git a/starters/editorial-publication/CMS-INTEGRATION.md b/starters/editorial-publication/CMS-INTEGRATION.md index af803ab7..1f7579ba 100644 --- a/starters/editorial-publication/CMS-INTEGRATION.md +++ b/starters/editorial-publication/CMS-INTEGRATION.md @@ -10,7 +10,8 @@ A multi-author publication with paid tiers. Author submissions are staged for re ## Files -- [`starters/editorial-publication/src/cms.config.ts`](./src/cms.config.ts): `registerEditorialPublicationCms()`, the schema, the `readPublicationIssue` and `sendNewsletterIssue` ops, and the in-memory `sentIssuesOutbox`. +- [`starters/editorial-publication/src/cms.definition.ts`](./src/cms.definition.ts): the collections (`definition`). It imports only `@tanstack/cms-core/definition`, so client code and Vite config can load it. +- [`starters/editorial-publication/src/cms.config.ts`](./src/cms.config.ts): `registerEditorialPublicationCms()`, the `readPublicationIssue` and `sendNewsletterIssue` ops, and the in-memory `sentIssuesOutbox`. - [`starters/editorial-publication/tests/seam.test.ts`](./tests/seam.test.ts): the S1/S3/S4/S6 suite. ## Features used diff --git a/starters/editorial-publication/src/cms.config.ts b/starters/editorial-publication/src/cms.config.ts index b7bcfdd0..14bc5081 100644 --- a/starters/editorial-publication/src/cms.config.ts +++ b/starters/editorial-publication/src/cms.config.ts @@ -1,16 +1,12 @@ import { z } from 'zod' -import { - CmsError, - defineCms, - defineCollection, - defineOp, -} from '@tanstack/cms-core' +import { CmsError, defineCms, defineOp } from '@tanstack/cms-core' import { commitDocument, queryDocuments, readDocument, } from '@tanstack/cms-core/server' import type { CmsConfig } from '@tanstack/cms-core' +import { definition } from './cms.definition' export interface SentEmailIssue { issueId: string @@ -46,60 +42,8 @@ export function registerEditorialPublicationCms( }, } - return defineCms({ + return defineCms(definition, { ...(options.dataDir ? { dataDir: options.dataDir } : {}), - collections: [ - defineCollection({ - name: 'issue', - label: 'Editorial Issues', - titleField: 'title', - bodyField: 'body', - fields: [ - { name: 'title', label: 'Headline', type: 'text', required: true }, - { name: 'authorName', label: 'Author', type: 'text', required: true }, - { - name: 'accessTier', - label: 'Access Tier', - type: 'select', - options: ['free', 'paid'], - defaultValue: 'free', - }, - { name: 'scheduledAt', label: 'Scheduled Publish ISO', type: 'text' }, - { - name: 'body', - label: 'Article Body', - type: 'richtext', - required: true, - }, - { - name: 'emailSent', - label: 'Newsletter Sent', - type: 'boolean', - defaultValue: false, - }, - ], - }), - defineCollection({ - name: 'memberSubscription', - label: 'Member Subscriptions', - titleField: 'email', - fields: [ - { - name: 'email', - label: 'Member Email', - type: 'email', - required: true, - }, - { - name: 'tier', - label: 'Tier', - type: 'select', - options: ['free', 'paid'], - defaultValue: 'free', - }, - ], - }), - ], ops: [ defineOp({ name: 'readPublicationIssue', diff --git a/starters/editorial-publication/src/cms.definition.ts b/starters/editorial-publication/src/cms.definition.ts new file mode 100644 index 00000000..c3e724fc --- /dev/null +++ b/starters/editorial-publication/src/cms.definition.ts @@ -0,0 +1,59 @@ +import { + defineCmsDefinition, + defineCollection, +} from '@tanstack/cms-core/definition' + +export const definition = defineCmsDefinition({ + collections: [ + defineCollection({ + name: 'issue', + label: 'Editorial Issues', + titleField: 'title', + bodyField: 'body', + fields: [ + { name: 'title', label: 'Headline', type: 'text', required: true }, + { name: 'authorName', label: 'Author', type: 'text', required: true }, + { + name: 'accessTier', + label: 'Access Tier', + type: 'select', + options: ['free', 'paid'], + defaultValue: 'free', + }, + { name: 'scheduledAt', label: 'Scheduled Publish ISO', type: 'text' }, + { + name: 'body', + label: 'Article Body', + type: 'richtext', + required: true, + }, + { + name: 'emailSent', + label: 'Newsletter Sent', + type: 'boolean', + defaultValue: false, + }, + ], + }), + defineCollection({ + name: 'memberSubscription', + label: 'Member Subscriptions', + titleField: 'email', + fields: [ + { + name: 'email', + label: 'Member Email', + type: 'email', + required: true, + }, + { + name: 'tier', + label: 'Tier', + type: 'select', + options: ['free', 'paid'], + defaultValue: 'free', + }, + ], + }), + ], +}) diff --git a/starters/existing-app/CMS-INTEGRATION.md b/starters/existing-app/CMS-INTEGRATION.md index 6b3a7651..39bdf609 100644 --- a/starters/existing-app/CMS-INTEGRATION.md +++ b/starters/existing-app/CMS-INTEGRATION.md @@ -10,7 +10,8 @@ This starter shows the CMS added to an existing app without taking it over (seam ## Files -- [`starters/existing-app/src/cms.config.ts`](./src/cms.config.ts): `initHostDatabase()`, `registerExistingAppCms()`, and `HOST_EMBEDDED_CMS_ROUTES`. +- [`starters/existing-app/src/cms.definition.ts`](./src/cms.definition.ts): the collections (`definition`) and `HOST_EMBEDDED_CMS_ROUTES`. It imports only `@tanstack/cms-core/definition`, so client code and Vite config can load it. +- [`starters/existing-app/src/cms.config.ts`](./src/cms.config.ts): `initHostDatabase()` and `registerExistingAppCms()`, and re-exports `HOST_EMBEDDED_CMS_ROUTES`. - [`starters/existing-app/tests/seam.test.ts`](./tests/seam.test.ts): the five S7 gates. - [`starters/existing-app/S7-CHECKLIST.md`](./S7-CHECKLIST.md): the gate list shared with the `tanstack.com` port. diff --git a/starters/existing-app/src/cms.config.ts b/starters/existing-app/src/cms.config.ts index 44e29fbc..fbe53433 100644 --- a/starters/existing-app/src/cms.config.ts +++ b/starters/existing-app/src/cms.config.ts @@ -1,26 +1,9 @@ import { DatabaseSync } from 'node:sqlite' import { join } from 'node:path' -import { defineCms, defineCollection } from '@tanstack/cms-core' +import { defineCms } from '@tanstack/cms-core' import type { CmsConfig } from '@tanstack/cms-core' - -/** - * Class #3 Starter: Existing App Adds CMS Later (`existing-app`). - * - * Proves Seam S7 (the non-colonizing boundary): - * 1. Host application already owns its route tree (`/`, `/dashboard`), its - * session cookie (`host_saas_session`), and its own database tables - * (`host_accounts`). - * 2. CMS mounts its admin under `/cms-admin` (`adminBasePath: '/cms-admin'`) - * with `include: { public: false }` so host routes are never shadowed. - * 3. CMS reuses the host session cookie via `defineCms({ auth })`. - * 4. CMS `redirect` collection preserves legacy URLs during cutover. - */ -export const HOST_EMBEDDED_CMS_ROUTES = { - adminBasePath: '/cms-admin', - include: { - public: false, - }, -} as const +import { definition } from './cms.definition' +export { HOST_EMBEDDED_CMS_ROUTES } from './cms.definition' export function initHostDatabase(dataDir: string) { const dbPath = join(dataDir, 'cms.db') @@ -53,50 +36,8 @@ export function registerExistingAppCms(options: { dataDir: string }) { }, } - return defineCms({ + return defineCms(definition, { dataDir: options.dataDir, - admin: { - basePath: HOST_EMBEDDED_CMS_ROUTES.adminBasePath, - }, - collections: [ - defineCollection({ - name: 'blogPost', - label: 'SaaS Blog Posts', - titleField: 'title', - bodyField: 'body', - fields: [ - { name: 'title', label: 'Title', type: 'text', required: true }, - { name: 'slug', label: 'Slug', type: 'slug', from: 'title' }, - { name: 'body', label: 'Body', type: 'richtext' }, - ], - }), - defineCollection({ - name: 'helpArticle', - label: 'Help Articles', - titleField: 'title', - bodyField: 'body', - fields: [ - { name: 'title', label: 'Title', type: 'text', required: true }, - { name: 'category', label: 'Category', type: 'text' }, - { name: 'body', label: 'Body', type: 'richtext' }, - ], - }), - defineCollection({ - name: 'redirect', - label: 'Cutover Redirects', - titleField: 'from', - fields: [ - { name: 'from', label: 'Old URL Path', type: 'text', required: true }, - { name: 'to', label: 'New URL Path', type: 'text', required: true }, - { - name: 'permanent', - label: 'Permanent (301)', - type: 'boolean', - defaultValue: true, - }, - ], - }), - ], blockTypes: [], auth, }) diff --git a/starters/existing-app/src/cms.definition.ts b/starters/existing-app/src/cms.definition.ts new file mode 100644 index 00000000..c802d530 --- /dev/null +++ b/starters/existing-app/src/cms.definition.ts @@ -0,0 +1,68 @@ +import { + defineCmsDefinition, + defineCollection, +} from '@tanstack/cms-core/definition' + +/** + * Class #3 Starter: Existing App Adds CMS Later (`existing-app`). + * + * Proves Seam S7 (the non-colonizing boundary): + * 1. Host application already owns its route tree (`/`, `/dashboard`), its + * session cookie (`host_saas_session`), and its own database tables + * (`host_accounts`). + * 2. CMS mounts its admin under `/cms-admin` (`adminBasePath: '/cms-admin'`) + * with `include: { public: false }` so host routes are never shadowed. + * 3. CMS reuses the host session cookie via `defineCms({ auth })`. + * 4. CMS `redirect` collection preserves legacy URLs during cutover. + */ +export const HOST_EMBEDDED_CMS_ROUTES = { + adminBasePath: '/cms-admin', + include: { + public: false, + }, +} as const + +export const definition = defineCmsDefinition({ + admin: { + basePath: HOST_EMBEDDED_CMS_ROUTES.adminBasePath, + }, + collections: [ + defineCollection({ + name: 'blogPost', + label: 'SaaS Blog Posts', + titleField: 'title', + bodyField: 'body', + fields: [ + { name: 'title', label: 'Title', type: 'text', required: true }, + { name: 'slug', label: 'Slug', type: 'slug', from: 'title' }, + { name: 'body', label: 'Body', type: 'richtext' }, + ], + }), + defineCollection({ + name: 'helpArticle', + label: 'Help Articles', + titleField: 'title', + bodyField: 'body', + fields: [ + { name: 'title', label: 'Title', type: 'text', required: true }, + { name: 'category', label: 'Category', type: 'text' }, + { name: 'body', label: 'Body', type: 'richtext' }, + ], + }), + defineCollection({ + name: 'redirect', + label: 'Cutover Redirects', + titleField: 'from', + fields: [ + { name: 'from', label: 'Old URL Path', type: 'text', required: true }, + { name: 'to', label: 'New URL Path', type: 'text', required: true }, + { + name: 'permanent', + label: 'Permanent (301)', + type: 'boolean', + defaultValue: true, + }, + ], + }), + ], +}) diff --git a/starters/headless-api/CMS-INTEGRATION.md b/starters/headless-api/CMS-INTEGRATION.md index e85e0589..914f5289 100644 --- a/starters/headless-api/CMS-INTEGRATION.md +++ b/starters/headless-api/CMS-INTEGRATION.md @@ -10,7 +10,8 @@ A backend-only package. It registers one schema and serves it through `createCms ## Files -- [`starters/headless-api/src/cms.config.ts`](./src/cms.config.ts): `registerHeadlessCms()`, the schema, and a bootstrap `auth.getUser`. +- [`starters/headless-api/src/cms.definition.ts`](./src/cms.definition.ts): the collections (`definition`). It imports only `@tanstack/cms-core/definition`, so client code and Vite config can load it. +- [`starters/headless-api/src/cms.config.ts`](./src/cms.config.ts): `registerHeadlessCms()` and a bootstrap `auth.getUser`. - [`starters/headless-api/src/server.ts`](./src/server.ts): `createHeadlessHandler()` wraps `createCmsApiHandler()` in `node:http`. It is the only starter whose `dev` script starts a server (port `3031`). - [`starters/headless-api/tests/contract.test.ts`](./tests/contract.test.ts): the S3/S5 contract suite. diff --git a/starters/headless-api/src/cms.config.ts b/starters/headless-api/src/cms.config.ts index 4382bdfa..48e2e65e 100644 --- a/starters/headless-api/src/cms.config.ts +++ b/starters/headless-api/src/cms.config.ts @@ -1,5 +1,6 @@ -import { defineCms, defineCollection } from '@tanstack/cms-core' +import { defineCms } from '@tanstack/cms-core' import type { CmsConfig } from '@tanstack/cms-core' +import { definition } from './cms.definition' export function registerHeadlessCms(options: { dataDir?: string } = {}) { const auth: NonNullable = { @@ -12,34 +13,8 @@ export function registerHeadlessCms(options: { dataDir?: string } = {}) { }, } - return defineCms({ + return defineCms(definition, { ...(options.dataDir ? { dataDir: options.dataDir } : {}), - collections: [ - defineCollection({ - name: 'contentItem', - label: 'Content Items', - titleField: 'title', - bodyField: 'body', - fields: [ - { name: 'title', label: 'Title', type: 'text', required: true }, - { name: 'slug', label: 'Slug', type: 'slug', from: 'title' }, - { - name: 'channel', - label: 'Channel', - type: 'select', - options: ['web', 'ios', 'android', 'agent'], - defaultValue: 'web', - }, - { - name: 'priority', - label: 'Priority', - type: 'number', - defaultValue: 1, - }, - { name: 'body', label: 'Body', type: 'richtext' }, - ], - }), - ], blockTypes: [], auth, }) diff --git a/starters/headless-api/src/cms.definition.ts b/starters/headless-api/src/cms.definition.ts new file mode 100644 index 00000000..f773cbce --- /dev/null +++ b/starters/headless-api/src/cms.definition.ts @@ -0,0 +1,33 @@ +import { + defineCmsDefinition, + defineCollection, +} from '@tanstack/cms-core/definition' + +export const definition = defineCmsDefinition({ + collections: [ + defineCollection({ + name: 'contentItem', + label: 'Content Items', + titleField: 'title', + bodyField: 'body', + fields: [ + { name: 'title', label: 'Title', type: 'text', required: true }, + { name: 'slug', label: 'Slug', type: 'slug', from: 'title' }, + { + name: 'channel', + label: 'Channel', + type: 'select', + options: ['web', 'ios', 'android', 'agent'], + defaultValue: 'web', + }, + { + name: 'priority', + label: 'Priority', + type: 'number', + defaultValue: 1, + }, + { name: 'body', label: 'Body', type: 'richtext' }, + ], + }), + ], +}) diff --git a/starters/membership-course/CMS-INTEGRATION.md b/starters/membership-course/CMS-INTEGRATION.md index 01e023b9..10b1b7c5 100644 --- a/starters/membership-course/CMS-INTEGRATION.md +++ b/starters/membership-course/CMS-INTEGRATION.md @@ -10,6 +10,7 @@ One course with ordered lessons and a per-member progress state machine. A singl ## Files +- [`starters/membership-course/src/cms.definition.ts`](./src/cms.definition.ts): the collections (`definition`). It imports only `@tanstack/cms-core/definition`, so client code and Vite config can load it. - [`starters/membership-course/src/cms.config.ts`](./src/cms.config.ts): `registerMembershipCourseCms()` and `completeLessonAndQuiz`. - [`starters/membership-course/tests/seam.test.ts`](./tests/seam.test.ts): the S4/S6 suite. diff --git a/starters/membership-course/src/cms.config.ts b/starters/membership-course/src/cms.config.ts index 12f74963..7fd5751b 100644 --- a/starters/membership-course/src/cms.config.ts +++ b/starters/membership-course/src/cms.config.ts @@ -1,16 +1,12 @@ import { z } from 'zod' -import { - CmsError, - defineCms, - defineCollection, - defineOp, -} from '@tanstack/cms-core' +import { CmsError, defineCms, defineOp } from '@tanstack/cms-core' import { commitDocument, queryDocuments, readDocument, } from '@tanstack/cms-core/server' import type { CmsConfig } from '@tanstack/cms-core' +import { definition } from './cms.definition' export function registerMembershipCourseCms( options: { dataDir?: string } = {}, @@ -30,73 +26,8 @@ export function registerMembershipCourseCms( }, } - return defineCms({ + return defineCms(definition, { ...(options.dataDir ? { dataDir: options.dataDir } : {}), - collections: [ - defineCollection({ - name: 'lesson', - label: 'Course Lessons', - titleField: 'title', - bodyField: 'body', - fields: [ - { - name: 'title', - label: 'Lesson Title', - type: 'text', - required: true, - }, - { - name: 'order', - label: 'Lesson Number', - type: 'number', - required: true, - }, - { - name: 'dripDayOffset', - label: 'Drip Unlock Day Offset', - type: 'number', - defaultValue: 0, - }, - { - name: 'quizAnswer', - label: 'Required Quiz Answer', - type: 'text', - }, - { name: 'body', label: 'Lesson Content', type: 'richtext' }, - ], - }), - defineCollection({ - name: 'enrolment', - label: 'Member Course Enrolments', - titleField: 'memberEmail', - fields: [ - { - name: 'memberEmail', - label: 'Member Email', - type: 'email', - required: true, - }, - { - name: 'daysSinceEnrolment', - label: 'Days Since Enrolment', - type: 'number', - defaultValue: 0, - }, - { - name: 'completedLessonIdsJson', - label: 'Completed Lesson IDs JSON', - type: 'textarea', - defaultValue: '[]', - }, - { - name: 'certificateIssued', - label: 'Certificate Issued', - type: 'boolean', - defaultValue: false, - }, - ], - }), - ], ops: [ defineOp({ name: 'completeLessonAndQuiz', diff --git a/starters/membership-course/src/cms.definition.ts b/starters/membership-course/src/cms.definition.ts new file mode 100644 index 00000000..3954e8d8 --- /dev/null +++ b/starters/membership-course/src/cms.definition.ts @@ -0,0 +1,72 @@ +import { + defineCmsDefinition, + defineCollection, +} from '@tanstack/cms-core/definition' + +export const definition = defineCmsDefinition({ + collections: [ + defineCollection({ + name: 'lesson', + label: 'Course Lessons', + titleField: 'title', + bodyField: 'body', + fields: [ + { + name: 'title', + label: 'Lesson Title', + type: 'text', + required: true, + }, + { + name: 'order', + label: 'Lesson Number', + type: 'number', + required: true, + }, + { + name: 'dripDayOffset', + label: 'Drip Unlock Day Offset', + type: 'number', + defaultValue: 0, + }, + { + name: 'quizAnswer', + label: 'Required Quiz Answer', + type: 'text', + }, + { name: 'body', label: 'Lesson Content', type: 'richtext' }, + ], + }), + defineCollection({ + name: 'enrolment', + label: 'Member Course Enrolments', + titleField: 'memberEmail', + fields: [ + { + name: 'memberEmail', + label: 'Member Email', + type: 'email', + required: true, + }, + { + name: 'daysSinceEnrolment', + label: 'Days Since Enrolment', + type: 'number', + defaultValue: 0, + }, + { + name: 'completedLessonIdsJson', + label: 'Completed Lesson IDs JSON', + type: 'textarea', + defaultValue: '[]', + }, + { + name: 'certificateIssued', + label: 'Certificate Issued', + type: 'boolean', + defaultValue: false, + }, + ], + }), + ], +}) diff --git a/starters/multi-tenant-fleet/CMS-INTEGRATION.md b/starters/multi-tenant-fleet/CMS-INTEGRATION.md index fdea59c3..3b6e959e 100644 --- a/starters/multi-tenant-fleet/CMS-INTEGRATION.md +++ b/starters/multi-tenant-fleet/CMS-INTEGRATION.md @@ -10,6 +10,7 @@ Many tenant sites run on one instance. Every document carries a `tenantId` field ## Files +- [`starters/multi-tenant-fleet/src/cms.definition.ts`](./src/cms.definition.ts): the collections (`definition`). It imports only `@tanstack/cms-core/definition`, so client code and Vite config can load it. - [`starters/multi-tenant-fleet/src/cms.config.ts`](./src/cms.config.ts): `resolveTenantActor()`, `effectiveTenantId()`, `registerMultiTenantFleetCms()`, the ops, and the in-memory `crossTenantAuditLog`. - [`starters/multi-tenant-fleet/tests/seam.test.ts`](./tests/seam.test.ts): the S4/S8 leak suite. diff --git a/starters/multi-tenant-fleet/src/cms.config.ts b/starters/multi-tenant-fleet/src/cms.config.ts index 9a238951..fc1f6936 100644 --- a/starters/multi-tenant-fleet/src/cms.config.ts +++ b/starters/multi-tenant-fleet/src/cms.config.ts @@ -1,10 +1,5 @@ import { z } from 'zod' -import { - CmsError, - defineCms, - defineCollection, - defineOp, -} from '@tanstack/cms-core' +import { CmsError, defineCms, defineOp } from '@tanstack/cms-core' import { commitDocument, queryDocumentSummaries, @@ -12,6 +7,7 @@ import { readDocument, } from '@tanstack/cms-core/server' import type { CmsConfig } from '@tanstack/cms-core' +import { definition } from './cms.definition' export interface TenantActor { actorId: string @@ -98,57 +94,8 @@ export function registerMultiTenantFleetCms( }, } - return defineCms({ + return defineCms(definition, { ...(options.dataDir ? { dataDir: options.dataDir } : {}), - collections: [ - defineCollection({ - name: 'tenantSite', - label: 'Tenant Sites', - titleField: 'domain', - fields: [ - { - name: 'tenantId', - label: 'Tenant ID', - type: 'text', - required: true, - }, - { name: 'domain', label: 'Domain', type: 'text', required: true }, - { name: 'theme', label: 'Theme', type: 'text', required: true }, - ], - }), - defineCollection({ - name: 'tenantPage', - label: 'Tenant Pages', - titleField: 'title', - bodyField: 'body', - fields: [ - { - name: 'tenantId', - label: 'Tenant ID', - type: 'text', - required: true, - }, - { name: 'title', label: 'Page Title', type: 'text', required: true }, - { name: 'slug', label: 'Slug', type: 'text', required: true }, - { name: 'body', label: 'Body', type: 'richtext' }, - ], - }), - defineCollection({ - name: 'tenantAsset', - label: 'Tenant Media Assets', - titleField: 'filename', - fields: [ - { - name: 'tenantId', - label: 'Tenant ID', - type: 'text', - required: true, - }, - { name: 'filename', label: 'Filename', type: 'text', required: true }, - { name: 'url', label: 'Asset URL', type: 'url', required: true }, - ], - }), - ], ops: [ defineOp({ name: 'provisionTenantFromTemplate', diff --git a/starters/multi-tenant-fleet/src/cms.definition.ts b/starters/multi-tenant-fleet/src/cms.definition.ts new file mode 100644 index 00000000..7c2ea812 --- /dev/null +++ b/starters/multi-tenant-fleet/src/cms.definition.ts @@ -0,0 +1,56 @@ +import { + defineCmsDefinition, + defineCollection, +} from '@tanstack/cms-core/definition' + +export const definition = defineCmsDefinition({ + collections: [ + defineCollection({ + name: 'tenantSite', + label: 'Tenant Sites', + titleField: 'domain', + fields: [ + { + name: 'tenantId', + label: 'Tenant ID', + type: 'text', + required: true, + }, + { name: 'domain', label: 'Domain', type: 'text', required: true }, + { name: 'theme', label: 'Theme', type: 'text', required: true }, + ], + }), + defineCollection({ + name: 'tenantPage', + label: 'Tenant Pages', + titleField: 'title', + bodyField: 'body', + fields: [ + { + name: 'tenantId', + label: 'Tenant ID', + type: 'text', + required: true, + }, + { name: 'title', label: 'Page Title', type: 'text', required: true }, + { name: 'slug', label: 'Slug', type: 'text', required: true }, + { name: 'body', label: 'Body', type: 'richtext' }, + ], + }), + defineCollection({ + name: 'tenantAsset', + label: 'Tenant Media Assets', + titleField: 'filename', + fields: [ + { + name: 'tenantId', + label: 'Tenant ID', + type: 'text', + required: true, + }, + { name: 'filename', label: 'Filename', type: 'text', required: true }, + { name: 'url', label: 'Asset URL', type: 'url', required: true }, + ], + }), + ], +}) diff --git a/starters/team-ops/CMS-INTEGRATION.md b/starters/team-ops/CMS-INTEGRATION.md index c645face..a62c306e 100644 --- a/starters/team-ops/CMS-INTEGRATION.md +++ b/starters/team-ops/CMS-INTEGRATION.md @@ -10,6 +10,7 @@ A staff-only job-tracking app with zero public surface. Field-level access hides ## Files +- [`starters/team-ops/src/cms.definition.ts`](./src/cms.definition.ts): the collections (`definition`). It imports only `@tanstack/cms-core/definition`, so client code and Vite config can load it. - [`starters/team-ops/src/cms.config.ts`](./src/cms.config.ts): `registerTeamOpsCms()` and `TEAM_OPS_ROUTES_CONFIG`. - [`starters/team-ops/tests/seam.test.ts`](./tests/seam.test.ts): the S1/S3/S4/S6 suite. diff --git a/starters/team-ops/src/cms.config.ts b/starters/team-ops/src/cms.config.ts index da20ce8b..89b1ec09 100644 --- a/starters/team-ops/src/cms.config.ts +++ b/starters/team-ops/src/cms.config.ts @@ -1,5 +1,6 @@ -import { defineCms, defineCollection } from '@tanstack/cms-core' +import { defineCms } from '@tanstack/cms-core' import type { CmsConfig } from '@tanstack/cms-core' +import { definition } from './cms.definition' /** * Class #11 Starter: Team Ops (`team-ops`). @@ -36,49 +37,8 @@ export function registerTeamOpsCms(options: { dataDir?: string } = {}) { }, } - return defineCms({ + return defineCms(definition, { ...(options.dataDir ? { dataDir: options.dataDir } : {}), - collections: [ - defineCollection({ - name: 'jobOrder', - label: 'Job Orders', - titleField: 'jobCode', - fields: [ - { name: 'jobCode', label: 'Job Code', type: 'text', required: true }, - { - name: 'status', - label: 'Job Status', - type: 'select', - options: ['queued', 'in-progress', 'completed'], - defaultValue: 'queued', - }, - { - name: 'technicianNotes', - label: 'Technician Notes', - type: 'textarea', - }, - { - name: 'unitCostCents', - label: 'Internal Unit Cost (cents)', - type: 'number', - access: { - read: ['admin'], - write: ['admin'], - }, - }, - { - name: 'managerSignOff', - label: 'Manager Sign-Off', - type: 'boolean', - defaultValue: false, - access: { - read: ['admin'], - write: ['admin'], - }, - }, - ], - }), - ], blockTypes: [], auth, }) diff --git a/starters/team-ops/src/cms.definition.ts b/starters/team-ops/src/cms.definition.ts new file mode 100644 index 00000000..197f6b51 --- /dev/null +++ b/starters/team-ops/src/cms.definition.ts @@ -0,0 +1,48 @@ +import { + defineCmsDefinition, + defineCollection, +} from '@tanstack/cms-core/definition' + +export const definition = defineCmsDefinition({ + collections: [ + defineCollection({ + name: 'jobOrder', + label: 'Job Orders', + titleField: 'jobCode', + fields: [ + { name: 'jobCode', label: 'Job Code', type: 'text', required: true }, + { + name: 'status', + label: 'Job Status', + type: 'select', + options: ['queued', 'in-progress', 'completed'], + defaultValue: 'queued', + }, + { + name: 'technicianNotes', + label: 'Technician Notes', + type: 'textarea', + }, + { + name: 'unitCostCents', + label: 'Internal Unit Cost (cents)', + type: 'number', + access: { + read: ['admin'], + write: ['admin'], + }, + }, + { + name: 'managerSignOff', + label: 'Manager Sign-Off', + type: 'boolean', + defaultValue: false, + access: { + read: ['admin'], + write: ['admin'], + }, + }, + ], + }), + ], +}) diff --git a/starters/themed-smb-site/CMS-INTEGRATION.md b/starters/themed-smb-site/CMS-INTEGRATION.md index de52f896..f84c7666 100644 --- a/starters/themed-smb-site/CMS-INTEGRATION.md +++ b/starters/themed-smb-site/CMS-INTEGRATION.md @@ -10,7 +10,8 @@ A brochure site for a local business. It has block-based pages, a services colle ## Files -- [`starters/themed-smb-site/src/cms.config.ts`](./src/cms.config.ts): `registerThemedSmbCms()`, with the schema, blocks, and SEO config. +- [`starters/themed-smb-site/src/cms.definition.ts`](./src/cms.definition.ts): the collections (`definition`). It imports only `@tanstack/cms-core/definition`, so client code and Vite config can load it. +- [`starters/themed-smb-site/src/cms.config.ts`](./src/cms.config.ts): `registerThemedSmbCms()`, with the blocks and SEO config. - [`starters/themed-smb-site/src/theme.tsx`](./src/theme.tsx): `SmbBrochurePage`, built on `SiteShell` and `BlocksView`. - [`starters/themed-smb-site/tests/seam.test.ts`](./tests/seam.test.ts): the S1/S6 suite. diff --git a/starters/themed-smb-site/src/cms.config.ts b/starters/themed-smb-site/src/cms.config.ts index cc851232..ec877d9e 100644 --- a/starters/themed-smb-site/src/cms.config.ts +++ b/starters/themed-smb-site/src/cms.config.ts @@ -1,10 +1,6 @@ -import { - defineBlock, - defineCms, - defineCollection, - seoField, -} from '@tanstack/cms-core' +import { defineBlock, defineCms } from '@tanstack/cms-core' import type { CmsConfig } from '@tanstack/cms-core' +import { definition } from './cms.definition' export function registerThemedSmbCms(options: { dataDir?: string } = {}) { const auth: NonNullable = { @@ -15,77 +11,11 @@ export function registerThemedSmbCms(options: { dataDir?: string } = {}) { }, } - return defineCms({ + return defineCms(definition, { ...(options.dataDir ? { dataDir: options.dataDir } : {}), seo: { siteUrl: 'https://oakridge-plumbing.example.com', }, - collections: [ - defineCollection({ - name: 'page', - label: 'Brochure Pages', - titleField: 'title', - path: (doc, id) => (id === 'home' ? '/' : `/${String(doc.slug ?? id)}`), - fields: [ - { name: 'title', label: 'Page Title', type: 'text', required: true }, - { name: 'slug', label: 'Slug', type: 'slug', from: 'title' }, - { name: 'blocks', label: 'Page Blocks', type: 'blocks' }, - seoField(), - ], - }), - defineCollection({ - name: 'service', - label: 'Services', - titleField: 'title', - summaryField: 'summary', - path: (_doc, id) => `/services/${id}`, - fields: [ - { - name: 'title', - label: 'Service Name', - type: 'text', - required: true, - }, - { name: 'summary', label: 'Summary', type: 'textarea' }, - { name: 'priceRange', label: 'Typical Price Range', type: 'text' }, - ], - }), - defineCollection({ - name: 'contactInquiry', - label: 'Contact Inquiries', - titleField: 'name', - fields: [ - { name: 'name', label: 'Sender Name', type: 'text', required: true }, - { - name: 'email', - label: 'Sender Email', - type: 'email', - required: true, - }, - { - name: 'message', - label: 'Message', - type: 'textarea', - required: true, - }, - ], - }), - defineCollection({ - name: 'redirect', - label: 'SEO Redirects', - titleField: 'from', - fields: [ - { name: 'from', label: 'From Path', type: 'text', required: true }, - { name: 'to', label: 'To Path', type: 'text', required: true }, - { - name: 'permanent', - label: 'Permanent (301)', - type: 'boolean', - defaultValue: true, - }, - ], - }), - ], blockTypes: [ defineBlock({ type: 'hero', diff --git a/starters/themed-smb-site/src/cms.definition.ts b/starters/themed-smb-site/src/cms.definition.ts new file mode 100644 index 00000000..fbaa4328 --- /dev/null +++ b/starters/themed-smb-site/src/cms.definition.ts @@ -0,0 +1,74 @@ +import { + defineCmsDefinition, + defineCollection, + seoField, +} from '@tanstack/cms-core/definition' + +export const definition = defineCmsDefinition({ + collections: [ + defineCollection({ + name: 'page', + label: 'Brochure Pages', + titleField: 'title', + path: (doc, id) => (id === 'home' ? '/' : `/${String(doc.slug ?? id)}`), + fields: [ + { name: 'title', label: 'Page Title', type: 'text', required: true }, + { name: 'slug', label: 'Slug', type: 'slug', from: 'title' }, + { name: 'blocks', label: 'Page Blocks', type: 'blocks' }, + seoField(), + ], + }), + defineCollection({ + name: 'service', + label: 'Services', + titleField: 'title', + summaryField: 'summary', + path: (_doc, id) => `/services/${id}`, + fields: [ + { + name: 'title', + label: 'Service Name', + type: 'text', + required: true, + }, + { name: 'summary', label: 'Summary', type: 'textarea' }, + { name: 'priceRange', label: 'Typical Price Range', type: 'text' }, + ], + }), + defineCollection({ + name: 'contactInquiry', + label: 'Contact Inquiries', + titleField: 'name', + fields: [ + { name: 'name', label: 'Sender Name', type: 'text', required: true }, + { + name: 'email', + label: 'Sender Email', + type: 'email', + required: true, + }, + { + name: 'message', + label: 'Message', + type: 'textarea', + required: true, + }, + ], + }), + defineCollection({ + name: 'redirect', + label: 'SEO Redirects', + titleField: 'from', + fields: [ + { name: 'from', label: 'From Path', type: 'text', required: true }, + { name: 'to', label: 'To Path', type: 'text', required: true }, + { + name: 'permanent', + label: 'Permanent (301)', + type: 'boolean', + defaultValue: true, + }, + ], + }), + ], +})