Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@ node_modules/
.dev.vars
.DS_Store
packages/frontend/src/assets.generated.ts
packages/frontend/public/scripts/vendor/
packages/frontend/.tmp-site/
packages/frontend/dist/
4 changes: 3 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ Performance is the top priority: every other requirement yields to it.
export is an uncached gateway that must stay cheap (no I/O on the hot path). Anything a page
renders from must be in its `Cache-Tag` (`tagsFor`), or a publish won't purge it. Nothing
personalised or per-request goes in cached HTML: no nonces, cookies or user data. Drafts live
only under `/__preview`.
only under `/__preview`, and so do the editing marks (`data-cw-ref`, `data-cw-slot`, through
`ctx.ref`), `scripts/live-preview.js` and `styles/preview.css`: a public render never changes
for live preview (`test/public-golden.test.ts`, `test/preview-marks.test.ts`).

- **The HTML is finished at first byte.** Sections, wrappers, buttons, image attributes and the
LCP choice are decided in the Worker. Block JS may add behaviour, elements and attributes; it
Expand Down
53 changes: 50 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,9 +134,56 @@ content and cached at the edge.
## Preview drafts

Set the entry preview link in ContentWorker to
`https://<your site>/__preview?entry={id}&token={token}`. Drafts render under `/__preview/…`,
never cached and never indexed. If your Preview API isn't at `api.<domain>`, set
`CONTENTWORKER_PREVIEW` to its origin.
`https://<your site>/__preview?entry={id}#token={token}`. The token rides in the fragment, so it
never reaches a server log or a `Referer`: the site answers a tiny page that reads it, removes it
from the address bar and history, and submits it in a same-origin form POST for an HttpOnly
cookie scoped to `/__preview`. The older `?entry={id}&token={token}` form still works. Drafts render
under `/__preview/…`, never cached and never indexed. If your Preview API isn't at
`api.<domain>`, set `CONTENTWORKER_PREVIEW` to its origin.

A preview link is a bearer link: anyone who opens it sees that entry's draft for an hour, in
their own browser, under `/__preview` only. Share it like a password. Prefer the `#token=` form;
`?token=` puts the token in the request URL, so it can reach request logs.

### Live preview in the admin

