# Block document format

The stored shape of a page built with blocks, and what is frozen about it.

A page built with blocks is stored as one JSON document. This page is the
format's specification: what a document contains, which parts are fixed, and
which parts are expected to grow.

It is written for anything that produces or consumes a document without going
through an editor — a migration script, a content generator, an AI agent
writing a page, or a build step reading one.

## What this format covers

This is the document format of `@nextlyhq/blocks-engine`. It is what the
`blocks` field stores and what `@nextlyhq/blocks-react` renders.

The `@nextlyhq/plugin-page-builder` editor writes this format too: its `pages`
collection stores each page in a `blocks` field named `content`. Use this
specification for that field, for the engine, for the renderer, and for anything
you generate yourself.

## Checking a document

```ts
import { parseBlockDocument } from "nextly";

declare const value: unknown; // the document you did not write

const result = parseBlockDocument(value);
if (!result.success) {
  console.error(result.issues);
}
```

`parseBlockDocument` is the entry point to use on a document you did not write.
It bounds both nesting **depth** and node **count** before parsing, so a hostile
or merely broken input comes back as invalid rather than consuming the process
doing the checking. Depth matters because the schema is self-referential, and a
long enough chain of nested slots exhausts the call stack; count matters because
a document can be shallow and still enormous, and parsing walks and copies the
whole forest before it can report anything.

The underlying schema is deliberately not exported, because those bounds are a
precondition rather than an option.

For a consumer with neither TypeScript nor zod, the format is also published as
plain JSON Schema:

```ts
import { blockDocumentJsonSchema } from "nextly";
```

It is derived from the same definition this package checks against, so what is
published cannot describe a different format from what Nextly accepts.

### What it does not repair

Anything it accepts, it returns **unchanged**. A checker that quietly tidied its
input would hand you a document the engine still rejects, with the diagnostic
already discarded — so unknown fields survive, and a malformed token reference
stays malformed for the engine to report.

> **Known limitation: the caps assume an ordinary object.** `parseBlockDocument`
> establishes its size, depth and node bounds by reading property descriptors,
> and then hands the same value to the schema, which reads it by ordinary
> property access. For anything `JSON.parse` produces, or any object you built
> yourself, those two readings are identical.
>
> A `Proxy` can make them differ. One whose descriptors report an empty array
> while its `get` returns thousands of nodes passes every bound and is then
> walked in full, so the bounds do not hold for it. A non-enumerable named
> property on an array is invisible in the same way, and survives on the value
> you get back although storage drops it.
>
> Both have the same cause — two readers of one untrusted value — and the fix is
> to have the bounded walk produce the value everything downstream uses, which
> changes what this function RETURNS and so is being done as its own change
> rather than folded in here. **Pass a value you own, or one from
> `JSON.parse`, and neither case arises.**

**It answers a narrower question than the engine does.** The schema asks *is
this the block document format at all*; `validate(doc, ctx)` asks *is this a
legal document for this app*, against the blocks that are actually registered
and the breakpoints that are actually configured. A document can satisfy the
schema and still be rejected — an unregistered block type, for example, is
invisible to a static schema.

Where the schema cannot be exact it stays permissive, because refusing a
document Nextly would have accepted is worse than accepting one the engine
rejects a moment later with a better message.

## The envelope

```json
{
  "formatVersion": 1,
  "kind": "page",
  "nodes": [],
  "settings": { "styles": {}, "customCss": "", "seo": {} },
  "assets": { "mediaIds": [] }
}
```

`nodes` is a plain array: a page **is** a list of sections. There is no
synthetic root block, so nothing has to special-case an undeletable, unmovable
pseudo-node. Document-level concerns live on the envelope instead.

`kind` is closed:

| kind        | what it is                                                           |
| ----------- | -------------------------------------------------------------------- |
| `page`      | an entry's blocks-field content                                      |
| `pattern`   | a copy-on-insert saved subtree, including full-page patterns         |
| `component` | a linked, reusable definition with exposed props, slots and variants |
| `region`    | a layout region such as a header or footer                           |
| `template`  | a collection template                                                |

A layout is a named bundle *referencing* region documents, so it is not a kind of
its own.

## A node

```json
{
  "id": "01J...",
  "type": "core/heading",
  "version": 1,
  "props": { "text": "Hello", "level": 2 }
}
```

`id` is the only way anything addresses a node. Editor operations, locale
overlays, scoped-CSS class derivation and selection all key on it. **Positional
addressing is never part of any stored or public contract** — an operation that
said "the third child" would break the moment anything moved.

