# Write content from code

Seed or import OrbPage pages and menus from a script. Sign in, write and publish a body, mint ids, use library pictures and pass the audit.

A seed, an import or a migration writes OrbPage content through `manageContent` from
`@orbpage/client`, on the same drafts and versions editors use in the admin. By the end of this
page your script makes a page and a menu, publishes both, and a second run changes nothing.

## Write and publish a page

```ts
import { manageContent } from "@orbpage/client";

const content = manageContent({
  baseUrl: process.env.ORBPAGE_URL, // http://localhost:8807 in pnpm dev
  token: process.env.ORBPAGE_STAFF_TOKEN,
});
const run = crypto.randomUUID();

const shipping = await content.ensurePage(
  { locale: "en", title: "Shipping", slug: "shipping" },
  `${run}:shipping`,
);
if (!shipping.ok) throw new Error(`OrbPage made no page: ${shipping.problem.code}`);
const { id } = shipping.content;

const opened = await content.page(id, "en");
if (!opened.ok) throw new Error(`OrbPage opened no draft: ${opened.problem.code}`);
```

The body names the slots and sections your shop [declared](/docs/shop/sections) for pages:

```ts continues
const text = {
  type: "doc",
  content: [{ type: "paragraph", content: [{ type: "text", text: "We ship within two days." }] }],
};

const applied = await content.applyPage(
  id,
  "en",
  {
    basedOn: opened.content.draft?.revision ?? null,
    content: {
      title: "Shipping",
      slug: "shipping",
      seo: { description: "How Clay & Crema ships coffee and stoneware." },
      slots: { body: [{ id: "sec_shippingtext", type: "text", settings: { body: text } }] },
    },
  },
  `${run}:shipping:en`,
);
if (!applied.ok) throw new Error(`OrbPage refused the page: ${applied.problem.code}`);
applied.content.status; // "applied", or "unchanged" when this body is already live
```

`ensurePage` finds the page that holds the address in the locale, drafted or live, or makes it.
`applyPage` saves the body as the draft and publishes it in one call.

- **`basedOn`** is the draft revision you read, `null` when the entry has no draft. A newer
  draft answers `draft_stale`, so an editor's work is never overwritten unread.
- **The idempotency key** makes a retry safe. The client sends `:save` and `:publish` keys
  derived from it; reusing a key for another body answers `idempotency_key_reused`.
- **A malformed body** throws a `ZodError` before anything is sent: an id, a link or the shape
  of a slot. OrbPage checks settings against your declaration and answers `body_invalid`,
  with a pointer such as `#/body/content/slots/body/0/settings/body`.

The home page is never made: it is always `homePageId` (`pag_home00000000`) and has no `slug`.

## Sign in from a script

| Where                      | Credential                              | `manageContent` takes |
| -------------------------- | --------------------------------------- | --------------------- |
| `pnpm dev` on your machine | The owner's staff token, from a sign-in | `token`               |
| A deployment script        | The environment's operator key          | `operatorKey`         |
| A person's tool            | A staff token with Content edit         | `token`               |

### Sign in as the owner locally

`pnpm dev` writes the owner's email and password into `catalog/.env`. Sign in at the admin, as a
browser would, and ask for a staff token:

```ts continues
const admin = "http://localhost:8789";
const signedIn = await fetch(`${admin}/api/auth/sign-in/email`, {
  method: "POST",
  headers: { "Content-Type": "application/json", Origin: admin },
  body: JSON.stringify({
    email: process.env.ORBCATALOG_OWNER_EMAIL,
    password: process.env.ORBCATALOG_OWNER_PASSWORD,
  }),
});
const cookie = signedIn.headers
  .getSetCookie()
  .map((each) => each.split(";")[0])
  .join("; ");
const answer = await fetch(`${admin}/api/auth/token`, { headers: { Cookie: cookie } });
const { token } = (await answer.json()) as { token: string };
```

The same token reads the catalog's media library. The local OrbPage has no operator key until
you set `OPERATOR_KEY_HASH` in its Worker's environment.

### Use the operator key when deployed

```ts continues
const deployed = manageContent({
  baseUrl: process.env.ORBPAGE_URL,
  operatorKey: process.env.ORBPAGE_OPERATOR_KEY,
});
```

