brease-client 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,14 +6,30 @@ Typed client for the Brease delivery API. Zero runtime dependencies, ESM + CJS,
6
6
  pnpm add brease-client
7
7
  ```
8
8
 
9
- Set these environment variables (Brease writes them into your Vercel project at onboarding):
9
+ Set these environment variables (Brease writes them into your Vercel or Cloudflare project at onboarding):
10
10
 
11
11
  | Variable | Purpose |
12
12
  | --- | --- |
13
- | `BREASE_TOKEN` | Read-only delivery token (`brs_live_…`). It identifies the site. |
13
+ | `BREASE_TOKEN` | Read-only delivery token (`brs_live_…`). It identifies the site. Brease writes two: a production token for production builds, which reads only published content, and a preview token for preview and development, which also reads the draft content of a known commit or draft branch. Keep both on the server. |
14
14
  | `BREASE_API_URL` | Optional. Defaults to `https://api.brease.io`. Inside a Brease sandbox it points at the local content server. |
15
15
  | `BREASE_REVALIDATE_SECRET` | ISR/SSR sites only: secret for the revalidate route. |
16
16
 
17
+ ## Getting started
18
+
19
+ For an existing Next.js site (other frameworks follow the same steps; see [Astro](#astro) and [Plain HTML](#plain-html--other-servers)):
20
+
21
+ 1. Connect the site in Brease. Onboarding writes the variables above into the hosting project; copy them into `.env.local` for local development.
22
+ 2. Create the client in `lib/brease.ts` with `breaseFetch()` ([Next.js](#nextjs-app-router)).
23
+ 3. Render every page from one catch-all route: `brease.route(path)`, then `getPage(slug, { locale })`, with `generateStaticParams = () => brease.routes()`.
24
+ 4. Move the texts, images and links editors should change into the page's content, in the shapes under [Content links](#content-links) and [Images](#images). Shared parts go on the site-wide `_global` page; menus come from `getNavigation()`.
25
+ 5. Add [editor markers](#editor-markers) (`data-brease`) to the elements that show content.
26
+ 6. Render SEO with `toMetadata(page.resolvedSeo)`, plus [`jsonLd`](#structured-data-json-ld) and [`customTags`](#custom-code).
27
+ 7. Add the revalidate route and the redirects proxy (both under [Next.js](#nextjs-app-router)).
28
+ 8. Add a `BREASE.md` that tells Brease's AI how the site is built. Brease counts a site as integrated only when the repo has both `brease-client` and `BREASE.md`.
29
+ 9. Optional: [sections](#sections) and `content.schema.json`. Then run `npx brease-client check`.
30
+
31
+ On Vercel, Cloudflare Workers Builds and Cloudflare Pages, the client picks up the commit and branch being built on its own (see commit pinning below), so every build reads the content released with its commit.
32
+
17
33
  ## API
18
34
 
19
35
  ```ts
@@ -22,7 +38,8 @@ import { createBrease } from 'brease-client'
22
38
  const brease = createBrease({
23
39
  token: process.env.BREASE_TOKEN, // default
24
40
  apiUrl: process.env.BREASE_API_URL, // default, falls back to https://api.brease.io
25
- commit: process.env.VERCEL_GIT_COMMIT_SHA, // default; false disables commit pinning
41
+ commit: process.env.VERCEL_GIT_COMMIT_SHA, // default (or WORKERS_CI_COMMIT_SHA, CF_PAGES_COMMIT_SHA); false disables commit pinning
42
+ branch: process.env.VERCEL_GIT_COMMIT_REF, // default (or WORKERS_CI_BRANCH, CF_PAGES_BRANCH); only Brease draft branches (brease/draft/…) are sent
26
43
  fetch // optional custom fetch, e.g. to add framework cache options
27
44
  })
28
45
 
@@ -30,6 +47,7 @@ await brease.getSite() // name, url (the public address), locales, defaultLocale
30
47
  await brease.getPage<Home>('', { locale: 'en' }) // Page<Home> | null ('' is the home page)
31
48
  await brease.getPages({ locale: 'en' }) // [{ pageId, locale, slug, url, hidden, name, index, parentId, order, template }]
32
49
  await brease.getPages({ locale: 'en', parentId: news.pageId, withContent: true }) // a news list, with each page's content
50
+ await brease.getPages({ locale: 'en', parentId: null }) // top-level pages only
33
51
  await brease.getNavigation('main', { locale: 'en' }) // { key, locale, items } | null
34
52
  await brease.getRedirects() // [{ source, destination, status }], cached for a minute
35
53
  await brease.resolve('/en/about') // { slug: 'about', locale: 'en' } | null
@@ -41,13 +59,14 @@ await brease.sitemap(site.url) // [{ url, alternates }]: pages search may show
41
59
 
42
60
  - `null` means 404. Every other failure throws a `BreaseError` with `status`, `code`, `requestId` and `details`.
43
61
  - 429 and 5xx responses (and network errors) are retried twice with backoff; `Retry-After` is honoured.
44
- - Commit pinning: the `x-brease-commit` header is sent from `VERCEL_GIT_COMMIT_SHA`, so every deployment reads the content release that was built and tested with its code.
62
+ - Commit pinning: the `x-brease-commit` header is sent from the commit the host is building (`VERCEL_GIT_COMMIT_SHA` on Vercel, `WORKERS_CI_COMMIT_SHA` on Cloudflare Workers Builds, `CF_PAGES_COMMIT_SHA` on Cloudflare Pages), so every deployment reads the content release that was built and tested with its code. On a Brease draft branch the `x-brease-branch` header (from the same host's `VERCEL_GIT_COMMIT_REF`, `WORKERS_CI_BRANCH` or `CF_PAGES_BRANCH`) lets later commits there, such as a developer's fix, still read the draft's content. Drafts need a preview token: with a production token a draft's commit or branch reads the live release. These are build-time variables: pages rendered at request time on Cloudflare read the live release unless you pass `commit` yourself.
45
63
  - `sitemap()` lists only pages search may show: not hidden, not kept out of search (`index: false`, the page's "Show in search results" switch), and no site-wide `_` pages. It has no `lastModified`: releases are immutable snapshots and do not track per-page edit times.
46
64
  - `getPages({ parentId, template, withContent })` narrows the list to a page's children or one template, and with
47
65
  `withContent` adds each page's content (one locale, hidden pages left out, up to 100 pages): build news, team or
48
66
  job lists from it instead of fetching every page.
49
67
  - `site.url` is the site's public address (its primary domain), the one Brease uses in canonical URLs and hreflang; use it for the sitemap and `metadataBase` rather than an env variable of your own.
50
- - `getSite()` is cached for a minute, so a locale added in Brease is served without a restart.
68
+ - `getSite()` and `getRedirects()` are cached in memory for a minute, so a locale added in Brease is served without a restart. The revalidate route (`revalidateHandler`) clears that cache on a publish, but only in the server instance that received the call; other instances (serverless functions, edge regions) catch up within the minute. The editor's preview (`BREASE_PREVIEW=1`) never caches it.
69
+ - `getRelease()` throws a `BreaseError` with status 404 until the site's first release is published: there is no release to report yet.
51
70
  - `buildPath(settings, slug, locale)` and `resolvePath(settings, pathname)` are exported for routing code that already has the site settings.
52
71
 
53
72
  ## Next.js (App Router)
@@ -77,7 +96,13 @@ async function load(params: Props['params']) {
77
96
  }
78
97
 
79
98
  export async function generateStaticParams() {
80
- return (await brease.routes()).map((r) => ({ slug: r.path })) // published pages, without site-wide "_" pages
99
+ // The build goes on without pre-rendered pages if the content API has a hiccup; pages then render on first request.
100
+ try {
101
+ return (await brease.routes()).map((r) => ({ slug: r.path })) // published pages, without site-wide "_" pages
102
+ } catch (err) {
103
+ console.warn(`Brease pages unavailable at build time: ${(err as Error).message}`)
104
+ return []
105
+ }
81
106
  }
82
107
 
83
108
  export async function generateMetadata({ params }: Props) {
@@ -128,15 +153,17 @@ Sources may use parameters as in Next's redirects (`/blog/:slug`, `/docs/:rest*`
128
153
 
129
154
  `route()` also resolves other forms of a page's URL (`/en/about` where English has no prefix, `/about` where every
130
155
  locale is prefixed); `resolvedSeo.canonical` points search engines at the real one. To redirect those forms too,
131
- add this to the same proxy, before `NextResponse.next()`:
156
+ add this to the same proxy, before `NextResponse.next()`. Keep it in the `try`: when Brease can't be reached, the
157
+ request goes on to the page instead of failing.
132
158
 
133
159
  ```ts
134
160
  import { canonicalPath } from 'brease-client'
135
161
 
136
- const site = await brease.getSite()
137
- const canonical = canonicalPath(site, req.nextUrl.pathname)
138
- if (canonical && (await brease.getPages()).some((p) => p.url === canonical))
139
- return NextResponse.redirect(new URL(canonical + req.nextUrl.search, req.url), 308)
162
+ try {
163
+ const canonical = canonicalPath(await brease.getSite(), req.nextUrl.pathname)
164
+ if (canonical && (await brease.getPages()).some((p) => p.url === canonical))
165
+ return NextResponse.redirect(new URL(canonical + req.nextUrl.search, req.url), 308)
166
+ } catch {}
140
167
  ```
141
168
 
142
169
  ### Structured data (JSON-LD)
@@ -264,7 +291,14 @@ async function load(params: Props['params']) {
264
291
  return page && route && Template ? { page, locale: route.locale, Template } : null
265
292
  }
266
293
 
267
- export const generateStaticParams = () => brease.routes()
294
+ export async function generateStaticParams() {
295
+ try {
296
+ return await brease.routes()
297
+ } catch (err) {
298
+ console.warn(`Brease pages unavailable at build time: ${(err as Error).message}`)
299
+ return []
300
+ }
301
+ }
268
302
 
269
303
  export async function generateMetadata({ params }: Props) {
270
304
  const loaded = await load(params)
@@ -308,15 +342,28 @@ Requests older than five minutes are rejected. The handler calls `revalidatePath
308
342
 
309
343
  ## Astro
310
344
 
345
+ ```ts
346
+ // src/lib/brease.ts
347
+ import { createBrease } from 'brease-client'
348
+
349
+ export const brease = createBrease({ token: import.meta.env.BREASE_TOKEN, apiUrl: import.meta.env.BREASE_API_URL })
350
+ ```
351
+
311
352
  ```astro
312
353
  ---
313
- import { createBrease } from 'brease-client'
354
+ // src/pages/[...path].astro
314
355
  import { breaseHead } from 'brease-client/astro'
356
+ import { brease } from '../lib/brease'
357
+
358
+ // Static output builds one file per published page in every locale. getStaticPaths can only use imports, so the
359
+ // client lives in its own module.
360
+ export async function getStaticPaths() {
361
+ return (await brease.routes()).map(({ path }) => ({ params: { path: path.join('/') || undefined } }))
362
+ }
315
363
 
316
- const brease = createBrease({ token: import.meta.env.BREASE_TOKEN, apiUrl: import.meta.env.BREASE_API_URL })
317
- const target = await brease.resolve(Astro.url.pathname)
318
- const page = target && (await brease.getPage(target.slug, { locale: target.locale }))
319
- if (!page) return Astro.redirect('/404')
364
+ const route = await brease.route(Astro.params.path)
365
+ const page = route && (await brease.getPage(route.slug, { locale: route.locale }))
366
+ if (!page) return new Response(null, { status: 404 })
320
367
  ---
321
368
  <html lang={page.locale}>
322
369
  <head><Fragment set:html={breaseHead(page.resolvedSeo)} /></head>
@@ -326,15 +373,76 @@ if (!page) return Astro.redirect('/404')
326
373
 
327
374
  `headTagList(seo)` returns the same tags as structured `{ tag, attrs, content }` objects.
328
375
 
329
- ## Plain HTML / other servers
376
+ ## Static HTML sites (no framework)
377
+
378
+ A site made of hand-written HTML pages gets its content from Brease at build time, with its markup, CSS, scripts and
379
+ animations untouched. Move each kind of page into `templates/`, mark the content in it, and let `brease-client` build
380
+ the site:
381
+
382
+ ```
383
+ templates/
384
+ home.html the home page (slug "")
385
+ page.html every other page, unless a page names its own template
386
+ room.html pages whose content has "template": "room"
387
+ css/ js/ img/ the site's own files, copied as they are
388
+ package.json "build": "brease-client build", "dev": "brease-client serve"
389
+ ```
390
+
391
+ ```html
392
+ <head>
393
+ <meta charset="utf-8" />
394
+ <!-- brease:head --> <!-- the page's title, meta, canonical, hreflang, structured data and custom code -->
395
+ <link rel="stylesheet" href="/css/site.css" />
396
+ </head>
397
+ <body>
398
+ <nav data-brease="nav:main"><a data-brease-item href="/">Home</a></nav>
399
+ <h1 data-brease="hero.title">Welcome</h1>
400
+ <div data-brease="hero.text" data-brease-html><p>Rich text</p></div>
401
+ <img data-brease="hero.image" src="/img/hero.jpg" alt="" />
402
+ <a data-brease="hero.cta" href="/contact">Contact us</a>
403
+ <ul data-brease="rooms">
404
+ <li data-brease-item><h2 data-brease="rooms.0.name">Room</h2></li>
405
+ </ul>
406
+ <p data-brease="_global:footer.copyright">© 2026</p>
407
+ </body>
408
+ ```
409
+
410
+ - `brease-client build` renders every published page in every locale to `dist/<url>/index.html`, copies the site's other files beside them, and writes Brease's redirects: `dist/_redirects` (Cloudflare) and, on Vercel, Vercel's Build Output (`.vercel/output`). Set the host's output directory to `dist`.
411
+ - `brease-client serve` renders each request as it comes in (on `$PORT`): the editor's preview shows an edit after a reload, without a rebuild.
412
+ - The `data-brease` markers both place the content and tell the editor what is editable, so they stay in the output. A field with no value keeps the template's own markup.
413
+ - Text: the element's text becomes the field (rich text keeps its HTML; mark it `data-brease-html`). Images: on `<img>` the `src`, `alt`, `width` and `height`; on other elements the background image. Links: on `<a>` the `href`, and the label where the link has no child elements.
414
+ - Lists and menus: the child marked `data-brease-item` repeats per item; its markers are written for the first item (`rooms.0.name`) and renumbered for the rest. In a menu (`nav:<key>`), the item's `<a>` gets the menu item's address and label (or the elements marked `data-brease-label` get the label).
415
+ - `_global:<path>` reads the site-wide page; the output carries that page's id, as the editor expects.
416
+ - New content goes live when Brease rebuilds the site after a publish.
417
+
418
+ `renderTemplate(html, { page, global, navigations })` (root export) does the filling, for other build setups.
419
+ `headTags(seo)` from `brease-client/html` returns the head tags alone.
420
+
421
+ ## Single-page apps (Vite, React without a server)
422
+
423
+ An app that renders in the browser reads its content at build time, so no token reaches the browser:
424
+
425
+ ```json
426
+ {
427
+ "scripts": {
428
+ "dev": "brease-client content src/brease/content.json --nav main,footer --watch & vite",
429
+ "build": "brease-client content src/brease/content.json --nav main,footer && vite build && brease-client output dist"
430
+ }
431
+ }
432
+ ```
330
433
 
331
434
  ```ts
332
- import { headTags } from 'brease-client/html'
435
+ import content from './brease/content.json'
333
436
 
334
- const html = `<head>${headTags(page.resolvedSeo, { xDefault: 'https://example.com/' })}</head>`
437
+ const page = content.pages[locale]?.[slug] // the same page object getPage() returns
438
+ const menu = content.navigations[locale]?.main
439
+ const global = content.global[locale]
335
440
  ```
336
441
 
337
- `customHead` and `customCode` from the site's SEO settings are inserted as raw HTML (they are authored by the site's team); pass `{ includeCustom: false }` to leave them out.
442
+ - `content.json` holds `{ site, pages: { <locale>: { <slug>: page } }, navigations, global, redirects }`. `--watch` rewrites it while the editor's preview runs, so the dev server shows edits.
443
+ - Mark elements with `data-brease` as in every other framework (see Editor markers).
444
+ - `brease-client output dist` writes the redirects for the host (`dist/_redirects`, or Vercel's Build Output on Vercel). Keep the SPA's own fallback to `index.html`.
445
+ - New content goes live when Brease rebuilds the site after a publish.
338
446
 
339
447
  ## Editor markers
340
448
 
@@ -390,15 +498,15 @@ export function Sections({ sections }: { sections: BreaseSection[] }) {
390
498
  ## Images
391
499
 
392
500
  ```ts
393
- import { imageProps, srcset } from 'brease-client/image'
501
+ import { imageProps } from 'brease-client/image'
394
502
 
395
- const props = imageProps(page.content.hero.image, { sizes: '(min-width: 768px) 50vw, 100vw' })
396
- // <img src={props.src} srcSet={props.srcSet} sizes={props.sizes} alt={props.alt} width={props.width} height={props.height} />
503
+ const props = imageProps(page.content.hero.image)
504
+ // <img src={props.src} alt={props.alt} width={props.width} height={props.height} />
397
505
  ```
398
506
 
399
507
  An image field is `{ assetId, url, alt, width?, height? }` (`BreaseImage`); `imageProps` takes the field or a plain
400
- URL. Brease files are served as-is from storage, which doesn't resize images: the helpers return the URL unchanged
401
- with an empty `srcset`. For responsive images, let your framework resize them, e.g. `next/image` with the host of
508
+ URL. Brease files are served as-is from storage, which doesn't resize images: the helpers return the URL unchanged,
509
+ without `srcSet` or `sizes` (`srcset()` and the resize options are deprecated no-ops). For responsive images, let your framework resize them, e.g. `next/image` with the host of
402
510
  your Brease image URLs in `images.remotePatterns`.
403
511
 
404
512
  ## Content links
@@ -416,4 +524,46 @@ Every call is a plain REST request:
416
524
  curl -H "Authorization: Bearer $BREASE_TOKEN" "https://api.brease.io/content-api/page?slug=about&locale=en"
417
525
  ```
418
526
 
419
- Routes: `GET /content-api/site`, `/content-api/pages?locale=`, `/content-api/page?slug=&locale=`, `/content-api/navigations/:key?locale=`, `/content-api/redirects`, `/content-api/release`.
527
+ | Route | Query | Returns |
528
+ | --- | --- | --- |
529
+ | `GET /content-api/site` | | `{ name, url, locales, defaultLocale, localeStrategy, urlTemplate, seo: { <locale>: … }, analytics }` |
530
+ | `GET /content-api/pages` | `locale`, `parentId`, `template`, `withContent` | `[{ pageId, locale, slug, url, hidden, name, index, parentId, order, template, content? }]` |
531
+ | `GET /content-api/page` | `slug`, `locale` | one page (below); 404 when missing or hidden |
532
+ | `GET /content-api/navigations/:key` | `locale` | `{ key, locale, items: [{ id, label, url, pageId?, target?, children }] }` |
533
+ | `GET /content-api/redirects` | | `[{ source, destination, status }]` |
534
+ | `GET /content-api/release` | | `{ id, number, commitSha, liveAt }` of the release served; 404 before the first publish |
535
+ | `GET /content-api/openapi.json` | | the OpenAPI document |
536
+
537
+ A page:
538
+
539
+ ```json
540
+ {
541
+ "pageId": "pg_about",
542
+ "name": "About",
543
+ "locale": "en",
544
+ "slug": "about",
545
+ "url": "/about",
546
+ "hidden": false,
547
+ "content": {
548
+ "template": "page",
549
+ "title": "About us",
550
+ "image": { "assetId": "ast_…", "url": "https://…/team.webp", "alt": "Our team", "width": 2400, "height": 1600 },
551
+ "cta": { "label": "Contact us", "href": "/contact", "pageId": "pg_contact" }
552
+ },
553
+ "seo": { "title": "About us" },
554
+ "resolvedSeo": {
555
+ "title": "About us – Acme",
556
+ "canonical": "https://www.acme.com/about",
557
+ "robots": { "index": true, "follow": true },
558
+ "openGraph": { "title": "About us – Acme" },
559
+ "twitter": {},
560
+ "structuredData": [],
561
+ "alternates": { "en": "https://www.acme.com/about", "de": "https://www.acme.com/de/ueber-uns" }
562
+ },
563
+ "alternates": { "de": "/de/ueber-uns" }
564
+ }
565
+ ```
566
+
567
+ `content` is the page's own JSON. `seo` is what the page sets; `resolvedSeo` has the site's defaults and title template applied, so render it as is.
568
+
569
+ Requests take `x-brease-commit` and `x-brease-branch` (see commit pinning above) and `If-None-Match`; responses carry `ETag`, `x-brease-release` and `Cache-Control: public, s-maxage=60, stale-while-revalidate=300`. Errors are `{ "error": { "code", "message" } }`: 401 `unauthorized`, 404 `not_found`, 422 `validation`, 429 `rate_limited` (with `Retry-After`).
package/dist/astro.js CHANGED
@@ -1,6 +1,5 @@
1
- import { headTags } from './chunk-QZXUMDB7.js';
2
- export { headTagList, headTags } from './chunk-QZXUMDB7.js';
3
- import './chunk-N3QOL5EU.js';
1
+ import { headTags } from './chunk-VQGKMILO.js';
2
+ export { headTagList, headTags } from './chunk-VQGKMILO.js';
4
3
  import './chunk-PKBMQBKP.js';
5
4
 
6
5
  // src/astro.ts