`version` is required on every node, not defaulted. It records which schema
version of its block the node was written against, and both forgiving rendering
and migration read it unconditionally. A node without one cannot be migrated,
only guessed at.

Optional fields: `bindings`, `slots`, `styles`, `classes`, `visibility`,
`locked`, `name`, `customCss`, `cssId`, `attributes`, `migrationFailed`.

### Bindings

A binding is a typed field path, never an expression:

```json
{ "$bind": "title", "source": "entry", "fallback": "Untitled" }
```

`source` is one of `entry`, `item`, `single` or `site`. **`single` requires
`sourceKey`**, the slug of the document to read from; the other sources are
implied by the render context. A binding naming `single` without a key resolves
to nothing at read time, so the format rejects it at the point where the slug
can still be supplied.

`fallback` is what renders when the bound value is empty or the binding cannot
be used. It must be a valid value of the prop. It is separate from `props`: the
prop keeps its own value there, which renders when the binding cannot be used
and has no valid fallback, and which stays when the binding is removed.

#### How a published page resolves bindings

Before blocks render, one pass fills each bound prop with its source's value,
so a block receives an ordinary prop and never sees the binding. Pass the
sources to `PageRenderer` as `bindings`. A route made with `createBlocksPage`,
`createPublicBlocksPage` or a Single's page factory reads them for you: the
entry, each Single and the site settings the page binds, each through the
route's public reader at one claim on the page's query budget, and the field
shapes each binding is checked against. A collection list hands each item to
its children. A binding to a source nobody read renders its fallback.

* **Sources.** `entry` is the entry the page shows, `item` the entry a
  collection list is drawing, `single` the Single named by `sourceKey`, and
  `site` the public site settings (`applicationName`, `siteUrl`, `logoUrl`,
  `timezone`), read from the instance the route is given as `nextly`, or the
  process's registered one when it is given none.
* **Public access.** Every source is read as an anonymous visitor reads it:
  published content only, and only fields the public may read. The route reads
  the entry again for this, rather than using the row it resolved, so a field
  the public may not read renders the fallback, and a draft preview shows the
  published values. The renderer never takes a value from `context.entry`.
* **One hop.** A path follows at most one to-one relation (`author.name`). The
  route reads the related entry by id through the public reader, at one more
  claim. A path through a field that holds a list, or past a second relation,
  renders the fallback. A relation on a list item's binding is not followed
  yet: it renders the fallback.
* **Empty values.** Absent, `null`, `""`, an empty list and rich text with
  nothing in it render the fallback, or the prop's own value when there is no
  fallback. `false` and `0` are values.
* **Formats.** `date` (a preset such as `{ "dateStyle": "long" }`, or parts
  such as `month` and `day`), `number` and `currency` (with an ISO 4217
  `currency`) format in the page's language, or English when the page has
  none; `options.locale` overrides it. A format turns a value into text, so it
  applies to text props only. A date picked as a day keeps its day in every
  time zone, and a month shows its month and year. A time of day picked
  without a date shows only its time, in UTC, never its placeholder date. A
  date-time is shown in the route's `timeZone`, else the site's time zone,
  else UTC. `relativeTime` and `list` are not applied yet: the value shows as it
  is when it fits the prop, and the fallback otherwise.
* **Dates keep their machine value.** A block receives a `bound` argument
  naming each bound prop. For a date, `bound.<prop>` is
  `{ kind: "date", datetime }`, and the core text blocks wrap the text in
  `<time datetime>`.

#### Bindings that break a rule

Every binding is checked before its value is used, whether or not it was
checked when it was saved, and none fails the page:

* a binding to a prop the block does not have fills nothing;
* a path past one relation or through a list, a field the source does not
  have, a field whose type does not fit the prop (a number reaching a text prop
  without a format), and a format a formatter would refuse (an unknown currency,
  an invalid locale or option) each render the fallback;
* a fallback that is not a valid value of the prop is ignored, and the prop's
  own value renders.

Each one is reported to `onBindingIssues` with a code from
`BINDING_ISSUE_CODES`, never with the value its source holds. The routes log
one warning per report, naming the page.

#### Image bindings

An image prop (`media` or `upload`) binds to a media field or a URL field:

* **A media field** fills the prop with the record's id, populated or not
  (and through the `{ relationTo, value }` an upload field to several
  collections holds, in the arm for that media collection), and
  the image draws exactly as one whose media was picked: the record's address,
  alternative text and size. The block's own alternative text wins over the
  record's. An upload field to another collection than the one the
  route reads media from (its `mediaCollection`, else Nextly's `media`
  library) names records the lookup doesn't read, so it renders the fallback.