[Deployment](/docs/run/deployment#set-up-catalog-and-orbpage-from-code) shows how to issue the key.
It configures the site, declares, and adds, saves and publishes pages, menus, forms, templates
and category content. It cannot withdraw, roll back, archive, restore or delete, and it cannot
publish over the audit's errors: those take a staff token.

## Write a menu

```ts continues
const footer = await content.addMenu("footer", `${run}:menu:footer`);
if (!footer.ok) throw new Error(`OrbPage opened no menu: ${footer.problem.code}`);
const menu = await content.menu(footer.content.id, "en");
if (!menu.ok) throw new Error(`OrbPage opened no draft: ${menu.problem.code}`);

const coffee = {
  id: "itm_coffee000001",
  label: "Coffee",
  link: { kind: "category", ref: "coffee" },
} as const;

const written = await content.applyMenu(
  footer.content.id,
  "en",
  {
    basedOn: menu.content.draft?.revision ?? null,
    content: { items: [{ id: "itm_colshop00001", label: "Shop", children: [coffee] }] },
  },
  `${run}:menu:footer:en`,
);
if (!written.ok) throw new Error(`OrbPage refused the menu: ${written.problem.code}`);
```

`addMenu` opens the entry of a menu your declaration names, new or existing, so a second run
finds the same one. A menu's body as JSON:

```json
{
  "items": [
    {
      "id": "itm_colshop00001",
      "label": "Shop",
      "children": [
        {
          "id": "itm_coffee000001",
          "label": "Coffee",
          "link": { "kind": "category", "ref": "coffee" }
        },
        {
          "id": "itm_journal00001",
          "label": "Journal",
          "link": { "kind": "page", "id": "pag_uxfcp1ysqmn5" }
        }
      ]
    },
    {
      "id": "itm_workshops001",
      "label": "Workshops",
      "link": { "kind": "path", "path": "/en/workshops" }
    },
    {
      "id": "itm_contact00001",
      "label": "Contact",
      "link": { "kind": "url", "href": "mailto:hello@claycrema.test" }
    }
  ]
}
```

An entry without a link heads its children, as a footer's column does. Children go one level
deep. A level holds at most 30 entries and a label at most 60 characters. A menu links to a
`page`, a `category`, a `path` or a `url`.

## A complete page body

The home page of Clay & Crema, as `applyPage` sends it in English:

```json
{
  "title": "Clay & Crema",
  "slots": {
    "body": [
      {
        "id": "sec_hero00000001",
        "type": "hero",
        "settings": {
          "title": "Slow coffee,",
          "picture": { "media": "med_j9ag8qeq8697", "decorative": true },
          "primary": { "kind": "category", "ref": "coffee" },
          "primaryLabel": "Shop coffee"
        }
      },
      {
        "kind": "row",
        "id": "row_tiles0000001",
        "layout": "halves",
        "columns": [
          [
            {
              "id": "sec_tilecoffee01",
              "type": "tile",
              "settings": {
                "title": "Coffee",
                "picture": { "media": "med_4k2v9x7p1q3m" },
                "link": { "kind": "category", "ref": "coffee" },
                "linkLabel": "Coffee"
              }
            }
          ],
          [
            {
              "id": "sec_tileceramic1",
              "type": "tile",
              "settings": {
                "title": "Ceramics",
                "picture": { "media": "med_8w3n5r2t6y0z" },
                "link": { "kind": "category", "ref": "ceramics" },
                "linkLabel": "Ceramics"
              }
            }
          ]
        ]
      },
      {
        "id": "sec_newpieces001",
        "type": "productRow",
        "settings": {
          "title": "New from the kiln",
          "products": { "kind": "category", "ref": "ceramics", "limit": 4 }
        }
      },
      {
        "id": "sec_journal00001",
        "type": "journal",
        "settings": { "title": "From the journal", "stories": ["pag_uxfcp1ysqmn5"] }
      }
    ]
  }
}
```

A section is `{ id, type, settings }`; `"kind": "section"` may stand beside them. A row is
`{ kind: "row", id, layout, columns }`, as [Arrange rows](/docs/shop/sections#arrange-rows) shows.
Each setting stores the value the "Stored as" column of
[the settings table](/docs/shop/sections#the-settings-a-section-can-have) names. A category or product
is named by the catalog's `ref`, a page by its `pag_` id.

## Mint section, row and entry ids

Your script makes the ids of sections (`sec_`), rows (`row_`) and menu entries (`itm_`): the
prefix and exactly 12 characters of `0-9` and `a-z`. Each is used once in its page or menu. A
readable id such as `sec_shippingtext` is fine. OrbPage makes page and menu ids itself.

Keep an id for the life of its section: the editor and the preview point at it. Derive it from a
name, and a second run sends the same body, which `applyPage` answers `unchanged`:

```ts continues
async function idOf(prefix: "sec" | "row" | "itm", name: string): Promise<string> {
  const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(name));
  const letters = [...new Uint8Array(digest).slice(0, 12)].map((byte) => (byte % 36).toString(36));
  return `${prefix}_${letters.join("")}`;
}

const heroId = await idOf("sec", "home:hero");
```

## Write running text

A `setting.text` stores a document: Tiptap's ProseMirror JSON, limited to a fixed set of nodes.

```json
{
  "type": "doc",
  "content": [
    {
      "type": "heading",
      "attrs": { "level": 1 },
      "content": [{ "type": "text", "text": "Roast days" }]
    },
    {
      "type": "paragraph",
      "content": [
        { "type": "text", "text": "We roast on " },
        { "type": "text", "text": "Tuesdays and Fridays", "marks": [{ "type": "bold" }] },
        { "type": "hardBreak" },
        {
          "type": "text",
          "text": "Read the journal",
          "marks": [
            { "type": "link", "attrs": { "link": { "kind": "page", "id": "pag_uxfcp1ysqmn5" } } }
          ]
        }
      ]
    },
    {
      "type": "bulletList",
      "content": [
        {
          "type": "listItem",
          "content": [
            {
              "type": "paragraph",
              "content": [{ "type": "text", "text": "Beans ship the next day." }]
            }
          ]
        }
      ]
    }
  ]
}
```

| Part   | Allowed                                                                          |
| ------ | -------------------------------------------------------------------------------- |
| Blocks | `paragraph`, `heading` (level 1 to 3), `bulletList`, `orderedList`, `blockquote` |
| Inline | `text`, never empty, and `hardBreak`                                             |
| Marks  | `bold`, `italic`, `link` with `attrs.link` holding a link                        |

Anything else is refused, and a document holds at least one node. A heading's level is relative:
delivery maps level 1 to the page's base level. Pictures, tables and videos inside running text
are blocks the admin's editor writes; write them there.

## Use pictures from the media library

A picture setting holds a file of the catalog's media library by its id. Find it by name with
the catalog's staff client:

```ts continues
import { staffCatalog } from "@orbcatalog/client/staff";

const catalog = staffCatalog({
  url: process.env.ORBCATALOG_URL,
  fetch: (request) => {
    request.headers.set("Authorization", `Bearer ${token}`);
    return fetch(request);
  },
});
const found = await catalog.library({ q: "hero.jpg" });
const file = found.ok ? found.value.files.find(({ name }) => name === "hero.jpg") : undefined;
const hero = file === undefined ? undefined : { media: file.media, decorative: true };
```

`library({ q })` lists every file whose name holds `q`; pass `next` as `after` for the next
page. The setting stores `{ media }`, and `decorative: true` for this use only. Delivery reads
the file's alt text in the page's language from the library. No client uploads a file into the
library today: upload it in the admin, or import it with a product's pictures.

## Pass the publication audit

`applyPage` publishes, so OrbPage's audit runs on every write. Errors block publishing:

| Code                   | Fix                                                       |
| ---------------------- | --------------------------------------------------------- |
| `image_alt_missing`    | Describe the file in the library, or `decorative: true`   |
| `link_text_empty`      | Give the link words; a decorative linked picture has none |
| `heading_empty`        | Write the heading, or remove it                           |
| `video_poster_missing` | Pick a poster for the video                               |

Warnings never block: `link_text_vague`, `link_text_url`, `link_text_ambiguous`,
`link_target_unavailable`, `heading_level_skipped`, `image_alt_file_name`, `image_alt_redundant`,
`image_alt_caption` and `image_alt_long`. Editors see them in the admin.

A blocked write answers `422` with `publish_blocked`; the draft stays saved.
`applied.problem.audit` names each issue:

```json
{
  "code": "publish_blocked",
  "detail": "The audit found errors; fix them, or the owner publishes with a reason.",
  "audit": {
    "issues": [
      {
        "code": "image_alt_missing",
        "severity": "error",
        "message": "Describe this image, or mark it decorative.",
        "path": "slots.body.0.settings.picture",
        "section": "sec_hero00000001"
      }
    ],
    "blocking": true
  }
}
```

Fix the body and apply it again. Only the owner publishes over errors, with
`publishPage(id, locale, { revision, overrideReason }, key)`. Anyone else, the operator key
included, gets `override_forbidden`.

## Customize

| You want to                 | Do this                                                       | Default                     |
| --------------------------- | ------------------------------------------------------------- | --------------------------- |
| Keep what editors published | Skip an entry whose `published` is set                        | `applyPage` writes it again |
| Describe a library picture  | `catalog.editFile(media, { alt: { en } }, key)`               | No alt text                 |
| Write forms                 | `addForm`, then `applyForm`                                   | None                        |
| Write templates             | `addTemplate`, `saveTemplate`, `publishTemplate`              | The default template        |
| Write a category's content  | `addCategory`, `saveCategory`, `publishCategory`              | Follows its template        |
| Retire a page               | `archivePage` or `deletePage` with a staff token              | Stays live                  |
| Take one language offline   | `POST /api/pages/{page}/{locale}/withdraw` with a staff token | Stays live                  |

Withdrawing has no `manageContent` method today; send the request with a staff token and an
`Idempotency-Key`. Menus and forms withdraw at `/api/menus/{menu}/{locale}/withdraw` and
`/api/forms/{form}/{locale}/withdraw`. [Read the content](/docs/shop/content#delete-or-archive-a-page)
covers deleting and archiving.

## Next steps

| You want to                          | Read                                                               |
| ------------------------------------ | ------------------------------------------------------------------ |
| Declare what a body may hold         | [Declare sections and slots](/docs/shop/sections)                       |
| Replace content after a re-declaring | [Re-declare and migrate](/docs/shop/content#re-declare-and-migrate)     |
| Read what your script published      | [Read the content](/docs/shop/content)                                  |
| Issue an operator key                | [Deployment](/docs/run/deployment#set-up-catalog-and-orbpage-from-code) |