@bettercms-ai/sdk 1.45.0 → 1.46.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/dist/index.cjs +30 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -3
- package/dist/index.d.ts +4 -3
- package/dist/index.js +28 -2
- package/dist/index.js.map +1 -1
- package/dist/{read-CMasc3wt.d.ts → read-B2lJr72F.d.ts} +1 -1
- package/dist/{read-DTTdE_Xl.d.cts → read-BZq0vVvs.d.cts} +1 -1
- package/dist/{read-client-E9OHtQAW.d.cts → read-client-DQhWuKf4.d.cts} +16 -0
- package/dist/{read-client-E9OHtQAW.d.ts → read-client-DQhWuKf4.d.ts} +16 -0
- package/dist/read.cjs +16 -1
- package/dist/read.cjs.map +1 -1
- package/dist/read.d.cts +2 -2
- package/dist/read.d.ts +2 -2
- package/dist/read.js +16 -1
- package/dist/read.js.map +1 -1
- package/dist/sections.cjs +16 -1
- package/dist/sections.cjs.map +1 -1
- package/dist/sections.d.cts +1 -1
- package/dist/sections.d.ts +1 -1
- package/dist/sections.js +16 -1
- package/dist/sections.js.map +1 -1
- package/dist/webhook.cjs +38 -0
- package/dist/webhook.cjs.map +1 -0
- package/dist/webhook.d.cts +15 -0
- package/dist/webhook.d.ts +15 -0
- package/dist/webhook.js +13 -0
- package/dist/webhook.js.map +1 -0
- package/package.json +6 -1
package/dist/read.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/retry.ts","../src/draft.ts","../src/read-client.ts","../src/forms.ts","../src/search.ts","../src/richtext.ts","../src/published-content.ts"],"sourcesContent":["import type { BetterCMSErrorCode } from \"@bettercms-ai/types\";\n\n/** Semantic error codes used by the SDK. */\nexport const ErrorCodes = {\n CONTENT_NOT_FOUND: \"CONTENT_NOT_FOUND\",\n UNAUTHORIZED: \"UNAUTHORIZED\",\n FORBIDDEN: \"FORBIDDEN\",\n RATE_LIMITED: \"RATE_LIMITED\",\n INTERNAL_ERROR: \"INTERNAL_ERROR\",\n VALIDATION_ERROR: \"VALIDATION_ERROR\",\n NETWORK_ERROR: \"NETWORK_ERROR\",\n ADMIN_NOT_IMPLEMENTED: \"ADMIN_NOT_IMPLEMENTED\",\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\n/** Maps HTTP status codes to semantic error codes. */\nfunction statusToCode(status: number): BetterCMSErrorCode {\n if (status === 404) return ErrorCodes.CONTENT_NOT_FOUND;\n if (status === 401) return ErrorCodes.UNAUTHORIZED;\n if (status === 403) return ErrorCodes.FORBIDDEN;\n if (status === 429) return ErrorCodes.RATE_LIMITED;\n if (status >= 500) return ErrorCodes.INTERNAL_ERROR;\n if (status === 422) return ErrorCodes.VALIDATION_ERROR;\n return ErrorCodes.INTERNAL_ERROR;\n}\n\n/**\n * BetterCMSError — normalized SDK error with a semantic code.\n */\nexport class BetterCMSError extends Error {\n readonly status: number;\n readonly code: BetterCMSErrorCode;\n /**\n * Raw machine-readable `code` from the response body (e.g. \"PROJECT_DELETED\"),\n * when the API supplies one. Distinct from `code` (which is derived from the\n * HTTP status), this lets callers branch on a specific server condition that\n * shares a status with others (e.g. 409 slug-conflict vs 409 project-deleted).\n */\n readonly bodyCode?: string;\n /**\n * Per-field validation messages from a 400 `{ errors: { field: message } }` body.\n * The backend returns validation failures in this shape (not `message`/`error`), so\n * without this the SDK collapsed every validation 400 to a bare \"Bad Request\" with no\n * hint which field or rule failed (FLO-474). Mirrors the forms client's `fieldErrors`.\n */\n readonly fieldErrors?: Record<string, string>;\n /**\n * The parsed response body, when there was one.\n *\n * Several refusals carry STRUCTURED detail that neither `message` nor `fieldErrors` can hold,\n * and which is the whole point of the refusal: a component publish 409s with the full\n * `readiness` tuple (what evidence is missing, whether a human still has to approve it) and\n * 422s with the `issues` naming the Layouts it would break. Collapsing those to a sentence\n * leaves a caller able to report that something failed and not what to do about it.\n */\n readonly body?: unknown;\n\n constructor(\n message: string,\n status: number,\n code: BetterCMSErrorCode,\n bodyCode?: string,\n fieldErrors?: Record<string, string>,\n body?: unknown,\n ) {\n super(message);\n this.name = \"BetterCMSError\";\n this.status = status;\n this.code = code;\n this.bodyCode = bodyCode;\n this.fieldErrors = fieldErrors;\n this.body = body;\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, BetterCMSError);\n }\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n status: this.status,\n code: this.code,\n bodyCode: this.bodyCode,\n fieldErrors: this.fieldErrors,\n };\n }\n\n /**\n * Factory — creates a BetterCMSError from a failed fetch Response. Reads the body's\n * `message` (or `error`) for the human message and `code` for a machine-readable\n * condition surfaced as `bodyCode`. Validation failures arrive as `{ errors: {...} }`\n * (no `message`/`error`), so fall back to the first field error for the message and\n * expose the full map as `fieldErrors` (FLO-474).\n */\n static async from(res: Response): Promise<BetterCMSError> {\n let message = res.statusText || \"An error occurred\";\n let bodyCode: string | undefined;\n let fieldErrors: Record<string, string> | undefined;\n let code = statusToCode(res.status);\n let raw: unknown;\n try {\n const body = (await res.json()) as {\n message?: string;\n error?: string;\n code?: string;\n errors?: Record<string, string>;\n };\n if (body?.errors && typeof body.errors === \"object\") {\n fieldErrors = body.errors;\n code = ErrorCodes.VALIDATION_ERROR;\n }\n if (body?.message) message = body.message;\n else if (body?.error) message = body.error;\n else if (fieldErrors) {\n const [field, detail] = Object.entries(fieldErrors).find(\n ([, v]) => typeof v === \"string\" && v.length > 0,\n ) ?? [];\n if (field) message = `${field}: ${detail}`;\n }\n if (body?.code) bodyCode = body.code;\n raw = body;\n } catch {\n // ignore parse errors\n }\n return new BetterCMSError(message, res.status, code, bodyCode, fieldErrors, raw);\n }\n}\n","/**\n * Shared 429/503 backoff for every SDK client.\n *\n * ── Why this exists ─────────────────────────────────────────────────────────\n * The backend limiter (src/lib/ratelimit.ts, windowHit) is a FIXED 60-SECOND\n * WINDOW: 100 requests per workspace per endpoint, and a denial answers\n * `Retry-After: <seconds until the window resets>` — anything up to 60.\n *\n * Every client here used to climb a private ladder that topped out at 7 seconds\n * ([250,750,1500] in read-client, [1000,2000,4000] in admin/management) and none\n * of them read Retry-After. So all three retries landed INSIDE the same exhausted\n * window and a 429 was fatal roughly whenever it was thrown. The retry code looked\n * like resilience but could only ever recover from a denial raised in the final\n * seconds of a window.\n *\n * That is what failed customer builds: `action/fetch-content.mjs` spends ~65 of the\n * 100 `delivery-content-entries-list` slots pulling a large workspace, `npm run build`\n * starts seconds later in the SAME window, and the first per-route delivery read past\n * the ceiling killed the deploy with \"Too many requests. Please retry later.\"\n *\n * ── The rule ────────────────────────────────────────────────────────────────\n * Obey Retry-After when the server sends one, and let a single request outlast a\n * whole window. A build waiting 60s is slow; a build that dies is a broken product.\n */\n\n/** Statuses worth retrying. 429 = rate limited, 503 = limiter/backend unavailable. */\nexport const RETRY_STATUSES = [429, 503] as const;\n\n/** Retries after the first attempt. 3 retries × up to ~65s spans three full windows. */\nexport const MAX_RETRIES = 3;\n\n/**\n * Hard ceiling on a single wait, jitter included. Must exceed the limiter's 60s\n * window, or a denial raised at the very start of a window still cannot be waited\n * out — and must be finite, so a hostile or mis-set Retry-After cannot hang a build.\n */\nexport const MAX_DELAY_MS = 65_000;\n\n/** Fallback ladder when the server sends no Retry-After: 1s, 2s, 4s, 8s. */\nconst BASE_DELAY_MS = 1_000;\n\n/**\n * De-sync jitter, added to every wait.\n *\n * Deliberately a small FLAT amount, not a percentage. Requests denied by one window\n * only need to stop firing in the same millisecond — the server's counter serialises\n * them after that. A proportional jitter would add up to 15 seconds to a 60-second\n * wait for no benefit, and would push the total past MAX_DELAY_MS.\n */\nconst JITTER_MS = 250;\n\nexport function isRetryableStatus(status: number): boolean {\n return (RETRY_STATUSES as readonly number[]).includes(status);\n}\n\n/**\n * Parse `Retry-After`, which RFC 9110 allows in either form: delay-seconds\n * (\"47\") or an HTTP-date (\"Wed, 21 Oct 2015 07:28:00 GMT\"). Returns ms to wait,\n * or null when the header is absent or unparseable.\n */\nexport function retryAfterMs(res: Pick<Response, \"headers\">): number | null {\n const raw = res.headers?.get?.(\"retry-after\");\n if (!raw) return null;\n\n const seconds = Number(raw);\n if (Number.isFinite(seconds)) {\n return Math.min(Math.max(seconds, 0) * 1000, MAX_DELAY_MS);\n }\n\n const at = Date.parse(raw);\n if (!Number.isNaN(at)) {\n return Math.min(Math.max(0, at - Date.now()), MAX_DELAY_MS);\n }\n return null;\n}\n\n/**\n * How long to wait before retry `attempt` (0-based).\n *\n * Server instruction wins; otherwise exponential. Jitter is added in both cases:\n * when a build's requests are all denied by the same window they would otherwise\n * wake in lockstep at the reset and re-exhaust it immediately (thundering herd).\n */\nexport function backoffMs(attempt: number, res?: Pick<Response, \"headers\">): number {\n const fromServer = res ? retryAfterMs(res) : null;\n // Base is capped with the jitter's headroom already reserved, so the total never\n // exceeds MAX_DELAY_MS AND the jitter is never clamped away at the ceiling — which\n // would put every capped caller back in lockstep, the exact thing jitter prevents.\n const base = Math.min(fromServer ?? BASE_DELAY_MS * 2 ** attempt, MAX_DELAY_MS - JITTER_MS);\n // Jitter is ADDED, never subtracted: waking before the server's Retry-After elapses\n // just burns a retry on a window that has not reset.\n return base + Math.random() * JITTER_MS;\n}\n\nexport const sleep = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms));\n","/**\n * Draft mode, shared by every framework adapter: the signed cookie that says \"this visitor is\n * previewing\", the preview token's slug, and the redirect a draft route may follow.\n *\n * Web Crypto and `atob` only, so it runs in Node, edge runtimes and workers alike. Each adapter\n * mounts its own routes around these; the rules live here once.\n */\n\n/** The draft cookie every adapter sets: one name, so an editor link works on any framework. */\nexport const DRAFT_COOKIE = \"bcms-draft\";\n\nconst enc = new TextEncoder();\n\nfunction base64url(bytes: ArrayBuffer): string {\n const b = btoa(String.fromCharCode(...new Uint8Array(bytes)));\n return b.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nasync function hmac(value: string, secret: string): Promise<string> {\n const key = await crypto.subtle.importKey(\"raw\", enc.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n return base64url(await crypto.subtle.sign(\"HMAC\", key, enc.encode(value)));\n}\n\n/** Sign a value as `value.sig` for tamper-evident cookie storage (HMAC-SHA256, base64url). */\nexport async function signValue(value: string, secret: string): Promise<string> {\n return `${value}.${await hmac(value, secret)}`;\n}\n\n/** The original value of a signed one, or null when it was tampered with. */\nexport async function verifyValue(signed: string, secret: string): Promise<string | null> {\n const idx = signed.lastIndexOf(\".\");\n if (idx < 0) return null;\n const value = signed.slice(0, idx);\n const sig = signed.slice(idx + 1);\n const expected = await hmac(value, secret);\n if (sig.length !== expected.length) return null;\n let diff = 0;\n for (let i = 0; i < sig.length; i++) diff |= sig.charCodeAt(i) ^ expected.charCodeAt(i);\n return diff === 0 ? value : null;\n}\n\n/** The header a server signs a content-branch read with (@see signBranchRead). */\nexport const BRANCH_SIGNATURE_HEADER = \"X-BCMS-Branch-Signature\";\n\n/**\n * Sign a read of content branch `branch` with `BCMS_BRANCH_SECRET`, which BetterCMS hosting gives a\n * server it runs (and nothing else has). The Delivery API serves the branch to this signature with\n * no draft key. A signature is good for five minutes: sign per request.\n */\nexport async function signBranchRead(branch: string, secret: string, now = Date.now()): Promise<string> {\n return signValue(`${Math.floor(now / 1000)}:${branch}`, secret);\n}\n\n/** Only same-origin relative paths: blocks \"//evil.com\", \"https://evil.com\" and \"/\\\\evil.com\". */\nexport function safeRedirectPath(to: string): string {\n return to.startsWith(\"/\") && !to.startsWith(\"//\") && !to.startsWith(\"/\\\\\") ? to : \"/\";\n}\n\nfunction tokenPayload(token: string): { entrySlug?: string; branch?: string } | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n // atob gives bytes as Latin-1: decoded as UTF-8, a slug like `über-uns` survives.\n const bytes = Uint8Array.from(atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\")), (c) => c.charCodeAt(0));\n return JSON.parse(new TextDecoder().decode(bytes)) as { entrySlug?: string; branch?: string };\n } catch {\n return null;\n }\n}\n\n/**\n * The content branch a preview token was minted on, or null for main. Read UNVERIFIED: an adapter\n * only stores a token the backend accepted, and branch reads need the site's draft key regardless.\n * Pass it as the client's `branch` in draft mode and the whole site previews from that branch.\n */\nexport function decodeTokenBranch(token: string | null | undefined): string | null {\n return (token && tokenPayload(token)?.branch) || null;\n}\n\n/** A preview token's `entrySlug`, read from its payload UNVERIFIED (the backend verifies it). */\nexport function decodeTokenSlug(token: string): string | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n // atob gives bytes as Latin-1: decoded as UTF-8, a slug like `über-uns` survives.\n const bytes = Uint8Array.from(atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\")), (c) => c.charCodeAt(0));\n const json = JSON.parse(new TextDecoder().decode(bytes)) as { entrySlug?: string };\n return json.entrySlug ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Ask the backend whether a preview token is good: the backend is the signature authority, so a\n * draft route enables draft mode only on its yes.\n */\nexport async function previewTokenValid(apiUrl: string, token: string, fetchImpl: typeof fetch = fetch): Promise<boolean> {\n const slug = decodeTokenSlug(token);\n if (!slug) return false;\n const res = await fetchImpl(`${apiUrl.replace(/\\/+$/, \"\")}/api/v1/preview/${encodeURIComponent(slug)}?token=${encodeURIComponent(token)}`);\n await res.body?.cancel().catch(() => {});\n return res.ok;\n}\n\n/** The draft cookie's preview token from a `Cookie` header, or null when absent or tampered with. */\nexport async function draftTokenFrom(cookieHeader: string | null | undefined, secret: string | undefined): Promise<string | null> {\n if (!cookieHeader || !secret) return null;\n const m = new RegExp(`(?:^|;\\\\s*)${DRAFT_COOKIE}=([^;]+)`).exec(cookieHeader);\n if (!m) return null;\n try {\n return await verifyValue(decodeURIComponent(m[1]!), secret);\n } catch {\n return null;\n }\n}\n\n/**\n * The draft-enable route for any server that speaks Web `Request`/`Response` (SvelteKit `+server.ts`,\n * Nuxt via `toWebRequest`, Remix, Hono): `GET ?token=…&redirect=/x` checks the token with the\n * backend, sets the signed draft cookie and redirects. 401 on a refused token; 500 without a secret.\n */\nexport async function draftEnableResponse(request: Request, opts: { apiUrl: string; secret: string | undefined; fetchImpl?: typeof fetch }): Promise<Response> {\n const url = new URL(request.url);\n const token = url.searchParams.get(\"token\");\n if (!opts.secret) return new Response(\"BCMS_DRAFT_SECRET is not configured\", { status: 500 });\n if (!token) return new Response(\"Missing token\", { status: 400 });\n if (!(await previewTokenValid(opts.apiUrl, token, opts.fetchImpl))) return new Response(\"Invalid or expired token\", { status: 401 });\n const cookie = `${DRAFT_COOKIE}=${encodeURIComponent(await signValue(token, opts.secret))}; Path=/; HttpOnly; SameSite=Lax; Max-Age=86400${url.protocol === \"https:\" ? \"; Secure\" : \"\"}`;\n return new Response(null, { status: 302, headers: { Location: safeRedirectPath(url.searchParams.get(\"redirect\") ?? \"/\"), \"Set-Cookie\": cookie } });\n}\n\n/** Leave draft mode: clear the cookie and redirect (`?redirect=/x`, same-origin only). */\nexport function draftDisableResponse(request: Request): Response {\n const url = new URL(request.url);\n return new Response(null, {\n status: 302,\n headers: { Location: safeRedirectPath(url.searchParams.get(\"redirect\") ?? \"/\"), \"Set-Cookie\": `${DRAFT_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0` },\n });\n}\n","/**\n * createClient — framework-agnostic typed read client for the Delivery API.\n *\n * Shared by @bettercms-ai/astro and @bettercms-ai/next so the fetch/typing/retry\n * logic lives in one place. Read-only; for schema authoring use the\n * Management client, for sessions use the Admin client.\n *\n * const client = createClient({ apiUrl, workspace, apiKey });\n * await client.getPage(\"home\");\n * await client.listEntries({ model: \"post\", perPage: 50 });\n */\nimport type {\n DeliveryComponent,\n DeliveryEntry,\n DeliveryList,\n DeliveryPage,\n DeliveredLayout,\n Perspective,\n} from \"@bettercms-ai/types\";\nimport { BetterCMSError } from \"./errors.js\";\nimport { MAX_RETRIES, backoffMs, isRetryableStatus, sleep } from \"./retry.js\";\nimport type { DeliveryForm } from \"./forms.js\";\nimport { BRANCH_SIGNATURE_HEADER } from \"./draft.js\";\n\nconst DEFAULT_TIMEOUT = 10_000;\n\nexport interface CreateClientOptions {\n /** Backend base, e.g. `https://api.bettercms.ai` (no trailing slash needed). */\n apiUrl: string;\n /** Workspace slug. */\n workspace: string;\n /** Delivery API key. Use a `content:read:draft` key for drafts. */\n apiKey?: string;\n /**\n * The project every read is addressed to. A workspace holds many projects whose slugs\n * collide (each has a `blog` model and a `home` page), so a site names its own; published\n * reads need no key for it. BetterCMS hosting supplies `PUBLIC_BCMS_PROJECT_ID`.\n */\n projectId?: string;\n /**\n * A content branch (its slug) to read instead of the live site, like a Sanity release\n * perspective: every read answers from the branch. Needs a `content:read:draft` key and a\n * `projectId`; a branch that is not open answers 404 (BRANCH_NOT_FOUND).\n */\n branch?: string;\n /**\n * `signBranchRead(branch, BCMS_BRANCH_SECRET)`: on a server BetterCMS hosts, reads the `branch`\n * with no draft key. `@bettercms-ai/astro` signs for you on a branch preview.\n */\n branchSignature?: string;\n /** `published` (default) or `drafts`. */\n perspective?: Perspective;\n /**\n * Preview-token JWT for token-based single-document draft reads via the\n * `/preview/:slug` endpoint. Only used when `perspective === \"drafts\"`.\n */\n previewToken?: string;\n /**\n * Embed invisible visual-editing provenance in draft reads, so a preview build can\n * deep-link each rendered value back to its editor. Requires `perspective: \"drafts\"`,\n * and then either a `previewToken` or a `content:read:draft` key. Ignored on published\n * reads — the payload must never reach a production build.\n *\n * **Defaults to `true` on `perspective: \"drafts\"`** (since 1.15.0). Provenance is the whole\n * reason the drafts perspective exists in a preview build, and an option nobody knew to pass\n * meant every such build rendered anonymous strings: the editor could bind them only by\n * guessing at their text. It stays OFF on every other perspective, unconditionally, so a\n * published build cannot acquire a payload by accident — pass `stega: false` to opt a draft\n * read out (a diff or a checksum over draft content is the case that wants it).\n */\n stega?: boolean;\n /** Per-attempt timeout in ms. Defaults to 10000. */\n timeout?: number;\n /**\n * Collapse identical GETs to one network round-trip for the life of this client.\n * Default false.\n *\n * Only correct where the content is a POINT-IN-TIME SNAPSHOT — i.e. a static build,\n * where every route renders from the same published dataset. `@bettercms-ai/astro`\n * turns this on automatically when Astro's `command === \"build\"` and never for `dev`,\n * SSR or the drafts perspective, where a repeat read must see the current row.\n *\n * A static build without it re-fetches the same nav/settings/collection once PER ROUTE.\n * That is what made a large site exhaust the delivery rate limit: hundreds of identical\n * requests, and `getPage()` re-scanning every page of the paginated list each time it is\n * called.\n */\n cache?: boolean;\n}\n\nexport interface ListEntriesOptions {\n /** Filter by content-model slug. */\n model?: string;\n page?: number;\n perPage?: number;\n /** Reference hydration depth (lists cap at 1). */\n depth?: 0 | 1;\n /** Projection — field names to return. */\n select?: string[];\n}\n\nexport interface GetEntryOptions {\n depth?: 0 | 1 | 2;\n select?: string[];\n}\n\nexport interface ListPagesOptions {\n page?: number;\n perPage?: number;\n /** Only the page with this slug (the list's `?slug=`). */\n slug?: string;\n}\n\nexport interface BetterCMSReadClient {\n readonly perspective: Perspective;\n getEntry<T = Record<string, unknown>>(\n slug: string,\n opts?: GetEntryOptions,\n ): Promise<DeliveryEntry<T>>;\n listEntries<T = Record<string, unknown>>(\n opts?: ListEntriesOptions,\n ): Promise<DeliveryList<DeliveryEntry<T>>>;\n getPage(slug: string): Promise<DeliveryPage | null>;\n listPages(opts?: ListPagesOptions): Promise<DeliveryList<DeliveryPage>>;\n /**\n * The workspace's reusable component definitions, for resolving `component` blocks.\n * Under `perspective: \"drafts\"` this is the DRAFT definition — what makes an SSR render\n * of a draft page look like the page the editor is showing.\n */\n listComponents(): Promise<DeliveryComponent[]>;\n /** Fetch the project-scoped Global Layout for the active perspective. */\n getLayout(): Promise<DeliveredLayout | null>;\n listForms(opts?: {\n projectId?: string;\n }): Promise<{ items: DeliveryForm[]; turnstileSiteKey: string | null }>;\n /** Build a deterministic Next/cache tag for a resource. */\n tag(resource: \"entry\" | \"page\" | \"forms\", id?: string): string;\n}\n\n/** Drop undefined values, stringify the rest into a query string. */\nfunction qs(params: Record<string, string | number | undefined>): string {\n const sp = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== \"\") sp.set(k, String(v));\n }\n const s = sp.toString();\n return s ? `?${s}` : \"\";\n}\n\n/**\n * Unwrap a `{ data: ... }` list/legacy envelope when present. A bare entry is\n * already the payload (it has `id`/`slug` and its own `data` field), so we only\n * unwrap when no payload markers are at the top level.\n */\nfunction unwrap<T>(json: unknown): T {\n if (json && typeof json === \"object\") {\n const o = json as Record<string, unknown>;\n const isPayload = \"id\" in o || \"slug\" in o || \"items\" in o;\n if (!isPayload && \"data\" in o) return o.data as T;\n }\n return json as T;\n}\n\n/**\n * The `entrySlug` claim of a preview-token JWT, UNVERIFIED.\n *\n * The backend is the signature authority — this read only decides WHICH url to call, and a\n * forged claim buys nothing: `/preview/:slug` re-verifies and 401s. Kept private to this file\n * (`@bettercms-ai/astro` has its own copy for the same reason: neither package may depend on\n * the other).\n */\nfunction tokenSlug(token: string): string | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n const json = atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n return (JSON.parse(json) as { entrySlug?: string }).entrySlug ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Per-URL request collapsing.\n *\n * Two jobs, both needed: coalesce requests that are IN FLIGHT (Astro renders routes\n * concurrently, so identical GETs overlap) and retain the ones that have COMPLETED\n * (routes render in batches, so the same GET recurs long after the first settled).\n *\n * Values are cloned on the way out. Callers get a fresh object graph, so a template that\n * sorts `items` in place — an easy thing to write and a brutal thing to debug — cannot\n * corrupt what every other route sees. Cloning costs memory bandwidth; the request it\n * replaces costs a network round-trip and a slot in the rate-limit window.\n *\n * A rejected request is never retained, so a transient failure does not become permanent.\n */\nfunction createRequestCache() {\n const inflight = new Map<string, Promise<unknown>>();\n const settled = new Map<string, unknown>();\n\n const copy = <T>(value: T): T =>\n typeof structuredClone === \"function\" ? structuredClone(value) : (JSON.parse(JSON.stringify(value)) as T);\n\n return async function collapse<T>(url: string, fetcher: () => Promise<T>): Promise<T> {\n if (settled.has(url)) return copy(settled.get(url) as T);\n\n const pending = inflight.get(url) as Promise<T> | undefined;\n if (pending) return copy(await pending);\n\n const run = (async () => {\n try {\n const value = await fetcher();\n settled.set(url, value);\n return value;\n } finally {\n inflight.delete(url);\n }\n })();\n inflight.set(url, run);\n return copy(await run);\n };\n}\n\nexport function createClient(options: CreateClientOptions): BetterCMSReadClient {\n const apiUrl = options.apiUrl.replace(/\\/+$/, \"\");\n const { workspace, apiKey, perspective = \"published\", previewToken } = options;\n const defaultProjectId = options.projectId;\n // Every delivery read names the project and, for a branch preview, the branch.\n const branch = options.branch && options.branch !== \"main\" ? options.branch : undefined;\n const timeout = options.timeout ?? DEFAULT_TIMEOUT;\n const base = `${apiUrl}/api/v1/delivery/${workspace}`;\n\n const headers = (): Record<string, string> => {\n const h: Record<string, string> = { \"Content-Type\": \"application/json\" };\n if (apiKey) h[\"X-API-Key\"] = apiKey;\n if (branch && options.branchSignature) h[BRANCH_SIGNATURE_HEADER] = options.branchSignature;\n return h;\n };\n\n // Drafts must never be collapsed even if a caller asks: a preview surface re-reads to\n // see the edit that just happened, and serving it a retained copy would show stale content.\n const collapse =\n options.cache && perspective === \"published\" ? createRequestCache() : undefined;\n\n const fetchJSON = <T>(url: string): Promise<T> =>\n collapse ? collapse(url, () => request<T>(url)) : request<T>(url);\n\n async function request<T>(url: string): Promise<T> {\n let lastError: unknown;\n for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeout);\n try {\n const res = await globalThis.fetch(url, {\n headers: headers(),\n signal: controller.signal,\n });\n clearTimeout(timer);\n if (res.ok) return (await res.json()) as T;\n\n const retryable = attempt < MAX_RETRIES && isRetryableStatus(res.status);\n if (!retryable) throw await BetterCMSError.from(res);\n // Honour Retry-After: the limiter's window is up to 60s, far longer than\n // any fixed ladder, so the server's own number is the only one that works.\n await sleep(backoffMs(attempt, res));\n } catch (err) {\n clearTimeout(timer);\n if (err instanceof Error && err.name === \"AbortError\") {\n throw new BetterCMSError(\"Request timeout\", 408, \"NETWORK_ERROR\");\n }\n if (err instanceof BetterCMSError) throw err;\n lastError = err;\n if (attempt < MAX_RETRIES) {\n await sleep(backoffMs(attempt));\n continue;\n }\n throw new BetterCMSError(\n `Network error: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n \"NETWORK_ERROR\",\n );\n }\n }\n throw lastError ?? new BetterCMSError(\"Unreachable\", 0, \"NETWORK_ERROR\");\n }\n\n const draft = perspective === \"drafts\";\n /**\n * Resolved ONCE, here, so the three call sites below cannot drift apart — they did exactly\n * that before (`options.stega` alone on the preview branch, `draft && options.stega` on the\n * other two), and a default expressed three times is a default that will eventually be two.\n * `??` and not `||`: an explicit `stega: false` on a draft read must win.\n */\n const stega = options.stega ?? draft;\n\n return {\n perspective,\n\n async getEntry<T = Record<string, unknown>>(slug: string, opts?: GetEntryOptions) {\n // Token-based draft reads go through the dedicated preview endpoint.\n // Without a token the drafts perspective is served by delivery itself, which needs\n // to be TOLD — `?perspective=draft` (honoured only for a `content:read:draft` key).\n // Until this branch sent it, `perspective: \"drafts\"` was silently inert here, and\n // with it `stega`, so a static build could never obtain provenance without minting\n // a preview token per entry.\n // The token names ONE entry (as on getPage below): any other slug reads delivery, or the\n // preview endpoint 404s the post list, related posts and nav a draft page also renders.\n const url =\n draft && previewToken && tokenSlug(previewToken) === slug\n ? `${apiUrl}/api/v1/preview/${encodeURIComponent(slug)}${qs({\n token: previewToken,\n depth: opts?.depth,\n select: opts?.select?.join(\",\"),\n stega: stega ? \"1\" : undefined,\n })}`\n : `${base}/content-entries/${encodeURIComponent(slug)}${qs({\n depth: opts?.depth,\n select: opts?.select?.join(\",\"),\n perspective: draft ? \"draft\" : undefined,\n stega: draft && stega ? \"1\" : undefined,\n projectId: defaultProjectId, branch,\n })}`;\n return unwrap<DeliveryEntry<T>>(await fetchJSON(url));\n },\n\n async listEntries<T = Record<string, unknown>>(opts?: ListEntriesOptions) {\n const url = `${base}/content-entries${qs({\n model: opts?.model,\n page: opts?.page,\n perPage: opts?.perPage,\n depth: opts?.depth,\n select: opts?.select?.join(\",\"),\n perspective: draft ? \"draft\" : undefined,\n stega: draft && stega ? \"1\" : undefined,\n projectId: defaultProjectId, branch,\n })}`;\n return unwrap<DeliveryList<DeliveryEntry<T>>>(await fetchJSON(url));\n },\n\n async getPage(slug: string) {\n // The token names ONE page, and for that page the preview endpoint is the only read\n // that returns the DRAFT block tree — the paginated delivery list is published-only, so\n // an SSR draft render would otherwise be the live structure with draft field values.\n // Any other slug falls through to the published scan, which is what a token for /about\n // rendering the site's nav or footer pages must keep doing.\n if (draft && previewToken && tokenSlug(previewToken) === slug) {\n const url = `${apiUrl}/api/v1/preview/${encodeURIComponent(slug)}${qs({\n token: previewToken,\n stega: stega ? \"1\" : undefined,\n })}`;\n const d = unwrap<Record<string, unknown>>(await fetchJSON(url));\n return {\n slug: d.slug as string,\n title: d.title as string,\n metaTitle: (d.metaTitle as string | null) ?? null,\n metaDescription: (d.metaDescription as string | null) ?? null,\n metaJson: (d.metaJson as DeliveryPage[\"metaJson\"]) ?? null,\n blocks: (d.blockJson as DeliveryPage[\"blocks\"]) ?? [],\n // C3: the DRAFT field styles, present only when the page styles a field.\n ...(d.fieldStyles ? { fieldStyles: d.fieldStyles as NonNullable<DeliveryPage[\"fieldStyles\"]> } : {}),\n updatedAt: (d.updatedAt as string | null) ?? null,\n publishedAt: (d.publishedAt as string | null) ?? null,\n } satisfies DeliveryPage;\n }\n // No dedicated single-page delivery endpoint: the list, narrowed to this slug. Unnarrowed, every\n // client-rendered page view read every page of the site (a converted React SPA's <BcmsSections>:\n // ~50 KB for one page's order). A server that ignores `slug` answers the whole list, scanned as before.\n let page = 1;\n for (;;) {\n const list = await this.listPages({ page, perPage: 100, slug });\n const found = list.items.find((p) => p.slug === slug);\n if (found) return found;\n if (!list.hasNextPage) return null;\n page += 1;\n }\n },\n\n async listPages(opts?: ListPagesOptions) {\n const url = `${base}/pages${qs({\n page: opts?.page,\n perPage: opts?.perPage,\n slug: opts?.slug,\n projectId: defaultProjectId, branch,\n })}`;\n return unwrap<DeliveryList<DeliveryPage>>(await fetchJSON(url));\n },\n\n async listComponents() {\n // Same shape as getLayout: `?perspective=draft` alone is the key-scoped path (the server\n // ignores it for a published key), and a preview token is the page-scoped one.\n const url = `${base}/components${qs({\n perspective: draft ? \"draft\" : undefined,\n token: draft ? previewToken : undefined,\n projectId: defaultProjectId, branch,\n })}`;\n return unwrap<DeliveryComponent[]>(await fetchJSON(url));\n },\n\n async getLayout() {\n const url = `${base}/layout${qs({ perspective: draft ? \"draft\" : undefined, projectId: defaultProjectId, branch })}`;\n try {\n return unwrap<DeliveredLayout>(await fetchJSON(url));\n } catch (error) {\n if (error instanceof BetterCMSError && error.status === 404) return null;\n throw error;\n }\n },\n\n async listForms(opts?: { projectId?: string }) {\n const url = `${base}/forms${qs({\n projectId: opts?.projectId ?? defaultProjectId,\n branch,\n })}`;\n return unwrap<{ items: DeliveryForm[]; turnstileSiteKey: string | null }>(\n await fetchJSON(url),\n );\n },\n\n tag(resource, id) {\n return id ? `bcms:${workspace}:${resource}:${id}` : `bcms:${workspace}:${resource}`;\n },\n };\n}\n","/**\n * Public forms — the headless integration surface for sites built on or imported\n * into BetterCMS (the \"render it yourself\" model, like Sanity's delivery API).\n *\n * Form definitions ship in the build-time content snapshot (`bcms-content.json` →\n * `forms` / `turnstileSiteKey`) and from `GET /api/v1/delivery/:workspace/forms`.\n * A site renders them with its own components (see `@bettercms-ai/next`'s <BcmsForm>)\n * and posts here. No API key — the endpoint is Turnstile-gated (Webflow model).\n *\n * This module is the single source of truth for the delivered form shape + the\n * pure logic (conditional visibility, initial values) the renderers share, so the\n * vanilla embed and the React component never drift.\n */\n\nimport { BetterCMSError, ErrorCodes } from \"./errors.js\";\nimport { fileExtension, fileFieldLimits } from \"@bettercms-ai/types\";\n\n/**\n * Field types the delivery API serializes. Must stay equal to the authoring\n * vocabulary in `packages/db/src/schema/forms.ts` — this list is what every site\n * renderer switches on, so a type missing HERE renders as a plain text input on\n * every published site while the builder happily offers it. `radio`/`checkboxes`\n * were exactly that gap.\n */\nexport type DeliveryFormFieldType =\n | \"text\"\n | \"email\"\n | \"phone\"\n | \"url\"\n | \"number\"\n | \"date\"\n | \"textarea\"\n | \"select\"\n | \"radio\"\n | \"checkboxes\"\n | \"checkbox\"\n | \"consent\"\n | \"hidden\"\n | \"file\" // attachments: upload each file first (`uploadFormFile`), then submit the returned ids\n | \"step\"; // a divider, not an input: renderers split the form into pages at it\n\nexport interface DeliveryFormField {\n key: string;\n label: string;\n type: DeliveryFormFieldType;\n placeholder?: string;\n /** Hint rendered under the control. */\n helpText?: string;\n required?: boolean;\n options?: string[];\n defaultValue?: string;\n /** Conditional visibility — render this field only when another field equals `equals`. */\n showIf?: { field: string; equals: string };\n /**\n * Per-field rules the API enforces on submit. Renderers should mirror them onto the\n * native control (`min`/`max`/`pattern`) so the browser reports them before the round\n * trip — the server check is the one that counts.\n */\n validation?: DeliveryFormFieldValidation;\n /**\n * Presentation options the renderer honours. Unlike `validation`, the API does NOT enforce\n * these on submit — they change what the visitor is shown, not what is accepted.\n */\n ui?: DeliveryFormFieldUi;\n}\n\n/**\n * @see FormFieldUi in @bettercms-ai/types — same shape, delivered to the site.\n *\n * ── The phone composition contract every renderer implements ──\n *\n * A picker-enabled phone field is rendered as a country control PLUS a `tel` input, but it\n * submits ONE value under the field's own key, in E.164. Whatever a renderer uses to hold the\n * country (a React state, a `{key}__country` select) is scaffolding: it must never reach the\n * POST body.\n *\n * Composition, from the visible input's raw text:\n * - empty → `\"\"`. NEVER `\"+CC\"`, and the reason is worse than \"the server rejects it\". The\n * server's loose phone shape is `{3,32}` chars, so the outcome depends on the calling\n * code's length: `\"+1\"` is REFUSED (an optional untouched field starts 400ing), while\n * `\"+91\"` is ACCEPTED and stored as a real-looking submission that is only a country code.\n * The silent case is the dangerous one. Pinned in `__tests__/lib/forms-validate.test.ts`.\n * - starts with `\"+\"` → `\"+\" + digits(raw)`. The visitor typed an international number; the\n * country control is ignored rather than fighting them.\n * - otherwise → `\"+\" + callingCode + digits(raw).replace(/^0/, \"\")`, dropping ONE trunk zero.\n * Known exception: Italian landlines keep their trunk zero, so this loses it. The value is\n * still accepted (shape-only check) — it is a formatting loss, not a refusal.\n *\n * `ui` changes what the visitor SEES. It never changes what the API accepts: enforcing a format\n * is `validation.phoneFormat`'s job and the two are independent.\n *\n * Renderer parity is behavioural, not implementational. FIVE lanes render this field, and they\n * agree on the VALUE, not on the implementation:\n *\n * | Lane | Control | As-you-type formatting |\n * |-------------------------------|---------------------------------|------------------------|\n * | dashboard form preview | searchable picker + formatter | yes |\n * | @bettercms-ai/next <BcmsForm> | native select + formatter | yes (lazy chunk) |\n * | hosted sites (render-page) | native select + tel input | NO |\n * | embed snippet | native select + tel input | NO |\n * | @bettercms-ai/astro BcmsForm | native select + tel input | NO |\n *\n * The missing as-you-type formatting on the three vanilla lanes is a NAMED degradation, not an\n * oversight: it is what keeps libphonenumber off a visitor's page entirely. `packages/next`\n * pays for it only on pages that actually render a picker, via a separate chunk.\n *\n * When a lane builds that option list, never pass a libphonenumber helper as a bare callback:\n * `getCountries().filter(isSupportedCountry)` hands it the array INDEX as its `metadata`\n * argument and throws. Always wrap — `.filter((iso) => isSupportedCountry(iso))`.\n *\n * And when a lane ships the composition rule inside a JS TEMPLATE LITERAL (the embed snippet\n * does), `\\D` collapses to `D` and the regex silently becomes `/D/g` — stripping the letter D\n * and leaving every other separator in place. Write `\\\\D` there. Raw HTML `<script>` text (the\n * hosted renderer, the Astro inline script) takes a single backslash. Nothing throws either\n * way; numbers just arrive malformed, so each lane pins it with an executed-script test.\n */\nexport interface DeliveryFormFieldUi {\n /** `phone` — render a country picker beside the number. The submitted value is E.164. */\n countryPicker?: boolean;\n /** `phone` — uppercase ISO 3166-1 alpha-2 the picker starts on. */\n defaultCountry?: string;\n /**\n * `phone` — show the country's flag beside the dialling code.\n *\n * Honoured only by a renderer with a custom picker. The native `<select>` the site lanes use\n * cannot hold an SVG, and an emoji flag renders as two grey letters on Windows, so those\n * lanes show the country NAME instead — the same information, legibly, everywhere.\n */\n showFlags?: boolean;\n}\n\n/** @see FormFieldValidation in @bettercms-ai/types — same shape, delivered to the site. */\nexport interface DeliveryFormFieldValidation {\n emailPolicy?: \"any\" | \"business\";\n min?: number;\n max?: number;\n phoneFormat?: \"any\" | \"e164\";\n pattern?: string;\n /** `file` — accepted extensions, lowercase, no dot. */\n accept?: string[];\n /** `file` — files per field. */\n maxFiles?: number;\n /** `file` — per-file cap in MB. */\n maxSizeMb?: number;\n}\n\n/** The pick-many type, whose value is an array rather than a scalar. */\nexport function isMultiValueField(type: DeliveryFormFieldType): boolean {\n return type === \"checkboxes\";\n}\n\n/** A form as delivered to a published/imported site. Mirrors the delivery `/forms` payload. */\nexport interface DeliveryForm {\n id: string;\n name: string;\n /** The project the form belongs to. */\n projectId?: string | null;\n /**\n * A `draft` form refuses every submission: render it as unavailable rather than as a form that\n * silently drops what a visitor sends. Delivered for exactly that reason, and missing from this\n * type until the contract test held the two together.\n */\n status?: \"draft\" | \"published\" | (string & {});\n /** Set on a form the site's owner told BetterCMS to leave alone (ISO time); such a form is not wired. */\n ignoredAt?: string | null;\n fields: DeliveryFormField[];\n submitLabel?: string;\n successMessage?: string;\n redirectUrl?: string;\n turnstileEnabled?: boolean;\n honeypotField?: string | null;\n}\n\n/** `string[]` is the `checkboxes` (pick-many) value; every other type is scalar. */\nexport type FormValue = string | boolean | string[];\nexport type FormValues = Record<string, FormValue>;\n\n/** Read a `checkboxes` value defensively — stored data may predate the array shape. */\nexport function asStringArray(value: FormValue | undefined): string[] {\n if (Array.isArray(value)) return value;\n return value ? [String(value)] : [];\n}\n\n/** Add/remove `option` from a `checkboxes` value, preserving the field's option order. */\nexport function toggleOption(value: FormValue | undefined, option: string, on: boolean): string[] {\n const current = asStringArray(value);\n if (on) return current.includes(option) ? current : [...current, option];\n return current.filter((v) => v !== option);\n}\n\nconst DEFAULT_BASE_URL = \"https://api.bettercms.ai\";\n\n// ── File fields ──────────────────────────────────────────────────────────────\n\n/**\n * The limits a renderer checks a chosen file against before uploading it: the field as\n * delivered, with the platform's defaults and ceilings. @see fileFieldLimits in @bettercms-ai/types\n */\nexport { fileFieldLimits };\n\n/** Why a chosen file is refused before upload, or null: a sentence the visitor can read. */\nexport function fileFieldRefusal(\n limits: { accept: string[]; maxSizeMb: number },\n file: { name: string; size: number },\n): string | null {\n const ext = fileExtension(file.name);\n if (!ext || !limits.accept.includes(ext)) {\n return `This type of file is not accepted here. Accepted: ${limits.accept.map((e) => `.${e}`).join(\", \")}.`;\n }\n if (file.size === 0) return \"This file is empty.\";\n if (file.size > limits.maxSizeMb * 1024 * 1024) return `This file is larger than ${limits.maxSizeMb} MB.`;\n return null;\n}\n\nexport interface UploadFormFileOptions {\n formId: string;\n /** The `file` field's key. */\n fieldKey: string;\n /** A browser `File` (anything with a name and a body). */\n file: Blob & { name: string };\n /** API origin. Defaults to https://api.bettercms.ai. */\n baseUrl?: string;\n /** Injectable fetch for tests / non-browser runtimes. */\n fetchImpl?: typeof fetch;\n}\n\nexport interface UploadedFormFile {\n /** What the submission names this file by: put it in the field's value. */\n id: string;\n name: string;\n size: number;\n}\n\n/**\n * Upload one file of a form's `file` field, ahead of the submit. Resolves with the id the\n * submission names it by (`data[fieldKey] = [id, …]`), or throws a BetterCMSError whose\n * `bodyCode` is the server's (FILE_TOO_LARGE, UPLOAD_TYPE_NOT_ALLOWED, UPLOAD_BUSY,\n * STORAGE_FULL, …) and whose message is a sentence for the visitor. No retry.\n *\n * The body is the file's bytes and nothing else; its name travels percent-encoded in a header,\n * so it never lands in an access log.\n */\nexport async function uploadFormFile(opts: UploadFormFileOptions): Promise<UploadedFormFile> {\n const baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n const doFetch = opts.fetchImpl ?? globalThis.fetch;\n let res: Response;\n try {\n res = await doFetch(\n `${baseUrl}/api/v1/forms/public/${encodeURIComponent(opts.formId)}/uploads?field=${encodeURIComponent(opts.fieldKey)}`,\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/octet-stream\", \"X-Bcms-Filename\": encodeURIComponent(opts.file.name) },\n body: opts.file,\n },\n );\n } catch (err) {\n throw new BetterCMSError(\n `Network error: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n ErrorCodes.NETWORK_ERROR,\n );\n }\n if (!res.ok) throw await BetterCMSError.from(res);\n const json = (await res.json().catch(() => ({}))) as { data?: Partial<UploadedFormFile> };\n const data = json.data;\n if (!data?.id) throw new BetterCMSError(\"The file could not be saved. Please try again.\", res.status, ErrorCodes.INTERNAL_ERROR);\n return { id: data.id, name: data.name ?? opts.file.name, size: data.size ?? opts.file.size };\n}\n\n/**\n * Conditional visibility. A `showIf` field is shown only when its trigger field's\n * current value equals the target; non-conditional fields are always shown. The\n * renderer must skip hidden fields when collecting/validating so a hidden required\n * field never blocks submit.\n */\nexport function shouldShowField(field: DeliveryFormField, values: FormValues): boolean {\n if (!field.showIf) return true;\n const trigger = values[field.showIf.field];\n // A pick-many trigger satisfies `equals` when the option is among those checked;\n // `String([\"a\",\"b\"])` would compare against \"a,b\" and never match.\n if (Array.isArray(trigger)) return trigger.includes(field.showIf.equals);\n return String(trigger ?? \"\") === field.showIf.equals;\n}\n\n/**\n * Build the initial value map: checkbox/consent default to false, checkboxes to an\n * empty array, every other field to its `defaultValue`, with `prefill` (e.g. URL\n * query params) taking precedence.\n */\nexport function formInitialValues(\n form: DeliveryForm,\n prefill: Record<string, string> = {},\n): FormValues {\n const values: FormValues = {};\n for (const field of form.fields) {\n if (field.type === \"step\") continue; // a divider holds no value\n // A file field starts empty, whatever the link or the field says: its value is the ids of\n // files THIS visitor uploaded. A prefilled id (`?cv=<id>`) would attach someone else's file.\n if (field.type === \"file\") {\n values[field.key] = [];\n continue;\n }\n if (field.type === \"checkbox\" || field.type === \"consent\") {\n values[field.key] = false;\n } else if (field.type === \"checkboxes\") {\n const seed = prefill[field.key] ?? field.defaultValue ?? \"\";\n // A prefill/default arrives as a scalar (query string, stored column), so split\n // it back into the option list the control renders against.\n values[field.key] = seed ? seed.split(\",\").map((v) => v.trim()).filter(Boolean) : [];\n } else {\n values[field.key] = prefill[field.key] ?? field.defaultValue ?? \"\";\n }\n }\n return values;\n}\n\nexport interface SubmitFormOptions {\n formId: string;\n data: FormValues;\n /** Cloudflare Turnstile token; required when the form has `turnstileEnabled`. */\n turnstileToken?: string;\n /** The path of the page the form sits on (\"/pricing\"). Defaults to `location.pathname` in a browser. */\n page?: string;\n /** API origin. Defaults to https://api.bettercms.ai. */\n baseUrl?: string;\n /** Injectable fetch for tests / non-browser runtimes. */\n fetchImpl?: typeof fetch;\n}\n\nexport interface SubmitFormResult {\n id: string;\n}\n\n/** A submit failure that carries per-field validation messages from the API (HTTP 400). */\nexport type FormSubmitError = BetterCMSError & { fieldErrors?: Record<string, string> };\n\n/**\n * Submit a public form. Resolves with the new submission id, or throws a\n * BetterCMSError — field-level validation errors are attached as `.fieldErrors`.\n */\nexport async function submitForm(opts: SubmitFormOptions): Promise<SubmitFormResult> {\n const baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n const doFetch = opts.fetchImpl ?? globalThis.fetch;\n const body: Record<string, unknown> = { data: opts.data };\n // The page the form sits on, for the submission's \"Sent from\" (browser only; a server call has none).\n const page = opts.page ?? (globalThis as { location?: { pathname?: string } }).location?.pathname;\n if (page) body.page = page;\n if (opts.turnstileToken) body[\"cf-turnstile-response\"] = opts.turnstileToken;\n\n let res: Response;\n try {\n res = await doFetch(`${baseUrl}/api/v1/forms/public/${opts.formId}/submissions`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n } catch (err) {\n throw new BetterCMSError(\n `Network error: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n ErrorCodes.NETWORK_ERROR,\n );\n }\n\n if (!res.ok) {\n // `.from` reads the body for message/code; clone so we can still read `errors`.\n const error = (await BetterCMSError.from(res.clone())) as FormSubmitError;\n const body = (await res.json().catch(() => ({}))) as { errors?: Record<string, string> };\n if (body.errors) error.fieldErrors = body.errors;\n throw error;\n }\n\n const json = (await res.json().catch(() => ({}))) as { id?: string | number };\n return { id: String(json.id ?? \"\") };\n}\n","/**\n * Public site search — the headless surface for the visitor-facing search box.\n *\n * Queries `GET /api/v1/delivery/search?project=…&q=…`, the same key-less public\n * endpoint the embeddable widget uses. Powers <BcmsSearch> in @bettercms-ai/next\n * and @bettercms-ai/astro, so the component and any custom UI never drift.\n *\n * `snippet` is HTML-safe: the server escapes the field content and keeps only the\n * <mark> highlight wrappers, so it can be rendered with dangerouslySetInnerHTML.\n */\n\nconst DEFAULT_BASE_URL = \"https://api.bettercms.ai\";\n\nexport interface SearchHit {\n title: string;\n slug: string;\n type: \"page\" | \"entry\";\n /** HTML-safe snippet with <mark> highlights around matched terms. */\n snippet: string;\n /** Site-relative URL, e.g. \"/about\". Absent on an entry no page of the site serves. */\n url?: string;\n}\n\nexport interface SearchOptions {\n /** The project id (from the dashboard's Site Search settings). */\n project: string;\n /** The query string. Calls with fewer than 1 char resolve to []. */\n q: string;\n /** Max hits, 1–20 (default 8). */\n limit?: number;\n /** API origin. Defaults to https://api.bettercms.ai. */\n baseUrl?: string;\n /** Injectable fetch for tests / non-browser runtimes. */\n fetchImpl?: typeof fetch;\n /** AbortSignal so callers can cancel a stale in-flight search. */\n signal?: AbortSignal;\n}\n\n/** Search a published site. Resolves with hits, or [] on an empty query / network error. */\nexport async function search(opts: SearchOptions): Promise<SearchHit[]> {\n const q = opts.q.trim();\n if (!q) return [];\n const baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n const doFetch = opts.fetchImpl ?? globalThis.fetch;\n const params = new URLSearchParams({ project: opts.project, q });\n if (opts.limit) params.set(\"limit\", String(opts.limit));\n\n try {\n const res = await doFetch(`${baseUrl}/api/v1/delivery/search?${params}`, { signal: opts.signal });\n if (!res.ok) return [];\n const json = (await res.json().catch(() => ({}))) as { hits?: SearchHit[] };\n return json.hits ?? [];\n } catch {\n return []; // network/abort → no results, never throw into a render path\n }\n}\n","/**\n * Reading a rich-text field, for any site.\n *\n * A `text` field delivers a bare string. A `richtext` field delivers the canonical envelope\n * `{ format, value, html }`. Those are different shapes, and switching a field's type in the\n * CMS switches which one your site receives — the Visual Editor offers exactly that switch,\n * so it happens on live projects. A template that interpolates the value directly then\n * renders `[object Object]` (or, in React, throws `Objects are not valid as a React child`).\n *\n * No payload can be both structured and safe to interpolate, which is why every headless CMS\n * requires a renderer for rich text. These are ours:\n *\n * plain(v) → text, for <title>, meta descriptions, JSON-LD, alt text, aria-label\n * rich(v) → HTML, for `set:html` / `dangerouslySetInnerHTML`\n *\n * Both accept a bare string, so a field can be switched in the CMS without touching the site.\n *\n * <h1 set:html={rich(page.heroTitle)} /> // Astro\n * <h1 dangerouslySetInnerHTML={{ __html: rich(f.heroTitle) }}/> // React\n * seo({ title: plain(page.heroTitle) })\n */\n\nimport type { RichTextEmbeds, RichTextResolved } from \"@bettercms-ai/types\";\n\n/**\n * A block in a Body field's `doc`. Bounded vocabulary — the server only emits what it can\n * parse back, so an unknown `type` means your SDK is older than the content, not that the\n * content is malformed. Handle the default case rather than exhausting on it.\n */\nexport type DocBlock = {\n /**\n * Stable within THIS document only — never a global key. Two different entries both have a\n * block called \"0.0\". A cross-document anchor is (entryId, fieldKey, id).\n *\n * Ids on content authored before block ids existed are derived from position, so they SHIFT\n * when that document is edited. Do not persist an id as a bookmark unless you know it came\n * from the editor rather than from the positional fallback.\n */\n readonly id: string;\n readonly type: string;\n readonly [key: string]: unknown;\n};\n\n/** The `doc` rendition of a Body field — a versioned block array. */\nexport type DocValue = {\n readonly version: 1;\n readonly blocks: readonly DocBlock[];\n};\n\n/** The canonical rich-text envelope returned by the Delivery API. */\nexport interface RichTextValue {\n readonly format?: string;\n readonly value?: unknown;\n /** Server-rendered, sanitized HTML. Computed on write. */\n readonly html?: string;\n /**\n * Structured blocks — present on `document` (Body) fields only, and NOT guaranteed even\n * there: it is derived at write time, so an entry saved before this existed carries none\n * until its next save. There is no backfill. Always branch on its absence; `html` is the\n * field that is always there.\n */\n readonly doc?: DocValue;\n /**\n * The embeds the server resolved when it built `html`: X cards keyed by canonical url (X's\n * script, when a site opts in, is the page's, never the value's). `html` already holds each card, so `rich()` never needs this; it is\n * for renderers of the STRUCTURE (`<PortableText embeds={…}>`). Absent on a value with no embed\n * and on any envelope written before it existed: read it through `embeds()`.\n */\n readonly embeds?: RichTextEmbeds;\n /**\n * What the value's related posts and author bios point at, resolved by the server for THIS\n * response from the published entries (never stored). `html` already draws them; this is for\n * renderers of the structure (`<PortableText resolved={…}>`). Absent on a value with neither block.\n * Read it through `resolved()`.\n */\n readonly resolved?: RichTextResolved;\n}\n\n/** The marker on a Portable Text envelope. `format` is a plain string, never a union — see below. */\nexport const PORTABLE_TEXT_FORMAT = \"portable-text-1\";\n\n/**\n * Structured blocks, when the field stores Portable Text.\n *\n * ── The compatibility guarantee, stated once ────────────────────────────────────────────\n * Portable Text did NOT change this envelope. `format`, `value` and `html` are the same three\n * keys they always were, so `isRichText`, `plain()` and `rich()` keep working untouched — and\n * they have to, because sites compiled months ago read `.html` directly and cannot be\n * rebuilt. `bettercms-starter-modern/lib/cms.ts` even carries its OWN copy of `rich()`, baked\n * into deployments nobody can reach. Storing a bare array instead would have made\n * `isRichText` return false (it rejects arrays), every shipped `rich()` call return \"\", and\n * every one of those pages go blank at 200 OK.\n *\n * `portableText()` is therefore ADDITIVE: `html` remains the always-present field, and this is\n * the opt-in for consumers that want to render structure with `@portabletext/react` instead.\n */\nexport function portableText(value: TextOrRich): readonly unknown[] | null {\n if (!isRichText(value)) return null;\n const v = value as RichTextValue & { format?: string; value?: unknown };\n return v.format === PORTABLE_TEXT_FORMAT && Array.isArray(v.value) ? (v.value as readonly unknown[]) : null;\n}\n\n/**\n * The value's resolved embeds, for a renderer of its structure (`<PortableText embeds>`), or null:\n * a bare string, a value with no embed, or an envelope written before embeds existed. Additive,\n * like `portableText()`: `rich()` reads `html`, which already holds the cards.\n */\nexport function embeds(value: TextOrRich): RichTextEmbeds | null {\n if (!isRichText(value)) return null;\n const e = (value as RichTextValue).embeds;\n return typeof e === \"object\" && e !== null && typeof e.cards === \"object\" && e.cards !== null ? e : null;\n}\n\n/** A delivered entry as far as `resolved()` reads it: its entry-level map. */\nexport interface ResolvedHolder {\n readonly resolved?: RichTextResolved | null;\n readonly data?: unknown;\n}\n\nconst resolvedMap = (r: unknown): RichTextResolved | null =>\n typeof r === \"object\" && r !== null && !Array.isArray(r) ? (r as RichTextResolved) : null;\n\n/**\n * What a rich-text value's related posts and author bios resolved to, for a renderer of its\n * structure (`<PortableText resolved>`), or null when there is nothing.\n *\n * resolved(entry.data.body, entry) // a field value, with the entry it came in\n * resolved(entry) // the entry's merged map\n *\n * An envelope value carries its own (`value.resolved`), which wins. A Body stored as a bare block\n * array has nowhere to carry one, so delivery puts the entry's merged map beside `data`\n * (`entry.resolved`): pass the entry and that is what you get. Additive, like `embeds()`: `rich()`\n * reads `html`, which already draws them.\n */\nexport function resolved(value: TextOrRich | readonly unknown[] | ResolvedHolder, entry?: ResolvedHolder | null): RichTextResolved | null {\n const own = isRichText(value) ? resolvedMap((value as RichTextValue).resolved) : null;\n if (own) return own;\n if (entry) return resolvedMap(entry.resolved);\n // An entry passed on its own: its merged map.\n const v = value as { data?: unknown; resolved?: unknown } | null;\n return v && typeof v === \"object\" && !Array.isArray(v) && \"data\" in v ? resolvedMap(v.resolved) : null;\n}\n\n/**\n * A field that may arrive as either shape. Type author-editable text fields with this and the\n * compiler routes you through `plain()`/`rich()`, so a type switch in the CMS can never reach\n * production as `[object Object]`.\n */\nexport type TextOrRich = string | RichTextValue | null | undefined;\n\n/** True when the value is a rich-text envelope rather than a bare string. */\nexport function isRichText(value: unknown): value is RichTextValue {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n (\"html\" in value || \"format\" in value)\n );\n}\n\n/**\n * Plain text for an attribute context — `<title>`, meta description, JSON-LD, `alt`.\n * Strips tags and decodes the entities that survive stripping, so the result is text the\n * consumer can escape once without double-escaping.\n */\nexport function plain(value: TextOrRich): string {\n if (typeof value === \"string\") return value;\n if (!isRichText(value) || typeof value.html !== \"string\") return \"\";\n return decodeEntities(value.html.replace(/<[^>]+>/g, \"\")).trim();\n}\n\n/**\n * Renderable HTML. Rich text keeps its inline marks (the server sanitizes `html` on write);\n * a bare string is escaped, so a plain field can never inject markup.\n *\n * A lone wrapping block is unwrapped: a field switched from `text` stores its value as\n * `<p>…</p>`, but it renders inside the element that already is the block — and\n * `<h1><p>…</p></h1>` is invalid, the parser closes the heading at the `<p>` and the text\n * falls out of it. Values with real block structure (several paragraphs, a list) are left\n * alone, so a body field still renders as a document.\n */\nexport function rich(value: TextOrRich, fallback = \"\"): string {\n const html = (typeof value === \"string\" ? escapeHtml(value) : isRichText(value) ? (value.html ?? \"\") : \"\").trim();\n return html ? unwrapLoneBlock(html) : escapeHtml(fallback);\n}\n\n/**\n * Renderable HTML for a ONE-LINE place: a heading, a button, a caption. `rich()`, except that several\n * paragraphs are that place's LINES, joined with `<br>` (a heading-styled first block counts as one).\n *\n * An author who presses Enter in a heading's editor stores a second paragraph. `rich()` leaves it a\n * paragraph, and `<h1><p>…</p><p>…</p></h1>` is what the build then draws, while a publish between\n * builds writes the same value into the built heading as lines. This draws what the publish draws.\n * A value holding anything else (a list, an image, a table) is returned as `rich()` returns it.\n */\nexport function lines(value: TextOrRich, fallback = \"\"): string {\n const html = rich(value, fallback);\n const block = /<(p|h[1-6])(?:\\s[^>]*)?>([\\s\\S]*?)<\\/\\1>/gi;\n // ponytail: a regex, not a parser. Past this size it is a body, never a one-line value.\n if (html.length > 10_000) return html;\n const found = [...html.matchAll(block)];\n if (found.length < 2 || html.replace(block, \"\").trim() !== \"\") return html;\n const shown = found.map((m) => m[2]!.trim()).filter((line) => line.replace(/<br\\s*\\/?>/gi, \"\").trim() !== \"\");\n return shown.length ? shown.join(\"<br>\") : html;\n}\n\nfunction unwrapLoneBlock(html: string): string {\n const m = html.match(/^<(p|div|h[1-6])(?:\\s[^>]*)?>([\\s\\S]*)<\\/\\1>$/i);\n return m && !new RegExp(`</${m[1]}>`, \"i\").test(m[2]) ? m[2] : html;\n}\n\nfunction escapeHtml(s: string): string {\n return s.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\");\n}\n\nfunction decodeEntities(s: string): string {\n return s\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/"/g, '\"')\n .replace(/�?39;/g, \"'\")\n .replace(/ /g, \" \")\n .replace(/&/g, \"&\");\n}\n","/**\n * The published content snapshot, read where the site RUNS — not bundled into it.\n *\n * Every BetterCMS build gets the published content as `bcms-content.json` in the project root,\n * and a server app hosted on BetterCMS runs with `BCMS_CONTENT_FILE` pointing at a copy the\n * platform rewrites on every publish. Read through this, a server-rendered page shows a publish\n * within seconds and the publish never rebuilds the site. Import the JSON instead (a JSON import,\n * `import.meta.glob`) and the bundle holds a frozen copy no publish can reach: the platform then\n * has to rebuild the whole site for every edit.\n *\n * - On a hosted server: `BCMS_CONTENT_FILE`, re-read when it changes (its time is asked on every call).\n * - At build time and in local dev: `<cwd>/bcms-content.json`, the snapshot the build was given.\n * - Anywhere without a filesystem (a browser, an edge runtime): `null`.\n *\n * A file that cannot be read keeps the last good copy; never throws into a render.\n * No `node:fs` import at module scope, so the SDK stays safe to bundle for the browser.\n */\n\n/** The snapshot's shape (`bcms-content/v1`, written by the platform's content fetch). */\nexport interface PublishedContent {\n generatedAt?: string;\n apiUrl?: string | null;\n workspace?: string;\n projectId?: string | null;\n /**\n * Published entries by model slug, each row AS THE DELIVERY API SERVES IT: `id`, `slug`, `status`,\n * `publishedAt`, `updatedAt`, `locale`, `translationOf`, `_meta`, and the field values under\n * `data`. Read a value through {@link publishedEntry}, which answers either spelling.\n */\n collections?: Record<string, Array<Record<string, unknown> & { slug?: string; data?: Record<string, unknown> }>>;\n pages?: unknown[];\n components?: unknown[];\n forms?: unknown[];\n layout?: unknown;\n [key: string]: unknown;\n}\n\ntype Proc = {\n env?: Record<string, string | undefined>;\n cwd?: () => string;\n getBuiltinModule?: (id: string) => unknown;\n};\ntype Fs = {\n statSync(path: string): { mtimeMs: number };\n readFileSync(path: string, encoding: \"utf8\"): string;\n};\n\nlet cache: { file: string; stamp: number; content: PublishedContent | null } | null = null;\n\n/** Where the published content is read from here, or null where there is no filesystem. */\nexport function publishedContentFile(): string | null {\n const proc = (globalThis as { process?: Proc }).process;\n if (typeof proc?.getBuiltinModule !== \"function\") return null;\n return proc.env?.BCMS_CONTENT_FILE || `${proc.cwd?.() ?? \".\"}/bcms-content.json`;\n}\n\n/**\n * The published content snapshot, or null when there is none here (no file, no filesystem).\n * Call it per render — it is cached and cheap — never once at module scope, which would freeze it.\n */\nexport function readPublishedContent<T extends PublishedContent = PublishedContent>(): T | null {\n const file = publishedContentFile();\n if (!file) return null;\n // A stat on every call (microseconds), the parse only when the file changed: a publish shows on the\n // very next request. A once-a-second check left a page on the old copy for up to a second.\n const proc = (globalThis as { process?: Proc }).process!;\n const fs = proc.getBuiltinModule!(\"node:fs\") as Fs;\n try {\n const stamp = fs.statSync(file).mtimeMs;\n if (cache && cache.file === file && cache.stamp === stamp) return cache.content as T | null;\n cache = { file, stamp, content: JSON.parse(fs.readFileSync(file, \"utf8\")) as PublishedContent };\n } catch {\n // Absent (a local build without a snapshot), or caught mid-write: keep the last good copy.\n if (!cache || cache.file !== file) cache = { file, stamp: -1, content: null };\n }\n return cache.content as T | null;\n}\n\n/** Each row flattened once: a page asks for the same entry for every field it renders. */\nconst flat = new WeakMap<object, Record<string, unknown>>();\n\n/**\n * One published entry by its slug, searched across every collection (first match wins, in the\n * snapshot's model order). Not keyed by model slug: a page's backing model is named by the CMS.\n *\n * 🔴 THE VALUES ARE ON THE ENTRY: `publishedEntry(\"home\")?.title`. The snapshot holds each row as\n * the delivery API serves it, values under `data`, and this used to hand that row back as it was\n * while its own doc (and the skill that names it) said \"the row carries its field values\" — so\n * `entry.title` was `undefined` and every field of a server-rendered page fell back to the copy in\n * the code, on every publish. Both spellings are answered: the values at the top level and the\n * row's own keys (`id`, `slug`, `status`, `data`, `_meta`, …) beside them, the row's winning where\n * a field is named like one — that field is read through `.data`, as before.\n */\nexport function publishedEntry<T extends Record<string, unknown> = Record<string, unknown>>(slug: string): (T & { slug: string }) | null {\n const collections = readPublishedContent()?.collections ?? {};\n for (const rows of Object.values(collections)) {\n if (!Array.isArray(rows)) continue;\n const hit = rows.find((row) => row?.slug === slug);\n if (!hit) continue;\n const data = hit.data;\n if (!data || typeof data !== \"object\" || Array.isArray(data)) return hit as T & { slug: string };\n let entry = flat.get(hit);\n if (!entry) flat.set(hit, (entry = { ...data, ...hit }));\n return entry as T & { slug: string };\n }\n return null;\n}\n\n/** Test seam: forget the cached snapshot. */\nexport function resetPublishedContentCache(): void {\n cache = null;\n}\n"],"mappings":";AAGO,IAAM,aAAa;AAAA,EACxB,mBAAmB;AAAA,EACnB,cAAc;AAAA,EACd,WAAW;AAAA,EACX,cAAc;AAAA,EACd,gBAAgB;AAAA,EAChB,kBAAkB;AAAA,EAClB,eAAe;AAAA,EACf,uBAAuB;AACzB;AAKA,SAAS,aAAa,QAAoC;AACxD,MAAI,WAAW,IAAK,QAAO,WAAW;AACtC,MAAI,WAAW,IAAK,QAAO,WAAW;AACtC,MAAI,WAAW,IAAK,QAAO,WAAW;AACtC,MAAI,WAAW,IAAK,QAAO,WAAW;AACtC,MAAI,UAAU,IAAK,QAAO,WAAW;AACrC,MAAI,WAAW,IAAK,QAAO,WAAW;AACtC,SAAO,WAAW;AACpB;AAKO,IAAM,iBAAN,MAAM,wBAAuB,MAAM;AAAA,EAC/B;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;A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AM,KAAK,KAAK,iBAAkB,SAAS;AAC3C,MAAI;AACF,UAAM,QAAQ,GAAG,SAAS,IAAI,EAAE;AAChC,QAAI,SAAS,MAAM,SAAS,QAAQ,MAAM,UAAU,MAAO,QAAO,MAAM;AACxE,YAAQ,EAAE,MAAM,OAAO,SAAS,KAAK,MAAM,GAAG,aAAa,MAAM,MAAM,CAAC,EAAsB;AAAA,EAChG,QAAQ;AAEN,QAAI,CAAC,SAAS,MAAM,SAAS,KAAM,SAAQ,EAAE,MAAM,OAAO,IAAI,SAAS,KAAK;AAAA,EAC9E;AACA,SAAO,MAAM;AACf;AAGA,IAAM,OAAO,oBAAI,QAAyC;AAcnD,SAAS,eAA4E,MAA6C;AACvI,QAAM,cAAc,qBAAqB,GAAG,eAAe,CAAC;AAC5D,aAAW,QAAQ,OAAO,OAAO,WAAW,GAAG;AAC7C,QAAI,CAAC,MAAM,QAAQ,IAAI,EAAG;AAC1B,UAAM,MAAM,KAAK,KAAK,CAAC,QAAQ,KAAK,SAAS,IAAI;AACjD,QAAI,CAAC,IAAK;AACV,UAAM,OAAO,IAAI;AACjB,QAAI,CAAC,QAAQ,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,EAAG,QAAO;AACrE,QAAI,QAAQ,KAAK,IAAI,GAAG;AACxB,QAAI,CAAC,MAAO,MAAK,IAAI,KAAM,QAAQ,EAAE,GAAG,MAAM,GAAG,IAAI,CAAE;AACvD,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAGO,SAAS,6BAAmC;AACjD,UAAQ;AACV;","names":["body","DEFAULT_BASE_URL"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/retry.ts","../src/draft.ts","../src/read-client.ts","../src/forms.ts","../src/search.ts","../src/richtext.ts","../src/published-content.ts"],"sourcesContent":["import type { BetterCMSErrorCode } from \"@bettercms-ai/types\";\n\n/** Semantic error codes used by the SDK. */\nexport const ErrorCodes = {\n CONTENT_NOT_FOUND: \"CONTENT_NOT_FOUND\",\n UNAUTHORIZED: \"UNAUTHORIZED\",\n FORBIDDEN: \"FORBIDDEN\",\n RATE_LIMITED: \"RATE_LIMITED\",\n INTERNAL_ERROR: \"INTERNAL_ERROR\",\n VALIDATION_ERROR: \"VALIDATION_ERROR\",\n NETWORK_ERROR: \"NETWORK_ERROR\",\n ADMIN_NOT_IMPLEMENTED: \"ADMIN_NOT_IMPLEMENTED\",\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\n/** Maps HTTP status codes to semantic error codes. */\nfunction statusToCode(status: number): BetterCMSErrorCode {\n if (status === 404) return ErrorCodes.CONTENT_NOT_FOUND;\n if (status === 401) return ErrorCodes.UNAUTHORIZED;\n if (status === 403) return ErrorCodes.FORBIDDEN;\n if (status === 429) return ErrorCodes.RATE_LIMITED;\n if (status >= 500) return ErrorCodes.INTERNAL_ERROR;\n if (status === 422) return ErrorCodes.VALIDATION_ERROR;\n return ErrorCodes.INTERNAL_ERROR;\n}\n\n/**\n * BetterCMSError — normalized SDK error with a semantic code.\n */\nexport class BetterCMSError extends Error {\n readonly status: number;\n readonly code: BetterCMSErrorCode;\n /**\n * Raw machine-readable `code` from the response body (e.g. \"PROJECT_DELETED\"),\n * when the API supplies one. Distinct from `code` (which is derived from the\n * HTTP status), this lets callers branch on a specific server condition that\n * shares a status with others (e.g. 409 slug-conflict vs 409 project-deleted).\n */\n readonly bodyCode?: string;\n /**\n * Per-field validation messages from a 400 `{ errors: { field: message } }` body.\n * The backend returns validation failures in this shape (not `message`/`error`), so\n * without this the SDK collapsed every validation 400 to a bare \"Bad Request\" with no\n * hint which field or rule failed (FLO-474). Mirrors the forms client's `fieldErrors`.\n */\n readonly fieldErrors?: Record<string, string>;\n /**\n * The parsed response body, when there was one.\n *\n * Several refusals carry STRUCTURED detail that neither `message` nor `fieldErrors` can hold,\n * and which is the whole point of the refusal: a component publish 409s with the full\n * `readiness` tuple (what evidence is missing, whether a human still has to approve it) and\n * 422s with the `issues` naming the Layouts it would break. Collapsing those to a sentence\n * leaves a caller able to report that something failed and not what to do about it.\n */\n readonly body?: unknown;\n\n constructor(\n message: string,\n status: number,\n code: BetterCMSErrorCode,\n bodyCode?: string,\n fieldErrors?: Record<string, string>,\n body?: unknown,\n ) {\n super(message);\n this.name = \"BetterCMSError\";\n this.status = status;\n this.code = code;\n this.bodyCode = bodyCode;\n this.fieldErrors = fieldErrors;\n this.body = body;\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, BetterCMSError);\n }\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n status: this.status,\n code: this.code,\n bodyCode: this.bodyCode,\n fieldErrors: this.fieldErrors,\n };\n }\n\n /**\n * Factory — creates a BetterCMSError from a failed fetch Response. Reads the body's\n * `message` (or `error`) for the human message and `code` for a machine-readable\n * condition surfaced as `bodyCode`. Validation failures arrive as `{ errors: {...} }`\n * (no `message`/`error`), so fall back to the first field error for the message and\n * expose the full map as `fieldErrors` (FLO-474).\n */\n static async from(res: Response): Promise<BetterCMSError> {\n let message = res.statusText || \"An error occurred\";\n let bodyCode: string | undefined;\n let fieldErrors: Record<string, string> | undefined;\n let code = statusToCode(res.status);\n let raw: unknown;\n try {\n const body = (await res.json()) as {\n message?: string;\n error?: string;\n code?: string;\n errors?: Record<string, string>;\n };\n if (body?.errors && typeof body.errors === \"object\") {\n fieldErrors = body.errors;\n code = ErrorCodes.VALIDATION_ERROR;\n }\n if (body?.message) message = body.message;\n else if (body?.error) message = body.error;\n else if (fieldErrors) {\n const [field, detail] = Object.entries(fieldErrors).find(\n ([, v]) => typeof v === \"string\" && v.length > 0,\n ) ?? [];\n if (field) message = `${field}: ${detail}`;\n }\n if (body?.code) bodyCode = body.code;\n raw = body;\n } catch {\n // ignore parse errors\n }\n return new BetterCMSError(message, res.status, code, bodyCode, fieldErrors, raw);\n }\n}\n","/**\n * Shared 429/503 backoff for every SDK client.\n *\n * ── Why this exists ─────────────────────────────────────────────────────────\n * The backend limiter (src/lib/ratelimit.ts, windowHit) is a FIXED 60-SECOND\n * WINDOW: 100 requests per workspace per endpoint, and a denial answers\n * `Retry-After: <seconds until the window resets>` — anything up to 60.\n *\n * Every client here used to climb a private ladder that topped out at 7 seconds\n * ([250,750,1500] in read-client, [1000,2000,4000] in admin/management) and none\n * of them read Retry-After. So all three retries landed INSIDE the same exhausted\n * window and a 429 was fatal roughly whenever it was thrown. The retry code looked\n * like resilience but could only ever recover from a denial raised in the final\n * seconds of a window.\n *\n * That is what failed customer builds: `action/fetch-content.mjs` spends ~65 of the\n * 100 `delivery-content-entries-list` slots pulling a large workspace, `npm run build`\n * starts seconds later in the SAME window, and the first per-route delivery read past\n * the ceiling killed the deploy with \"Too many requests. Please retry later.\"\n *\n * ── The rule ────────────────────────────────────────────────────────────────\n * Obey Retry-After when the server sends one, and let a single request outlast a\n * whole window. A build waiting 60s is slow; a build that dies is a broken product.\n */\n\n/** Statuses worth retrying. 429 = rate limited, 503 = limiter/backend unavailable. */\nexport const RETRY_STATUSES = [429, 503] as const;\n\n/** Retries after the first attempt. 3 retries × up to ~65s spans three full windows. */\nexport const MAX_RETRIES = 3;\n\n/**\n * Hard ceiling on a single wait, jitter included. Must exceed the limiter's 60s\n * window, or a denial raised at the very start of a window still cannot be waited\n * out — and must be finite, so a hostile or mis-set Retry-After cannot hang a build.\n */\nexport const MAX_DELAY_MS = 65_000;\n\n/** Fallback ladder when the server sends no Retry-After: 1s, 2s, 4s, 8s. */\nconst BASE_DELAY_MS = 1_000;\n\n/**\n * De-sync jitter, added to every wait.\n *\n * Deliberately a small FLAT amount, not a percentage. Requests denied by one window\n * only need to stop firing in the same millisecond — the server's counter serialises\n * them after that. A proportional jitter would add up to 15 seconds to a 60-second\n * wait for no benefit, and would push the total past MAX_DELAY_MS.\n */\nconst JITTER_MS = 250;\n\nexport function isRetryableStatus(status: number): boolean {\n return (RETRY_STATUSES as readonly number[]).includes(status);\n}\n\n/**\n * Parse `Retry-After`, which RFC 9110 allows in either form: delay-seconds\n * (\"47\") or an HTTP-date (\"Wed, 21 Oct 2015 07:28:00 GMT\"). Returns ms to wait,\n * or null when the header is absent or unparseable.\n */\nexport function retryAfterMs(res: Pick<Response, \"headers\">): number | null {\n const raw = res.headers?.get?.(\"retry-after\");\n if (!raw) return null;\n\n const seconds = Number(raw);\n if (Number.isFinite(seconds)) {\n return Math.min(Math.max(seconds, 0) * 1000, MAX_DELAY_MS);\n }\n\n const at = Date.parse(raw);\n if (!Number.isNaN(at)) {\n return Math.min(Math.max(0, at - Date.now()), MAX_DELAY_MS);\n }\n return null;\n}\n\n/**\n * How long to wait before retry `attempt` (0-based).\n *\n * Server instruction wins; otherwise exponential. Jitter is added in both cases:\n * when a build's requests are all denied by the same window they would otherwise\n * wake in lockstep at the reset and re-exhaust it immediately (thundering herd).\n */\nexport function backoffMs(attempt: number, res?: Pick<Response, \"headers\">): number {\n const fromServer = res ? retryAfterMs(res) : null;\n // Base is capped with the jitter's headroom already reserved, so the total never\n // exceeds MAX_DELAY_MS AND the jitter is never clamped away at the ceiling — which\n // would put every capped caller back in lockstep, the exact thing jitter prevents.\n const base = Math.min(fromServer ?? BASE_DELAY_MS * 2 ** attempt, MAX_DELAY_MS - JITTER_MS);\n // Jitter is ADDED, never subtracted: waking before the server's Retry-After elapses\n // just burns a retry on a window that has not reset.\n return base + Math.random() * JITTER_MS;\n}\n\nexport const sleep = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms));\n","/**\n * Draft mode, shared by every framework adapter: the signed cookie that says \"this visitor is\n * previewing\", the preview token's slug, and the redirect a draft route may follow.\n *\n * Web Crypto and `atob` only, so it runs in Node, edge runtimes and workers alike. Each adapter\n * mounts its own routes around these; the rules live here once.\n */\n\n/** The draft cookie every adapter sets: one name, so an editor link works on any framework. */\nexport const DRAFT_COOKIE = \"bcms-draft\";\n\nconst enc = new TextEncoder();\n\nfunction base64url(bytes: ArrayBuffer): string {\n const b = btoa(String.fromCharCode(...new Uint8Array(bytes)));\n return b.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nasync function hmac(value: string, secret: string): Promise<string> {\n const key = await crypto.subtle.importKey(\"raw\", enc.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n return base64url(await crypto.subtle.sign(\"HMAC\", key, enc.encode(value)));\n}\n\n/** Sign a value as `value.sig` for tamper-evident cookie storage (HMAC-SHA256, base64url). */\nexport async function signValue(value: string, secret: string): Promise<string> {\n return `${value}.${await hmac(value, secret)}`;\n}\n\n/** The original value of a signed one, or null when it was tampered with. */\nexport async function verifyValue(signed: string, secret: string): Promise<string | null> {\n const idx = signed.lastIndexOf(\".\");\n if (idx < 0) return null;\n const value = signed.slice(0, idx);\n const sig = signed.slice(idx + 1);\n const expected = await hmac(value, secret);\n if (sig.length !== expected.length) return null;\n let diff = 0;\n for (let i = 0; i < sig.length; i++) diff |= sig.charCodeAt(i) ^ expected.charCodeAt(i);\n return diff === 0 ? value : null;\n}\n\n/** The header a server signs a content-branch read with (@see signBranchRead). */\nexport const BRANCH_SIGNATURE_HEADER = \"X-BCMS-Branch-Signature\";\n\n/**\n * Sign a read of content branch `branch` with `BCMS_BRANCH_SECRET`, which BetterCMS hosting gives a\n * server it runs (and nothing else has). The Delivery API serves the branch to this signature with\n * no draft key. A signature is good for five minutes: sign per request.\n */\nexport async function signBranchRead(branch: string, secret: string, now = Date.now()): Promise<string> {\n return signValue(`${Math.floor(now / 1000)}:${branch}`, secret);\n}\n\n/** Only same-origin relative paths: blocks \"//evil.com\", \"https://evil.com\" and \"/\\\\evil.com\". */\nexport function safeRedirectPath(to: string): string {\n return to.startsWith(\"/\") && !to.startsWith(\"//\") && !to.startsWith(\"/\\\\\") ? to : \"/\";\n}\n\nfunction tokenPayload(token: string): { entrySlug?: string; branch?: string } | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n // atob gives bytes as Latin-1: decoded as UTF-8, a slug like `über-uns` survives.\n const bytes = Uint8Array.from(atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\")), (c) => c.charCodeAt(0));\n return JSON.parse(new TextDecoder().decode(bytes)) as { entrySlug?: string; branch?: string };\n } catch {\n return null;\n }\n}\n\n/**\n * The content branch a preview token was minted on, or null for main. Read UNVERIFIED: an adapter\n * only stores a token the backend accepted, and branch reads need the site's draft key regardless.\n * Pass it as the client's `branch` in draft mode and the whole site previews from that branch.\n */\nexport function decodeTokenBranch(token: string | null | undefined): string | null {\n return (token && tokenPayload(token)?.branch) || null;\n}\n\n/** A preview token's `entrySlug`, read from its payload UNVERIFIED (the backend verifies it). */\nexport function decodeTokenSlug(token: string): string | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n // atob gives bytes as Latin-1: decoded as UTF-8, a slug like `über-uns` survives.\n const bytes = Uint8Array.from(atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\")), (c) => c.charCodeAt(0));\n const json = JSON.parse(new TextDecoder().decode(bytes)) as { entrySlug?: string };\n return json.entrySlug ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Ask the backend whether a preview token is good: the backend is the signature authority, so a\n * draft route enables draft mode only on its yes.\n */\nexport async function previewTokenValid(apiUrl: string, token: string, fetchImpl: typeof fetch = fetch): Promise<boolean> {\n const slug = decodeTokenSlug(token);\n if (!slug) return false;\n const res = await fetchImpl(`${apiUrl.replace(/\\/+$/, \"\")}/api/v1/preview/${encodeURIComponent(slug)}?token=${encodeURIComponent(token)}`);\n await res.body?.cancel().catch(() => {});\n return res.ok;\n}\n\n/** The draft cookie's preview token from a `Cookie` header, or null when absent or tampered with. */\nexport async function draftTokenFrom(cookieHeader: string | null | undefined, secret: string | undefined): Promise<string | null> {\n if (!cookieHeader || !secret) return null;\n const m = new RegExp(`(?:^|;\\\\s*)${DRAFT_COOKIE}=([^;]+)`).exec(cookieHeader);\n if (!m) return null;\n try {\n return await verifyValue(decodeURIComponent(m[1]!), secret);\n } catch {\n return null;\n }\n}\n\n/**\n * The draft-enable route for any server that speaks Web `Request`/`Response` (SvelteKit `+server.ts`,\n * Nuxt via `toWebRequest`, Remix, Hono): `GET ?token=…&redirect=/x` checks the token with the\n * backend, sets the signed draft cookie and redirects. 401 on a refused token; 500 without a secret.\n */\nexport async function draftEnableResponse(request: Request, opts: { apiUrl: string; secret: string | undefined; fetchImpl?: typeof fetch }): Promise<Response> {\n const url = new URL(request.url);\n const token = url.searchParams.get(\"token\");\n if (!opts.secret) return new Response(\"BCMS_DRAFT_SECRET is not configured\", { status: 500 });\n if (!token) return new Response(\"Missing token\", { status: 400 });\n if (!(await previewTokenValid(opts.apiUrl, token, opts.fetchImpl))) return new Response(\"Invalid or expired token\", { status: 401 });\n const cookie = `${DRAFT_COOKIE}=${encodeURIComponent(await signValue(token, opts.secret))}; Path=/; HttpOnly; SameSite=Lax; Max-Age=86400${url.protocol === \"https:\" ? \"; Secure\" : \"\"}`;\n return new Response(null, { status: 302, headers: { Location: safeRedirectPath(url.searchParams.get(\"redirect\") ?? \"/\"), \"Set-Cookie\": cookie } });\n}\n\n/** Leave draft mode: clear the cookie and redirect (`?redirect=/x`, same-origin only). */\nexport function draftDisableResponse(request: Request): Response {\n const url = new URL(request.url);\n return new Response(null, {\n status: 302,\n headers: { Location: safeRedirectPath(url.searchParams.get(\"redirect\") ?? \"/\"), \"Set-Cookie\": `${DRAFT_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0` },\n });\n}\n","/**\n * createClient — framework-agnostic typed read client for the Delivery API.\n *\n * Shared by @bettercms-ai/astro and @bettercms-ai/next so the fetch/typing/retry\n * logic lives in one place. Read-only; for schema authoring use the\n * Management client, for sessions use the Admin client.\n *\n * const client = createClient({ apiUrl, workspace, apiKey });\n * await client.getPage(\"home\");\n * await client.listEntries({ model: \"post\", perPage: 50 });\n */\nimport type {\n DeliveryComponent,\n DeliveryEntry,\n DeliveryList,\n DeliveryPage,\n DeliveredLayout,\n Perspective,\n} from \"@bettercms-ai/types\";\nimport { BetterCMSError } from \"./errors.js\";\nimport { MAX_RETRIES, backoffMs, isRetryableStatus, sleep } from \"./retry.js\";\nimport type { DeliveryForm } from \"./forms.js\";\nimport { BRANCH_SIGNATURE_HEADER } from \"./draft.js\";\n\nconst DEFAULT_TIMEOUT = 10_000;\n\nexport interface CreateClientOptions {\n /** Backend base, e.g. `https://api.bettercms.ai` (no trailing slash needed). */\n apiUrl: string;\n /** Workspace slug. */\n workspace: string;\n /** Delivery API key. Use a `content:read:draft` key for drafts. */\n apiKey?: string;\n /**\n * The project every read is addressed to. A workspace holds many projects whose slugs\n * collide (each has a `blog` model and a `home` page), so a site names its own; published\n * reads need no key for it. BetterCMS hosting supplies `PUBLIC_BCMS_PROJECT_ID`.\n */\n projectId?: string;\n /**\n * A content branch (its slug) to read instead of the live site, like a Sanity release\n * perspective: every read answers from the branch. Needs a `content:read:draft` key and a\n * `projectId`; a branch that is not open answers 404 (BRANCH_NOT_FOUND).\n */\n branch?: string;\n /**\n * `signBranchRead(branch, BCMS_BRANCH_SECRET)`: on a server BetterCMS hosts, reads the `branch`\n * with no draft key. `@bettercms-ai/astro` signs for you on a branch preview.\n */\n branchSignature?: string;\n /** `published` (default) or `drafts`. */\n perspective?: Perspective;\n /**\n * Preview-token JWT for token-based single-document draft reads via the\n * `/preview/:slug` endpoint. Only used when `perspective === \"drafts\"`.\n */\n previewToken?: string;\n /**\n * Embed invisible visual-editing provenance in draft reads, so a preview build can\n * deep-link each rendered value back to its editor. Requires `perspective: \"drafts\"`,\n * and then either a `previewToken` or a `content:read:draft` key. Ignored on published\n * reads — the payload must never reach a production build.\n *\n * **Defaults to `true` on `perspective: \"drafts\"`** (since 1.15.0). Provenance is the whole\n * reason the drafts perspective exists in a preview build, and an option nobody knew to pass\n * meant every such build rendered anonymous strings: the editor could bind them only by\n * guessing at their text. It stays OFF on every other perspective, unconditionally, so a\n * published build cannot acquire a payload by accident — pass `stega: false` to opt a draft\n * read out (a diff or a checksum over draft content is the case that wants it).\n */\n stega?: boolean;\n /** Per-attempt timeout in ms. Defaults to 10000. */\n timeout?: number;\n /**\n * Collapse identical GETs to one network round-trip for the life of this client.\n * Default false.\n *\n * Only correct where the content is a POINT-IN-TIME SNAPSHOT — i.e. a static build,\n * where every route renders from the same published dataset. `@bettercms-ai/astro`\n * turns this on automatically when Astro's `command === \"build\"` and never for `dev`,\n * SSR or the drafts perspective, where a repeat read must see the current row.\n *\n * A static build without it re-fetches the same nav/settings/collection once PER ROUTE.\n * That is what made a large site exhaust the delivery rate limit: hundreds of identical\n * requests, and `getPage()` re-scanning every page of the paginated list each time it is\n * called.\n */\n cache?: boolean;\n}\n\n/** A value a list filter compares against. */\ntype FilterValue = string | number | boolean;\ntype FilterOps = Partial<Record<\"eq\" | \"ne\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"contains\", FilterValue>> & { in?: FilterValue[] };\n\n/**\n * The delivery list's filter grammar as an object: `{ category: \"news\" }` is `filter[category]=news`,\n * `{ startsAt: { gte: \"2026-01-01\" } }` is `filter[startsAt][gte]=…`, `{ tags: [\"a\", \"b\"] }` is\n * `filter[tags][in]=a,b`. A content field needs `model`; `slug`, `status`, `publishedAt` and `locale`\n * do not. The server allowlists the fields (src/lib/delivery/list-query.ts) and 400s anything else.\n */\nexport type EntryFilter = Record<string, FilterValue | FilterValue[] | FilterOps | undefined>;\n\nexport interface ListEntriesOptions {\n /** Filter by content-model slug. */\n model?: string;\n page?: number;\n perPage?: number;\n /** Reference hydration depth (lists cap at 1). */\n depth?: 0 | 1;\n /** Projection — field names to return. */\n select?: string[];\n /** Field filters, ANDed. */\n filter?: EntryFilter;\n /** `\"-publishedAt\"` or `[\"startsAt\", \"title\"]`: a leading `-` sorts descending. Default: newest published first. */\n sort?: string | string[];\n}\n\nexport interface GetEntryOptions {\n depth?: 0 | 1 | 2;\n select?: string[];\n}\n\nexport interface ListPagesOptions {\n page?: number;\n perPage?: number;\n /** Only the page with this slug (the list's `?slug=`). */\n slug?: string;\n}\n\nexport interface BetterCMSReadClient {\n readonly perspective: Perspective;\n getEntry<T = Record<string, unknown>>(\n slug: string,\n opts?: GetEntryOptions,\n ): Promise<DeliveryEntry<T>>;\n listEntries<T = Record<string, unknown>>(\n opts?: ListEntriesOptions,\n ): Promise<DeliveryList<DeliveryEntry<T>>>;\n getPage(slug: string): Promise<DeliveryPage | null>;\n listPages(opts?: ListPagesOptions): Promise<DeliveryList<DeliveryPage>>;\n /**\n * The workspace's reusable component definitions, for resolving `component` blocks.\n * Under `perspective: \"drafts\"` this is the DRAFT definition — what makes an SSR render\n * of a draft page look like the page the editor is showing.\n */\n listComponents(): Promise<DeliveryComponent[]>;\n /** Fetch the project-scoped Global Layout for the active perspective. */\n getLayout(): Promise<DeliveredLayout | null>;\n listForms(opts?: {\n projectId?: string;\n }): Promise<{ items: DeliveryForm[]; turnstileSiteKey: string | null }>;\n /** Build a deterministic Next/cache tag for a resource. */\n tag(resource: \"entry\" | \"page\" | \"forms\", id?: string): string;\n}\n\n/**\n * `filter` and `sort` as the list route's params, in the order given: the same grammar the MCP's\n * `where` serialises to (packages/mcp/src/entry-query.ts).\n */\nfunction listQueryParams(filter?: EntryFilter, sort?: string | string[]): Record<string, string> {\n const text = (v: FilterValue | FilterValue[]) => (Array.isArray(v) ? v.join(\",\") : String(v));\n const out: Record<string, string> = {};\n for (const [field, cond] of Object.entries(filter ?? {})) {\n if (cond == null) continue;\n if (Array.isArray(cond)) out[`filter[${field}][in]`] = text(cond);\n else if (typeof cond === \"object\") {\n for (const [op, v] of Object.entries(cond)) if (v != null) out[`filter[${field}][${op}]`] = text(v);\n } else out[`filter[${field}]`] = text(cond);\n }\n const order = Array.isArray(sort) ? sort.join(\",\") : sort;\n if (order) out.sort = order;\n return out;\n}\n\n/**\n * Drop undefined and empty values, stringify the rest into a query string. An empty filter value\n * is kept, as createBetterCMS sends it: dropped, `filter: { author: [] }` would list every entry;\n * sent, the route answers it (an empty `in` list is a 400, list-query.ts).\n */\nfunction qs(params: Record<string, string | number | undefined>): string {\n const sp = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && (v !== \"\" || k.startsWith(\"filter[\"))) sp.set(k, String(v));\n }\n const s = sp.toString();\n return s ? `?${s}` : \"\";\n}\n\n/**\n * Unwrap a `{ data: ... }` list/legacy envelope when present. A bare entry is\n * already the payload (it has `id`/`slug` and its own `data` field), so we only\n * unwrap when no payload markers are at the top level.\n */\nfunction unwrap<T>(json: unknown): T {\n if (json && typeof json === \"object\") {\n const o = json as Record<string, unknown>;\n const isPayload = \"id\" in o || \"slug\" in o || \"items\" in o;\n if (!isPayload && \"data\" in o) return o.data as T;\n }\n return json as T;\n}\n\n/**\n * The `entrySlug` claim of a preview-token JWT, UNVERIFIED.\n *\n * The backend is the signature authority — this read only decides WHICH url to call, and a\n * forged claim buys nothing: `/preview/:slug` re-verifies and 401s. Kept private to this file\n * (`@bettercms-ai/astro` has its own copy for the same reason: neither package may depend on\n * the other).\n */\nfunction tokenSlug(token: string): string | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n const json = atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n return (JSON.parse(json) as { entrySlug?: string }).entrySlug ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Per-URL request collapsing.\n *\n * Two jobs, both needed: coalesce requests that are IN FLIGHT (Astro renders routes\n * concurrently, so identical GETs overlap) and retain the ones that have COMPLETED\n * (routes render in batches, so the same GET recurs long after the first settled).\n *\n * Values are cloned on the way out. Callers get a fresh object graph, so a template that\n * sorts `items` in place — an easy thing to write and a brutal thing to debug — cannot\n * corrupt what every other route sees. Cloning costs memory bandwidth; the request it\n * replaces costs a network round-trip and a slot in the rate-limit window.\n *\n * A rejected request is never retained, so a transient failure does not become permanent.\n */\nfunction createRequestCache() {\n const inflight = new Map<string, Promise<unknown>>();\n const settled = new Map<string, unknown>();\n\n const copy = <T>(value: T): T =>\n typeof structuredClone === \"function\" ? structuredClone(value) : (JSON.parse(JSON.stringify(value)) as T);\n\n return async function collapse<T>(url: string, fetcher: () => Promise<T>): Promise<T> {\n if (settled.has(url)) return copy(settled.get(url) as T);\n\n const pending = inflight.get(url) as Promise<T> | undefined;\n if (pending) return copy(await pending);\n\n const run = (async () => {\n try {\n const value = await fetcher();\n settled.set(url, value);\n return value;\n } finally {\n inflight.delete(url);\n }\n })();\n inflight.set(url, run);\n return copy(await run);\n };\n}\n\nexport function createClient(options: CreateClientOptions): BetterCMSReadClient {\n const apiUrl = options.apiUrl.replace(/\\/+$/, \"\");\n const { workspace, apiKey, perspective = \"published\", previewToken } = options;\n const defaultProjectId = options.projectId;\n // Every delivery read names the project and, for a branch preview, the branch.\n const branch = options.branch && options.branch !== \"main\" ? options.branch : undefined;\n const timeout = options.timeout ?? DEFAULT_TIMEOUT;\n const base = `${apiUrl}/api/v1/delivery/${workspace}`;\n\n const headers = (): Record<string, string> => {\n const h: Record<string, string> = { \"Content-Type\": \"application/json\" };\n if (apiKey) h[\"X-API-Key\"] = apiKey;\n if (branch && options.branchSignature) h[BRANCH_SIGNATURE_HEADER] = options.branchSignature;\n return h;\n };\n\n // Drafts must never be collapsed even if a caller asks: a preview surface re-reads to\n // see the edit that just happened, and serving it a retained copy would show stale content.\n const collapse =\n options.cache && perspective === \"published\" ? createRequestCache() : undefined;\n\n const fetchJSON = <T>(url: string): Promise<T> =>\n collapse ? collapse(url, () => request<T>(url)) : request<T>(url);\n\n async function request<T>(url: string): Promise<T> {\n let lastError: unknown;\n for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeout);\n try {\n const res = await globalThis.fetch(url, {\n headers: headers(),\n signal: controller.signal,\n });\n clearTimeout(timer);\n if (res.ok) return (await res.json()) as T;\n\n const retryable = attempt < MAX_RETRIES && isRetryableStatus(res.status);\n if (!retryable) throw await BetterCMSError.from(res);\n // Honour Retry-After: the limiter's window is up to 60s, far longer than\n // any fixed ladder, so the server's own number is the only one that works.\n await sleep(backoffMs(attempt, res));\n } catch (err) {\n clearTimeout(timer);\n if (err instanceof Error && err.name === \"AbortError\") {\n throw new BetterCMSError(\"Request timeout\", 408, \"NETWORK_ERROR\");\n }\n if (err instanceof BetterCMSError) throw err;\n lastError = err;\n if (attempt < MAX_RETRIES) {\n await sleep(backoffMs(attempt));\n continue;\n }\n throw new BetterCMSError(\n `Network error: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n \"NETWORK_ERROR\",\n );\n }\n }\n throw lastError ?? new BetterCMSError(\"Unreachable\", 0, \"NETWORK_ERROR\");\n }\n\n const draft = perspective === \"drafts\";\n /**\n * Resolved ONCE, here, so the three call sites below cannot drift apart — they did exactly\n * that before (`options.stega` alone on the preview branch, `draft && options.stega` on the\n * other two), and a default expressed three times is a default that will eventually be two.\n * `??` and not `||`: an explicit `stega: false` on a draft read must win.\n */\n const stega = options.stega ?? draft;\n\n return {\n perspective,\n\n async getEntry<T = Record<string, unknown>>(slug: string, opts?: GetEntryOptions) {\n // Token-based draft reads go through the dedicated preview endpoint.\n // Without a token the drafts perspective is served by delivery itself, which needs\n // to be TOLD — `?perspective=draft` (honoured only for a `content:read:draft` key).\n // Until this branch sent it, `perspective: \"drafts\"` was silently inert here, and\n // with it `stega`, so a static build could never obtain provenance without minting\n // a preview token per entry.\n // The token names ONE entry (as on getPage below): any other slug reads delivery, or the\n // preview endpoint 404s the post list, related posts and nav a draft page also renders.\n const url =\n draft && previewToken && tokenSlug(previewToken) === slug\n ? `${apiUrl}/api/v1/preview/${encodeURIComponent(slug)}${qs({\n token: previewToken,\n depth: opts?.depth,\n select: opts?.select?.join(\",\"),\n stega: stega ? \"1\" : undefined,\n })}`\n : `${base}/content-entries/${encodeURIComponent(slug)}${qs({\n depth: opts?.depth,\n select: opts?.select?.join(\",\"),\n perspective: draft ? \"draft\" : undefined,\n stega: draft && stega ? \"1\" : undefined,\n projectId: defaultProjectId, branch,\n })}`;\n return unwrap<DeliveryEntry<T>>(await fetchJSON(url));\n },\n\n async listEntries<T = Record<string, unknown>>(opts?: ListEntriesOptions) {\n const url = `${base}/content-entries${qs({\n model: opts?.model,\n page: opts?.page,\n perPage: opts?.perPage,\n depth: opts?.depth,\n select: opts?.select?.join(\",\"),\n ...listQueryParams(opts?.filter, opts?.sort),\n perspective: draft ? \"draft\" : undefined,\n stega: draft && stega ? \"1\" : undefined,\n projectId: defaultProjectId, branch,\n })}`;\n return unwrap<DeliveryList<DeliveryEntry<T>>>(await fetchJSON(url));\n },\n\n async getPage(slug: string) {\n // The token names ONE page, and for that page the preview endpoint is the only read\n // that returns the DRAFT block tree — the paginated delivery list is published-only, so\n // an SSR draft render would otherwise be the live structure with draft field values.\n // Any other slug falls through to the published scan, which is what a token for /about\n // rendering the site's nav or footer pages must keep doing.\n if (draft && previewToken && tokenSlug(previewToken) === slug) {\n const url = `${apiUrl}/api/v1/preview/${encodeURIComponent(slug)}${qs({\n token: previewToken,\n stega: stega ? \"1\" : undefined,\n })}`;\n const d = unwrap<Record<string, unknown>>(await fetchJSON(url));\n return {\n slug: d.slug as string,\n title: d.title as string,\n metaTitle: (d.metaTitle as string | null) ?? null,\n metaDescription: (d.metaDescription as string | null) ?? null,\n metaJson: (d.metaJson as DeliveryPage[\"metaJson\"]) ?? null,\n blocks: (d.blockJson as DeliveryPage[\"blocks\"]) ?? [],\n // C3: the DRAFT field styles, present only when the page styles a field.\n ...(d.fieldStyles ? { fieldStyles: d.fieldStyles as NonNullable<DeliveryPage[\"fieldStyles\"]> } : {}),\n updatedAt: (d.updatedAt as string | null) ?? null,\n publishedAt: (d.publishedAt as string | null) ?? null,\n } satisfies DeliveryPage;\n }\n // No dedicated single-page delivery endpoint: the list, narrowed to this slug. Unnarrowed, every\n // client-rendered page view read every page of the site (a converted React SPA's <BcmsSections>:\n // ~50 KB for one page's order). A server that ignores `slug` answers the whole list, scanned as before.\n let page = 1;\n for (;;) {\n const list = await this.listPages({ page, perPage: 100, slug });\n const found = list.items.find((p) => p.slug === slug);\n if (found) return found;\n if (!list.hasNextPage) return null;\n page += 1;\n }\n },\n\n async listPages(opts?: ListPagesOptions) {\n const url = `${base}/pages${qs({\n page: opts?.page,\n perPage: opts?.perPage,\n slug: opts?.slug,\n projectId: defaultProjectId, branch,\n })}`;\n return unwrap<DeliveryList<DeliveryPage>>(await fetchJSON(url));\n },\n\n async listComponents() {\n // Same shape as getLayout: `?perspective=draft` alone is the key-scoped path (the server\n // ignores it for a published key), and a preview token is the page-scoped one.\n const url = `${base}/components${qs({\n perspective: draft ? \"draft\" : undefined,\n token: draft ? previewToken : undefined,\n projectId: defaultProjectId, branch,\n })}`;\n return unwrap<DeliveryComponent[]>(await fetchJSON(url));\n },\n\n async getLayout() {\n const url = `${base}/layout${qs({ perspective: draft ? \"draft\" : undefined, projectId: defaultProjectId, branch })}`;\n try {\n return unwrap<DeliveredLayout>(await fetchJSON(url));\n } catch (error) {\n if (error instanceof BetterCMSError && error.status === 404) return null;\n throw error;\n }\n },\n\n async listForms(opts?: { projectId?: string }) {\n const url = `${base}/forms${qs({\n projectId: opts?.projectId ?? defaultProjectId,\n branch,\n })}`;\n return unwrap<{ items: DeliveryForm[]; turnstileSiteKey: string | null }>(\n await fetchJSON(url),\n );\n },\n\n tag(resource, id) {\n return id ? `bcms:${workspace}:${resource}:${id}` : `bcms:${workspace}:${resource}`;\n },\n };\n}\n","/**\n * Public forms — the headless integration surface for sites built on or imported\n * into BetterCMS (the \"render it yourself\" model, like Sanity's delivery API).\n *\n * Form definitions ship in the build-time content snapshot (`bcms-content.json` →\n * `forms` / `turnstileSiteKey`) and from `GET /api/v1/delivery/:workspace/forms`.\n * A site renders them with its own components (see `@bettercms-ai/next`'s <BcmsForm>)\n * and posts here. No API key — the endpoint is Turnstile-gated (Webflow model).\n *\n * This module is the single source of truth for the delivered form shape + the\n * pure logic (conditional visibility, initial values) the renderers share, so the\n * vanilla embed and the React component never drift.\n */\n\nimport { BetterCMSError, ErrorCodes } from \"./errors.js\";\nimport { fileExtension, fileFieldLimits } from \"@bettercms-ai/types\";\n\n/**\n * Field types the delivery API serializes. Must stay equal to the authoring\n * vocabulary in `packages/db/src/schema/forms.ts` — this list is what every site\n * renderer switches on, so a type missing HERE renders as a plain text input on\n * every published site while the builder happily offers it. `radio`/`checkboxes`\n * were exactly that gap.\n */\nexport type DeliveryFormFieldType =\n | \"text\"\n | \"email\"\n | \"phone\"\n | \"url\"\n | \"number\"\n | \"date\"\n | \"textarea\"\n | \"select\"\n | \"radio\"\n | \"checkboxes\"\n | \"checkbox\"\n | \"consent\"\n | \"hidden\"\n | \"file\" // attachments: upload each file first (`uploadFormFile`), then submit the returned ids\n | \"step\"; // a divider, not an input: renderers split the form into pages at it\n\nexport interface DeliveryFormField {\n key: string;\n label: string;\n type: DeliveryFormFieldType;\n placeholder?: string;\n /** Hint rendered under the control. */\n helpText?: string;\n required?: boolean;\n options?: string[];\n defaultValue?: string;\n /** Conditional visibility — render this field only when another field equals `equals`. */\n showIf?: { field: string; equals: string };\n /**\n * Per-field rules the API enforces on submit. Renderers should mirror them onto the\n * native control (`min`/`max`/`pattern`) so the browser reports them before the round\n * trip — the server check is the one that counts.\n */\n validation?: DeliveryFormFieldValidation;\n /**\n * Presentation options the renderer honours. Unlike `validation`, the API does NOT enforce\n * these on submit — they change what the visitor is shown, not what is accepted.\n */\n ui?: DeliveryFormFieldUi;\n}\n\n/**\n * @see FormFieldUi in @bettercms-ai/types — same shape, delivered to the site.\n *\n * ── The phone composition contract every renderer implements ──\n *\n * A picker-enabled phone field is rendered as a country control PLUS a `tel` input, but it\n * submits ONE value under the field's own key, in E.164. Whatever a renderer uses to hold the\n * country (a React state, a `{key}__country` select) is scaffolding: it must never reach the\n * POST body.\n *\n * Composition, from the visible input's raw text:\n * - empty → `\"\"`. NEVER `\"+CC\"`, and the reason is worse than \"the server rejects it\". The\n * server's loose phone shape is `{3,32}` chars, so the outcome depends on the calling\n * code's length: `\"+1\"` is REFUSED (an optional untouched field starts 400ing), while\n * `\"+91\"` is ACCEPTED and stored as a real-looking submission that is only a country code.\n * The silent case is the dangerous one. Pinned in `__tests__/lib/forms-validate.test.ts`.\n * - starts with `\"+\"` → `\"+\" + digits(raw)`. The visitor typed an international number; the\n * country control is ignored rather than fighting them.\n * - otherwise → `\"+\" + callingCode + digits(raw).replace(/^0/, \"\")`, dropping ONE trunk zero.\n * Known exception: Italian landlines keep their trunk zero, so this loses it. The value is\n * still accepted (shape-only check) — it is a formatting loss, not a refusal.\n *\n * `ui` changes what the visitor SEES. It never changes what the API accepts: enforcing a format\n * is `validation.phoneFormat`'s job and the two are independent.\n *\n * Renderer parity is behavioural, not implementational. FIVE lanes render this field, and they\n * agree on the VALUE, not on the implementation:\n *\n * | Lane | Control | As-you-type formatting |\n * |-------------------------------|---------------------------------|------------------------|\n * | dashboard form preview | searchable picker + formatter | yes |\n * | @bettercms-ai/next <BcmsForm> | native select + formatter | yes (lazy chunk) |\n * | hosted sites (render-page) | native select + tel input | NO |\n * | embed snippet | native select + tel input | NO |\n * | @bettercms-ai/astro BcmsForm | native select + tel input | NO |\n *\n * The missing as-you-type formatting on the three vanilla lanes is a NAMED degradation, not an\n * oversight: it is what keeps libphonenumber off a visitor's page entirely. `packages/next`\n * pays for it only on pages that actually render a picker, via a separate chunk.\n *\n * When a lane builds that option list, never pass a libphonenumber helper as a bare callback:\n * `getCountries().filter(isSupportedCountry)` hands it the array INDEX as its `metadata`\n * argument and throws. Always wrap — `.filter((iso) => isSupportedCountry(iso))`.\n *\n * And when a lane ships the composition rule inside a JS TEMPLATE LITERAL (the embed snippet\n * does), `\\D` collapses to `D` and the regex silently becomes `/D/g` — stripping the letter D\n * and leaving every other separator in place. Write `\\\\D` there. Raw HTML `<script>` text (the\n * hosted renderer, the Astro inline script) takes a single backslash. Nothing throws either\n * way; numbers just arrive malformed, so each lane pins it with an executed-script test.\n */\nexport interface DeliveryFormFieldUi {\n /** `phone` — render a country picker beside the number. The submitted value is E.164. */\n countryPicker?: boolean;\n /** `phone` — uppercase ISO 3166-1 alpha-2 the picker starts on. */\n defaultCountry?: string;\n /**\n * `phone` — show the country's flag beside the dialling code.\n *\n * Honoured only by a renderer with a custom picker. The native `<select>` the site lanes use\n * cannot hold an SVG, and an emoji flag renders as two grey letters on Windows, so those\n * lanes show the country NAME instead — the same information, legibly, everywhere.\n */\n showFlags?: boolean;\n}\n\n/** @see FormFieldValidation in @bettercms-ai/types — same shape, delivered to the site. */\nexport interface DeliveryFormFieldValidation {\n emailPolicy?: \"any\" | \"business\";\n min?: number;\n max?: number;\n phoneFormat?: \"any\" | \"e164\";\n pattern?: string;\n /** `file` — accepted extensions, lowercase, no dot. */\n accept?: string[];\n /** `file` — files per field. */\n maxFiles?: number;\n /** `file` — per-file cap in MB. */\n maxSizeMb?: number;\n}\n\n/** The pick-many type, whose value is an array rather than a scalar. */\nexport function isMultiValueField(type: DeliveryFormFieldType): boolean {\n return type === \"checkboxes\";\n}\n\n/** A form as delivered to a published/imported site. Mirrors the delivery `/forms` payload. */\nexport interface DeliveryForm {\n id: string;\n name: string;\n /** The project the form belongs to. */\n projectId?: string | null;\n /**\n * A `draft` form refuses every submission: render it as unavailable rather than as a form that\n * silently drops what a visitor sends. Delivered for exactly that reason, and missing from this\n * type until the contract test held the two together.\n */\n status?: \"draft\" | \"published\" | (string & {});\n /** Set on a form the site's owner told BetterCMS to leave alone (ISO time); such a form is not wired. */\n ignoredAt?: string | null;\n fields: DeliveryFormField[];\n submitLabel?: string;\n successMessage?: string;\n redirectUrl?: string;\n turnstileEnabled?: boolean;\n honeypotField?: string | null;\n}\n\n/** `string[]` is the `checkboxes` (pick-many) value; every other type is scalar. */\nexport type FormValue = string | boolean | string[];\nexport type FormValues = Record<string, FormValue>;\n\n/** Read a `checkboxes` value defensively — stored data may predate the array shape. */\nexport function asStringArray(value: FormValue | undefined): string[] {\n if (Array.isArray(value)) return value;\n return value ? [String(value)] : [];\n}\n\n/** Add/remove `option` from a `checkboxes` value, preserving the field's option order. */\nexport function toggleOption(value: FormValue | undefined, option: string, on: boolean): string[] {\n const current = asStringArray(value);\n if (on) return current.includes(option) ? current : [...current, option];\n return current.filter((v) => v !== option);\n}\n\nconst DEFAULT_BASE_URL = \"https://api.bettercms.ai\";\n\n// ── File fields ──────────────────────────────────────────────────────────────\n\n/**\n * The limits a renderer checks a chosen file against before uploading it: the field as\n * delivered, with the platform's defaults and ceilings. @see fileFieldLimits in @bettercms-ai/types\n */\nexport { fileFieldLimits };\n\n/** Why a chosen file is refused before upload, or null: a sentence the visitor can read. */\nexport function fileFieldRefusal(\n limits: { accept: string[]; maxSizeMb: number },\n file: { name: string; size: number },\n): string | null {\n const ext = fileExtension(file.name);\n if (!ext || !limits.accept.includes(ext)) {\n return `This type of file is not accepted here. Accepted: ${limits.accept.map((e) => `.${e}`).join(\", \")}.`;\n }\n if (file.size === 0) return \"This file is empty.\";\n if (file.size > limits.maxSizeMb * 1024 * 1024) return `This file is larger than ${limits.maxSizeMb} MB.`;\n return null;\n}\n\nexport interface UploadFormFileOptions {\n formId: string;\n /** The `file` field's key. */\n fieldKey: string;\n /** A browser `File` (anything with a name and a body). */\n file: Blob & { name: string };\n /** API origin. Defaults to https://api.bettercms.ai. */\n baseUrl?: string;\n /** Injectable fetch for tests / non-browser runtimes. */\n fetchImpl?: typeof fetch;\n}\n\nexport interface UploadedFormFile {\n /** What the submission names this file by: put it in the field's value. */\n id: string;\n name: string;\n size: number;\n}\n\n/**\n * Upload one file of a form's `file` field, ahead of the submit. Resolves with the id the\n * submission names it by (`data[fieldKey] = [id, …]`), or throws a BetterCMSError whose\n * `bodyCode` is the server's (FILE_TOO_LARGE, UPLOAD_TYPE_NOT_ALLOWED, UPLOAD_BUSY,\n * STORAGE_FULL, …) and whose message is a sentence for the visitor. No retry.\n *\n * The body is the file's bytes and nothing else; its name travels percent-encoded in a header,\n * so it never lands in an access log.\n */\nexport async function uploadFormFile(opts: UploadFormFileOptions): Promise<UploadedFormFile> {\n const baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n const doFetch = opts.fetchImpl ?? globalThis.fetch;\n let res: Response;\n try {\n res = await doFetch(\n `${baseUrl}/api/v1/forms/public/${encodeURIComponent(opts.formId)}/uploads?field=${encodeURIComponent(opts.fieldKey)}`,\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/octet-stream\", \"X-Bcms-Filename\": encodeURIComponent(opts.file.name) },\n body: opts.file,\n },\n );\n } catch (err) {\n throw new BetterCMSError(\n `Network error: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n ErrorCodes.NETWORK_ERROR,\n );\n }\n if (!res.ok) throw await BetterCMSError.from(res);\n const json = (await res.json().catch(() => ({}))) as { data?: Partial<UploadedFormFile> };\n const data = json.data;\n if (!data?.id) throw new BetterCMSError(\"The file could not be saved. Please try again.\", res.status, ErrorCodes.INTERNAL_ERROR);\n return { id: data.id, name: data.name ?? opts.file.name, size: data.size ?? opts.file.size };\n}\n\n/**\n * Conditional visibility. A `showIf` field is shown only when its trigger field's\n * current value equals the target; non-conditional fields are always shown. The\n * renderer must skip hidden fields when collecting/validating so a hidden required\n * field never blocks submit.\n */\nexport function shouldShowField(field: DeliveryFormField, values: FormValues): boolean {\n if (!field.showIf) return true;\n const trigger = values[field.showIf.field];\n // A pick-many trigger satisfies `equals` when the option is among those checked;\n // `String([\"a\",\"b\"])` would compare against \"a,b\" and never match.\n if (Array.isArray(trigger)) return trigger.includes(field.showIf.equals);\n return String(trigger ?? \"\") === field.showIf.equals;\n}\n\n/**\n * Build the initial value map: checkbox/consent default to false, checkboxes to an\n * empty array, every other field to its `defaultValue`, with `prefill` (e.g. URL\n * query params) taking precedence.\n */\nexport function formInitialValues(\n form: DeliveryForm,\n prefill: Record<string, string> = {},\n): FormValues {\n const values: FormValues = {};\n for (const field of form.fields) {\n if (field.type === \"step\") continue; // a divider holds no value\n // A file field starts empty, whatever the link or the field says: its value is the ids of\n // files THIS visitor uploaded. A prefilled id (`?cv=<id>`) would attach someone else's file.\n if (field.type === \"file\") {\n values[field.key] = [];\n continue;\n }\n if (field.type === \"checkbox\" || field.type === \"consent\") {\n values[field.key] = false;\n } else if (field.type === \"checkboxes\") {\n const seed = prefill[field.key] ?? field.defaultValue ?? \"\";\n // A prefill/default arrives as a scalar (query string, stored column), so split\n // it back into the option list the control renders against.\n values[field.key] = seed ? seed.split(\",\").map((v) => v.trim()).filter(Boolean) : [];\n } else {\n values[field.key] = prefill[field.key] ?? field.defaultValue ?? \"\";\n }\n }\n return values;\n}\n\nexport interface SubmitFormOptions {\n formId: string;\n data: FormValues;\n /** Cloudflare Turnstile token; required when the form has `turnstileEnabled`. */\n turnstileToken?: string;\n /** The path of the page the form sits on (\"/pricing\"). Defaults to `location.pathname` in a browser. */\n page?: string;\n /** API origin. Defaults to https://api.bettercms.ai. */\n baseUrl?: string;\n /** Injectable fetch for tests / non-browser runtimes. */\n fetchImpl?: typeof fetch;\n}\n\nexport interface SubmitFormResult {\n id: string;\n}\n\n/** A submit failure that carries per-field validation messages from the API (HTTP 400). */\nexport type FormSubmitError = BetterCMSError & { fieldErrors?: Record<string, string> };\n\n/**\n * Submit a public form. Resolves with the new submission id, or throws a\n * BetterCMSError — field-level validation errors are attached as `.fieldErrors`.\n */\nexport async function submitForm(opts: SubmitFormOptions): Promise<SubmitFormResult> {\n const baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n const doFetch = opts.fetchImpl ?? globalThis.fetch;\n const body: Record<string, unknown> = { data: opts.data };\n // The page the form sits on, for the submission's \"Sent from\" (browser only; a server call has none).\n const page = opts.page ?? (globalThis as { location?: { pathname?: string } }).location?.pathname;\n if (page) body.page = page;\n if (opts.turnstileToken) body[\"cf-turnstile-response\"] = opts.turnstileToken;\n\n let res: Response;\n try {\n res = await doFetch(`${baseUrl}/api/v1/forms/public/${opts.formId}/submissions`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n } catch (err) {\n throw new BetterCMSError(\n `Network error: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n ErrorCodes.NETWORK_ERROR,\n );\n }\n\n if (!res.ok) {\n // `.from` reads the body for message/code; clone so we can still read `errors`.\n const error = (await BetterCMSError.from(res.clone())) as FormSubmitError;\n const body = (await res.json().catch(() => ({}))) as { errors?: Record<string, string> };\n if (body.errors) error.fieldErrors = body.errors;\n throw error;\n }\n\n const json = (await res.json().catch(() => ({}))) as { id?: string | number };\n return { id: String(json.id ?? \"\") };\n}\n","/**\n * Public site search — the headless surface for the visitor-facing search box.\n *\n * Queries `GET /api/v1/delivery/search?project=…&q=…`, the same key-less public\n * endpoint the embeddable widget uses. Powers <BcmsSearch> in @bettercms-ai/next\n * and @bettercms-ai/astro, so the component and any custom UI never drift.\n *\n * `snippet` is HTML-safe: the server escapes the field content and keeps only the\n * <mark> highlight wrappers, so it can be rendered with dangerouslySetInnerHTML.\n */\n\nconst DEFAULT_BASE_URL = \"https://api.bettercms.ai\";\n\nexport interface SearchHit {\n title: string;\n slug: string;\n type: \"page\" | \"entry\";\n /** HTML-safe snippet with <mark> highlights around matched terms. */\n snippet: string;\n /** Site-relative URL, e.g. \"/about\". Absent on an entry no page of the site serves. */\n url?: string;\n}\n\nexport interface SearchOptions {\n /** The project id (from the dashboard's Site Search settings). */\n project: string;\n /** The query string. Calls with fewer than 1 char resolve to []. */\n q: string;\n /** Max hits, 1–20 (default 8). */\n limit?: number;\n /** API origin. Defaults to https://api.bettercms.ai. */\n baseUrl?: string;\n /** Injectable fetch for tests / non-browser runtimes. */\n fetchImpl?: typeof fetch;\n /** AbortSignal so callers can cancel a stale in-flight search. */\n signal?: AbortSignal;\n}\n\n/** Search a published site. Resolves with hits, or [] on an empty query / network error. */\nexport async function search(opts: SearchOptions): Promise<SearchHit[]> {\n const q = opts.q.trim();\n if (!q) return [];\n const baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n const doFetch = opts.fetchImpl ?? globalThis.fetch;\n const params = new URLSearchParams({ project: opts.project, q });\n if (opts.limit) params.set(\"limit\", String(opts.limit));\n\n try {\n const res = await doFetch(`${baseUrl}/api/v1/delivery/search?${params}`, { signal: opts.signal });\n if (!res.ok) return [];\n const json = (await res.json().catch(() => ({}))) as { hits?: SearchHit[] };\n return json.hits ?? [];\n } catch {\n return []; // network/abort → no results, never throw into a render path\n }\n}\n","/**\n * Reading a rich-text field, for any site.\n *\n * A `text` field delivers a bare string. A `richtext` field delivers the canonical envelope\n * `{ format, value, html }`. Those are different shapes, and switching a field's type in the\n * CMS switches which one your site receives — the Visual Editor offers exactly that switch,\n * so it happens on live projects. A template that interpolates the value directly then\n * renders `[object Object]` (or, in React, throws `Objects are not valid as a React child`).\n *\n * No payload can be both structured and safe to interpolate, which is why every headless CMS\n * requires a renderer for rich text. These are ours:\n *\n * plain(v) → text, for <title>, meta descriptions, JSON-LD, alt text, aria-label\n * rich(v) → HTML, for `set:html` / `dangerouslySetInnerHTML`\n *\n * Both accept a bare string, so a field can be switched in the CMS without touching the site.\n *\n * <h1 set:html={rich(page.heroTitle)} /> // Astro\n * <h1 dangerouslySetInnerHTML={{ __html: rich(f.heroTitle) }}/> // React\n * seo({ title: plain(page.heroTitle) })\n */\n\nimport type { RichTextEmbeds, RichTextResolved } from \"@bettercms-ai/types\";\n\n/**\n * A block in a Body field's `doc`. Bounded vocabulary — the server only emits what it can\n * parse back, so an unknown `type` means your SDK is older than the content, not that the\n * content is malformed. Handle the default case rather than exhausting on it.\n */\nexport type DocBlock = {\n /**\n * Stable within THIS document only — never a global key. Two different entries both have a\n * block called \"0.0\". A cross-document anchor is (entryId, fieldKey, id).\n *\n * Ids on content authored before block ids existed are derived from position, so they SHIFT\n * when that document is edited. Do not persist an id as a bookmark unless you know it came\n * from the editor rather than from the positional fallback.\n */\n readonly id: string;\n readonly type: string;\n readonly [key: string]: unknown;\n};\n\n/** The `doc` rendition of a Body field — a versioned block array. */\nexport type DocValue = {\n readonly version: 1;\n readonly blocks: readonly DocBlock[];\n};\n\n/** The canonical rich-text envelope returned by the Delivery API. */\nexport interface RichTextValue {\n readonly format?: string;\n readonly value?: unknown;\n /** Server-rendered, sanitized HTML. Computed on write. */\n readonly html?: string;\n /**\n * Structured blocks — present on `document` (Body) fields only, and NOT guaranteed even\n * there: it is derived at write time, so an entry saved before this existed carries none\n * until its next save. There is no backfill. Always branch on its absence; `html` is the\n * field that is always there.\n */\n readonly doc?: DocValue;\n /**\n * The embeds the server resolved when it built `html`: X cards keyed by canonical url (X's\n * script, when a site opts in, is the page's, never the value's). `html` already holds each card, so `rich()` never needs this; it is\n * for renderers of the STRUCTURE (`<PortableText embeds={…}>`). Absent on a value with no embed\n * and on any envelope written before it existed: read it through `embeds()`.\n */\n readonly embeds?: RichTextEmbeds;\n /**\n * What the value's related posts and author bios point at, resolved by the server for THIS\n * response from the published entries (never stored). `html` already draws them; this is for\n * renderers of the structure (`<PortableText resolved={…}>`). Absent on a value with neither block.\n * Read it through `resolved()`.\n */\n readonly resolved?: RichTextResolved;\n}\n\n/** The marker on a Portable Text envelope. `format` is a plain string, never a union — see below. */\nexport const PORTABLE_TEXT_FORMAT = \"portable-text-1\";\n\n/**\n * Structured blocks, when the field stores Portable Text.\n *\n * ── The compatibility guarantee, stated once ────────────────────────────────────────────\n * Portable Text did NOT change this envelope. `format`, `value` and `html` are the same three\n * keys they always were, so `isRichText`, `plain()` and `rich()` keep working untouched — and\n * they have to, because sites compiled months ago read `.html` directly and cannot be\n * rebuilt. `bettercms-starter-modern/lib/cms.ts` even carries its OWN copy of `rich()`, baked\n * into deployments nobody can reach. Storing a bare array instead would have made\n * `isRichText` return false (it rejects arrays), every shipped `rich()` call return \"\", and\n * every one of those pages go blank at 200 OK.\n *\n * `portableText()` is therefore ADDITIVE: `html` remains the always-present field, and this is\n * the opt-in for consumers that want to render structure with `@portabletext/react` instead.\n */\nexport function portableText(value: TextOrRich): readonly unknown[] | null {\n if (!isRichText(value)) return null;\n const v = value as RichTextValue & { format?: string; value?: unknown };\n return v.format === PORTABLE_TEXT_FORMAT && Array.isArray(v.value) ? (v.value as readonly unknown[]) : null;\n}\n\n/**\n * The value's resolved embeds, for a renderer of its structure (`<PortableText embeds>`), or null:\n * a bare string, a value with no embed, or an envelope written before embeds existed. Additive,\n * like `portableText()`: `rich()` reads `html`, which already holds the cards.\n */\nexport function embeds(value: TextOrRich): RichTextEmbeds | null {\n if (!isRichText(value)) return null;\n const e = (value as RichTextValue).embeds;\n return typeof e === \"object\" && e !== null && typeof e.cards === \"object\" && e.cards !== null ? e : null;\n}\n\n/** A delivered entry as far as `resolved()` reads it: its entry-level map. */\nexport interface ResolvedHolder {\n readonly resolved?: RichTextResolved | null;\n readonly data?: unknown;\n}\n\nconst resolvedMap = (r: unknown): RichTextResolved | null =>\n typeof r === \"object\" && r !== null && !Array.isArray(r) ? (r as RichTextResolved) : null;\n\n/**\n * What a rich-text value's related posts and author bios resolved to, for a renderer of its\n * structure (`<PortableText resolved>`), or null when there is nothing.\n *\n * resolved(entry.data.body, entry) // a field value, with the entry it came in\n * resolved(entry) // the entry's merged map\n *\n * An envelope value carries its own (`value.resolved`), which wins. A Body stored as a bare block\n * array has nowhere to carry one, so delivery puts the entry's merged map beside `data`\n * (`entry.resolved`): pass the entry and that is what you get. Additive, like `embeds()`: `rich()`\n * reads `html`, which already draws them.\n */\nexport function resolved(value: TextOrRich | readonly unknown[] | ResolvedHolder, entry?: ResolvedHolder | null): RichTextResolved | null {\n const own = isRichText(value) ? resolvedMap((value as RichTextValue).resolved) : null;\n if (own) return own;\n if (entry) return resolvedMap(entry.resolved);\n // An entry passed on its own: its merged map.\n const v = value as { data?: unknown; resolved?: unknown } | null;\n return v && typeof v === \"object\" && !Array.isArray(v) && \"data\" in v ? resolvedMap(v.resolved) : null;\n}\n\n/**\n * A field that may arrive as either shape. Type author-editable text fields with this and the\n * compiler routes you through `plain()`/`rich()`, so a type switch in the CMS can never reach\n * production as `[object Object]`.\n */\nexport type TextOrRich = string | RichTextValue | null | undefined;\n\n/** True when the value is a rich-text envelope rather than a bare string. */\nexport function isRichText(value: unknown): value is RichTextValue {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n (\"html\" in value || \"format\" in value)\n );\n}\n\n/**\n * Plain text for an attribute context — `<title>`, meta description, JSON-LD, `alt`.\n * Strips tags and decodes the entities that survive stripping, so the result is text the\n * consumer can escape once without double-escaping.\n */\nexport function plain(value: TextOrRich): string {\n if (typeof value === \"string\") return value;\n if (!isRichText(value) || typeof value.html !== \"string\") return \"\";\n return decodeEntities(value.html.replace(/<[^>]+>/g, \"\")).trim();\n}\n\n/**\n * Renderable HTML. Rich text keeps its inline marks (the server sanitizes `html` on write);\n * a bare string is escaped, so a plain field can never inject markup.\n *\n * A lone wrapping block is unwrapped: a field switched from `text` stores its value as\n * `<p>…</p>`, but it renders inside the element that already is the block — and\n * `<h1><p>…</p></h1>` is invalid, the parser closes the heading at the `<p>` and the text\n * falls out of it. Values with real block structure (several paragraphs, a list) are left\n * alone, so a body field still renders as a document.\n */\nexport function rich(value: TextOrRich, fallback = \"\"): string {\n const html = (typeof value === \"string\" ? escapeHtml(value) : isRichText(value) ? (value.html ?? \"\") : \"\").trim();\n return html ? unwrapLoneBlock(html) : escapeHtml(fallback);\n}\n\n/**\n * Renderable HTML for a ONE-LINE place: a heading, a button, a caption. `rich()`, except that several\n * paragraphs are that place's LINES, joined with `<br>` (a heading-styled first block counts as one).\n *\n * An author who presses Enter in a heading's editor stores a second paragraph. `rich()` leaves it a\n * paragraph, and `<h1><p>…</p><p>…</p></h1>` is what the build then draws, while a publish between\n * builds writes the same value into the built heading as lines. This draws what the publish draws.\n * A value holding anything else (a list, an image, a table) is returned as `rich()` returns it.\n */\nexport function lines(value: TextOrRich, fallback = \"\"): string {\n const html = rich(value, fallback);\n const block = /<(p|h[1-6])(?:\\s[^>]*)?>([\\s\\S]*?)<\\/\\1>/gi;\n // ponytail: a regex, not a parser. Past this size it is a body, never a one-line value.\n if (html.length > 10_000) return html;\n const found = [...html.matchAll(block)];\n if (found.length < 2 || html.replace(block, \"\").trim() !== \"\") return html;\n const shown = found.map((m) => m[2]!.trim()).filter((line) => line.replace(/<br\\s*\\/?>/gi, \"\").trim() !== \"\");\n return shown.length ? shown.join(\"<br>\") : html;\n}\n\nfunction unwrapLoneBlock(html: string): string {\n const m = html.match(/^<(p|div|h[1-6])(?:\\s[^>]*)?>([\\s\\S]*)<\\/\\1>$/i);\n return m && !new RegExp(`</${m[1]}>`, \"i\").test(m[2]) ? m[2] : html;\n}\n\nfunction escapeHtml(s: string): string {\n return s.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\");\n}\n\nfunction decodeEntities(s: string): string {\n return s\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/"/g, '\"')\n .replace(/�?39;/g, \"'\")\n .replace(/ /g, \" \")\n .replace(/&/g, \"&\");\n}\n","/**\n * The published content snapshot, read where the site RUNS — not bundled into it.\n *\n * Every BetterCMS build gets the published content as `bcms-content.json` in the project root,\n * and a server app hosted on BetterCMS runs with `BCMS_CONTENT_FILE` pointing at a copy the\n * platform rewrites on every publish. Read through this, a server-rendered page shows a publish\n * within seconds and the publish never rebuilds the site. Import the JSON instead (a JSON import,\n * `import.meta.glob`) and the bundle holds a frozen copy no publish can reach: the platform then\n * has to rebuild the whole site for every edit.\n *\n * - On a hosted server: `BCMS_CONTENT_FILE`, re-read when it changes (its time is asked on every call).\n * - At build time and in local dev: `<cwd>/bcms-content.json`, the snapshot the build was given.\n * - Anywhere without a filesystem (a browser, an edge runtime): `null`.\n *\n * A file that cannot be read keeps the last good copy; never throws into a render.\n * No `node:fs` import at module scope, so the SDK stays safe to bundle for the browser.\n */\n\n/** The snapshot's shape (`bcms-content/v1`, written by the platform's content fetch). */\nexport interface PublishedContent {\n generatedAt?: string;\n apiUrl?: string | null;\n workspace?: string;\n projectId?: string | null;\n /**\n * Published entries by model slug, each row AS THE DELIVERY API SERVES IT: `id`, `slug`, `status`,\n * `publishedAt`, `updatedAt`, `locale`, `translationOf`, `_meta`, and the field values under\n * `data`. Read a value through {@link publishedEntry}, which answers either spelling.\n */\n collections?: Record<string, Array<Record<string, unknown> & { slug?: string; data?: Record<string, unknown> }>>;\n pages?: unknown[];\n components?: unknown[];\n forms?: unknown[];\n layout?: unknown;\n [key: string]: unknown;\n}\n\ntype Proc = {\n env?: Record<string, string | undefined>;\n cwd?: () => string;\n getBuiltinModule?: (id: string) => unknown;\n};\ntype Fs = {\n statSync(path: string): { mtimeMs: number };\n readFileSync(path: string, encoding: \"utf8\"): string;\n};\n\nlet cache: { file: string; stamp: number; content: PublishedContent | null } | null = null;\n\n/** Where the published content is read from here, or null where there is no filesystem. */\nexport function publishedContentFile(): string | null {\n const proc = (globalThis as { process?: Proc }).process;\n if (typeof proc?.getBuiltinModule !== \"function\") return null;\n return proc.env?.BCMS_CONTENT_FILE || `${proc.cwd?.() ?? \".\"}/bcms-content.json`;\n}\n\n/**\n * The published content snapshot, or null when there is none here (no file, no filesystem).\n * Call it per render — it is cached and cheap — never once at module scope, which would freeze it.\n */\nexport function readPublishedContent<T extends PublishedContent = PublishedContent>(): T | null {\n const file = publishedContentFile();\n if (!file) return null;\n // A stat on every call (microseconds), the parse only when the file changed: a publish shows on the\n // very next request. A once-a-second check left a page on the old copy for up to a second.\n const proc = (globalThis as { process?: Proc }).process!;\n const fs = proc.getBuiltinModule!(\"node:fs\") as Fs;\n try {\n const stamp = fs.statSync(file).mtimeMs;\n if (cache && cache.file === file && cache.stamp === stamp) return cache.content as T | null;\n cache = { file, stamp, content: JSON.parse(fs.readFileSync(file, \"utf8\")) as PublishedContent };\n } catch {\n // Absent (a local build without a snapshot), or caught mid-write: keep the last good copy.\n if (!cache || cache.file !== file) cache = { file, stamp: -1, content: null };\n }\n return cache.content as T | null;\n}\n\n/** Each row flattened once: a page asks for the same entry for every field it renders. */\nconst flat = new WeakMap<object, Record<string, unknown>>();\n\n/**\n * One published entry by its slug, searched across every collection (first match wins, in the\n * snapshot's model order). Not keyed by model slug: a page's backing model is named by the CMS.\n *\n * 🔴 THE VALUES ARE ON THE ENTRY: `publishedEntry(\"home\")?.title`. The snapshot holds each row as\n * the delivery API serves it, values under `data`, and this used to hand that row back as it was\n * while its own doc (and the skill that names it) said \"the row carries its field values\" — so\n * `entry.title` was `undefined` and every field of a server-rendered page fell back to the copy in\n * the code, on every publish. Both spellings are answered: the values at the top level and the\n * row's own keys (`id`, `slug`, `status`, `data`, `_meta`, …) beside them, the row's winning where\n * a field is named like one — that field is read through `.data`, as before.\n */\nexport function publishedEntry<T extends Record<string, unknown> = Record<string, unknown>>(slug: string): (T & { slug: string }) | null {\n const collections = readPublishedContent()?.collections ?? {};\n for (const rows of Object.values(collections)) {\n if (!Array.isArray(rows)) continue;\n const hit = rows.find((row) => row?.slug === slug);\n if (!hit) continue;\n const data = hit.data;\n if (!data || typeof data !== \"object\" || Array.isArray(data)) return hit as T & { slug: string };\n let entry = flat.get(hit);\n if (!entry) flat.set(hit, (entry = { ...data, ...hit }));\n return entry as T & { slug: string };\n }\n return null;\n}\n\n/** Test seam: forget the cached snapshot. */\nexport function resetPublishedContentCache(): void {\n cache = null;\n}\n"],"mappings":";AAGO,IAAM,aAAa;AAAA,EACxB,mBAAmB;AAAA,EACnB,cAAc;AAAA,EACd,WAAW;AAAA,EACX,cAAc;AAAA,EACd,gBAAgB;AAAA,EAChB,kBAAkB;AAAA,EAClB,eAAe;AAAA,EACf,uBAAuB;AACzB;AAKA,SAAS,aAAa,QAAoC;AACxD,MAAI,WAAW,IAAK,QAAO,WAAW;AACtC,MAAI,WAAW,IAAK,QAAO,WAAW;AACtC,MAAI,WAAW,IAAK,QAAO,WAAW;AACtC,MAAI,WAAW,IAAK,QAAO,WAAW;AACtC,MAAI,UAAU,IAAK,QAAO,WAAW;AACrC,MAAI,WAAW,IAAK,QAAO,WAAW;AACtC,SAAO,WAAW;AACpB;AAKO,IAAM,iBAAN,MAAM,wBAAuB,MAAM;AAAA,EAC/B;AAAA,EACA;AAAA;AAAA;AAAA;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,qBAAqB,GAAG,eAAe,CAAC;AAC5D,aAAW,QAAQ,OAAO,OAAO,WAAW,GAAG;AAC7C,QAAI,CAAC,MAAM,QAAQ,IAAI,EAAG;AAC1B,UAAM,MAAM,KAAK,KAAK,CAAC,QAAQ,KAAK,SAAS,IAAI;AACjD,QAAI,CAAC,IAAK;AACV,UAAM,OAAO,IAAI;AACjB,QAAI,CAAC,QAAQ,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,EAAG,QAAO;AACrE,QAAI,QAAQ,KAAK,IAAI,GAAG;AACxB,QAAI,CAAC,MAAO,MAAK,IAAI,KAAM,QAAQ,EAAE,GAAG,MAAM,GAAG,IAAI,CAAE;AACvD,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAGO,SAAS,6BAAmC;AACjD,UAAQ;AACV;","names":["body","DEFAULT_BASE_URL"]}
|
package/dist/sections.cjs
CHANGED
|
@@ -248,10 +248,24 @@ function draftDisableResponse(request) {
|
|
|
248
248
|
|
|
249
249
|
// src/read-client.ts
|
|
250
250
|
var DEFAULT_TIMEOUT = 1e4;
|
|
251
|
+
function listQueryParams(filter, sort) {
|
|
252
|
+
const text = (v) => Array.isArray(v) ? v.join(",") : String(v);
|
|
253
|
+
const out = {};
|
|
254
|
+
for (const [field, cond] of Object.entries(filter ?? {})) {
|
|
255
|
+
if (cond == null) continue;
|
|
256
|
+
if (Array.isArray(cond)) out[`filter[${field}][in]`] = text(cond);
|
|
257
|
+
else if (typeof cond === "object") {
|
|
258
|
+
for (const [op, v] of Object.entries(cond)) if (v != null) out[`filter[${field}][${op}]`] = text(v);
|
|
259
|
+
} else out[`filter[${field}]`] = text(cond);
|
|
260
|
+
}
|
|
261
|
+
const order = Array.isArray(sort) ? sort.join(",") : sort;
|
|
262
|
+
if (order) out.sort = order;
|
|
263
|
+
return out;
|
|
264
|
+
}
|
|
251
265
|
function qs(params) {
|
|
252
266
|
const sp = new URLSearchParams();
|
|
253
267
|
for (const [k, v] of Object.entries(params)) {
|
|
254
|
-
if (v !== void 0 && v !== "") sp.set(k, String(v));
|
|
268
|
+
if (v !== void 0 && (v !== "" || k.startsWith("filter["))) sp.set(k, String(v));
|
|
255
269
|
}
|
|
256
270
|
const s = sp.toString();
|
|
257
271
|
return s ? `?${s}` : "";
|
|
@@ -372,6 +386,7 @@ function createClient(options) {
|
|
|
372
386
|
perPage: opts?.perPage,
|
|
373
387
|
depth: opts?.depth,
|
|
374
388
|
select: opts?.select?.join(","),
|
|
389
|
+
...listQueryParams(opts?.filter, opts?.sort),
|
|
375
390
|
perspective: draft ? "draft" : void 0,
|
|
376
391
|
stega: draft && stega ? "1" : void 0,
|
|
377
392
|
projectId: defaultProjectId,
|