* **A URL field** fills it only with an image address: `https://`, `http://`
  or a path on the site (`/media/a.png`). `javascript:`, `data:`, `mailto:`,
  a relative path and `//host` are not image addresses, so they render the
  fallback. The address keeps the block's own alternative text, and has no
  size.
* **The fallback** is an image address. Any other value, a media id
  included, is refused when the document is saved and ignored when it
  renders. With no value to draw and no fallback, the prop keeps its own
  value, as any bound prop does.
* **What draws.** An address goes through the same scheme and host checks as
  a typed one, so a host outside the site's `remotePatterns` is not loaded. A
  value that can't be drawn, a record the host can't find included, shows the
  fallback, then nothing; never the block's own typed address and never an
  empty image.
* **No responsive sizes.** An image draws one address with its width and
  height, as a picked one does: there is no `srcset` or size variant yet.

A block receives `bound.<prop>` as
`{ kind: "image", holds: "media" | "address", from: "value" | "fallback" | "own", fallback? }`,
so a contributed block can tell an id to look up from an address to draw.
Its `seo` receives the same values as `seo(props, { bound })`, so the page's
metadata offers the picture the page draws.

#### Bindings checked when a document is saved

With the Page Builder plugin, saving a document checks its bindings by the
same rules, on its blocks and in its own metadata (`settings.seo`), through
the API as in the editor, and refuses one that breaks them, naming the
binding and the code. The fields are read as the source declares them, not as
a visitor may read them: a binding to a field visitors may not read is saved,
and the published page renders its fallback. `createdAt` and `updatedAt` are
dates where a read of the source returns them: an entry's both, unless its
collection turns timestamps off, and a Single's `updatedAt` alone. Only the
sources the document binds are read: the page's own entry, each Single it
names, and the collection a path's one relation leads into, through any group
on the way. A document binding more than 32 of them is refused. A path into a
built-in collection such as `media` or `users` is judged by its length, as
the renderer judges it.

A binding a schema change broke after the document was saved is kept: a field
renamed or removed, a Single's field renamed, a bound prop's type changed, or a
bound prop removed. The document still saves, with the binding as it was, and
renders it as the list above says. The same binding added to another block is
refused, since that one is the save's own.

Not checked at save: a binding to a list item, whose fields depend on the list
around it; a binding to the site settings, whose fields are a fixed set; and
any binding in a write made inside a transaction (a batch or an import), whose
schema read could wait behind the transaction's own connection. A
component's own document has no entry, so its bindings to the entry are checked
when a page that places it is saved, against that page's entry, and named by
the component.

#### Bindings checked when a document is saved

With the Page Builder plugin, saving a document checks its bindings by the
same rules, on its blocks and in its own metadata (`settings.seo`), through
the API as in the editor, and refuses one that breaks them, naming the
binding and the code. The fields are read as the source declares them, not as
a visitor may read them: a binding to a field visitors may not read is saved,
and the published page renders its fallback. `createdAt` and `updatedAt` are
dates where a read of the source returns them: an entry's both, unless its
collection turns timestamps off, and a Single's `updatedAt` alone. Only the
sources the document binds are read: the page's own entry, each Single it
names, and the collection a path's one relation leads into, through any group
on the way. A document binding more than 32 of them is refused. A path into a
built-in collection such as `media` or `users` is judged by its length, as
the renderer judges it.

A binding a schema change broke after the document was saved is kept: a field
renamed or removed, a Single's field renamed, a bound prop's type changed, or a
bound prop removed. The document still saves, with the binding as it was, and
renders it as the list above says. The same binding added to another block is
refused, since that one is the save's own.

Not checked at save: a binding to a list item, whose fields depend on the list
around it; a binding to the site settings, whose fields are a fixed set; and
any binding in a write made inside a transaction (a batch or an import), whose
schema read could wait behind the transaction's own connection. A
component's own document has no entry, so its bindings to the entry are checked
when a page that places it is saved, against that page's entry, and named by
the component.

#### Documents whose bindings no longer fit

The Page Builder keeps a report of every document holding a binding that no
longer fits what it reads, so authors can find and fix them after a schema
change. Each save marks its document, and a background job judges it as
stored, soon after; every document is checked again once a collection's or a
Single's fields, a block's props, a component or a Layout change, the job
walking the site a part at a time. A page is judged with the components it
places and its Layout's regions, against its own entry, as its published page
draws them. Each row says which block and prop the binding fills, what it reads, the
codes above, and what a visitor sees instead: the binding's fallback, the
block's own value, or nothing for a prop the block no longer has.