The ContentWorker admin frames `/__preview` pages (the entry editor's Site pane and the canvas)
and re-renders each unsaved edit in them, through `connectPreview` from
`@contentworker/sdk/live-preview`, which the runtime serves for you.
Preview responses may be framed by the admin's origin only (`Content-Security-Policy:
frame-ancestors <admin>`) and send no `Referer`; public pages still refuse every frame but their
own. The admin's origin comes from your backend setting: `cdn.<domain>` (or a
`CONTENTWORKER_PREVIEW` of `api.<domain>`) means the admin is `https://<domain>`. Otherwise, or
over a service binding with a bare namespace, set it:

```jsonc
"vars": { "CONTENTWORKER_ADMIN": "https://<your admin host>" }
```

It must be an https origin (http only on localhost). A value that isn't one is logged and
framing stays off, as it does when no admin can be found or the derived one is the site itself;
public pages are never affected. The preview cookie is `SameSite=None; Secure; Partitioned`, so it
works inside the admin's frame and lives only in the admin's partition there. A preview link sets
it only when opened as a page (top level or in a frame), never as an image or other subresource.

Under `/__preview`, the draft's markup says what is editable, in the content-ref format of
`@contentworker/sdk`: `data-cw-ref` on the page's own fields (`title`, `body`), on each block
(`sections[<key>]`) and on fields inside it (`sections[<key>].heading`), and `data-cw-slot` (the
`sections` ref) on the element holding the blocks. Public pages carry none of it. A page showing
the draft also loads `scripts/live-preview.js`, which connects only when the admin frames it,
re-renders edited blocks through `POST /__preview/render` in the site's locale
(`CONTENTWORKER_LOCALE`), and shows Coworker's proposed blocks as ghosts (`styles/preview.css`).

On every `/__preview` page, links to the site's own pages point to `/__preview/<path>`, so browsing
in the admin's frame shows drafts where they exist and published content elsewhere; external,
`mailto:`, `tel:` and fragment links are left alone. Loaded in a frame, the preview bar drops its
exit link: the admin has its own controls, and public pages can't load inside its frame. Your
own block renderers can mark their fields too: `<h2${ctx.ref('heading')}>` adds the field's ref
under preview and nothing on public pages.

A block that styles itself from content writes CSS custom properties with
`attrs({ style: ctx.cssVars({ '--accent': fields.accent }) })`: every value is checked with the
SDK's `isSafeTokenValue` on every render, and an unsafe one is dropped whole.

## Develop

Expand Down
8 changes: 7 additions & 1 deletion biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,13 @@
},
"files": {
"ignoreUnknown": true,
"includes": ["**", "!**/.wrangler", "!**/node_modules", "!**/worker-configuration.d.ts"]
"includes": [
"**",
"!**/.wrangler",
"!**/node_modules",
"!**/worker-configuration.d.ts",
"!packages/frontend/public/scripts/vendor"
]
},
"formatter": {
"enabled": true,
Expand Down
29 changes: 18 additions & 11 deletions docs/budget.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,19 @@
The target is Lighthouse 100 in all four categories, on mobile and desktop, for every page. These
budgets keep it there as a site adds blocks. `budgets.json` is enforced by `npm run budgets` in CI.

| What | Budget (gzip) | Why |
| -------------------------------------------------- | -------------------------------------- | --------------------------------------------------------------------------------------------- |
| `styles/critical.css` | 8 KB | The only render-blocking stylesheet. |
| Critical JS (`enhance.js`, `boot.js`, `shared.js`) | 10 KB | Modules never block, but they compete with the LCP image. |
| Deferred CSS (`deferred.css`, `fonts.css`) | 8 KB | Loaded after the first section. |
| Idle JS | 20 KB | Runs 3 s after `load`; still counts toward TBT on slow phones. |
| Each block | 3 KB CSS, 4 KB JS | Blocks add up; a block over this needs a recorded reason. |
| HTML document | first 14 KB holds head + first section | One round trip to first paint. |
| Requests before LCP | ≤ 5 | Document, critical.css, boot.js (+ enhance.js preloaded), LCP image, first-section block CSS. |
| Third-party before `load` | 0 | |
| What | Budget (gzip) | Why |
| -------------------------------------------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------- |
| `styles/critical.css` | 8 KB | The only render-blocking stylesheet. |
| Critical JS (`enhance.js`, `boot.js`, `shared.js`) | 10 KB | Modules never block, but they compete with the LCP image. |
| Deferred CSS (`deferred.css`, `fonts.css`) | 8 KB | Loaded after the first section. |
| Idle JS | 20 KB | Runs 3 s after `load`; still counts toward TBT on slow phones. |
| Preview JS (`live-preview.js`) | 4 KB | Loads only on `/__preview` pages showing a draft, never on a public page. |
| Preview CSS (`preview.css`) | 1 KB | Linked only by the live preview script, once the admin frames the page. |
| Vendored live preview SDK (`scripts/vendor/sdk/`) | 20 KB | `@contentworker/sdk/live-preview` as published (16 KB today), imported only by `live-preview.js`. |
| Each block | 3 KB CSS, 4 KB JS | Blocks add up; a block over this needs a recorded reason. |
| HTML document | first 14 KB holds head + first section | One round trip to first paint. |
| Requests before LCP | ≤ 5 | Document, critical.css, boot.js (+ enhance.js preloaded), LCP image, first-section block CSS. |
| Third-party before `load` | 0 | |

Field targets (p75): LCP ≤ 1.2 s, CLS ≤ 0.02, INP ≤ 100 ms. Lab: TBT ≤ 50 ms.

Expand All @@ -30,7 +33,11 @@ Field targets (p75): LCP ≤ 1.2 s, CLS ≤ 0.02, INP ≤ 100 ms. Lab: TBT ≤ 5
Record each raised budget here: the block or file, the new number, the measurement that shows
Lighthouse still scores 100, and the date.

_None yet._
- **Vendored live preview SDK, 20 KB (2026-11-09).** The channel's frontend half
(`connectPreview`, message schemas, patching, layout) as `@contentworker/[email protected]` publishes it,
copied unminified by `scripts/embed-assets.ts`: 15,966 B gzip. It loads only on `/__preview`
pages showing a draft, after the page has painted, so it never reaches a public page or the
Lighthouse fixtures. The budget leaves room for SDK patch releases; a larger jump needs a look.

## Measured decisions

Expand Down
12 changes: 6 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions packages/create-site/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
`@contentworker/create-site` follows semantic versioning. Release it like the runtime: bump
`version`, add its section here, merge, then push the tag `create-site@v<version>`.

## 0.1.3

- New sites use `@contentworker/frontend` 0.5.0: live preview in the ContentWorker admin.

## 0.1.2

- New sites use `@contentworker/frontend` 0.4.0, and the `site.css` template names its new
Expand Down
2 changes: 1 addition & 1 deletion packages/create-site/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@contentworker/create-site",
"version": "0.1.2",
"version": "0.1.3",
"description": "npm create @contentworker/site: a new ContentWorker site on @contentworker/frontend, ready to run, optionally with its content model and starter pages.",
"keywords": [
"contentworker",
Expand Down
2 changes: 1 addition & 1 deletion packages/create-site/src/templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/

/** The @contentworker/frontend range new sites depend on; a test holds it to the package. */
export const FRONTEND_RANGE = '^0.4.0';
export const FRONTEND_RANGE = '^0.5.0';
/** wrangler for new sites: the version the runtime is tested with. */
export const WRANGLER_RANGE = '^4.156.1';
export const COMPATIBILITY_DATE = '2026-10-15';
Expand Down
27 changes: 27 additions & 0 deletions packages/frontend/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,33 @@ tokens or options are **minor**; fixes that keep output stable are **patch**.
Bump `version` in `package.json`, add its section here, merge, then push the tag
`frontend@v<version>`: `release.yml` checks and publishes it to npm with provenance.

## 0.5.0

- **Live preview in the ContentWorker admin.** Pages under `/__preview` showing a draft load
`scripts/live-preview.js`, which connects through `connectPreview` from
`@contentworker/sdk/live-preview` (0.3, vendored into `scripts/vendor/sdk/` with its own budget)
when the admin frames the page: unsaved edits re-render through `POST /__preview/render`, only
the blocks that changed when that is safe; Coworker's proposals show as ghosts
(`styles/preview.css`); the page reports its entry (at most `PAGE_REPORT_LIMIT`) to each
session and starts over on `disconnect`.
- Under `/__preview` only, drafts carry content refs with field paths (`data-cw-ref` on the page's
fields, each block and the fields in it, `data-cw-slot` on the blocks' container); block
renderers mark their own fields with `ctx.ref(field)`. Links to the site's pages stay under
`/__preview`. Public pages are byte-identical (a golden test holds them).
- Preview links can carry the token in the fragment (`/__preview?entry={id}#token={token}`): a
tiny page reads it, drops it from history and submits it in a same-origin form POST, so it
never reaches a log or a `Referer`. `?token=` still works, and sets the cookie only for a
navigation. `/__preview/exit?to=` goes only to a path on the site.
- Preview responses may be framed only by the admin (`frame-ancestors`, derived from
`CONTENTWORKER` or the new optional `CONTENTWORKER_ADMIN`; never the site's own origin; a
malformed value is logged and turns framing off), send no `Referer`, and the preview cookie is
`SameSite=None; Secure; Partitioned` (grants also clear the older unpartitioned cookie).
- `ctx.cssVars({...})` is the one way to write CSS custom properties from content: every value
passes `isSafeTokenValue` from `@contentworker/sdk`, on every render, and an unsafe one is
dropped whole.
- `npm run seed` resolves a signed upload URL relative to the API (a local stack answers one).
- Depends on `@contentworker/sdk` ^0.3.0 (its content-ref helpers replace the runtime's copy).

## 0.4.0

**Breaking** for sites that override a runtime file, target its markup, or set CSS tokens. The
Expand Down
3 changes: 3 additions & 0 deletions packages/frontend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,8 @@ Then `wrangler secret put CONTENTWORKER_KEY` (a Content Delivery API key).
`defineSite({ routes })`.
- **Any runtime file:** a file at the same path in your `public/` wins.
- **Content model and starter content:** `npx contentworker-site seed --dry-run`.
- **Live preview:** set a type's preview URL in ContentWorker to
`https://<your site>/__preview?entry={id}#token={token}`; the admin frames it and shows unsaved
edits as you type. `CONTENTWORKER_ADMIN` names the admin when it can't be derived.

The full guide is at https://contentworker.site/integrate.
15 changes: 15 additions & 0 deletions packages/frontend/budgets.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,21 @@
"files": ["styles/deferred.css", "styles/fonts.css"],
"max": 8192
},
{
"name": "preview JS (only /__preview drafts)",
"files": ["scripts/live-preview.js"],
"max": 4096
},
{
"name": "vendored live preview SDK (only /__preview drafts)",
"dir": "scripts/vendor/sdk",
"max": 20480
},
{
"name": "preview CSS (only /__preview drafts)",
"files": ["styles/preview.css"],
"max": 1024
},
{
"name": "idle JS",
"files": ["scripts/idle.js", "scripts/consent.js", "scripts/consented.js"],
Expand Down
3 changes: 2 additions & 1 deletion packages/frontend/content-model/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,8 @@ export async function seed(o: SeedOptions): Promise<SeedReport> {
contentType: 'image/png',
title: { [o.locale]: a.title },
});
const put = await doFetch(created.upload.url, {
// The signed upload URL may be relative to the API (a local stack answers one).
const put = await doFetch(new URL(created.upload.url, o.api).href, {
method: 'PUT',
headers: created.upload.headers,
body: o.image(a.width, a.height, i + 1),
Expand Down
4 changes: 2 additions & 2 deletions packages/frontend/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@contentworker/frontend",
"version": "0.4.0",
"version": "0.5.0",
"description": "The ContentWorker site runtime: edge-cached rendering from the Delivery API, purge on publish, preview, SEO and GEO, and the primary blocks, styles and scripts. Sites need only a wrangler.jsonc.",
"keywords": [
"contentworker",
Expand Down Expand Up @@ -69,6 +69,6 @@
"provenance": true
},
"dependencies": {
"@contentworker/sdk": "^0.2.0"
"@contentworker/sdk": "^0.3.0"
}
}
2 changes: 1 addition & 1 deletion packages/frontend/public/blocks/cards/cards.render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export default function render(entry: Entry, ctx: RenderCtx): Safe {
title ? ctx.raw(`<${itemLevel}>${title}</${itemLevel}>`) : ''
}${item.body ? ctx.richText(item.body) : ''}</div></li>`;
});
return html`${heading ? ctx.raw(`<${level}>${html`${heading}`}</${level}>`) : ''}<ul class="cards-list">${cards}</ul>`;
return html`${heading ? ctx.raw(`<${level}${ctx.ref('heading')}>${html`${heading}`}</${level}>`) : ''}<ul class="cards-list">${cards}</ul>`;
}

export function markdown(entry: Entry, ctx: MarkdownCtx): string {
Expand Down
2 changes: 1 addition & 1 deletion packages/frontend/public/blocks/cta/cta.render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export default function render(entry: Entry, ctx: RenderCtx): Safe {
const href = ctx.href(link ?? url);
const v = VARIANTS.has(variant) ? variant : 'accent';
ctx.headingLevel = 2;
return html`<div class="cta-body">${heading ? html`<h2>${heading}</h2>` : ''}${body ? ctx.richText(body) : ''}${
return html`<div class="cta-body">${heading ? html`<h2${ctx.ref('heading')}>${heading}</h2>` : ''}${body ? ctx.richText(body) : ''}${
href && label
? html`<p class="cta-row"><a class="button ${v}" href="${href}">${label}</a></p>`
: ''
Expand Down
2 changes: 1 addition & 1 deletion packages/frontend/public/blocks/faq/faq.render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export default function render(entry: Entry, ctx: RenderCtx): Safe {
const level = `h${n}`;
const itemLevel = `h${heading ? n + 1 : Math.max(n, 2)}`;
if (heading && n === 1) ctx.headingLevel = 2;
return html`${heading ? ctx.raw(`<${level}>${html`${heading}`}</${level}>`) : ''}${itemsOf(
return html`${heading ? ctx.raw(`<${level}${ctx.ref('heading')}>${html`${heading}`}</${level}>`) : ''}${itemsOf(
entry,
).map(
(i: Fields) =>
Expand Down
2 changes: 1 addition & 1 deletion packages/frontend/public/blocks/hero/hero.render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@ export default function render(entry: Entry, ctx: RenderCtx): Safe {
const Heading = ctx.headingLevel === 1 ? 'h1' : 'h2';
ctx.headingLevel = 2;
return html`${image ? html`<picture>${ctx.image(image, { sizes: '100vw' })}</picture>` : ''}<div class="hero-body">${ctx.raw(
`<${Heading}>`,
`<${Heading}${ctx.ref('heading')}>`,
)}${heading}${ctx.raw(`</${Heading}>`)}${lead ? ctx.richText(lead) : ''}</div>`;
}
Loading
Loading