diff --git a/.changeset/events-and-hooks.md b/.changeset/events-and-hooks.md index 5154498a..411a8eed 100644 --- a/.changeset/events-and-hooks.md +++ b/.changeset/events-and-hooks.md @@ -4,9 +4,7 @@ --- Add the events & hooks system. Synchronous collection hooks gain the -`preValidate` / `postValidate` / `preDelete` / `postRead` stages (the existing -`beforeValidate` / `beforeChange` / `beforeDelete` / `afterRead` names stay as -aliases). A new durable async event system delivers `defineEventHandler` +`preValidate` / `postValidate` / `preDelete` / `postRead` stages. A new durable async event system delivers `defineEventHandler` handlers after commit: event rows are written to a transactional outbox in the same transaction as the content change, then claimed and delivered at-least-once with exponential backoff, dead-lettering, and per-handler auto-disable. Handlers diff --git a/.changeset/hooks-events-framing.md b/.changeset/hooks-events-framing.md new file mode 100644 index 00000000..b9e20f33 --- /dev/null +++ b/.changeset/hooks-events-framing.md @@ -0,0 +1,25 @@ +--- +'@tanstack/cms-core': minor +--- + +Hooks are the pre-commit consultation ("anything we should know before we go +in?"); events are the post-commit announcement. The API now says so. + +**Breaking:** the legacy collection hook aliases are removed. Rename them: + +| Removed | Use | +| ---------------- | -------------- | +| `beforeValidate` | `preValidate` | +| `beforeChange` | `postValidate` | +| `beforeDelete` | `preDelete` | +| `afterRead` | `postRead` | + +**Deprecated:** the synchronous post-commit hooks `afterChange` and +`afterDelete`. They still run, but will be removed before 1.0. Move the work to +a durable `defineEventHandler` in `defineCms({ eventHandlers })`, on +`document.created` / `document.updated` (for `afterChange`) or +`document.deleted` (for `afterDelete`). + +Outside production (`NODE_ENV !== 'production'`), a hook that takes longer +than the documented 50ms guideline logs a warning once per collection and +stage per process. diff --git a/.claude/skills/payload-to-tanstack-cms/SKILL.md b/.claude/skills/payload-to-tanstack-cms/SKILL.md index de01d1b0..ed919420 100644 --- a/.claude/skills/payload-to-tanstack-cms/SKILL.md +++ b/.claude/skills/payload-to-tanstack-cms/SKILL.md @@ -149,15 +149,21 @@ reads. Public writes (`create: () => true` for form submissions) belong in an app server function that calls `commitDocument` from `@tanstack/cms-core/server`, not in `collection.access`. -**Hooks.** `beforeValidate`, `beforeChange`, `afterChange`, `afterRead`, -`beforeDelete`, `afterDelete` map 1:1 and may be async. Arguments differ: +**Hooks.** Core hooks are a pre-commit consultation; anything after the +commit is an event. Payload `beforeValidate` → `preValidate`, `beforeChange` +→ `postValidate`, `beforeDelete` → `preDelete`, `afterRead` → `postRead`; all +may be async. Payload `afterChange` / `afterDelete` → a durable +`defineEventHandler` on `document.created` / `document.updated` / +`document.deleted` in `defineCms({ eventHandlers })` (core's own +`afterChange` / `afterDelete` hooks are deprecated). Arguments differ: Payload `{ data, originalDoc, req, operation }` → core -`{ doc, id, operation, actor }` (before/after change), `{ doc, id }` -(`afterRead`), `{ id, actor }` (delete hooks). Return the transformed doc from -`before*`/`afterRead`; throw to abort a write. Replace `req.payload.find(…)` -with `queryDocuments`/`readDocument` from `@tanstack/cms-core/server`. Hooks -that only fan out to other systems (cache purges, search indexing) usually -become `defineCms({ webhooks })` instead. No equivalent: `beforeOperation`, +`{ doc, id, operation, actor }` (`preValidate` / `postValidate`), +`{ 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 +only fan out to other systems (cache purges, search indexing) usually become +`defineCms({ webhooks })` instead. No equivalent: `beforeOperation`, `afterOperation`, `beforeRead`, `afterError`, auth hooks. **Auth.** Payload's `users` collection becomes diff --git a/app/prm/src/collections.ts b/app/prm/src/collections.ts index 5b817281..fcbb7b94 100644 --- a/app/prm/src/collections.ts +++ b/app/prm/src/collections.ts @@ -81,7 +81,7 @@ export const person = defineCollection({ // Search priority: headline, role, name, aliasesText, notes search: { fields: ['headline', 'role', 'name', 'aliasesText', 'notes'] }, hooks: { - beforeValidate: ({ doc }) => { + preValidate: ({ doc }) => { const next = { ...doc } const rawAliases = Array.isArray(next.aliases) ? next.aliases : [] const cleaned = rawAliases diff --git a/docs/agents/review-queue.md b/docs/agents/review-queue.md index bee3ea7b..ccb10dbb 100644 --- a/docs/agents/review-queue.md +++ b/docs/agents/review-queue.md @@ -56,7 +56,7 @@ runOp(name, input, actor) permission, collection, and field rules │ ▼ stageWrite({ collection, docId, type, doc, actor, instruction }) - ├─ runs beforeValidate hooks and validates against the collection schema + ├─ runs preValidate hooks and validates against the collection schema ├─ checks field rules (unique, min/max, validate) ├─ records the `before` snapshot and the document's current revision └─ inserts or coalesces one pending change per document diff --git a/docs/api/cms-core-server.md b/docs/api/cms-core-server.md index 129da9e0..008f7074 100644 --- a/docs/api/cms-core-server.md +++ b/docs/api/cms-core-server.md @@ -163,7 +163,7 @@ Paginated summaries for one collection: the admin list view. Pending creates (st function readDocument(collectionName: string, id: string): Promise ``` -The committed document, after `afterRead` hooks. +The committed document, after `postRead` hooks. ### `readDocumentWithPending(collection, id)` diff --git a/docs/api/cms-core.md b/docs/api/cms-core.md index d0b19510..086eeba3 100644 --- a/docs/api/cms-core.md +++ b/docs/api/cms-core.md @@ -614,7 +614,7 @@ function isFieldVisible(field: Field, siblings: Record; defaultSort?: { field: string; dir?: 'asc' \| 'desc' } }`. | -| `CollectionHooks` | Synchronous lifecycle hooks: `preValidate`, `postValidate`, `preDelete`, `postRead` (and the legacy aliases `beforeValidate`, `beforeChange`, `beforeDelete`, `afterRead`), plus `afterChange` / `afterDelete`. See [Events & Hooks](../architecture/events-and-hooks). | +| `CollectionHooks` | Pre-commit lifecycle hooks: `preValidate`, `postValidate`, `preDelete`, plus the `postRead` response transform. `afterChange` / `afterDelete` are deprecated in favour of `defineEventHandler`. See [Events & Hooks](../architecture/events-and-hooks). | | `ChangeHookArgs` | `{ doc, id, operation, actor }` — what a pre-commit mutating hook receives. | | `BlockType` | `{ type, label, fields, component? }`. | | `Block` | `{ _type: string } & { [key: string]: JsonValue }`. | diff --git a/docs/architecture/events-and-hooks.md b/docs/architecture/events-and-hooks.md index ffc71064..1fc18786 100644 --- a/docs/architecture/events-and-hooks.md +++ b/docs/architecture/events-and-hooks.md @@ -2,7 +2,7 @@ title: Events & Hooks id: events-and-hooks order: 5 -description: "The two halves of reacting to content changes in TanStack CMS: synchronous collection hooks that run inside the write transaction and may mutate or veto, and durable asynchronous event handlers delivered after commit with at-least-once retries, loop prevention, and cron schedules." +description: "The two halves of reacting to content changes in TanStack CMS: collection hooks, a pre-commit consultation that may mutate or veto a write, and durable asynchronous event handlers, a post-commit announcement delivered with at-least-once retries, loop prevention, and cron schedules." keywords: - tanstack cms - events @@ -15,16 +15,18 @@ keywords: - causationId --- -TanStack CMS reacts to content changes on two sides of one bright line — **the commit**. +TanStack CMS reacts to content changes on two sides of one bright line: **the commit**. Think of a write as a game. -- **Before commit:** synchronous **hooks** run inside the write request (and, for the pre-commit stages, inside the database transaction). They may rewrite the document and they may veto the write by throwing. Use them for work that must be fast, deterministic, and part of the write itself — normalizing input, deriving fields, enforcing an invariant. -- **After commit:** asynchronous **event handlers** run off the write path. They receive an immutable record of what already happened. They can cause *new* writes but can never alter or undo the change that fired them. Use them for anything slow, networked, or allowed to fail — sending mail, calling an API, recomputing a derived collection. +- **Hooks ask "we're about to go into the game: anything you want to make us aware of before we do?"** They are a pre-commit consultation. Collection hooks run inside the write request (and, for the pre-commit stages, inside the database transaction). They may rewrite the document, and they may veto the write by throwing. Use them for work that must be fast, deterministic, and part of the write itself: normalizing input, deriving fields, enforcing an invariant. +- **Events announce "we won the game!"** They are a post-commit announcement. Event handlers run asynchronously, off the write path, and receive an immutable record of what already happened. They can cause *new* writes but can never alter or undo the change that fired them. Use them for anything slow, networked, or allowed to fail: sending mail, calling an API, recomputing a derived collection. + +The commit is a firewall between the two. Nothing a hook does survives a vetoed write, and nothing an event handler does can reach back across the commit. The rule of thumb: *if it can be slow or fail, it is an event, not a hook.* -## Synchronous hooks +## Hooks: before the game -Hooks live on a collection. Every hook may be async; the engine awaits it. Throwing from a pre-commit hook aborts the write and rolls back the transaction — no document, no revision, no events. +Hooks live on a collection. Every hook may be async; the engine awaits it. Throwing from a pre-commit hook aborts the write and rolls back the transaction: no document, no revision, no events. ```ts import { defineCollection, slugify } from '@tanstack/cms-core' @@ -58,11 +60,38 @@ export const post = defineCollection({ | `preDelete` | before the delete transaction | — | throw → rollback | | `postRead` | after a read, before the response | yes — response only, never stored | — | -The older names `beforeValidate`, `beforeChange`, `beforeDelete`, and `afterRead` remain as stable aliases for `preValidate`, `postValidate`, `preDelete`, and `postRead`. When both a new name and its alias are set, the new name runs first and the alias sees its output (a pipeline). `afterChange` / `afterDelete` still fire post-commit, but prefer an async handler for anything that can be slow or fail. +`postRead` runs on reads rather than writes, so it is not part of the consultation before a commit. It is a response transform that shares the hook shape. + +> **The 50ms guideline.** Hooks must be fast and deterministic. Network calls, LLM calls, or any unbounded work in a hook blocks the request and risks the transaction, so move it to an event handler. Outside production (`NODE_ENV !== 'production'`), the engine times every hook and logs one warning per hook (per collection and stage, per process) that takes longer than 50ms. + +### Deprecated: `afterChange` and `afterDelete` + +`afterChange` and `afterDelete` run synchronously *after* the commit, inside the request. That is announcing the result in the style of a consultation: the work blocks the response, isn't retried, and is lost on a crash. Both are deprecated and will be removed before 1.0. Move the work to a durable event handler: + +| Deprecated hook | Event handler | +|---|---| +| `afterChange` | `on: 'document.created'` and `on: 'document.updated'` (plus `document.published` / `document.unpublished` if only publish state matters) | +| `afterDelete` | `on: 'document.deleted'` | + +```ts +// Before +hooks: { + afterChange: async ({ id }) => { await purgeCache(`/post/${id}`) }, +} + +// After +eventHandlers: [ + defineEventHandler({ + on: 'document.updated', + collection: 'post', + run: async ({ event }) => { await purgeCache(`/post/${event.documentId}`) }, + }), +] +``` -> **The 50ms guideline.** Synchronous hooks must be fast and deterministic. Network calls, LLM calls, or any unbounded work in a hook blocks the writer and risks the transaction — move it to an event handler. +The legacy alias names `beforeValidate`, `beforeChange`, `beforeDelete`, and `afterRead` were removed. Rename them to `preValidate`, `postValidate`, `preDelete`, and `postRead`. -## Asynchronous event handlers +## Events: after the game `defineEventHandler` registers a handler, and `defineCms({ eventHandlers })` installs it. Handlers are delivered **at-least-once** from a durable outbox, so they must be idempotent (check-then-write is the blessed pattern). @@ -208,5 +237,5 @@ push updates; a full-read fallback recovers missed events. ## When to use which -- **Hook** — the work is part of the write, must be fast, and should block or veto it: slugify, derive a field, enforce an invariant, transform a response. -- **Event handler** — the work reacts to a committed change and may be slow or fail: send a notification, call an external API, recompute a derived collection, run a nightly job. +- **Hook** (before the game) — the work is part of the write, must be fast, and should block or veto it: slugify, derive a field, enforce an invariant, transform a response. +- **Event handler** (after the game) — the work reacts to a committed change and may be slow or fail: send a notification, call an external API, recompute a derived collection, run a nightly job. This includes anything you would once have put in `afterChange` or `afterDelete`. diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md index 130f8cb9..575b4f22 100644 --- a/docs/architecture/overview.md +++ b/docs/architecture/overview.md @@ -152,7 +152,7 @@ sequenceDiagram Op->>Core: commitDocument() Core->>Core: preValidate hooks, schema validation, field rules, postValidate hooks Core->>Core: transaction: re-check access and expectedRevision, write document, record revision, enqueue events and webhooks - Core->>Core: afterChange hook, emit change / publish + Core->>Core: emit change / publish Core-->>Op: committed document Op-->>DB: staged: false DB->>Op: refetch listPublishedDocuments diff --git a/docs/migration/from-payload.md b/docs/migration/from-payload.md index 0723c279..09c6ebd5 100644 --- a/docs/migration/from-payload.md +++ b/docs/migration/from-payload.md @@ -60,7 +60,8 @@ Payload v3 and TanStack CMS are both **code-first TypeScript CMSs** with schema | `admin.defaultColumns` | `admin.columns` | Scalar fields after the title column | | `defaultSort: '-field'` | `admin.defaultSort: { field, dir: 'desc' }` | | | `access.{read,create,update,delete}` | `access.{read,create,update,delete}` (+ `publish`, `write`) | Role arrays or `({ session, doc }) => boolean` | -| `hooks.*` | `hooks.*` | `beforeValidate`, `beforeChange`, `afterChange`, `afterRead`, `beforeDelete`, `afterDelete` | +| `hooks.beforeValidate` / `beforeChange` / `beforeDelete` / `afterRead` | `hooks.preValidate` / `postValidate` / `preDelete` / `postRead` | | +| `hooks.afterChange` / `afterDelete` | `defineEventHandler` on `document.created` / `document.updated` / `document.deleted` | Post-commit work is an event, not a hook | | `versions.drafts` | Built in | Saving a published doc stores a draft; `_status` → `published` | | `schedulePublish` | `publishAt` / `unpublishAt` | System fields on every document | | `upload: true` collection | Media library + `image` fields | Not a content collection | @@ -97,7 +98,7 @@ Field options carry over by name: `required`, `unique`, `index`, `defaultValue`, - `({ req: { user } }) => Boolean(user)` becomes `({ session }) => session.isAuthenticated`; a role check becomes a role array such as `['editor', 'admin']`. - Published documents are always publicly readable, so Payload's common `read: () => true` needs no rule. `access.read` governs drafts and admin reads. - Public writes (form submissions) belong in an app server function that calls `commitDocument` from `@tanstack/cms-core/server`. -- Hook arguments change from `{ data, originalDoc, req, operation }` to `{ doc, id, operation, actor }`. Return the transformed doc from `before*` hooks and throw to abort. Replace `req.payload.find()` with `queryDocuments()` or `readDocument()`. Fan-out hooks (cache purges, search sync) often become `defineCms({ webhooks })`. +- Hook arguments change from `{ data, originalDoc, req, operation }` to `{ doc, id, operation, actor }`. Return the transformed doc from `preValidate` / `postValidate` hooks and throw to abort. Replace `req.payload.find()` with `queryDocuments()` or `readDocument()`. Fan-out hooks (cache purges, search sync) often become `defineCms({ webhooks })`. ### Blocks (`pages.layout` → `page.blocks`) diff --git a/docs/schema/building-pages.md b/docs/schema/building-pages.md index ccb8cdf2..cdf7a567 100644 --- a/docs/schema/building-pages.md +++ b/docs/schema/building-pages.md @@ -38,7 +38,7 @@ Readers see published documents only. Sessions with `content.read` (viewers and ## Loading content -There are three ways to read content from a route loader. All of them respect drafts, field access rules, and `afterRead` hooks. +There are three ways to read content from a route loader. All of them respect drafts, field access rules, and `postRead` hooks. ### 1. The CMS server functions diff --git a/docs/schema/collections-and-fields.md b/docs/schema/collections-and-fields.md index 57ce0437..3be3778b 100644 --- a/docs/schema/collections-and-fields.md +++ b/docs/schema/collections-and-fields.md @@ -404,43 +404,49 @@ export const invoice = defineCollection({ ## Hooks -Every hook may be async; the engine awaits it. Throwing from a `before*` hook aborts the write. +A hook is the engine asking, just before a commit, "anything you want to make us aware of before we go in?" Hooks may rewrite the document or veto the write by throwing. Anything that reacts to the result after the commit is an [event handler](../architecture/events-and-hooks) instead. Every hook may be async; the engine awaits it. Keep each one under about 50ms: outside production the engine warns once per hook that runs longer. | Hook | Arguments | Runs | | --- | --- | --- | -| `beforeValidate` | `{ doc, id, operation, actor }` | Before validation, on saves and when a change is staged. May return a transformed doc (merged over the input). | -| `beforeChange` | `{ doc, id, operation, actor }` | After validation, right before a commit (direct save or approval). May return a transformed doc. | -| `afterChange` | `{ doc, id, operation, actor }` | After a commit, with the committed document. | -| `afterRead` | `{ doc, id }` | On every read. May return a transformed doc. | -| `beforeDelete` | `{ id, actor }` | Before a delete commits. | -| `afterDelete` | `{ id, actor }` | After a delete commits. | +| `preValidate` | `{ doc, id, operation, actor }` | Before validation, on saves and when a change is staged. May return a transformed doc (merged over the input). | +| `postValidate` | `{ doc, id, operation, actor }` | After validation, right before a commit (direct save or approval). May return a transformed doc, which is re-validated. | +| `preDelete` | `{ id, actor }` | Before a delete commits. Throw to veto. | +| `postRead` | `{ doc, id }` | On every read. May return a transformed doc (the response only; never stored). | +| `afterChange` | `{ doc, id, operation, actor }` | **Deprecated.** After a commit, with the committed document. Use a `document.created` / `document.updated` event handler. | +| `afterDelete` | `{ id, actor }` | **Deprecated.** After a delete commits. Use a `document.deleted` event handler. | `operation` is `'create'` or `'update'`. `actor` identifies who made the change (`human`, an agent name such as `content-agent`, `mcp`, or `webmcp`). ```ts validate=type -import { defineCollection } from '@tanstack/cms-core' +import { defineCollection, defineEventHandler } from '@tanstack/cms-core' export const article = defineCollection({ name: 'article', label: 'Articles', titleField: 'title', hooks: { - beforeValidate: ({ doc }) => ({ + preValidate: ({ doc }) => ({ ...doc, title: typeof doc.title === 'string' ? doc.title.trim() : doc.title, }), - afterChange: async ({ id, operation }) => { - await fetch('https://example.com/revalidate', { - method: 'POST', - body: JSON.stringify({ id, operation }), - }) - }, - beforeDelete: ({ id }) => { + preDelete: ({ id }) => { if (id === 'home') throw new Error('The home article cannot be deleted.') }, }, fields: [{ name: 'title', label: 'Title', type: 'text', required: true }], }) + +// Post-commit work goes in an event handler: `defineCms({ eventHandlers: [revalidate] })`. +export const revalidate = defineEventHandler({ + on: 'document.updated', + collection: 'article', + run: async ({ event }) => { + await fetch('https://example.com/revalidate', { + method: 'POST', + body: JSON.stringify({ id: event.documentId }), + }) + }, +}) ``` For outgoing notifications on publish, unpublish, and delete, prefer [webhooks](../api/cms-core#cmswebhook-and-cmswebhookevent), which are signed and retried. diff --git a/packages/cms-skills/src/registry/redirects-and-broken-links.ts b/packages/cms-skills/src/registry/redirects-and-broken-links.ts index 6e71e8e5..b6b3b3f0 100644 --- a/packages/cms-skills/src/registry/redirects-and-broken-links.ts +++ b/packages/cms-skills/src/registry/redirects-and-broken-links.ts @@ -12,7 +12,7 @@ export const redirectsAndBrokenLinksSkill = defineSkill({ 'eps-301-redirects', ], description: - 'Replaces Redirection, Pretty Links, and Broken Link Checker with a managed redirects collection and an automatic afterUpdate hook that creates 301 redirects whenever a published slug changes.', + 'Replaces Redirection, Pretty Links, and Broken Link Checker with a managed redirects collection and an automatic `document.updated` event handler that creates 301 redirects whenever a published slug changes.', collections: [ { name: 'redirects', @@ -106,6 +106,6 @@ Replaces Redirection, Pretty Links, and Broken Link Checker. ## Capabilities 1. **Redirects Collection**: Stores \`sourcePath\`, \`destinationUrl\`, \`statusCode\` (\`301 | 302 | 307\`), and \`hitCount\`. -2. **Automatic Link-Rot Prevention**: Hooks into \`document.updated\` so any slug change on a published record automatically creates a 301 redirect from the old slug to the new slug. +2. **Automatic Link-Rot Prevention**: A \`document.updated\` event handler means any slug change on a published record automatically creates a 301 redirect from the old slug to the new slug. `, }) diff --git a/packages/core/src/schema.ts b/packages/core/src/schema.ts index 18d7ca80..cf7cf2af 100644 --- a/packages/core/src/schema.ts +++ b/packages/core/src/schema.ts @@ -377,17 +377,16 @@ export interface ChangeHookArgs { } /** - * Collection lifecycle hooks — the *synchronous* half of the eventing design. - * They run inside the write request (and, pre-commit, inside the transaction), - * may mutate the document, and abort the write by throwing. Post-commit side - * effects that can be slow, call the network, or fail belong in an async event - * handler (`defineEventHandler`) instead. + * Collection lifecycle hooks: the pre-commit consultation. A hook is the + * engine asking "we're about to go into the game: anything you want to make us + * aware of before we do?" It runs inside the request (and, pre-commit, inside + * the transaction), may rewrite the document, and vetoes the write by + * throwing. The post-commit announcement ("we won the game!") is an event: + * side effects that can be slow, call the network, or fail belong in a durable + * event handler (`defineEventHandler`). * - * Every hook may be async; the engine awaits it. The spec names the stages - * `preValidate` / `postValidate` / `preDelete` / `postRead`; the older - * `beforeValidate` / `beforeChange` / `beforeDelete` / `afterRead` names are - * kept as stable aliases. When both are set the spec name runs first, then the - * alias, each seeing the previous hook's output (a pipeline). + * Every hook may be async; the engine awaits it. Keep each one under about + * 50ms: outside production the engine warns once per hook that takes longer. */ export interface CollectionHooks { /** @@ -395,24 +394,30 @@ export interface CollectionHooks { * Return a (partial) doc to merge, or mutate in place. */ preValidate?: (args: ChangeHookArgs) => MaybePromise - /** Alias of `preValidate` (legacy name). */ - beforeValidate?: (args: ChangeHookArgs) => MaybePromise /** * After Zod validation, before the write transaction; derive fields. The * returned doc is re-validated with Zod before it is written. */ postValidate?: (args: ChangeHookArgs) => MaybePromise - /** Alias of `postValidate` (legacy name). */ - beforeChange?: (args: ChangeHookArgs) => MaybePromise + /** + * Runs synchronously after a commit, with the committed document. + * + * @deprecated Post-commit work is an event, not a hook. Use a durable + * handler on `document.created` / `document.updated`: + * `defineEventHandler` in `defineCms({ eventHandlers })`. Removed before 1.0. + */ afterChange?: (args: ChangeHookArgs) => MaybePromise /** After a read, before the response; transforms the response only, never stored. */ postRead?: (args: { doc: TDoc; id: string }) => MaybePromise - /** Alias of `postRead` (legacy name). */ - afterRead?: (args: { doc: TDoc; id: string }) => MaybePromise /** Before a delete transaction; throw to veto. */ preDelete?: (args: { id: string; actor: string }) => MaybePromise - /** Alias of `preDelete` (legacy name). */ - beforeDelete?: (args: { id: string; actor: string }) => MaybePromise + /** + * Runs synchronously after a delete commits. + * + * @deprecated Post-commit work is an event, not a hook. Use a durable + * handler on `document.deleted`: `defineEventHandler` in + * `defineCms({ eventHandlers })`. Removed before 1.0. + */ afterDelete?: (args: { id: string; actor: string }) => MaybePromise } diff --git a/packages/core/src/server/store/internal.ts b/packages/core/src/server/store/internal.ts index 41b824c9..47555db6 100644 --- a/packages/core/src/server/store/internal.ts +++ b/packages/core/src/server/store/internal.ts @@ -6,7 +6,7 @@ * Server-only. */ import { randomUUID } from 'node:crypto' -import { contentLocales, getCmsConfig } from '../../config' +import { cmsLogger, contentLocales, getCmsConfig } from '../../config' import { CmsError } from '../../errors' import { blockTypeMap, @@ -22,6 +22,7 @@ import { emitCmsEvent } from '../events' import { collectRelations } from './relations' import type { Collection, + CollectionHooks, Doc, Field, FieldValidator, @@ -62,18 +63,55 @@ export function requireWritableCollection(name: string): Collection { return collection } -export async function applyAfterRead( +/** The documented per-hook budget; slower hooks warn outside production. */ +export const SLOW_HOOK_MS = 50 + +const warnedSlowHooks = new Set() + +/** Test seam: forget which hooks already warned. */ +export function resetSlowHookWarnings(): void { + warnedSlowHooks.clear() +} + +/** + * Await one collection hook. Outside production, a hook slower than + * {@link SLOW_HOOK_MS} logs a warning once per `collection.stage` per process. + */ +export async function runHook( + collectionName: string, + stage: keyof CollectionHooks, + call: () => T | Promise, +): Promise { + if (process.env.NODE_ENV === 'production') return call() + const started = performance.now() + try { + return await call() + } finally { + const elapsed = performance.now() - started + const key = `${collectionName}.${stage}` + if (elapsed > SLOW_HOOK_MS && !warnedSlowHooks.has(key)) { + warnedSlowHooks.add(key) + cmsLogger().warn( + `[tanstack-cms] Hook ${key} took ${Math.round(elapsed)}ms (guideline: ${SLOW_HOOK_MS}ms). ` + + 'Hooks block the request they run in; move slow, networked, or fallible work to an ' + + 'event handler (defineEventHandler). Shown once per hook, outside production.', + ) + } + } +} + +export async function applyPostRead( collectionName: string, id: string, stored: Doc, ): Promise { - let doc = await upgradeStoredDoc(collectionName, id, stored) - const hooks = collections()[collectionName]?.hooks - for (const hook of [hooks?.postRead, hooks?.afterRead]) { - const result = await hook?.({ doc, id }) - if (result && typeof result === 'object') doc = result as Doc - } - return doc + const doc = await upgradeStoredDoc(collectionName, id, stored) + const hook = collections()[collectionName]?.hooks?.postRead + if (!hook) return doc + const result = await runHook(collectionName, 'postRead', () => + hook({ doc, id }), + ) + return result && typeof result === 'object' ? (result as Doc) : doc } export function stripUndefined(obj: Record): Doc { @@ -84,27 +122,25 @@ export function stripUndefined(obj: Record): Doc { return clean } -export async function runBeforeValidate( +/** The `preValidate` stage: runs before Zod. Returns the merged input. */ +export async function runPreValidate( collection: Collection, doc: Record, id: string, operation: 'create' | 'update', actor: string, ): Promise> { - let next = doc - for (const hook of [ - collection.hooks?.preValidate, - collection.hooks?.beforeValidate, - ]) { - const result = await hook?.({ doc: next as Doc, id, operation, actor }) - if (result && typeof result === 'object') next = { ...next, ...result } - } - return next + const hook = collection.hooks?.preValidate + if (!hook) return doc + const result = await runHook(collection.name, 'preValidate', () => + hook({ doc: doc as Doc, id, operation, actor }), + ) + return result && typeof result === 'object' ? { ...doc, ...result } : doc } /** - * The `postValidate` stage (and its `beforeChange` alias): runs after Zod, - * before the write. Returns the merged doc; callers re-validate it with Zod. + * The `postValidate` stage: runs after Zod, before the write. Returns the + * merged doc; callers re-validate it with Zod. */ export async function runPostValidate( collection: Collection | undefined, @@ -113,25 +149,48 @@ export async function runPostValidate( operation: 'create' | 'update', actor: string, ): Promise { - let next = doc - for (const hook of [ - collection?.hooks?.postValidate, - collection?.hooks?.beforeChange, - ]) { - const result = await hook?.({ doc: next, id, operation, actor }) - if (result && typeof result === 'object') next = { ...next, ...result } - } - return next + const hook = collection?.hooks?.postValidate + if (!collection || !hook) return doc + const result = await runHook(collection.name, 'postValidate', () => + hook({ doc, id, operation, actor }), + ) + return result && typeof result === 'object' ? { ...doc, ...result } : doc } -/** The `preDelete` stage (and its `beforeDelete` alias). Throwing vetoes the delete. */ +/** The `preDelete` stage. Throwing vetoes the delete. */ export async function runPreDelete( collection: Collection | undefined, id: string, actor: string, ): Promise { - await collection?.hooks?.preDelete?.({ id, actor }) - await collection?.hooks?.beforeDelete?.({ id, actor }) + const hook = collection?.hooks?.preDelete + if (!collection || !hook) return + await runHook(collection.name, 'preDelete', () => hook({ id, actor })) +} + +/** The deprecated post-commit `afterChange` hook. */ +export async function runAfterChange( + collection: Collection | undefined, + args: { + doc: Doc + id: string + operation: 'create' | 'update' + actor: string + }, +): Promise { + const hook = collection?.hooks?.afterChange + if (!collection || !hook) return + await runHook(collection.name, 'afterChange', () => hook(args)) +} + +/** The deprecated post-commit `afterDelete` hook. */ +export async function runAfterDelete( + collection: Collection | undefined, + args: { id: string; actor: string }, +): Promise { + const hook = collection?.hooks?.afterDelete + if (!collection || !hook) return + await runHook(collection.name, 'afterDelete', () => hook(args)) } export function validate( diff --git a/packages/core/src/server/store/query.ts b/packages/core/src/server/store/query.ts index eee0a87d..de74f546 100644 --- a/packages/core/src/server/store/query.ts +++ b/packages/core/src/server/store/query.ts @@ -25,7 +25,7 @@ import { } from '../access-context' import { denormalize } from '../indexing' import { getStorage } from '../storage' -import { applyAfterRead, collections, isScalarField } from './internal' +import { applyPostRead, collections, isScalarField } from './internal' import { populateRelationsAs } from './read' import type { AccessContext } from '../access-context' import type { CmsSession } from '../../lib/auth' @@ -295,7 +295,7 @@ export async function queryDocumentsAs( const relationsCtx = withoutPublicRead(ctx) const page: QueryDocumentsResult['items'] = [] for (const row of result.items) { - const doc = await applyAfterRead(row.collection, row.id, row.doc) + const doc = await applyPostRead(row.collection, row.id, row.doc) const visible = redactFor(ctx, row.collection, doc) const title = visible[collections()[row.collection]?.titleField ?? 'title'] page.push({ diff --git a/packages/core/src/server/store/read.ts b/packages/core/src/server/store/read.ts index 4a45ebf5..af302bf6 100644 --- a/packages/core/src/server/store/read.ts +++ b/packages/core/src/server/store/read.ts @@ -25,7 +25,7 @@ import { withoutPublicRead, } from '../access-context' import { getStorage } from '../storage' -import { applyAfterRead, collections, requireCollection } from './internal' +import { applyPostRead, collections, requireCollection } from './internal' import { collectRelations, nestedRelationTargets } from './relations' import type { AccessContext } from '../access-context' import type { CmsSession } from '../../lib/auth' @@ -116,7 +116,7 @@ async function summarize( columns: ReadonlyArray | undefined, ctx: AccessContext, ): Promise { - const original = await applyAfterRead(collection.name, row.id, row.doc) + const original = await applyPostRead(collection.name, row.id, row.doc) const doc = redactFor(ctx, collection.name, original) const rawTitle = doc[collection.titleField] const title = typeof rawTitle === 'string' && rawTitle ? rawTitle : row.id @@ -289,7 +289,7 @@ async function pendingCreateSummaries( const needle = search?.trim().toLowerCase() const summaries: Array = [] for (const p of rows) { - const original = await applyAfterRead(collection.name, p.docId, p.after) + const original = await applyPostRead(collection.name, p.docId, p.after) if ( !canReadDocument(ctx, collection.name, { id: p.docId, @@ -406,7 +406,7 @@ export async function readDocumentAs( const live = isLiveRead(ctx) if (live && !row.published) return null if (!canReadDocument(ctx, collectionName, row)) return null - const doc = await applyAfterRead(collectionName, id, row.doc) + const doc = await applyPostRead(collectionName, id, row.doc) if (live && !doc.published) return null return redactFor(ctx, collectionName, doc) } @@ -422,7 +422,7 @@ export async function readTrashedDocument( const storage = await getStorage() const row = await storage.getDocument(collectionName, id) if (!row || !row.deletedAt) return null - return applyAfterRead(collectionName, id, row.doc) + return applyPostRead(collectionName, id, row.doc) } /** What `readDocumentWithPending` returns. */ @@ -485,7 +485,7 @@ export async function readDocumentWithPendingAs( }) ) return hidden - const doc = await applyAfterRead(collectionName, id, pending.after) + const doc = await applyPostRead(collectionName, id, pending.after) return { doc: redactFor(ctx, collectionName, doc), isPending: true, @@ -501,7 +501,7 @@ export async function readDocumentWithPendingAs( return hidden if (isLiveRead(ctx) && !committed?.published) return hidden const doc = committed - ? await applyAfterRead(collectionName, id, committed.doc) + ? await applyPostRead(collectionName, id, committed.doc) : null if (isLiveRead(ctx) && !doc?.published) return hidden return { @@ -570,7 +570,7 @@ export async function populateRelationsAs( const docs: Array = [] for (const row of rows) { if (live && !row.published) continue - const targetDoc = await applyAfterRead(targetName, row.id, row.doc) + const targetDoc = await applyPostRead(targetName, row.id, row.doc) if (live && !targetDoc.published) continue if (!canReadDocument(ctx, targetName, row)) continue docs.push(redactFor(ctx, targetName, targetDoc)) @@ -658,7 +658,7 @@ export async function readSingletonAs( if (!row) return null if (live && !row.published) return null if (!canReadDocument(ctx, collectionName, row)) return null - const doc = await applyAfterRead(collectionName, row.id, row.doc) + const doc = await applyPostRead(collectionName, row.id, row.doc) if (live && !doc.published) return null return { id: row.id, doc: redactFor(ctx, collectionName, doc) } } @@ -741,7 +741,7 @@ async function readBySlug( if (!canReadDocument(ctx, collectionName, direct)) return null return withRelations( slugOrId, - await applyAfterRead(collectionName, slugOrId, direct.doc), + await applyPostRead(collectionName, slugOrId, direct.doc), ) } for (const row of await storage.findDocumentsBySlug( @@ -750,7 +750,7 @@ async function readBySlug( )) { if (live && !row.published) continue if (!canReadDocument(ctx, collectionName, row)) continue - const doc = await applyAfterRead(collectionName, row.id, row.doc) + const doc = await applyPostRead(collectionName, row.id, row.doc) if (live && !doc.published) continue return withRelations(row.id, doc) } @@ -843,7 +843,7 @@ export async function listPublicDocuments( ) out[col] = {} for (const row of items) { - out[col][row.id] = await applyAfterRead(col, row.id, row.doc) + out[col][row.id] = await applyPostRead(col, row.id, row.doc) } } return out @@ -1107,7 +1107,7 @@ export async function listTranslationsAs( const mapped = await storage.getDocuments(collectionName, mappedIds) for (const row of [...linked.items, ...mapped]) { if (row.id === canonicalId || out.has(row.id)) continue - const doc = await applyAfterRead(collectionName, row.id, row.doc) + const doc = await applyPostRead(collectionName, row.id, row.doc) out.set(row.id, summarizeVariant(row.id, doc, false, row.id)) } const live = isLiveRead(ctx) diff --git a/packages/core/src/server/store/review.ts b/packages/core/src/server/store/review.ts index 85669b38..22f510b5 100644 --- a/packages/core/src/server/store/review.ts +++ b/packages/core/src/server/store/review.ts @@ -19,7 +19,7 @@ import { } from '../content-migrations' import { getStorage, notifyStorageCommit } from '../storage' import { - applyAfterRead, + applyPostRead, assertExpectedRevision, assertSingletonSlot, checkFieldRules, @@ -27,7 +27,9 @@ import { recordAudit, recordRevision, requireWritableCollection, - runBeforeValidate, + runAfterChange, + runAfterDelete, + runPreValidate, runPostValidate, runPreDelete, validate, @@ -64,7 +66,7 @@ export async function stageWrite(args: StageWriteArgs): Promise { const storage = await getStorage() const beforeRow = await storage.getDocument(args.collection, args.docId) const before = beforeRow - ? await applyAfterRead(args.collection, args.docId, beforeRow.doc) + ? await applyPostRead(args.collection, args.docId, beforeRow.doc) : null const existing = await storage.getPendingFor(args.collection, args.docId) @@ -89,7 +91,7 @@ export async function stageWrite(args: StageWriteArgs): Promise { ) after = validate( collection, - await runBeforeValidate( + await runPreValidate( collection, { ...emptyDoc(collection), ...incoming }, args.docId, @@ -316,7 +318,7 @@ export async function approve( return removed }) notifyStorageCommit() - await collection?.hooks?.afterDelete?.({ + await runAfterDelete(collection, { id: pending.docId, actor: pending.actor, }) @@ -436,7 +438,7 @@ export async function approve( return final }) notifyStorageCommit() - await collection?.hooks?.afterChange?.({ + await runAfterChange(collection, { doc: committed, id: pending.docId, operation, diff --git a/packages/core/src/server/store/scheduling.ts b/packages/core/src/server/store/scheduling.ts index e29fe85c..132ebaad 100644 --- a/packages/core/src/server/store/scheduling.ts +++ b/packages/core/src/server/store/scheduling.ts @@ -18,7 +18,8 @@ import { collections, recordAudit, recordRevision, - runBeforeValidate, + runAfterChange, + runPreValidate, runPostValidate, validate, writeDocument, @@ -49,7 +50,7 @@ async function applyScheduledDocument( if (col) { next = validate( col, - await runBeforeValidate(col, next, row.id, 'update', 'scheduler'), + await runPreValidate(col, next, row.id, 'update', 'scheduler'), ) await checkFieldRules(storage, col, row.id, next) } @@ -104,7 +105,7 @@ async function applyScheduledDocument( }) if (!committed) return false notifyStorageCommit() - await col?.hooks?.afterChange?.({ + await runAfterChange(col, { doc: committed, id: row.id, operation: 'update', diff --git a/packages/core/src/server/store/write.ts b/packages/core/src/server/store/write.ts index 826a3793..db370da4 100644 --- a/packages/core/src/server/store/write.ts +++ b/packages/core/src/server/store/write.ts @@ -18,7 +18,9 @@ import { recordAudit, recordRevision, requireWritableCollection, - runBeforeValidate, + runAfterChange, + runAfterDelete, + runPreValidate, runPostValidate, runPreDelete, validate, @@ -83,7 +85,7 @@ export async function commitDocument( const operation: 'create' | 'update' = existing ? 'update' : 'create' const parsed = validate( collection, - await runBeforeValidate(collection, merged, id, operation, actor), + await runPreValidate(collection, merged, id, operation, actor), ) await checkFieldRules(storage, collection, id, parsed) let next: Doc = await runPostValidate( @@ -153,7 +155,7 @@ export async function commitDocument( return final }) notifyStorageCommit() - await collection.hooks?.afterChange?.({ + await runAfterChange(collection, { doc: committed, id, operation, @@ -227,7 +229,7 @@ export async function deleteDocument( ) }) notifyStorageCommit() - await collection.hooks?.afterDelete?.({ id, actor }) + await runAfterDelete(collection, { id, actor }) emitCmsEvent('delete', { collection: collectionName, id, diff --git a/packages/core/tests/field-access.test.ts b/packages/core/tests/field-access.test.ts index 3f16bcb9..0370ca22 100644 --- a/packages/core/tests/field-access.test.ts +++ b/packages/core/tests/field-access.test.ts @@ -584,7 +584,7 @@ describe('nested and document-aware field access', () => { ) }) - it('runs afterRead and validates sort fields in queryDocumentSummaries', async () => { + it('runs postRead and validates sort fields in queryDocumentSummaries', async () => { const dataDir = mkdtempSync(join(tmpdir(), 'tanstack-cms-summaries-')) dirs.push(dataDir) defineCms({ @@ -605,9 +605,9 @@ describe('nested and document-aware field access', () => { }, ], hooks: { - afterRead: ({ doc }) => ({ + postRead: ({ doc }) => ({ ...doc, - title: `${String(doc.title)} [afterRead]`, + title: `${String(doc.title)} [postRead]`, }), }, }, @@ -624,8 +624,8 @@ describe('nested and document-aware field access', () => { columns: ['title'], session: as('editor'), }) - expect(summaries.items[0]?.title).toBe('Original [afterRead]') - expect(summaries.items[0]?.values?.title).toBe('Original [afterRead]') + expect(summaries.items[0]?.title).toBe('Original [postRead]') + expect(summaries.items[0]?.values?.title).toBe('Original [postRead]') await expect( queryDocumentSummaries({ diff --git a/packages/core/tests/fields.test.ts b/packages/core/tests/fields.test.ts index dc43bd7a..5f94dde1 100644 --- a/packages/core/tests/fields.test.ts +++ b/packages/core/tests/fields.test.ts @@ -303,11 +303,11 @@ describe('server-side field rules', () => { it('awaits async hooks', async () => { setup({ hooks: { - beforeValidate: async ({ doc }) => { + preValidate: async ({ doc }) => { await new Promise((r) => setTimeout(r, 1)) return { ...doc, name: String(doc.name).trim() } }, - afterRead: async ({ doc }) => ({ ...doc, readAt: 'now' }), + postRead: async ({ doc }) => ({ ...doc, readAt: 'now' }), }, }) await commitDocument('product', 'p1', { ...base, name: ' Spaced ' }) diff --git a/packages/core/tests/readiness.test.ts b/packages/core/tests/readiness.test.ts index 8ea68d69..0099c592 100644 --- a/packages/core/tests/readiness.test.ts +++ b/packages/core/tests/readiness.test.ts @@ -138,7 +138,7 @@ describe('1.0 workflow invariants', () => { { ...post, hooks: { - beforeChange: async () => { + postValidate: async () => { entered.resolve() await release.promise }, @@ -171,7 +171,7 @@ describe('1.0 workflow invariants', () => { { ...post, hooks: { - beforeChange: async () => { + postValidate: async () => { entered.resolve() await release.promise }, @@ -307,7 +307,7 @@ describe('1.0 workflow invariants', () => { update: ({ session, doc }) => doc?.owner === session.user?.id, }, hooks: { - beforeChange: async ({ actor }) => { + postValidate: async ({ actor }) => { if (actor === 'agent') { entered.resolve() await release.promise @@ -445,7 +445,7 @@ describe('1.0 workflow invariants', () => { { ...post, hooks: { - beforeChange: async ({ actor }) => { + postValidate: async ({ actor }) => { if (actor !== 'scheduler') return if (++calls === 2) release.resolve() await release.promise @@ -484,7 +484,7 @@ describe('1.0 workflow invariants', () => { { ...post, hooks: { - beforeChange: async ({ actor }) => { + postValidate: async ({ actor }) => { if (actor !== 'scheduler') return entered.resolve() await release.promise @@ -509,10 +509,10 @@ describe('1.0 workflow invariants', () => { expect((await readDocument('post', 'one'))?.title).toBe('Newer edit') }) - it('validates the final document returned by beforeChange', async () => { + it('validates the final document returned by postValidate', async () => { await setup({ collections: [ - { ...post, hooks: { beforeChange: () => ({ title: 42 }) } }, + { ...post, hooks: { postValidate: () => ({ title: 42 }) } }, ], }) await expect( diff --git a/packages/core/tests/slow-hooks.test.ts b/packages/core/tests/slow-hooks.test.ts new file mode 100644 index 00000000..b1641f6c --- /dev/null +++ b/packages/core/tests/slow-hooks.test.ts @@ -0,0 +1,117 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { closeStore, commitDocument, readDocument } from '../src/server' +import { defineCms } from '../src/config' +import { + SLOW_HOOK_MS, + resetSlowHookWarnings, +} from '../src/server/store/internal' +import type { CollectionHooks } from '../src/index' + +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)) + +describe('dev-mode slow-hook warning', () => { + const tempDirs: Array = [] + + afterEach(async () => { + vi.unstubAllEnvs() + resetSlowHookWarnings() + await closeStore() + for (const dir of tempDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }) + } + }) + + function setup(hooks: CollectionHooks) { + const dataDir = mkdtempSync(join(tmpdir(), 'tanstack-cms-slow-hooks-')) + tempDirs.push(dataDir) + const warnings: Array = [] + defineCms({ + dataDir, + logger: { + warn: (message: string) => warnings.push(message), + error: () => {}, + }, + collections: [ + { + name: 'post', + label: 'Posts', + titleField: 'title', + fields: [{ name: 'title', label: 'Title', type: 'text' }], + hooks, + }, + ], + blockTypes: [], + events: { dispatch: 'manual' }, + }) + return () => warnings.filter((w) => w.includes('[tanstack-cms] Hook ')) + } + + it('warns once per hook when a hook exceeds the guideline', async () => { + const hookWarnings = setup({ + preValidate: async () => { + await sleep(SLOW_HOOK_MS + 30) + }, + }) + await commitDocument('post', 'a', { title: 'A' }) + await commitDocument('post', 'b', { title: 'B' }) + expect(hookWarnings()).toHaveLength(1) + expect(hookWarnings()[0]).toContain('post.preValidate') + expect(hookWarnings()[0]).toContain(`guideline: ${SLOW_HOOK_MS}ms`) + expect(hookWarnings()[0]).toContain('defineEventHandler') + }) + + it('tracks each stage separately, including reads and deprecated post-commit hooks', async () => { + const hookWarnings = setup({ + postRead: async ({ doc }) => { + await sleep(SLOW_HOOK_MS + 30) + return doc + }, + afterChange: async () => { + await sleep(SLOW_HOOK_MS + 30) + }, + }) + await commitDocument('post', 'a', { title: 'A' }) + await readDocument('post', 'a') + await readDocument('post', 'a') + const stages = hookWarnings().map((w) => /Hook (\S+) took/.exec(w)?.[1]) + expect(stages.sort()).toEqual(['post.afterChange', 'post.postRead']) + }) + + it('stays quiet for fast hooks', async () => { + const hookWarnings = setup({ + preValidate: ({ doc }) => ({ ...doc, title: String(doc.title).trim() }), + postRead: ({ doc }) => doc, + }) + await commitDocument('post', 'a', { title: ' A ' }) + expect((await readDocument('post', 'a'))?.title).toBe('A') + expect(hookWarnings()).toEqual([]) + }) + + it('warns even when the slow hook throws', async () => { + const hookWarnings = setup({ + postValidate: async () => { + await sleep(SLOW_HOOK_MS + 30) + throw new Error('veto') + }, + }) + await expect(commitDocument('post', 'a', { title: 'A' })).rejects.toThrow( + 'veto', + ) + expect(hookWarnings()).toHaveLength(1) + expect(hookWarnings()[0]).toContain('post.postValidate') + }) + + it('does not time hooks in production', async () => { + vi.stubEnv('NODE_ENV', 'production') + const hookWarnings = setup({ + preValidate: async () => { + await sleep(SLOW_HOOK_MS + 30) + }, + }) + await commitDocument('post', 'a', { title: 'A' }) + expect(hookWarnings()).toEqual([]) + }) +}) diff --git a/packages/core/tests/store-index.test.ts b/packages/core/tests/store-index.test.ts index d5e01da8..dea822bf 100644 --- a/packages/core/tests/store-index.test.ts +++ b/packages/core/tests/store-index.test.ts @@ -328,11 +328,11 @@ describe('indexed read path', () => { ).toBe(1) }) - it('applies afterRead hooks on indexed batch reads', async () => { + it('applies postRead hooks on indexed batch reads', async () => { const dir = makeTempDir() setup(dir, { hooks: { - afterRead: ({ doc }: any) => ({ ...doc, title: `${doc.title}!` }), + postRead: ({ doc }: any) => ({ ...doc, title: `${doc.title}!` }), }, }) await commitDocument('post', 'a', { title: 'Hello', published: true }) diff --git a/packages/core/tests/store.test.ts b/packages/core/tests/store.test.ts index f0b95206..35a02f9e 100644 --- a/packages/core/tests/store.test.ts +++ b/packages/core/tests/store.test.ts @@ -649,7 +649,7 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { expect(byTag.items[0]?.id).toBe('beta') }) - it('invokes collection lifecycle hooks (beforeChange, afterChange, afterRead, beforeDelete)', async () => { + it('invokes collection lifecycle hooks (postValidate, afterChange, postRead, preDelete)', async () => { const dir = makeTempDir() const events: Array = [] setupTestCms( @@ -657,19 +657,19 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { {}, { hooks: { - beforeChange: ({ doc, operation }: any) => { - events.push(`beforeChange:${operation}`) + postValidate: ({ doc, operation }: any) => { + events.push(`postValidate:${operation}`) return { ...doc, slug: `/auto/${String(doc.title).toLowerCase()}` } }, afterChange: ({ id, operation }: any) => { events.push(`afterChange:${operation}:${id}`) }, - afterRead: ({ doc }: any) => ({ + postRead: ({ doc }: any) => ({ ...doc, readHookTag: 'enriched', }), - beforeDelete: ({ id, actor }: any) => { - events.push(`beforeDelete:${id}:${actor}`) + preDelete: ({ id, actor }: any) => { + events.push(`preDelete:${id}:${actor}`) }, }, }, @@ -687,9 +687,9 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { await deleteDocument('post', 'hooked', { actor: 'editor' }) expect(events).toEqual([ - 'beforeChange:create', + 'postValidate:create', 'afterChange:create:hooked', - 'beforeDelete:hooked:editor', + 'preDelete:hooked:editor', ]) }) @@ -969,7 +969,7 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { expect(viewerKey.reason).toMatch(/agent\.use/) }) - it('runs beforeChange and afterChange hooks and emits events with doc on scheduled publish and unpublish', async () => { + it('runs postValidate and afterChange hooks and emits events with doc on scheduled publish and unpublish', async () => { const dir = makeTempDir() const hookCalls: Array<{ hook: string; id: string; published: unknown }> = [] @@ -978,7 +978,7 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { setupTestCms(dir, undefined, { hooks: { - beforeChange: ({ + postValidate: ({ id, doc, }: { @@ -986,7 +986,7 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { doc: Record }) => { hookCalls.push({ - hook: 'beforeChange', + hook: 'postValidate', id, published: doc.published, }) @@ -1035,9 +1035,9 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { } expect(hookCalls).toEqual([ - { hook: 'beforeChange', id: 'sched-1', published: true }, + { hook: 'postValidate', id: 'sched-1', published: true }, { hook: 'afterChange', id: 'sched-1', published: true }, - { hook: 'beforeChange', id: 'unsched-1', published: false }, + { hook: 'postValidate', id: 'unsched-1', published: false }, { hook: 'afterChange', id: 'unsched-1', published: false }, ]) expect((await readDocument('post', 'sched-1'))?.hookStamped).toBe(true) @@ -1058,7 +1058,7 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { const dir = makeTempDir() setupTestCms(dir, undefined, { hooks: { - beforeChange: ({ + postValidate: ({ id, doc, actor, diff --git a/packages/ui-react/tests/interface-view.test.tsx b/packages/ui-react/tests/interface-view.test.tsx index 3ad9b2d2..12887068 100644 --- a/packages/ui-react/tests/interface-view.test.tsx +++ b/packages/ui-react/tests/interface-view.test.tsx @@ -63,6 +63,8 @@ it('keeps invalidations from an interrupted partial refresh when another collect ) render() await screen.findByRole('heading', { name: 'Live report' }) + // The stream opens in a passive effect that can run after the heading paints. + await waitFor(() => expect(Stream.current).toBeDefined()) act(() => Stream.current.dispatchEvent(new Event('connected'))) await waitFor(() => expect(api.readInterface).toHaveBeenCalledTimes(2)) await waitFor(() =>