```text
GET /admin/api/plugins/@nextlyhq/plugin-page-builder/bindings-to-fix
```

It answers people who can update pages, listing only the documents the caller
may read, each by its title, and only the bindings in blocks fields their field
rules let them read. A binding inside a component a page places is listed on
that page, judged against its entry. `?document=<key>` narrows it to one
document, `?place=` to one place (`pages`, `components`, `patterns`, `layouts`,
`entries` or `singles`), and `?page=` pages it, a hundred documents a page. Its `meta` adds the number of broken bindings in each
place (`byPlace`), their total (`bindings`), when every document was last
checked (`checkedAt`), and whether a check is under way (`checking`).

#### The document's own metadata

`settings.seo` holds the title, description and social image a document states
for its page as a whole. A collection template uses it to give each entry's
page its own metadata:

```json
{
  "settings": {
    "seo": {
      "title": [
        { "$bind": "title" },
        " | ",
        { "$bind": "applicationName", "source": "site" }
      ],
      "description": [{ "$bind": "excerpt", "fallback": "Read the post." }],
      "image": { "$bind": "featuredImage" }
    }
  }
}
```

* **Text is a list of segments**, joined in order: a string is literal text,
  used as written, and an object is a binding, filled the way a text prop's
  binding is, with its checks, format and fallback. It is never a template
  string: nothing in the literal text is read as a placeholder. A value holds
  at most 32 segments, each literal at most 1,000 characters.
* **The image is one binding**, to a media field (its address when the read
  populates it, its media otherwise) or a URL field. Any other field renders the
  binding's fallback. An address goes through the same scheme and host checks
  as a picture on the page.
* **Sources** are the entry, a Single and the site settings. A list item is
  refused when the document is saved, since the metadata is read once for the
  page.
* **What wins.** A value the document states replaces what its blocks offer for
  that field, so `metadata`'s `derived` argument carries it. The document's
  image is tried before the blocks' images. A blank value states nothing, and
  the blocks answer.

### Visibility

```json
{
  "conditions": [[{ "field": "tier", "op": "equals", "value": "vip" }]],
  "devices": { "mobile": false }
}
```

The two mechanisms are deliberately separate and must not be conflated:

* **`conditions`** decides whether a node is *served*. A hidden node is omitted
  from server output entirely, not CSS-hidden. Stored as OR-of-AND (outer array
  ORs, inner arrays AND) from the start, so a richer editing UI never needs a
  storage migration.
* **`devices`** decides whether a *served* node is shown at a breakpoint. This
  is presentation, and it is CSS-based.

Conflating them would either leak a conditioned node into the payload or stop a
hidden-on-mobile node being indexed.

A condition names one field of the entry the page shows, or of the list item
when the block is inside a list. Its `op` is one of `equals`, `not_equals`,
`contains`, `not_contains`, `greater_than`, `less_than`, `exists`, `not_exists`,
`is_true` and `is_false`. Which ones a field takes depends on its kind: an order
only on a number or a date (compared by whole days, written `YYYY-MM-DD`), text
search only on text, and only `exists` and `not_exists` on a field holding
several values. The older spellings `eq`, `ne`, `neq`, `gt` and `lt` are read
as the operators they name. A condition may check only a field the public may
read, since whether the block shows would otherwise reveal its value. Saving
refuses any other operator or field.

The published page decides conditions on the server, against the entry as
an anonymous visitor reads it: its published values, and only the fields the
public may read. A block whose conditions hold is served; one whose conditions
don't hold is left out of the HTML, its styles and the page's metadata. A block
inside a list is decided for each entry the list draws, against that entry.

> **A condition that can't be checked fails CLOSED.** An unknown operator or
> field, a field the public may not read, a value of the wrong type, or a page
> with no entry to check all leave the block out for every visitor, and the
> route logs which block and why. Showing everyone what was meant for some of
> them cannot be taken back, while content missing from a page is visible and
> reportable.
>
> `devices` is unaffected and works as described.

### Styles

```json
{
  "base": {
    "desktop": { "padding": "16px", "color": { "$token": "brand.primary" } }
  }
}
```

Two axes: state, then breakpoint. The **state** axis is closed — `base`,
`hover`, `focus`, `active`. The breakpoint axis is not, because breakpoint ids
are site configuration.

