@bettercms-ai/sdk 1.45.0 → 1.47.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/editable.cjs +229 -0
- package/dist/editable.cjs.map +1 -0
- package/dist/editable.d.cts +5 -0
- package/dist/editable.d.ts +5 -0
- package/dist/editable.js +202 -0
- package/dist/editable.js.map +1 -0
- package/dist/index.cjs +194 -26
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +85 -13
- package/dist/index.d.ts +85 -13
- package/dist/index.js +190 -25
- package/dist/index.js.map +1 -1
- package/dist/{read-CMasc3wt.d.ts → read-CpX17LTf.d.ts} +1 -1
- package/dist/{read-DTTdE_Xl.d.cts → read-DlLBgPVS.d.cts} +1 -1
- package/dist/{read-client-E9OHtQAW.d.cts → read-client-D5jzCGEc.d.cts} +24 -1
- package/dist/{read-client-E9OHtQAW.d.ts → read-client-D5jzCGEc.d.ts} +24 -1
- package/dist/read.cjs +24 -6
- 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 +24 -6
- package/dist/read.js.map +1 -1
- package/dist/sections.cjs +24 -6
- 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 +24 -6
- package/dist/sections.js.map +1 -1
- package/dist/seo.cjs +26 -1
- package/dist/seo.cjs.map +1 -1
- package/dist/seo.d.cts +1 -1
- package/dist/seo.d.ts +1 -1
- package/dist/seo.js +24 -1
- package/dist/seo.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 +11 -1
package/dist/seo.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/seo.ts"],"sourcesContent":["/**\n * resolveSeo — framework-agnostic page-over-site SEO merge for headless consumers.\n *\n * The single source of truth for \"per-page meta layered over project defaults\",\n * mirroring the server renderer's `mergeSeoMeta` so `*.bettercms.site` and headless\n * sites (@bettercms-ai/next, @bettercms-ai/astro) emit identical <head> SEO. Pure: empty\n * inputs collapse to empty strings (\"omit the tag\"), never fabricated values.\n *\n * const seo = resolveSeo(page, siteDefaults);\n * // → { title, description, canonical, og, twitter, jsonLd }\n *\n * Next consumers map this to a `Metadata` via `buildMetadata` (@bettercms-ai/next);\n * Astro consumers read the fields straight into `<head>`.\n */\nimport type { DeliveryEntrySeo, PageMetaJson, SiteSeoDefaults } from \"@bettercms-ai/types\";\n\n/** Minimal page shape `resolveSeo` reads — a `DeliveryPage`/`BetterCMSPage` satisfies it. */\nexport interface SeoInput {\n title: string;\n metaTitle?: string | null;\n metaDescription?: string | null;\n metaJson?: PageMetaJson | null;\n /** `\"home\"` makes the Automatic JSON-LD a WebSite, as the hosted renderer does. */\n slug?: string | null;\n /** Exclude from search engines. Surfaces as `ResolvedSeo.noindex` / `robots`. */\n noindex?: boolean | null;\n}\n\n/** Fully-resolved SEO values, page-over-site. Empty string ⇒ omit that tag. */\nexport interface ResolvedSeo {\n title: string;\n description: string;\n /**\n * Canonical URL — the page's own `canonical`, else `siteUrl` + `path` when both are given,\n * else \"\". Empty means the consumer must omit the tag: a RELATIVE canonical is worse than\n * none at all.\n */\n canonical: string;\n og: {\n title: string;\n description: string;\n type: string;\n image: string;\n url: string;\n };\n twitter: {\n card: string;\n title: string;\n description: string;\n image: string;\n site: string;\n };\n /**\n * JSON-LD nodes (site schema first, then the page's), already flattened + de-empted. The page's\n * part follows the renderer's precedence: Custom (`metaJson.schema`) > `metaJson.schemaType` >\n * Automatic (WebPage; WebSite on the home page).\n */\n jsonLd: Array<Record<string, unknown>>;\n /** True when the page is excluded from search engines (the renderer's `<meta name=\"robots\" content=\"noindex\">`). */\n noindex: boolean;\n /** `noindex` in the `{ index, follow }` shape Next's `Metadata.robots` takes. */\n robots: { index: boolean; follow: boolean };\n}\n\n/**\n * `siteUrl` + `path` → an absolute canonical, or \"\" when either is missing or unparseable.\n * Never returns a relative URL: a relative canonical is worse than no canonical.\n */\nfunction derivedCanonical({ siteUrl, path }: SeoLocation): string {\n if (!siteUrl || !path) return \"\";\n try {\n return new URL(path, siteUrl.endsWith(\"/\") ? siteUrl : `${siteUrl}/`).toString();\n } catch {\n return \"\";\n }\n}\n\n/** Flatten one-or-many JSON-LD into a node array, dropping empty objects. */\nfunction jsonLdNodes(\n schema: Record<string, unknown> | Array<Record<string, unknown>> | undefined,\n): Array<Record<string, unknown>> {\n if (!schema) return [];\n const arr = Array.isArray(schema) ? schema : [schema];\n const out: Array<Record<string, unknown>> = [];\n for (const node of arr) {\n if (!node || Object.keys(node).length === 0) continue;\n const graph = node[\"@graph\"];\n if (Array.isArray(graph)) {\n for (const child of graph) {\n if (child && typeof child === \"object\" && !Array.isArray(child) && Object.keys(child).length > 0) {\n out.push(child as Record<string, unknown>);\n }\n }\n continue;\n }\n out.push(node);\n }\n return out;\n}\n\n/*\n * Structured data for a page whose `metaJson.schema` is empty. A port of the page path of\n * `resolveStructuredData` in the backend (src/lib/seo/structured-data.ts, called from\n * `pageStructuredData` in src/lib/sites/render-page.ts), with `site.include: false` as the\n * Delivery API calls it: the site-wide schema is emitted separately, from `siteSchema`.\n * A page has no field data, so only the properties the page's own meta supplies are filled.\n * Keep in step with that file; the parity test imports it.\n */\nconst SCHEMA_TYPE_CHOICES = [\n \"WebPage\",\n \"AboutPage\",\n \"ContactPage\",\n \"CollectionPage\",\n \"Blog\",\n \"BlogPosting\",\n \"Article\",\n \"Product\",\n \"FAQPage\",\n \"Event\",\n \"Organization\",\n \"LocalBusiness\",\n] as const;\n\ntype PageProps = { name: string; description: string; image: string; url: string };\n\n/** Drop \"\", null and undefined so a node never carries a blank. */\nfunction compact(node: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(Object.entries(node).filter(([, value]) => value != null && value !== \"\"));\n}\n\nfunction schemaNode(type: string, { name, description, image, url }: PageProps): Record<string, unknown> {\n switch (type) {\n case \"BlogPosting\":\n case \"Article\":\n return compact({ \"@type\": type, headline: name, description, image, url, mainEntityOfPage: url });\n case \"Product\":\n case \"Event\":\n return compact({ \"@type\": type, name, description, image, url });\n case \"FAQPage\":\n case \"WebSite\":\n return compact({ \"@type\": type, name, description, url });\n case \"Organization\":\n return compact({ \"@type\": type, name, description, url, logo: image });\n default:\n // WebPage, AboutPage, ContactPage, CollectionPage, Blog, LocalBusiness\n return compact({ \"@type\": type, name, description, url, image });\n }\n}\n\n/** The page's own JSON-LD nodes: Custom > explicit `schemaType` > Automatic. */\nfunction pageJsonLd(\n page: SeoInput,\n meta: PageMetaJson,\n canonical: string,\n siteSchema: SiteSeoDefaults[\"siteSchema\"],\n): Array<Record<string, unknown>> {\n const custom = jsonLdNodes(meta.schema);\n if (custom.length > 0) return custom;\n const props: PageProps = {\n name: (page.metaTitle || page.title || \"\").trim(),\n description: (page.metaDescription || \"\").trim(),\n image: (meta.og?.image || \"\").trim(),\n url: canonical.trim(),\n };\n const schemaType = (meta as { schemaType?: unknown }).schemaType;\n if (typeof schemaType === \"string\" && (SCHEMA_TYPE_CHOICES as readonly string[]).includes(schemaType)) {\n return [schemaNode(schemaType, props)];\n }\n if (page.slug === \"home\") {\n // The home page IS the WebSite, unless the site-wide schema already describes it.\n return jsonLdNodes(siteSchema).length > 0 ? [] : [schemaNode(\"WebSite\", props)];\n }\n return [schemaNode(\"WebPage\", props)];\n}\n\n/**\n * A Delivery API entry as a `resolveSeo` input. The server already resolved the collection\n * template's `{{field}}` tokens for this entry and merged the entry's own SEO over it, so this is\n * a reshape, not a resolver:\n *\n * const entry = await bcms.getEntry(\"astro\");\n * const seo = resolveSeo(entrySeoInput(entry), siteDefaults, { siteUrl, path: `/tags/${entry.slug}` });\n * // seo.jsonLd holds the template's schema, resolved for this entry\n */\nexport function entrySeoInput(entry: { slug: string; seo?: DeliveryEntrySeo | null }): SeoInput {\n const { metaTitle, metaDescription, noindex, ...metaJson } = entry.seo ?? {};\n return {\n title: metaTitle || entry.slug,\n metaTitle: metaTitle ?? null,\n metaDescription: metaDescription ?? null,\n metaJson,\n noindex: noindex === true,\n };\n}\n\n/** Where this page lives, so a canonical can be derived when the page sets none. */\nexport interface SeoLocation {\n /** Absolute site origin, e.g. `https://acme.com`. Trailing slash optional. */\n siteUrl?: string;\n /** This page's path, e.g. `/about` or `/`. */\n path?: string;\n}\n\n/**\n * Merge a page's own SEO over the site defaults: page meta wins, then site defaults, then\n * sensible fallbacks.\n *\n * The CANONICAL is the one field that cannot be resolved from content alone, and getting this\n * wrong is silent. The hosted renderer (`mergeSeoMeta` in the backend) falls back to a canonical\n * it derives from the request's own origin and path — headless consumers have no request, so\n * they must pass `location`. Without it this returns \"\" and the caller ships no\n * `<link rel=\"canonical\">` and no `og:url`, exactly as it did before `location` existed.\n */\nexport function resolveSeo(\n page: SeoInput,\n defaults: SiteSeoDefaults = {},\n location: SeoLocation = {},\n): ResolvedSeo {\n const meta = page.metaJson ?? {};\n const title = page.metaTitle || page.title || \"\";\n const description = page.metaDescription || defaults.metaDescription || \"\";\n const ogImage = meta.og?.image || defaults.og?.image || defaults.ogImage || \"\";\n const ogTitle = meta.og?.title || title;\n const ogDescription = meta.og?.description || description;\n const twImage = meta.twitter?.image || ogImage;\n const canonical = meta.canonical || derivedCanonical(location);\n return {\n title,\n description,\n canonical,\n og: {\n title: ogTitle,\n description: ogDescription,\n type: meta.og?.type || defaults.og?.type || \"website\",\n image: ogImage,\n url: canonical,\n },\n twitter: {\n card: meta.twitter?.card || defaults.twitter?.card || (twImage ? \"summary_large_image\" : \"summary\"),\n title: meta.twitter?.title || ogTitle,\n description: meta.twitter?.description || ogDescription,\n image: twImage,\n site: defaults.twitterHandle || \"\",\n },\n jsonLd: [...jsonLdNodes(defaults.siteSchema), ...pageJsonLd(page, meta, canonical, defaults.siteSchema)],\n noindex: page.noindex === true,\n rob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/seo.ts"],"sourcesContent":["/**\n * Stega — embed invisible content-provenance into string values for visual\n * editing, then decode it in the browser overlay to open the right dashboard\n * editor. Uses zero-width characters so the payload is invisible and copy-safe.\n *\n * Scheme: `<clean text><START><bits…><END>` where each byte of the UTF-8 JSON\n * payload is 8 zero-width bits (ZERO=U+200B, ONE=U+200C), framed by START\n * (U+2060) and END (U+2061). The backend encodes draft responses; the overlay\n * decodes. Both sides MUST share this module's scheme.\n */\nconst ZERO = \"\";\nconst ONE = \"\";\nconst START = \"\";\nconst END = \"\";\nconst FRAMES = new RegExp(`${START}([${ZERO}${ONE}]*)${END}`, \"g\");\n\n/**\n * Provenance describing where a string came from, for editor deep-linking. A `stega=2` payload\n * (`{t, id, f}`) is read into this same shape: `type` from `t`, `field` from `f`, and `ws`/`slug`\n * empty, because v2 does not carry them.\n */\nexport interface StegaPayload {\n /** Workspace slug (v1 only; \"\" from a v2 payload). */\n ws: string;\n type: \"entry\" | \"page\" | \"layout\" | \"component\";\n /** Entry/page id. */\n id: string;\n /** v1 only; \"\" from a v2 payload. */\n slug: string;\n /** Field key (or block id) the value belongs to. */\n field: string;\n /** The binding kind (`text`), where the encoder knows it. */\n kind?: string;\n}\n\nfunction toBits(s: string): string {\n const bytes = new TextEncoder().encode(s);\n let out = \"\";\n for (const b of bytes) {\n for (let i = 7; i >= 0; i--) out += (b >> i) & 1 ? ONE : ZERO;\n }\n return out;\n}\n\nfunction fromBits(bits: string): string {\n const bytes: number[] = [];\n for (let i = 0; i + 8 <= bits.length; i += 8) {\n let b = 0;\n for (let j = 0; j < 8; j++) b = (b << 1) | (bits[i + j] === ONE ? 1 : 0);\n bytes.push(b);\n }\n return new TextDecoder().decode(new Uint8Array(bytes));\n}\n\n/** Append an invisible provenance payload to a string (the v1 frame). */\nexport function encodeStega(clean: string, payload: StegaPayload): string {\n return `${clean}${START}${toBits(JSON.stringify(payload))}${END}`;\n}\n\nconst V2_TYPES = { e: \"entry\", p: \"page\", l: \"layout\", c: \"component\" } as const;\n\n/**\n * A frame's bits as a payload, or null when they are not JSON. A v2 payload is read into the v1\n * shape; any other JSON is returned as it decodes (v1, or the convert helper's source-map payload).\n */\nfunction payloadOf(bits: string): StegaPayload | null {\n try {\n const raw = JSON.parse(fromBits(bits)) as Record<string, unknown>;\n if (typeof raw.t === \"string\" && raw.t in V2_TYPES && typeof raw.id === \"string\" && typeof raw.f === \"string\") {\n return { ws: \"\", type: V2_TYPES[raw.t as keyof typeof V2_TYPES], id: raw.id, slug: \"\", field: raw.f };\n }\n return raw as unknown as StegaPayload;\n } catch {\n return null;\n }\n}\n\n/**\n * The field ref a payload addresses, `<target>:<id>:<path>`, the one address grammar every writer\n * reads; null for a payload that names no document (the convert helper's source map).\n */\nconst TARGETS = { entry: 1, page: 1, layout: 1, component: 1 };\nexport const stegaRef = (payload: StegaPayload): string | null =>\n typeof payload.type === \"string\" && payload.type in TARGETS && typeof payload.id === \"string\" && typeof payload.field === \"string\"\n ? `${payload.type}:${payload.id}:${payload.field}`\n : null;\n\n/**\n * Extract `{ clean, payload }` from a stega-encoded string (v1 or v2), or null if absent. `ref` is\n * the field ref, present when the payload names a document.\n */\nexport function decodeStega(value: string): { clean: string; payload: StegaPayload; ref?: string } | null {\n for (const frame of value.matchAll(FRAMES)) {\n // An empty frame is a v2 open marker, not a payload.\n if (!frame[1]) continue;\n const payload = payloadOf(frame[1]);\n if (!payload) return null;\n const ref = stegaRef(payload);\n return { clean: stegaClean(value), payload, ...(ref ? { ref } : {}) };\n }\n return null;\n}\n\n/**\n * A value's clean text and the field ref it carries (`entry:e_1:title`, `page:pg_1:hero.title`,\n * `layout:nav:brand`), or `ref: null` when it carries none. What a template uses when it needs both\n * the string to compare and the address to bind.\n */\nexport function stegaSplit(value: string): { clean: string; ref: string | null } {\n const decoded = decodeStega(value);\n return { clean: decoded?.clean ?? stegaClean(value), ref: decoded?.ref ?? null };\n}\n\n/**\n * Where a value BEGINS in a rendered page: an empty frame. The canvas brackets every bound\n * string with it and the payload frame, so a text node can be told inside a value from text\n * that merely precedes one. @see resolveStega\n */\nexport const STEGA_OPEN = `${START}${END}`;\n\n/**\n * A value with EVERY stega frame taken out, markers included, from every string in it at any depth\n * (arrays and plain objects). The SAME value back when it holds none. What a value passes through\n * before it is compared, used as a key or attribute, saved or published.\n */\nexport function stegaClean<T>(value: T): T {\n if (typeof value === \"string\") return (value.includes(START) ? value.replace(FRAMES, \"\") : value) as T;\n if (Array.isArray(value)) {\n const out = value.map((v) => stegaClean(v));\n return (out.some((v, i) => v !== value[i]) ? out : value) as T;\n }\n if (value && typeof value === \"object\" && Object.getPrototypeOf(value) === Object.prototype) {\n const entries = Object.entries(value).map(([k, v]) => [k, stegaClean(v)] as const);\n return (entries.some(([k, v]) => v !== (value as Record<string, unknown>)[k]) ? Object.fromEntries(entries) : value) as T;\n }\n return value;\n}\n\n/**\n * Remove every stega frame. An alias of {@link stegaClean}: it used to remove only the FIRST frame,\n * which left the payload behind on a `stega=2` value (an open marker, then the payload).\n */\nexport const stripStega = stegaClean;\n\n/** Each frame in `text`, in order: where it starts and ends, and its payload (null for an open marker or bits that are not one). */\nexport function stegaFrames(text: string): Array<{ index: number; end: number; payload: StegaPayload | null; open: boolean }> {\n return [...text.matchAll(FRAMES)].map((m) => ({ index: m.index, end: m.index + m[0].length, payload: m[1] ? payloadOf(m[1]) : null, open: !m[1] }));\n}\n\n/** The least of a DOM node this needs: a real `Node` satisfies it, and so does a test's plain object. */\nexport interface StegaNode {\n textContent: string | null;\n parentNode: StegaNode | null;\n childNodes?: ArrayLike<StegaNode>;\n}\n\n/**\n * Which value does this node render? Its payload and the nearest ancestor that holds the whole\n * value, or null when the node's text belongs to none.\n *\n * By CONTENT, not by attribute: a splitting library cuts a heading into one element per\n * character, a marquee clones its track, a component redraws its children, and the element a\n * build stamped is gone or copied. The string survives all of that, in order, across however\n * many text nodes: climbing from the clicked node, the first ancestor whose text holds a value\n * (its open marker to its payload frame) that overlaps the node is the value's extent.\n * Every copy of a value resolves to the same payload.\n */\nexport function resolveStega(node: StegaNode): { payload: StegaPayload; element: StegaNode } | null {\n let offset = 0;\n const length = node.textContent?.length ?? 0;\n for (let cur = node, up = node.parentNode; up; cur = up, up = up.parentNode) {\n for (const sibling of Array.from(up.childNodes ?? [])) {\n if (sibling === cur) break;\n offset += sibling.textContent?.length ?? 0;\n }\n const text = up.textContent ?? \"\";\n // Values nest (a field inside a field), so the open markers are a stack and a payload closes the last.\n const opens: number[] = [];\n for (const frame of stegaFrames(text)) {\n if (frame.open) {\n opens.push(frame.index);\n continue;\n }\n const open = opens.pop();\n // A value overlaps the node when it ends after the node starts and begins before the node\n // ends: the node that holds a value's first characters holds its open marker too.\n if (frame.end <= offset || open === undefined || open >= offset + length) continue;\n if (!frame.payload) break;\n return { payload: frame.payload, element: up };\n }\n }\n return null;\n}\n","/**\n * resolveSeo — framework-agnostic page-over-site SEO merge for headless consumers.\n *\n * The single source of truth for \"per-page meta layered over project defaults\",\n * mirroring the server renderer's `mergeSeoMeta` so `*.bettercms.site` and headless\n * sites (@bettercms-ai/next, @bettercms-ai/astro) emit identical <head> SEO. Pure: empty\n * inputs collapse to empty strings (\"omit the tag\"), never fabricated values.\n *\n * const seo = resolveSeo(page, siteDefaults);\n * // → { title, description, canonical, og, twitter, jsonLd }\n *\n * Next consumers map this to a `Metadata` via `buildMetadata` (@bettercms-ai/next);\n * Astro consumers read the fields straight into `<head>`.\n */\nimport type { DeliveryEntrySeo, PageMetaJson, SiteSeoDefaults } from \"@bettercms-ai/types\";\nimport { stegaClean } from \"./stega.js\";\n\n/** Minimal page shape `resolveSeo` reads — a `DeliveryPage`/`BetterCMSPage` satisfies it. */\nexport interface SeoInput {\n title: string;\n metaTitle?: string | null;\n metaDescription?: string | null;\n metaJson?: PageMetaJson | null;\n /** `\"home\"` makes the Automatic JSON-LD a WebSite, as the hosted renderer does. */\n slug?: string | null;\n /** Exclude from search engines. Surfaces as `ResolvedSeo.noindex` / `robots`. */\n noindex?: boolean | null;\n}\n\n/** Fully-resolved SEO values, page-over-site. Empty string ⇒ omit that tag. */\nexport interface ResolvedSeo {\n title: string;\n description: string;\n /**\n * Canonical URL — the page's own `canonical`, else `siteUrl` + `path` when both are given,\n * else \"\". Empty means the consumer must omit the tag: a RELATIVE canonical is worse than\n * none at all.\n */\n canonical: string;\n og: {\n title: string;\n description: string;\n type: string;\n image: string;\n url: string;\n };\n twitter: {\n card: string;\n title: string;\n description: string;\n image: string;\n site: string;\n };\n /**\n * JSON-LD nodes (site schema first, then the page's), already flattened + de-empted. The page's\n * part follows the renderer's precedence: Custom (`metaJson.schema`) > `metaJson.schemaType` >\n * Automatic (WebPage; WebSite on the home page).\n */\n jsonLd: Array<Record<string, unknown>>;\n /** True when the page is excluded from search engines (the renderer's `<meta name=\"robots\" content=\"noindex\">`). */\n noindex: boolean;\n /** `noindex` in the `{ index, follow }` shape Next's `Metadata.robots` takes. */\n robots: { index: boolean; follow: boolean };\n}\n\n/**\n * `siteUrl` + `path` → an absolute canonical, or \"\" when either is missing or unparseable.\n * Never returns a relative URL: a relative canonical is worse than no canonical.\n */\nfunction derivedCanonical({ siteUrl, path }: SeoLocation): string {\n if (!siteUrl || !path) return \"\";\n try {\n return new URL(path, siteUrl.endsWith(\"/\") ? siteUrl : `${siteUrl}/`).toString();\n } catch {\n return \"\";\n }\n}\n\n/** Flatten one-or-many JSON-LD into a node array, dropping empty objects. */\nfunction jsonLdNodes(\n schema: Record<string, unknown> | Array<Record<string, unknown>> | undefined,\n): Array<Record<string, unknown>> {\n if (!schema) return [];\n const arr = Array.isArray(schema) ? schema : [schema];\n const out: Array<Record<string, unknown>> = [];\n for (const node of arr) {\n if (!node || Object.keys(node).length === 0) continue;\n const graph = node[\"@graph\"];\n if (Array.isArray(graph)) {\n for (const child of graph) {\n if (child && typeof child === \"object\" && !Array.isArray(child) && Object.keys(child).length > 0) {\n out.push(child as Record<string, unknown>);\n }\n }\n continue;\n }\n out.push(node);\n }\n return out;\n}\n\n/*\n * Structured data for a page whose `metaJson.schema` is empty. A port of the page path of\n * `resolveStructuredData` in the backend (src/lib/seo/structured-data.ts, called from\n * `pageStructuredData` in src/lib/sites/render-page.ts), with `site.include: false` as the\n * Delivery API calls it: the site-wide schema is emitted separately, from `siteSchema`.\n * A page has no field data, so only the properties the page's own meta supplies are filled.\n * Keep in step with that file; the parity test imports it.\n */\nconst SCHEMA_TYPE_CHOICES = [\n \"WebPage\",\n \"AboutPage\",\n \"ContactPage\",\n \"CollectionPage\",\n \"Blog\",\n \"BlogPosting\",\n \"Article\",\n \"Product\",\n \"FAQPage\",\n \"Event\",\n \"Organization\",\n \"LocalBusiness\",\n] as const;\n\ntype PageProps = { name: string; description: string; image: string; url: string };\n\n/** Drop \"\", null and undefined so a node never carries a blank. */\nfunction compact(node: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(Object.entries(node).filter(([, value]) => value != null && value !== \"\"));\n}\n\nfunction schemaNode(type: string, { name, description, image, url }: PageProps): Record<string, unknown> {\n switch (type) {\n case \"BlogPosting\":\n case \"Article\":\n return compact({ \"@type\": type, headline: name, description, image, url, mainEntityOfPage: url });\n case \"Product\":\n case \"Event\":\n return compact({ \"@type\": type, name, description, image, url });\n case \"FAQPage\":\n case \"WebSite\":\n return compact({ \"@type\": type, name, description, url });\n case \"Organization\":\n return compact({ \"@type\": type, name, description, url, logo: image });\n default:\n // WebPage, AboutPage, ContactPage, CollectionPage, Blog, LocalBusiness\n return compact({ \"@type\": type, name, description, url, image });\n }\n}\n\n/** The page's own JSON-LD nodes: Custom > explicit `schemaType` > Automatic. */\nfunction pageJsonLd(\n page: SeoInput,\n meta: PageMetaJson,\n canonical: string,\n siteSchema: SiteSeoDefaults[\"siteSchema\"],\n): Array<Record<string, unknown>> {\n const custom = jsonLdNodes(meta.schema);\n if (custom.length > 0) return custom;\n const props: PageProps = {\n name: (page.metaTitle || page.title || \"\").trim(),\n description: (page.metaDescription || \"\").trim(),\n image: (meta.og?.image || \"\").trim(),\n url: canonical.trim(),\n };\n const schemaType = (meta as { schemaType?: unknown }).schemaType;\n if (typeof schemaType === \"string\" && (SCHEMA_TYPE_CHOICES as readonly string[]).includes(schemaType)) {\n return [schemaNode(schemaType, props)];\n }\n if (page.slug === \"home\") {\n // The home page IS the WebSite, unless the site-wide schema already describes it.\n return jsonLdNodes(siteSchema).length > 0 ? [] : [schemaNode(\"WebSite\", props)];\n }\n return [schemaNode(\"WebPage\", props)];\n}\n\n/**\n * A Delivery API entry as a `resolveSeo` input. The server already resolved the collection\n * template's `{{field}}` tokens for this entry and merged the entry's own SEO over it, so this is\n * a reshape, not a resolver:\n *\n * const entry = await bcms.getEntry(\"astro\");\n * const seo = resolveSeo(entrySeoInput(entry), siteDefaults, { siteUrl, path: `/tags/${entry.slug}` });\n * // seo.jsonLd holds the template's schema, resolved for this entry\n */\nexport function entrySeoInput(entry: { slug: string; seo?: DeliveryEntrySeo | null }): SeoInput {\n const { metaTitle, metaDescription, noindex, ...metaJson } = entry.seo ?? {};\n return {\n title: metaTitle || entry.slug,\n metaTitle: metaTitle ?? null,\n metaDescription: metaDescription ?? null,\n metaJson,\n noindex: noindex === true,\n };\n}\n\n/** Where this page lives, so a canonical can be derived when the page sets none. */\nexport interface SeoLocation {\n /** Absolute site origin, e.g. `https://acme.com`. Trailing slash optional. */\n siteUrl?: string;\n /** This page's path, e.g. `/about` or `/`. */\n path?: string;\n}\n\n/**\n * Merge a page's own SEO over the site defaults: page meta wins, then site defaults, then\n * sensible fallbacks.\n *\n * The CANONICAL is the one field that cannot be resolved from content alone, and getting this\n * wrong is silent. The hosted renderer (`mergeSeoMeta` in the backend) falls back to a canonical\n * it derives from the request's own origin and path — headless consumers have no request, so\n * they must pass `location`. Without it this returns \"\" and the caller ships no\n * `<link rel=\"canonical\">` and no `og:url`, exactly as it did before `location` existed.\n */\nexport function resolveSeo(\n framedPage: SeoInput,\n framedDefaults: SiteSeoDefaults = {},\n location: SeoLocation = {},\n): ResolvedSeo {\n // A draft read's strings carry stega frames; none may reach a <title>, a meta tag or JSON-LD. Only\n // what is read here is cleaned: a whole DeliveryPage passed in keeps its block tree unwalked.\n const { title: pageTitle, metaTitle, metaDescription, metaJson, slug, noindex } = framedPage;\n const page: SeoInput = stegaClean({ title: pageTitle, metaTitle, metaDescription, metaJson, slug, noindex });\n const defaults = stegaClean(framedDefaults);\n const meta = page.metaJson ?? {};\n const title = page.metaTitle || page.title || \"\";\n const description = page.metaDescription || defaults.metaDescription || \"\";\n const ogImage = meta.og?.image || defaults.og?.image || defaults.ogImage || \"\";\n const ogTitle = meta.og?.title || title;\n const ogDescription = meta.og?.description || description;\n const twImage = meta.twitter?.image || ogImage;\n const canonical = meta.canonical || derivedCanonical(location);\n return {\n title,\n description,\n canonical,\n og: {\n title: ogTitle,\n description: ogDescription,\n type: meta.og?.type || defaults.og?.type || \"website\",\n image: ogImage,\n url: canonical,\n },\n twitter: {\n card: meta.twitter?.card || defaults.twitter?.card || (twImage ? \"summary_large_image\" : \"summary\"),\n title: meta.twitter?.title || ogTitle,\n description: meta.twitter?.description || ogDescription,\n image: twImage,\n site: defaults.twitterHandle || \"\",\n },\n jsonLd: [...jsonLdNodes(defaults.siteSchema), ...pageJsonLd(page, meta, canonical, defaults.siteSchema)],\n noindex: page.noindex === true,\n robots: { index: page.noindex !== true, follow: true },\n };\n}\n"],"mappings":";AAUA,IAAM,OAAO;AACb,IAAM,MAAM;AACZ,IAAM,QAAQ;AACd,IAAM,MAAM;AACZ,IAAM,SAAS,IAAI,OAAO,GAAG,KAAK,KAAK,IAAI,GAAG,GAAG,MAAM,GAAG,IAAI,GAAG;AAwG1D,IAAM,aAAa,GAAG,KAAK,GAAG,GAAG;AAOjC,SAAS,WAAc,OAAa;AACzC,MAAI,OAAO,UAAU,SAAU,QAAQ,MAAM,SAAS,KAAK,IAAI,MAAM,QAAQ,QAAQ,EAAE,IAAI;AAC3F,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,UAAM,MAAM,MAAM,IAAI,CAAC,MAAM,WAAW,CAAC,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MAAM,KAAK,IAAI,QAAQ,SAAS,IAAI,QAAQ;AAAA,MAC5C,OAAO;AAAA,MACP,KAAK;AAAA,IACP;AAAA,IACA,SAAS;AAAA,MACP,MAAM,KAAK,SAAS,QAAQ,SAAS,SAAS,SAAS,UAAU,wBAAwB;AAAA,MACzF,OAAO,KAAK,SAAS,SAAS;AAAA,MAC9B,aAAa,KAAK,SAAS,eAAe;AAAA,MAC1C,OAAO;AAAA,MACP,MAAM,SAAS,iBAAiB;AAAA,IAClC;AAAA,IACA,QAAQ,CAAC,GAAG,YAAY,SAAS,UAAU,GAAG,GAAG,WAAW,MAAM,MAAM,WAAW,SAAS,UAAU,CAAC;AAAA,IACvG,SAAS,KAAK,YAAY;AAAA,IAC1B,QAAQ,EAAE,OAAO,KAAK,YAAY,MAAM,QAAQ,KAAK;AAAA,EACvD;AACF;","names":[]}
|
package/dist/webhook.cjs
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/webhook.ts
|
|
21
|
+
var webhook_exports = {};
|
|
22
|
+
__export(webhook_exports, {
|
|
23
|
+
verifyWebhookSignature: () => verifyWebhookSignature
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(webhook_exports);
|
|
26
|
+
async function verifyWebhookSignature(rawBody, header, secret) {
|
|
27
|
+
const hex = /^sha256=([0-9a-f]{64})$/.exec(header ?? "")?.[1];
|
|
28
|
+
if (!hex || !secret) return false;
|
|
29
|
+
const utf8 = new TextEncoder();
|
|
30
|
+
const key = await crypto.subtle.importKey("raw", utf8.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
|
|
31
|
+
const signature = Uint8Array.from(hex.match(/../g), (byte) => parseInt(byte, 16));
|
|
32
|
+
return crypto.subtle.verify("HMAC", key, signature, utf8.encode(rawBody));
|
|
33
|
+
}
|
|
34
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
35
|
+
0 && (module.exports = {
|
|
36
|
+
verifyWebhookSignature
|
|
37
|
+
});
|
|
38
|
+
//# sourceMappingURL=webhook.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/webhook.ts"],"sourcesContent":["/**\n * Is `header` (`sha256=<hex>`, the `X-BetterCMS-Signature` value) the HMAC-SHA256 of `rawBody` under\n * `secret`? Check the raw body before parsing it: a re-serialised JSON body no longer matches.\n *\n * Web Crypto, not `node:crypto`: it runs on Node 18+, Bun, Deno, Workers and the Edge runtime, and\n * `verify` compares in constant time. Code a browser bundle can reach imports it from this subpath,\n * never the SDK root, whose media upload helpers import Node's `dns` and `fs`.\n *\n * import { verifyWebhookSignature } from \"@bettercms-ai/sdk/webhook\";\n * const raw = await request.text();\n * if (!(await verifyWebhookSignature(raw, request.headers.get(\"x-bettercms-signature\"), secret))) return new Response(null, { status: 401 });\n */\nexport async function verifyWebhookSignature(rawBody: string, header: string | null | undefined, secret: string): Promise<boolean> {\n const hex = /^sha256=([0-9a-f]{64})$/.exec(header ?? \"\")?.[1];\n if (!hex || !secret) return false;\n const utf8 = new TextEncoder();\n const key = await crypto.subtle.importKey(\"raw\", utf8.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"verify\"]);\n const signature = Uint8Array.from(hex.match(/../g)!, (byte) => parseInt(byte, 16));\n return crypto.subtle.verify(\"HMAC\", key, signature, utf8.encode(rawBody));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA,eAAsB,uBAAuB,SAAiB,QAAmC,QAAkC;AACjI,QAAM,MAAM,0BAA0B,KAAK,UAAU,EAAE,IAAI,CAAC;AAC5D,MAAI,CAAC,OAAO,CAAC,OAAQ,QAAO;AAC5B,QAAM,OAAO,IAAI,YAAY;AAC7B,QAAM,MAAM,MAAM,OAAO,OAAO,UAAU,OAAO,KAAK,OAAO,MAAM,GAAG,EAAE,MAAM,QAAQ,MAAM,UAAU,GAAG,OAAO,CAAC,QAAQ,CAAC;AAC1H,QAAM,YAAY,WAAW,KAAK,IAAI,MAAM,KAAK,GAAI,CAAC,SAAS,SAAS,MAAM,EAAE,CAAC;AACjF,SAAO,OAAO,OAAO,OAAO,QAAQ,KAAK,WAAW,KAAK,OAAO,OAAO,CAAC;AAC1E;","names":[]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Is `header` (`sha256=<hex>`, the `X-BetterCMS-Signature` value) the HMAC-SHA256 of `rawBody` under
|
|
3
|
+
* `secret`? Check the raw body before parsing it: a re-serialised JSON body no longer matches.
|
|
4
|
+
*
|
|
5
|
+
* Web Crypto, not `node:crypto`: it runs on Node 18+, Bun, Deno, Workers and the Edge runtime, and
|
|
6
|
+
* `verify` compares in constant time. Code a browser bundle can reach imports it from this subpath,
|
|
7
|
+
* never the SDK root, whose media upload helpers import Node's `dns` and `fs`.
|
|
8
|
+
*
|
|
9
|
+
* import { verifyWebhookSignature } from "@bettercms-ai/sdk/webhook";
|
|
10
|
+
* const raw = await request.text();
|
|
11
|
+
* if (!(await verifyWebhookSignature(raw, request.headers.get("x-bettercms-signature"), secret))) return new Response(null, { status: 401 });
|
|
12
|
+
*/
|
|
13
|
+
declare function verifyWebhookSignature(rawBody: string, header: string | null | undefined, secret: string): Promise<boolean>;
|
|
14
|
+
|
|
15
|
+
export { verifyWebhookSignature };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Is `header` (`sha256=<hex>`, the `X-BetterCMS-Signature` value) the HMAC-SHA256 of `rawBody` under
|
|
3
|
+
* `secret`? Check the raw body before parsing it: a re-serialised JSON body no longer matches.
|
|
4
|
+
*
|
|
5
|
+
* Web Crypto, not `node:crypto`: it runs on Node 18+, Bun, Deno, Workers and the Edge runtime, and
|
|
6
|
+
* `verify` compares in constant time. Code a browser bundle can reach imports it from this subpath,
|
|
7
|
+
* never the SDK root, whose media upload helpers import Node's `dns` and `fs`.
|
|
8
|
+
*
|
|
9
|
+
* import { verifyWebhookSignature } from "@bettercms-ai/sdk/webhook";
|
|
10
|
+
* const raw = await request.text();
|
|
11
|
+
* if (!(await verifyWebhookSignature(raw, request.headers.get("x-bettercms-signature"), secret))) return new Response(null, { status: 401 });
|
|
12
|
+
*/
|
|
13
|
+
declare function verifyWebhookSignature(rawBody: string, header: string | null | undefined, secret: string): Promise<boolean>;
|
|
14
|
+
|
|
15
|
+
export { verifyWebhookSignature };
|
package/dist/webhook.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// src/webhook.ts
|
|
2
|
+
async function verifyWebhookSignature(rawBody, header, secret) {
|
|
3
|
+
const hex = /^sha256=([0-9a-f]{64})$/.exec(header ?? "")?.[1];
|
|
4
|
+
if (!hex || !secret) return false;
|
|
5
|
+
const utf8 = new TextEncoder();
|
|
6
|
+
const key = await crypto.subtle.importKey("raw", utf8.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
|
|
7
|
+
const signature = Uint8Array.from(hex.match(/../g), (byte) => parseInt(byte, 16));
|
|
8
|
+
return crypto.subtle.verify("HMAC", key, signature, utf8.encode(rawBody));
|
|
9
|
+
}
|
|
10
|
+
export {
|
|
11
|
+
verifyWebhookSignature
|
|
12
|
+
};
|
|
13
|
+
//# sourceMappingURL=webhook.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/webhook.ts"],"sourcesContent":["/**\n * Is `header` (`sha256=<hex>`, the `X-BetterCMS-Signature` value) the HMAC-SHA256 of `rawBody` under\n * `secret`? Check the raw body before parsing it: a re-serialised JSON body no longer matches.\n *\n * Web Crypto, not `node:crypto`: it runs on Node 18+, Bun, Deno, Workers and the Edge runtime, and\n * `verify` compares in constant time. Code a browser bundle can reach imports it from this subpath,\n * never the SDK root, whose media upload helpers import Node's `dns` and `fs`.\n *\n * import { verifyWebhookSignature } from \"@bettercms-ai/sdk/webhook\";\n * const raw = await request.text();\n * if (!(await verifyWebhookSignature(raw, request.headers.get(\"x-bettercms-signature\"), secret))) return new Response(null, { status: 401 });\n */\nexport async function verifyWebhookSignature(rawBody: string, header: string | null | undefined, secret: string): Promise<boolean> {\n const hex = /^sha256=([0-9a-f]{64})$/.exec(header ?? \"\")?.[1];\n if (!hex || !secret) return false;\n const utf8 = new TextEncoder();\n const key = await crypto.subtle.importKey(\"raw\", utf8.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"verify\"]);\n const signature = Uint8Array.from(hex.match(/../g)!, (byte) => parseInt(byte, 16));\n return crypto.subtle.verify(\"HMAC\", key, signature, utf8.encode(rawBody));\n}\n"],"mappings":";AAYA,eAAsB,uBAAuB,SAAiB,QAAmC,QAAkC;AACjI,QAAM,MAAM,0BAA0B,KAAK,UAAU,EAAE,IAAI,CAAC;AAC5D,MAAI,CAAC,OAAO,CAAC,OAAQ,QAAO;AAC5B,QAAM,OAAO,IAAI,YAAY;AAC7B,QAAM,MAAM,MAAM,OAAO,OAAO,UAAU,OAAO,KAAK,OAAO,MAAM,GAAG,EAAE,MAAM,QAAQ,MAAM,UAAU,GAAG,OAAO,CAAC,QAAQ,CAAC;AAC1H,QAAM,YAAY,WAAW,KAAK,IAAI,MAAM,KAAK,GAAI,CAAC,SAAS,SAAS,MAAM,EAAE,CAAC;AACjF,SAAO,OAAO,OAAO,OAAO,QAAQ,KAAK,WAAW,KAAK,OAAO,OAAO,CAAC;AAC1E;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bettercms-ai/sdk",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.47.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -50,6 +50,16 @@
|
|
|
50
50
|
"types": "./dist/live.d.ts",
|
|
51
51
|
"import": "./dist/live.js",
|
|
52
52
|
"default": "./dist/live.js"
|
|
53
|
+
},
|
|
54
|
+
"./editable": {
|
|
55
|
+
"types": "./dist/editable.d.ts",
|
|
56
|
+
"import": "./dist/editable.js",
|
|
57
|
+
"default": "./dist/editable.js"
|
|
58
|
+
},
|
|
59
|
+
"./webhook": {
|
|
60
|
+
"types": "./dist/webhook.d.ts",
|
|
61
|
+
"import": "./dist/webhook.js",
|
|
62
|
+
"default": "./dist/webhook.js"
|
|
53
63
|
}
|
|
54
64
|
},
|
|
55
65
|
"dependencies": {
|