A value of `{ "$token": "..." }` is a design-token reference rather than a
literal.

## What is frozen, and what may still change

The format follows one rule: **additive-open, semantically-closed.**

| change                                             | cost                   |
| -------------------------------------------------- | ---------------------- |
| a new style property                               | free; no format change |
| a new optional field                               | free                   |
| removing a field                                   | a format migration     |
| changing what an existing field means              | a format migration     |
| widening a closed vocabulary (`kind`, style state) | a format migration     |

So the format can grow without breaking stored documents. What it cannot do is
change its mind about something already written.

The frozen surface is:

1. **The document and node shapes** above, including `Binding`, `NodeVisibility`,
   locale overlays, the component-instance node shape, and the document limits.

   The freeze is over the **stored shape**, not over runtime behaviour. `Binding`
   is resolved on published pages, and `NodeVisibility.conditions` is decided
   on them (see the notes in those sections). That was the intended order: a
   document written against the frozen shape stayed valid when resolution and
   evaluation arrived, whereas shipping a shape that later had to change would
   have invalidated everything already stored.

2. **The typed-style envelope** — the states × breakpoints structure and the
   token-reference convention. The style *property catalog* inside it is
   additive-open and is not frozen.

3. **The validation API** — `validate(doc, ctx) → ValidationIssue[]`, where an
   issue is `{ path, code, message, suggestion?, severity }` and `path` is an
   RFC 6901 JSON Pointer.

   > **`customCss` is stored, and nothing reads it yet.** The field is part of
   > the frozen shape on both a node and the document settings, and no validator
   > inspects it and no compiler emits it. Custom CSS has to be sanitized before
   > it can be written into a page at all, and that sanitizer does not exist, so
   > the value round-trips through storage and reaches no stylesheet. Do not
   > rely on it to style anything yet.

4. **The tree primitives and the reserved operation vocabulary.** The primitives
   are pure, id-addressed functions over a forest: insert, remove, move, reid,
   update.

   The editor's operation layer **builds on** these; it does not mirror them.
   The primitives are permissive by design — `removeNode` removes every node
   matching an id — while the operation layer refuses cases a stored, replayable
   edit cannot express safely, such as an id that appears twice, where an
   inverse could only ever restore one of them. That difference is deliberate,
   and closing it would reintroduce silent data loss.

5. **The manifest artifact format**, whose block entries carry name, version,
   description, example, prop schemas, serialized `supports`, and slot rules.

6. **The bindability rule** — whether a prop can be bound is derived from its
   field type, never opted into per block. The predicate is `isBindablePropType`.

7. **The registry read API.** A plugin contributing blocks does so through the
   page builder's block-registration service rather than a core `contributes`
   key — blocks belong to the page builder, not to Nextly — so the shape frozen
   here is the read side (`getBlock`, `allBlocks`, `getBlockSource`,
   `getSupport`, `allSupports`), not a contribution field.

### Reserved operation names

⚠️ **These names are reserved, not yet callable.** None of them is implemented
today. They are listed here so that nothing else claims one before the
composition features ship, and so an implementer can see the intended shape.

| name                 | what it will do                                         |
| -------------------- | ------------------------------------------------------- |
| `saveAsPattern`      | save a subtree as a copy-on-insert pattern              |
| `saveAsComponent`    | save a subtree as a linked, reusable component          |
| `convertToComponent` | replace a subtree in place with a component instance    |
| `detachComponent`    | replace a component instance with a copy of its content |

The reservation is a value rather than a sentence, because a list that exists
only in prose cannot be consulted by the code that would have to honour it:

```ts
import {
  RESERVED_OPERATION_NAMES,
  isReservedOperationName,
} from "@nextlyhq/blocks-engine";
```

An operation layer should refuse a reserved name it does not implement, rather
than reporting it as unknown. "Unknown operation" invites a caller to define
their own `saveAsPattern`, which is the collision the reservation exists to
prevent, and it would surface only once the real one shipped.

When these are built they will be operations and API actions rather than editor
gestures, so a script or an agent can perform them without driving a UI.

## What documents never contain

**Custom JavaScript.** There is no mechanism for custom JS anywhere in the
format, and this is a deliberate limit rather than an unbuilt feature — unlike
the reserved fields above, it is not waiting on an implementation.

A block may carry custom CSS at the document level and per node. That CSS is
**not** sanitized today, because the sanitizer does not exist; the field is
stored and nothing reads it (see the note on `customCss` above). Sanitization is
a precondition of ever emitting it, not a property it already has.
