@bettercms-ai/sdk 1.38.0 → 1.40.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/bindings.cjs +146 -0
- package/dist/bindings.cjs.map +1 -0
- package/dist/bindings.d.cts +174 -0
- package/dist/bindings.d.ts +174 -0
- package/dist/bindings.js +109 -0
- package/dist/bindings.js.map +1 -0
- package/dist/draft.cjs +8 -0
- package/dist/draft.cjs.map +1 -1
- package/dist/draft.d.cts +9 -1
- package/dist/draft.d.ts +9 -1
- package/dist/draft.js +6 -0
- package/dist/draft.js.map +1 -1
- package/dist/in-editor-D1vXPgJh.d.cts +63 -0
- package/dist/in-editor-D1vXPgJh.d.ts +63 -0
- package/dist/index.cjs +5 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -218
- package/dist/index.d.ts +6 -218
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/live.cjs +158 -0
- package/dist/live.cjs.map +1 -0
- package/dist/live.d.cts +95 -0
- package/dist/live.d.ts +95 -0
- package/dist/live.js +120 -0
- package/dist/live.js.map +1 -0
- package/dist/read-AYzXKCU-.d.cts +191 -0
- package/dist/read-Bb60mWmW.d.ts +191 -0
- package/dist/{read-client-B1uDVNKk.d.cts → read-client-CnkVzNP0.d.cts} +5 -0
- package/dist/{read-client-B1uDVNKk.d.ts → read-client-CnkVzNP0.d.ts} +5 -0
- package/dist/read.cjs +54 -0
- package/dist/read.cjs.map +1 -1
- package/dist/read.d.cts +2 -39
- package/dist/read.d.ts +2 -39
- package/dist/read.js +49 -0
- package/dist/read.js.map +1 -1
- package/dist/sections.cjs +144 -75
- package/dist/sections.cjs.map +1 -1
- package/dist/sections.d.cts +56 -4
- package/dist/sections.d.ts +56 -4
- package/dist/sections.js +138 -75
- package/dist/sections.js.map +1 -1
- package/package.json +11 -1
package/dist/live.cjs
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
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/live.ts
|
|
21
|
+
var live_exports = {};
|
|
22
|
+
__export(live_exports, {
|
|
23
|
+
CONTENT_APPLIED: () => CONTENT_APPLIED,
|
|
24
|
+
EDITOR_FRAME_NAME: () => EDITOR_FRAME_NAME,
|
|
25
|
+
GENERATOR_META: () => GENERATOR_META,
|
|
26
|
+
inEditor: () => inEditor,
|
|
27
|
+
liveSrc: () => liveSrc,
|
|
28
|
+
loadVisualEditing: () => loadVisualEditing,
|
|
29
|
+
markDraft: () => markDraft,
|
|
30
|
+
onCanvasRefresh: () => onCanvasRefresh,
|
|
31
|
+
onContentApplied: () => onContentApplied,
|
|
32
|
+
startBcmsLive: () => startBcmsLive,
|
|
33
|
+
subscribeLive: () => subscribeLive,
|
|
34
|
+
withGenerator: () => withGenerator
|
|
35
|
+
});
|
|
36
|
+
module.exports = __toCommonJS(live_exports);
|
|
37
|
+
|
|
38
|
+
// src/in-editor.ts
|
|
39
|
+
var EDITOR_FRAME_NAME = "bcms-editor";
|
|
40
|
+
function inEditor(win = globalThis.window) {
|
|
41
|
+
try {
|
|
42
|
+
return !!win && win.name === EDITOR_FRAME_NAME && win.self !== win.top;
|
|
43
|
+
} catch {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// src/content-applied.ts
|
|
49
|
+
var CONTENT_APPLIED = "bcms:content-applied";
|
|
50
|
+
function onContentApplied(handler, target = globalThis.window) {
|
|
51
|
+
if (!target) return () => {
|
|
52
|
+
};
|
|
53
|
+
const listener = (event) => {
|
|
54
|
+
const data = event.data;
|
|
55
|
+
if (!data || typeof data !== "object" || data.type !== CONTENT_APPLIED) return;
|
|
56
|
+
handler({ type: CONTENT_APPLIED, fields: Array.isArray(data.fields) ? data.fields.filter((f) => typeof f === "string") : [] });
|
|
57
|
+
};
|
|
58
|
+
target.addEventListener("message", listener);
|
|
59
|
+
return () => target.removeEventListener("message", listener);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// src/live.ts
|
|
63
|
+
var pools = /* @__PURE__ */ new Map();
|
|
64
|
+
function subscribeLive(src, fn) {
|
|
65
|
+
let pool = pools.get(src);
|
|
66
|
+
if (!pool) {
|
|
67
|
+
const es = new EventSource(src);
|
|
68
|
+
pool = { es, listeners: /* @__PURE__ */ new Set() };
|
|
69
|
+
es.addEventListener("change", (e) => {
|
|
70
|
+
let parsed;
|
|
71
|
+
try {
|
|
72
|
+
parsed = JSON.parse(e.data);
|
|
73
|
+
} catch {
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
for (const l of pools.get(src)?.listeners ?? []) l(parsed);
|
|
77
|
+
});
|
|
78
|
+
pools.set(src, pool);
|
|
79
|
+
}
|
|
80
|
+
pool.listeners.add(fn);
|
|
81
|
+
return () => {
|
|
82
|
+
const p = pools.get(src);
|
|
83
|
+
if (!p) return;
|
|
84
|
+
p.listeners.delete(fn);
|
|
85
|
+
if (p.listeners.size === 0) {
|
|
86
|
+
p.es.close();
|
|
87
|
+
pools.delete(src);
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
function onCanvasRefresh(refresh) {
|
|
92
|
+
if (typeof window === "undefined" || window.parent === window) return () => {
|
|
93
|
+
};
|
|
94
|
+
const onMessage = (e) => {
|
|
95
|
+
if (e.origin !== window.location.origin || e.source !== window.parent) return;
|
|
96
|
+
if (e.data?.type !== "bcms:refresh") return;
|
|
97
|
+
window.parent.postMessage({ type: "bcms:refreshed" }, e.origin);
|
|
98
|
+
void refresh();
|
|
99
|
+
};
|
|
100
|
+
window.addEventListener("message", onMessage);
|
|
101
|
+
return () => window.removeEventListener("message", onMessage);
|
|
102
|
+
}
|
|
103
|
+
function loadVisualEditing(studioUrl = "https://bettercms.ai") {
|
|
104
|
+
if (typeof document === "undefined") return;
|
|
105
|
+
const src = `${studioUrl.replace(/\/+$/, "")}/bcms-visual-editing.js`;
|
|
106
|
+
if (document.querySelector(`script[src="${src}"]`)) return;
|
|
107
|
+
const el = document.createElement("script");
|
|
108
|
+
el.src = src;
|
|
109
|
+
el.defer = true;
|
|
110
|
+
el.dataset.bcmsStudio = studioUrl;
|
|
111
|
+
document.head.appendChild(el);
|
|
112
|
+
}
|
|
113
|
+
function startBcmsLive(opts) {
|
|
114
|
+
if (typeof window === "undefined") return () => {
|
|
115
|
+
};
|
|
116
|
+
if (opts.draft ?? document.documentElement.hasAttribute("data-bcms-draft")) loadVisualEditing(opts.studioUrl);
|
|
117
|
+
const stopRefresh = onCanvasRefresh(opts.refresh);
|
|
118
|
+
const stopLive = opts.src ? subscribeLive(opts.src, (event) => {
|
|
119
|
+
if (opts.tags?.length && !event.tags.some((t) => opts.tags.includes(t))) return;
|
|
120
|
+
opts.onChange?.(event);
|
|
121
|
+
void opts.refresh();
|
|
122
|
+
}) : () => {
|
|
123
|
+
};
|
|
124
|
+
return () => {
|
|
125
|
+
stopRefresh();
|
|
126
|
+
stopLive();
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
var GENERATOR_META = '<meta name="generator" content="BetterCMS">';
|
|
130
|
+
function withGenerator(html) {
|
|
131
|
+
const at = html.search(/<\/head>/i);
|
|
132
|
+
return at < 0 || html.includes(GENERATOR_META) ? html : html.slice(0, at) + GENERATOR_META + html.slice(at);
|
|
133
|
+
}
|
|
134
|
+
function markDraft(html) {
|
|
135
|
+
return html.includes("data-bcms-draft=") ? html : html.replace(/<html(?=[\s>])/i, '<html data-bcms-draft="1"');
|
|
136
|
+
}
|
|
137
|
+
function liveSrc(opts) {
|
|
138
|
+
const q = new URLSearchParams({ key: opts.apiKey });
|
|
139
|
+
if (opts.depth !== void 0) q.set("depth", String(opts.depth));
|
|
140
|
+
if (opts.drafts) q.set("drafts", "1");
|
|
141
|
+
return `${opts.apiUrl.replace(/\/+$/, "")}/api/v1/delivery/${opts.workspace}/live?${q}`;
|
|
142
|
+
}
|
|
143
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
144
|
+
0 && (module.exports = {
|
|
145
|
+
CONTENT_APPLIED,
|
|
146
|
+
EDITOR_FRAME_NAME,
|
|
147
|
+
GENERATOR_META,
|
|
148
|
+
inEditor,
|
|
149
|
+
liveSrc,
|
|
150
|
+
loadVisualEditing,
|
|
151
|
+
markDraft,
|
|
152
|
+
onCanvasRefresh,
|
|
153
|
+
onContentApplied,
|
|
154
|
+
startBcmsLive,
|
|
155
|
+
subscribeLive,
|
|
156
|
+
withGenerator
|
|
157
|
+
});
|
|
158
|
+
//# sourceMappingURL=live.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/live.ts","../src/in-editor.ts","../src/content-applied.ts"],"sourcesContent":["/// <reference lib=\"dom\" />\n/**\n * The site half of BetterCMS live editing, framework-agnostic. Every adapter wires its own\n * re-render into it (Next `router.refresh`, SvelteKit `invalidateAll`, Nuxt `refreshNuxtData`,\n * a React app's refetch), so the protocol lives here once:\n *\n * const stop = startBcmsLive({ src: liveSrc, refresh: () => invalidateAll() });\n *\n * - The delivery SSE stream (`src`): a publish elsewhere re-renders this page.\n * - The canvas soft refresh: the editor asks for a re-render after a STRUCTURAL draft write and\n * waits for the ack, so it does not remount the frame (which ends an inline text session).\n * - In draft mode, the click-to-edit overlay script from the studio origin.\n */\n\n/** A `change` frame off the live stream (the backend's routes/delivery/live.ts). */\nexport interface BcmsChangeEvent<T = unknown> {\n type: \"entry\" | \"page\";\n slug: string;\n reason: \"publish\" | \"unpublish\" | \"draft\";\n /** Cache tags, `bcms:{ws}:all` + `bcms:{ws}:{type}:{slug}`. */\n tags: string[];\n projectId: string | null;\n /** When the change was committed. */\n at: string;\n /** When the server flushed this frame — `at`→`sentAt` is its own cost. */\n sentAt?: string;\n /**\n * The finished delivery payload. Absent on `unpublish`, and when the server could not hydrate\n * it (over quota, deleted, larger than the frame cap): then the client refetches.\n */\n doc?: T;\n}\n\n// One EventSource per URL, refcounted, because HTTP/1.1 browsers cap ~6 sockets per host: a page\n// with a handful of live components would otherwise spend its whole connection budget on this\n// stream and stall its own image loads.\ntype Listener = (e: BcmsChangeEvent) => void;\nconst pools = new Map<string, { es: EventSource; listeners: Set<Listener> }>();\n\n/** Listen to the live stream at `src`. Returns the function that stops listening. */\nexport function subscribeLive(src: string, fn: Listener): () => void {\n let pool = pools.get(src);\n if (!pool) {\n const es = new EventSource(src);\n pool = { es, listeners: new Set() };\n es.addEventListener(\"change\", (e) => {\n let parsed: BcmsChangeEvent;\n try {\n parsed = JSON.parse((e as MessageEvent).data) as BcmsChangeEvent;\n } catch {\n return; // malformed frame — ignore, the next one will do\n }\n for (const l of pools.get(src)?.listeners ?? []) l(parsed);\n });\n pools.set(src, pool);\n }\n pool.listeners.add(fn);\n return () => {\n const p = pools.get(src);\n if (!p) return;\n p.listeners.delete(fn);\n if (p.listeners.size === 0) {\n p.es.close();\n pools.delete(src);\n }\n };\n}\n\n/**\n * Answer the canvas's soft-refresh request with `refresh`. The editor — not the page — decides\n * which of its writes are structural; the page must never re-render on draft events itself, which\n * fire on every autosave, including the inline edit the author is in the middle of.\n *\n * Accepted only from the page's own origin AND from the parent frame (the editor serves the site\n * through a same-origin proxy), so a third-party page framing the live site can trigger nothing.\n * The ack goes out BEFORE the refresh: after a reload this frame is gone.\n */\nexport function onCanvasRefresh(refresh: () => unknown): () => void {\n if (typeof window === \"undefined\" || window.parent === window) return () => {};\n const onMessage = (e: MessageEvent) => {\n if (e.origin !== window.location.origin || e.source !== window.parent) return;\n if ((e.data as { type?: unknown } | null)?.type !== \"bcms:refresh\") return;\n window.parent.postMessage({ type: \"bcms:refreshed\" }, e.origin);\n void refresh();\n };\n window.addEventListener(\"message\", onMessage);\n return () => window.removeEventListener(\"message\", onMessage);\n}\n\n/**\n * Load the click-to-edit overlay (`/bcms-visual-editing.js` on the studio origin). Served, never\n * bundled: a customer build is un-upgradable, so a copy baked into one could never be fixed. The\n * tag is its own guard; it is never removed, because removing it would not detach its listeners.\n */\nexport function loadVisualEditing(studioUrl = \"https://bettercms.ai\"): void {\n if (typeof document === \"undefined\") return;\n const src = `${studioUrl.replace(/\\/+$/, \"\")}/bcms-visual-editing.js`;\n if (document.querySelector(`script[src=\"${src}\"]`)) return;\n const el = document.createElement(\"script\");\n el.src = src;\n el.defer = true;\n el.dataset.bcmsStudio = studioUrl;\n document.head.appendChild(el);\n}\n\nexport interface StartBcmsLiveOptions {\n /** The page's own re-render: SvelteKit `invalidateAll`, Nuxt `refreshNuxtData`, a refetch. */\n refresh: () => unknown;\n /** The live SSE URL (a content:read key rides in it: EventSource cannot send headers). */\n src?: string;\n /** Only react to changes carrying one of these tags. Omit to react to all. */\n tags?: string[];\n /** Every matching change, with the pushed `doc` when there is one. */\n onChange?: (event: BcmsChangeEvent) => void;\n /** Where the click-to-edit overlay loads from in drafts. Default `https://bettercms.ai`. */\n studioUrl?: string;\n /** Drafts on? Default: the page's `<html data-bcms-draft>` marker, which the server stamps. */\n draft?: boolean;\n}\n\n/** Live stream + canvas soft refresh + (in drafts) the overlay. Returns the function that stops it. */\nexport function startBcmsLive(opts: StartBcmsLiveOptions): () => void {\n if (typeof window === \"undefined\") return () => {};\n if (opts.draft ?? document.documentElement.hasAttribute(\"data-bcms-draft\")) loadVisualEditing(opts.studioUrl);\n const stopRefresh = onCanvasRefresh(opts.refresh);\n const stopLive = opts.src\n ? subscribeLive(opts.src, (event) => {\n if (opts.tags?.length && !event.tags.some((t) => opts.tags!.includes(t))) return;\n opts.onChange?.(event);\n void opts.refresh();\n })\n : () => {};\n return () => {\n stopRefresh();\n stopLive();\n };\n}\n\n/** The standard tag Wappalyzer and BuiltWith read to name the CMS. */\nexport const GENERATOR_META = '<meta name=\"generator\" content=\"BetterCMS\">';\n\n/** The tag before the first `</head>`; unchanged without one, or when the page already has it. */\nexport function withGenerator(html: string): string {\n const at = html.search(/<\\/head>/i);\n return at < 0 || html.includes(GENERATOR_META) ? html : html.slice(0, at) + GENERATOR_META + html.slice(at);\n}\n\n/**\n * `<html data-bcms-draft=\"1\">`: the only thing the canvas trusts as proof that the frame really is\n * this site rendering a draft, not the published page it falls back to. Server renders stamp it.\n */\nexport function markDraft(html: string): string {\n return html.includes(\"data-bcms-draft=\") ? html : html.replace(/<html(?=[\\s>])/i, '<html data-bcms-draft=\"1\"');\n}\n\n// The other two halves of living inside the editor's canvas, browser-safe here too.\nexport { inEditor, EDITOR_FRAME_NAME } from \"./in-editor.js\";\nexport { onContentApplied, CONTENT_APPLIED, type ContentAppliedMessage } from \"./content-applied.js\";\n\nexport interface LiveSrcOptions {\n /** Backend base, e.g. `https://api.bettercms.ai`. */\n apiUrl: string;\n workspace: string;\n /** A content:read key — exposed to the browser in the URL (EventSource cannot send headers). */\n apiKey: string;\n /** Reference hydration depth of the pushed document; default 1, like the delivery API. */\n depth?: 0 | 1 | 2;\n /**\n * Stream draft autosaves too. Needs a `content:read:draft` key (the server ignores the flag for\n * any other key). Never on a public site: that key reads unpublished content.\n */\n drafts?: boolean;\n}\n\n/** The live SSE URL for `startBcmsLive({ src })`. */\nexport function liveSrc(opts: LiveSrcOptions): string {\n const q = new URLSearchParams({ key: opts.apiKey });\n if (opts.depth !== undefined) q.set(\"depth\", String(opts.depth));\n if (opts.drafts) q.set(\"drafts\", \"1\");\n return `${opts.apiUrl.replace(/\\/+$/, \"\")}/api/v1/delivery/${opts.workspace}/live?${q}`;\n}\n","/**\n * `inEditor()`: is this page running inside the BetterCMS Visual Editor's canvas?\n *\n * The editor frames the site and names the frame, so the answer is the page's own `window.name`:\n * there from the first script, kept through every navigation inside the frame, and never set on\n * a published page a visitor opens. A site asks before it starts what the canvas cannot share:\n *\n * const smooth = inEditor() ? null : new LocomotiveScroll({ el, smooth: true });\n *\n * The canvas owns the scroll, the pointer and the place on the page; the site's motion (scroll\n * triggers, timelines, WebGL scenes) runs there as it does live. What has to stand down is only\n * what takes those three away: scroll that is not the window's own, an intro that holds the\n * page, a cursor drawn over it.\n */\n\n/** The canvas frame's name. The dashboard sets this exact word (`EDITOR_FRAME_NAME`). */\nexport const EDITOR_FRAME_NAME = \"bcms-editor\";\n\n/** The least of `window` this needs. */\ninterface FramedWindow {\n name: string;\n self: unknown;\n top: unknown;\n}\n\n/** True inside the editor's canvas. Safe where there is no window (a server render): false. */\nexport function inEditor(win: FramedWindow | undefined = (globalThis as { window?: FramedWindow }).window): boolean {\n try {\n return !!win && win.name === EDITOR_FRAME_NAME && win.self !== win.top;\n } catch {\n return false;\n }\n}\n","/**\n * `bcms:content-applied` — what the visual editor tells a page after it has applied an edit to\n * the page's DOM.\n *\n * An edit changes how tall a heading is. Everything on the page that measured the layout once\n * (ScrollTrigger's start and end positions, Lenis's scroll limit, a carousel's slide widths, a\n * text splitter's lines) is now wrong, and only the page's own code can measure again. So the\n * editor posts one message to the frame's window after each applied edit, and the site listens:\n *\n * onContentApplied(() => ScrollTrigger.refresh());\n *\n * A published page receives no such message: nothing there posts it, and the listener is inert.\n */\n\n/** The `type` of the message. */\nexport const CONTENT_APPLIED = \"bcms:content-applied\";\n\nexport interface ContentAppliedMessage {\n type: typeof CONTENT_APPLIED;\n /** The field addresses whose rendering changed; empty when the editor does not say. */\n fields: string[];\n}\n\n/** The message the editor posts: `frame.contentWindow.postMessage(contentApplied(fields), origin)`. */\nexport const contentApplied = (fields: readonly string[] = []): ContentAppliedMessage => ({ type: CONTENT_APPLIED, fields: [...fields] });\n\n/** The least of `window` this needs. */\ninterface MessageTarget {\n addEventListener(type: \"message\", listener: (event: { data: unknown }) => void): void;\n removeEventListener(type: \"message\", listener: (event: { data: unknown }) => void): void;\n}\n\n/**\n * Run `handler` after every edit the editor applies to this page. Returns the function that\n * stops listening. Safe to call where there is no window (a server render): it does nothing.\n */\nexport function onContentApplied(\n handler: (message: ContentAppliedMessage) => void,\n target: MessageTarget | undefined = (globalThis as { window?: MessageTarget }).window,\n): () => void {\n if (!target) return () => {};\n const listener = (event: { data: unknown }) => {\n const data = event.data as Partial<ContentAppliedMessage> | null;\n if (!data || typeof data !== \"object\" || data.type !== CONTENT_APPLIED) return;\n handler({ type: CONTENT_APPLIED, fields: Array.isArray(data.fields) ? data.fields.filter((f): f is string => typeof f === \"string\") : [] });\n };\n target.addEventListener(\"message\", listener);\n return () => target.removeEventListener(\"message\", listener);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACgBO,IAAM,oBAAoB;AAU1B,SAAS,SAAS,MAAiC,WAAyC,QAAiB;AAClH,MAAI;AACF,WAAO,CAAC,CAAC,OAAO,IAAI,SAAS,qBAAqB,IAAI,SAAS,IAAI;AAAA,EACrE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;;;ACjBO,IAAM,kBAAkB;AAqBxB,SAAS,iBACd,SACA,SAAqC,WAA0C,QACnE;AACZ,MAAI,CAAC,OAAQ,QAAO,MAAM;AAAA,EAAC;AAC3B,QAAM,WAAW,CAAC,UAA6B;AAC7C,UAAM,OAAO,M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AM,EAAE;AAC5G;AAMO,SAAS,UAAU,MAAsB;AAC9C,SAAO,KAAK,SAAS,kBAAkB,IAAI,OAAO,KAAK,QAAQ,mBAAmB,2BAA2B;AAC/G;AAsBO,SAAS,QAAQ,MAA8B;AACpD,QAAM,IAAI,IAAI,gBAAgB,EAAE,KAAK,KAAK,OAAO,CAAC;AAClD,MAAI,KAAK,UAAU,OAAW,GAAE,IAAI,SAAS,OAAO,KAAK,KAAK,CAAC;AAC/D,MAAI,KAAK,OAAQ,GAAE,IAAI,UAAU,GAAG;AACpC,SAAO,GAAG,KAAK,OAAO,QAAQ,QAAQ,EAAE,CAAC,oBAAoB,KAAK,SAAS,SAAS,CAAC;AACvF;","names":[]}
|
package/dist/live.d.cts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
export { C as CONTENT_APPLIED, a as ContentAppliedMessage, E as EDITOR_FRAME_NAME, i as inEditor, o as onContentApplied } from './in-editor-D1vXPgJh.cjs';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The site half of BetterCMS live editing, framework-agnostic. Every adapter wires its own
|
|
5
|
+
* re-render into it (Next `router.refresh`, SvelteKit `invalidateAll`, Nuxt `refreshNuxtData`,
|
|
6
|
+
* a React app's refetch), so the protocol lives here once:
|
|
7
|
+
*
|
|
8
|
+
* const stop = startBcmsLive({ src: liveSrc, refresh: () => invalidateAll() });
|
|
9
|
+
*
|
|
10
|
+
* - The delivery SSE stream (`src`): a publish elsewhere re-renders this page.
|
|
11
|
+
* - The canvas soft refresh: the editor asks for a re-render after a STRUCTURAL draft write and
|
|
12
|
+
* waits for the ack, so it does not remount the frame (which ends an inline text session).
|
|
13
|
+
* - In draft mode, the click-to-edit overlay script from the studio origin.
|
|
14
|
+
*/
|
|
15
|
+
/** A `change` frame off the live stream (the backend's routes/delivery/live.ts). */
|
|
16
|
+
interface BcmsChangeEvent<T = unknown> {
|
|
17
|
+
type: "entry" | "page";
|
|
18
|
+
slug: string;
|
|
19
|
+
reason: "publish" | "unpublish" | "draft";
|
|
20
|
+
/** Cache tags, `bcms:{ws}:all` + `bcms:{ws}:{type}:{slug}`. */
|
|
21
|
+
tags: string[];
|
|
22
|
+
projectId: string | null;
|
|
23
|
+
/** When the change was committed. */
|
|
24
|
+
at: string;
|
|
25
|
+
/** When the server flushed this frame — `at`→`sentAt` is its own cost. */
|
|
26
|
+
sentAt?: string;
|
|
27
|
+
/**
|
|
28
|
+
* The finished delivery payload. Absent on `unpublish`, and when the server could not hydrate
|
|
29
|
+
* it (over quota, deleted, larger than the frame cap): then the client refetches.
|
|
30
|
+
*/
|
|
31
|
+
doc?: T;
|
|
32
|
+
}
|
|
33
|
+
type Listener = (e: BcmsChangeEvent) => void;
|
|
34
|
+
/** Listen to the live stream at `src`. Returns the function that stops listening. */
|
|
35
|
+
declare function subscribeLive(src: string, fn: Listener): () => void;
|
|
36
|
+
/**
|
|
37
|
+
* Answer the canvas's soft-refresh request with `refresh`. The editor — not the page — decides
|
|
38
|
+
* which of its writes are structural; the page must never re-render on draft events itself, which
|
|
39
|
+
* fire on every autosave, including the inline edit the author is in the middle of.
|
|
40
|
+
*
|
|
41
|
+
* Accepted only from the page's own origin AND from the parent frame (the editor serves the site
|
|
42
|
+
* through a same-origin proxy), so a third-party page framing the live site can trigger nothing.
|
|
43
|
+
* The ack goes out BEFORE the refresh: after a reload this frame is gone.
|
|
44
|
+
*/
|
|
45
|
+
declare function onCanvasRefresh(refresh: () => unknown): () => void;
|
|
46
|
+
/**
|
|
47
|
+
* Load the click-to-edit overlay (`/bcms-visual-editing.js` on the studio origin). Served, never
|
|
48
|
+
* bundled: a customer build is un-upgradable, so a copy baked into one could never be fixed. The
|
|
49
|
+
* tag is its own guard; it is never removed, because removing it would not detach its listeners.
|
|
50
|
+
*/
|
|
51
|
+
declare function loadVisualEditing(studioUrl?: string): void;
|
|
52
|
+
interface StartBcmsLiveOptions {
|
|
53
|
+
/** The page's own re-render: SvelteKit `invalidateAll`, Nuxt `refreshNuxtData`, a refetch. */
|
|
54
|
+
refresh: () => unknown;
|
|
55
|
+
/** The live SSE URL (a content:read key rides in it: EventSource cannot send headers). */
|
|
56
|
+
src?: string;
|
|
57
|
+
/** Only react to changes carrying one of these tags. Omit to react to all. */
|
|
58
|
+
tags?: string[];
|
|
59
|
+
/** Every matching change, with the pushed `doc` when there is one. */
|
|
60
|
+
onChange?: (event: BcmsChangeEvent) => void;
|
|
61
|
+
/** Where the click-to-edit overlay loads from in drafts. Default `https://bettercms.ai`. */
|
|
62
|
+
studioUrl?: string;
|
|
63
|
+
/** Drafts on? Default: the page's `<html data-bcms-draft>` marker, which the server stamps. */
|
|
64
|
+
draft?: boolean;
|
|
65
|
+
}
|
|
66
|
+
/** Live stream + canvas soft refresh + (in drafts) the overlay. Returns the function that stops it. */
|
|
67
|
+
declare function startBcmsLive(opts: StartBcmsLiveOptions): () => void;
|
|
68
|
+
/** The standard tag Wappalyzer and BuiltWith read to name the CMS. */
|
|
69
|
+
declare const GENERATOR_META = "<meta name=\"generator\" content=\"BetterCMS\">";
|
|
70
|
+
/** The tag before the first `</head>`; unchanged without one, or when the page already has it. */
|
|
71
|
+
declare function withGenerator(html: string): string;
|
|
72
|
+
/**
|
|
73
|
+
* `<html data-bcms-draft="1">`: the only thing the canvas trusts as proof that the frame really is
|
|
74
|
+
* this site rendering a draft, not the published page it falls back to. Server renders stamp it.
|
|
75
|
+
*/
|
|
76
|
+
declare function markDraft(html: string): string;
|
|
77
|
+
|
|
78
|
+
interface LiveSrcOptions {
|
|
79
|
+
/** Backend base, e.g. `https://api.bettercms.ai`. */
|
|
80
|
+
apiUrl: string;
|
|
81
|
+
workspace: string;
|
|
82
|
+
/** A content:read key — exposed to the browser in the URL (EventSource cannot send headers). */
|
|
83
|
+
apiKey: string;
|
|
84
|
+
/** Reference hydration depth of the pushed document; default 1, like the delivery API. */
|
|
85
|
+
depth?: 0 | 1 | 2;
|
|
86
|
+
/**
|
|
87
|
+
* Stream draft autosaves too. Needs a `content:read:draft` key (the server ignores the flag for
|
|
88
|
+
* any other key). Never on a public site: that key reads unpublished content.
|
|
89
|
+
*/
|
|
90
|
+
drafts?: boolean;
|
|
91
|
+
}
|
|
92
|
+
/** The live SSE URL for `startBcmsLive({ src })`. */
|
|
93
|
+
declare function liveSrc(opts: LiveSrcOptions): string;
|
|
94
|
+
|
|
95
|
+
export { type BcmsChangeEvent, GENERATOR_META, type LiveSrcOptions, type StartBcmsLiveOptions, liveSrc, loadVisualEditing, markDraft, onCanvasRefresh, startBcmsLive, subscribeLive, withGenerator };
|
package/dist/live.d.ts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
export { C as CONTENT_APPLIED, a as ContentAppliedMessage, E as EDITOR_FRAME_NAME, i as inEditor, o as onContentApplied } from './in-editor-D1vXPgJh.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The site half of BetterCMS live editing, framework-agnostic. Every adapter wires its own
|
|
5
|
+
* re-render into it (Next `router.refresh`, SvelteKit `invalidateAll`, Nuxt `refreshNuxtData`,
|
|
6
|
+
* a React app's refetch), so the protocol lives here once:
|
|
7
|
+
*
|
|
8
|
+
* const stop = startBcmsLive({ src: liveSrc, refresh: () => invalidateAll() });
|
|
9
|
+
*
|
|
10
|
+
* - The delivery SSE stream (`src`): a publish elsewhere re-renders this page.
|
|
11
|
+
* - The canvas soft refresh: the editor asks for a re-render after a STRUCTURAL draft write and
|
|
12
|
+
* waits for the ack, so it does not remount the frame (which ends an inline text session).
|
|
13
|
+
* - In draft mode, the click-to-edit overlay script from the studio origin.
|
|
14
|
+
*/
|
|
15
|
+
/** A `change` frame off the live stream (the backend's routes/delivery/live.ts). */
|
|
16
|
+
interface BcmsChangeEvent<T = unknown> {
|
|
17
|
+
type: "entry" | "page";
|
|
18
|
+
slug: string;
|
|
19
|
+
reason: "publish" | "unpublish" | "draft";
|
|
20
|
+
/** Cache tags, `bcms:{ws}:all` + `bcms:{ws}:{type}:{slug}`. */
|
|
21
|
+
tags: string[];
|
|
22
|
+
projectId: string | null;
|
|
23
|
+
/** When the change was committed. */
|
|
24
|
+
at: string;
|
|
25
|
+
/** When the server flushed this frame — `at`→`sentAt` is its own cost. */
|
|
26
|
+
sentAt?: string;
|
|
27
|
+
/**
|
|
28
|
+
* The finished delivery payload. Absent on `unpublish`, and when the server could not hydrate
|
|
29
|
+
* it (over quota, deleted, larger than the frame cap): then the client refetches.
|
|
30
|
+
*/
|
|
31
|
+
doc?: T;
|
|
32
|
+
}
|
|
33
|
+
type Listener = (e: BcmsChangeEvent) => void;
|
|
34
|
+
/** Listen to the live stream at `src`. Returns the function that stops listening. */
|
|
35
|
+
declare function subscribeLive(src: string, fn: Listener): () => void;
|
|
36
|
+
/**
|
|
37
|
+
* Answer the canvas's soft-refresh request with `refresh`. The editor — not the page — decides
|
|
38
|
+
* which of its writes are structural; the page must never re-render on draft events itself, which
|
|
39
|
+
* fire on every autosave, including the inline edit the author is in the middle of.
|
|
40
|
+
*
|
|
41
|
+
* Accepted only from the page's own origin AND from the parent frame (the editor serves the site
|
|
42
|
+
* through a same-origin proxy), so a third-party page framing the live site can trigger nothing.
|
|
43
|
+
* The ack goes out BEFORE the refresh: after a reload this frame is gone.
|
|
44
|
+
*/
|
|
45
|
+
declare function onCanvasRefresh(refresh: () => unknown): () => void;
|
|
46
|
+
/**
|
|
47
|
+
* Load the click-to-edit overlay (`/bcms-visual-editing.js` on the studio origin). Served, never
|
|
48
|
+
* bundled: a customer build is un-upgradable, so a copy baked into one could never be fixed. The
|
|
49
|
+
* tag is its own guard; it is never removed, because removing it would not detach its listeners.
|
|
50
|
+
*/
|
|
51
|
+
declare function loadVisualEditing(studioUrl?: string): void;
|
|
52
|
+
interface StartBcmsLiveOptions {
|
|
53
|
+
/** The page's own re-render: SvelteKit `invalidateAll`, Nuxt `refreshNuxtData`, a refetch. */
|
|
54
|
+
refresh: () => unknown;
|
|
55
|
+
/** The live SSE URL (a content:read key rides in it: EventSource cannot send headers). */
|
|
56
|
+
src?: string;
|
|
57
|
+
/** Only react to changes carrying one of these tags. Omit to react to all. */
|
|
58
|
+
tags?: string[];
|
|
59
|
+
/** Every matching change, with the pushed `doc` when there is one. */
|
|
60
|
+
onChange?: (event: BcmsChangeEvent) => void;
|
|
61
|
+
/** Where the click-to-edit overlay loads from in drafts. Default `https://bettercms.ai`. */
|
|
62
|
+
studioUrl?: string;
|
|
63
|
+
/** Drafts on? Default: the page's `<html data-bcms-draft>` marker, which the server stamps. */
|
|
64
|
+
draft?: boolean;
|
|
65
|
+
}
|
|
66
|
+
/** Live stream + canvas soft refresh + (in drafts) the overlay. Returns the function that stops it. */
|
|
67
|
+
declare function startBcmsLive(opts: StartBcmsLiveOptions): () => void;
|
|
68
|
+
/** The standard tag Wappalyzer and BuiltWith read to name the CMS. */
|
|
69
|
+
declare const GENERATOR_META = "<meta name=\"generator\" content=\"BetterCMS\">";
|
|
70
|
+
/** The tag before the first `</head>`; unchanged without one, or when the page already has it. */
|
|
71
|
+
declare function withGenerator(html: string): string;
|
|
72
|
+
/**
|
|
73
|
+
* `<html data-bcms-draft="1">`: the only thing the canvas trusts as proof that the frame really is
|
|
74
|
+
* this site rendering a draft, not the published page it falls back to. Server renders stamp it.
|
|
75
|
+
*/
|
|
76
|
+
declare function markDraft(html: string): string;
|
|
77
|
+
|
|
78
|
+
interface LiveSrcOptions {
|
|
79
|
+
/** Backend base, e.g. `https://api.bettercms.ai`. */
|
|
80
|
+
apiUrl: string;
|
|
81
|
+
workspace: string;
|
|
82
|
+
/** A content:read key — exposed to the browser in the URL (EventSource cannot send headers). */
|
|
83
|
+
apiKey: string;
|
|
84
|
+
/** Reference hydration depth of the pushed document; default 1, like the delivery API. */
|
|
85
|
+
depth?: 0 | 1 | 2;
|
|
86
|
+
/**
|
|
87
|
+
* Stream draft autosaves too. Needs a `content:read:draft` key (the server ignores the flag for
|
|
88
|
+
* any other key). Never on a public site: that key reads unpublished content.
|
|
89
|
+
*/
|
|
90
|
+
drafts?: boolean;
|
|
91
|
+
}
|
|
92
|
+
/** The live SSE URL for `startBcmsLive({ src })`. */
|
|
93
|
+
declare function liveSrc(opts: LiveSrcOptions): string;
|
|
94
|
+
|
|
95
|
+
export { type BcmsChangeEvent, GENERATOR_META, type LiveSrcOptions, type StartBcmsLiveOptions, liveSrc, loadVisualEditing, markDraft, onCanvasRefresh, startBcmsLive, subscribeLive, withGenerator };
|
package/dist/live.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// src/in-editor.ts
|
|
2
|
+
var EDITOR_FRAME_NAME = "bcms-editor";
|
|
3
|
+
function inEditor(win = globalThis.window) {
|
|
4
|
+
try {
|
|
5
|
+
return !!win && win.name === EDITOR_FRAME_NAME && win.self !== win.top;
|
|
6
|
+
} catch {
|
|
7
|
+
return false;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// src/content-applied.ts
|
|
12
|
+
var CONTENT_APPLIED = "bcms:content-applied";
|
|
13
|
+
function onContentApplied(handler, target = globalThis.window) {
|
|
14
|
+
if (!target) return () => {
|
|
15
|
+
};
|
|
16
|
+
const listener = (event) => {
|
|
17
|
+
const data = event.data;
|
|
18
|
+
if (!data || typeof data !== "object" || data.type !== CONTENT_APPLIED) return;
|
|
19
|
+
handler({ type: CONTENT_APPLIED, fields: Array.isArray(data.fields) ? data.fields.filter((f) => typeof f === "string") : [] });
|
|
20
|
+
};
|
|
21
|
+
target.addEventListener("message", listener);
|
|
22
|
+
return () => target.removeEventListener("message", listener);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// src/live.ts
|
|
26
|
+
var pools = /* @__PURE__ */ new Map();
|
|
27
|
+
function subscribeLive(src, fn) {
|
|
28
|
+
let pool = pools.get(src);
|
|
29
|
+
if (!pool) {
|
|
30
|
+
const es = new EventSource(src);
|
|
31
|
+
pool = { es, listeners: /* @__PURE__ */ new Set() };
|
|
32
|
+
es.addEventListener("change", (e) => {
|
|
33
|
+
let parsed;
|
|
34
|
+
try {
|
|
35
|
+
parsed = JSON.parse(e.data);
|
|
36
|
+
} catch {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
for (const l of pools.get(src)?.listeners ?? []) l(parsed);
|
|
40
|
+
});
|
|
41
|
+
pools.set(src, pool);
|
|
42
|
+
}
|
|
43
|
+
pool.listeners.add(fn);
|
|
44
|
+
return () => {
|
|
45
|
+
const p = pools.get(src);
|
|
46
|
+
if (!p) return;
|
|
47
|
+
p.listeners.delete(fn);
|
|
48
|
+
if (p.listeners.size === 0) {
|
|
49
|
+
p.es.close();
|
|
50
|
+
pools.delete(src);
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function onCanvasRefresh(refresh) {
|
|
55
|
+
if (typeof window === "undefined" || window.parent === window) return () => {
|
|
56
|
+
};
|
|
57
|
+
const onMessage = (e) => {
|
|
58
|
+
if (e.origin !== window.location.origin || e.source !== window.parent) return;
|
|
59
|
+
if (e.data?.type !== "bcms:refresh") return;
|
|
60
|
+
window.parent.postMessage({ type: "bcms:refreshed" }, e.origin);
|
|
61
|
+
void refresh();
|
|
62
|
+
};
|
|
63
|
+
window.addEventListener("message", onMessage);
|
|
64
|
+
return () => window.removeEventListener("message", onMessage);
|
|
65
|
+
}
|
|
66
|
+
function loadVisualEditing(studioUrl = "https://bettercms.ai") {
|
|
67
|
+
if (typeof document === "undefined") return;
|
|
68
|
+
const src = `${studioUrl.replace(/\/+$/, "")}/bcms-visual-editing.js`;
|
|
69
|
+
if (document.querySelector(`script[src="${src}"]`)) return;
|
|
70
|
+
const el = document.createElement("script");
|
|
71
|
+
el.src = src;
|
|
72
|
+
el.defer = true;
|
|
73
|
+
el.dataset.bcmsStudio = studioUrl;
|
|
74
|
+
document.head.appendChild(el);
|
|
75
|
+
}
|
|
76
|
+
function startBcmsLive(opts) {
|
|
77
|
+
if (typeof window === "undefined") return () => {
|
|
78
|
+
};
|
|
79
|
+
if (opts.draft ?? document.documentElement.hasAttribute("data-bcms-draft")) loadVisualEditing(opts.studioUrl);
|
|
80
|
+
const stopRefresh = onCanvasRefresh(opts.refresh);
|
|
81
|
+
const stopLive = opts.src ? subscribeLive(opts.src, (event) => {
|
|
82
|
+
if (opts.tags?.length && !event.tags.some((t) => opts.tags.includes(t))) return;
|
|
83
|
+
opts.onChange?.(event);
|
|
84
|
+
void opts.refresh();
|
|
85
|
+
}) : () => {
|
|
86
|
+
};
|
|
87
|
+
return () => {
|
|
88
|
+
stopRefresh();
|
|
89
|
+
stopLive();
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
var GENERATOR_META = '<meta name="generator" content="BetterCMS">';
|
|
93
|
+
function withGenerator(html) {
|
|
94
|
+
const at = html.search(/<\/head>/i);
|
|
95
|
+
return at < 0 || html.includes(GENERATOR_META) ? html : html.slice(0, at) + GENERATOR_META + html.slice(at);
|
|
96
|
+
}
|
|
97
|
+
function markDraft(html) {
|
|
98
|
+
return html.includes("data-bcms-draft=") ? html : html.replace(/<html(?=[\s>])/i, '<html data-bcms-draft="1"');
|
|
99
|
+
}
|
|
100
|
+
function liveSrc(opts) {
|
|
101
|
+
const q = new URLSearchParams({ key: opts.apiKey });
|
|
102
|
+
if (opts.depth !== void 0) q.set("depth", String(opts.depth));
|
|
103
|
+
if (opts.drafts) q.set("drafts", "1");
|
|
104
|
+
return `${opts.apiUrl.replace(/\/+$/, "")}/api/v1/delivery/${opts.workspace}/live?${q}`;
|
|
105
|
+
}
|
|
106
|
+
export {
|
|
107
|
+
CONTENT_APPLIED,
|
|
108
|
+
EDITOR_FRAME_NAME,
|
|
109
|
+
GENERATOR_META,
|
|
110
|
+
inEditor,
|
|
111
|
+
liveSrc,
|
|
112
|
+
loadVisualEditing,
|
|
113
|
+
markDraft,
|
|
114
|
+
onCanvasRefresh,
|
|
115
|
+
onContentApplied,
|
|
116
|
+
startBcmsLive,
|
|
117
|
+
subscribeLive,
|
|
118
|
+
withGenerator
|
|
119
|
+
};
|
|
120
|
+
//# sourceMappingURL=live.js.map
|
package/dist/live.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/in-editor.ts","../src/content-applied.ts","../src/live.ts"],"sourcesContent":["/**\n * `inEditor()`: is this page running inside the BetterCMS Visual Editor's canvas?\n *\n * The editor frames the site and names the frame, so the answer is the page's own `window.name`:\n * there from the first script, kept through every navigation inside the frame, and never set on\n * a published page a visitor opens. A site asks before it starts what the canvas cannot share:\n *\n * const smooth = inEditor() ? null : new LocomotiveScroll({ el, smooth: true });\n *\n * The canvas owns the scroll, the pointer and the place on the page; the site's motion (scroll\n * triggers, timelines, WebGL scenes) runs there as it does live. What has to stand down is only\n * what takes those three away: scroll that is not the window's own, an intro that holds the\n * page, a cursor drawn over it.\n */\n\n/** The canvas frame's name. The dashboard sets this exact word (`EDITOR_FRAME_NAME`). */\nexport const EDITOR_FRAME_NAME = \"bcms-editor\";\n\n/** The least of `window` this needs. */\ninterface FramedWindow {\n name: string;\n self: unknown;\n top: unknown;\n}\n\n/** True inside the editor's canvas. Safe where there is no window (a server render): false. */\nexport function inEditor(win: FramedWindow | undefined = (globalThis as { window?: FramedWindow }).window): boolean {\n try {\n return !!win && win.name === EDITOR_FRAME_NAME && win.self !== win.top;\n } catch {\n return false;\n }\n}\n","/**\n * `bcms:content-applied` — what the visual editor tells a page after it has applied an edit to\n * the page's DOM.\n *\n * An edit changes how tall a heading is. Everything on the page that measured the layout once\n * (ScrollTrigger's start and end positions, Lenis's scroll limit, a carousel's slide widths, a\n * text splitter's lines) is now wrong, and only the page's own code can measure again. So the\n * editor posts one message to the frame's window after each applied edit, and the site listens:\n *\n * onContentApplied(() => ScrollTrigger.refresh());\n *\n * A published page receives no such message: nothing there posts it, and the listener is inert.\n */\n\n/** The `type` of the message. */\nexport const CONTENT_APPLIED = \"bcms:content-applied\";\n\nexport interface ContentAppliedMessage {\n type: typeof CONTENT_APPLIED;\n /** The field addresses whose rendering changed; empty when the editor does not say. */\n fields: string[];\n}\n\n/** The message the editor posts: `frame.contentWindow.postMessage(contentApplied(fields), origin)`. */\nexport const contentApplied = (fields: readonly string[] = []): ContentAppliedMessage => ({ type: CONTENT_APPLIED, fields: [...fields] });\n\n/** The least of `window` this needs. */\ninterface MessageTarget {\n addEventListener(type: \"message\", listener: (event: { data: unknown }) => void): void;\n removeEventListener(type: \"message\", listener: (event: { data: unknown }) => void): void;\n}\n\n/**\n * Run `handler` after every edit the editor applies to this page. Returns the function that\n * stops listening. Safe to call where there is no window (a server render): it does nothing.\n */\nexport function onContentApplied(\n handler: (message: ContentAppliedMessage) => void,\n target: MessageTarget | undefined = (globalThis as { window?: MessageTarget }).window,\n): () => void {\n if (!target) return () => {};\n const listener = (event: { data: unknown }) => {\n const data = event.data as Partial<ContentAppliedMessage> | null;\n if (!data || typeof data !== \"object\" || data.type !== CONTENT_APPLIED) return;\n handler({ type: CONTENT_APPLIED, fields: Array.isArray(data.fields) ? data.fields.filter((f): f is string => typeof f === \"string\") : [] });\n };\n target.addEventListener(\"message\", listener);\n return () => target.removeEventListener(\"message\", listener);\n}\n","/// <reference lib=\"dom\" />\n/**\n * The site half of BetterCMS live editing, framework-agnostic. Every adapter wires its own\n * re-render into it (Next `router.refresh`, SvelteKit `invalidateAll`, Nuxt `refreshNuxtData`,\n * a React app's refetch), so the protocol lives here once:\n *\n * const stop = startBcmsLive({ src: liveSrc, refresh: () => invalidateAll() });\n *\n * - The delivery SSE stream (`src`): a publish elsewhere re-renders this page.\n * - The canvas soft refresh: the editor asks for a re-render after a STRUCTURAL draft write and\n * waits for the ack, so it does not remount the frame (which ends an inline text session).\n * - In draft mode, the click-to-edit overlay script from the studio origin.\n */\n\n/** A `change` frame off the live stream (the backend's routes/delivery/live.ts). */\nexport interface BcmsChangeEvent<T = unknown> {\n type: \"entry\" | \"page\";\n slug: string;\n reason: \"publish\" | \"unpublish\" | \"draft\";\n /** Cache tags, `bcms:{ws}:all` + `bcms:{ws}:{type}:{slug}`. */\n tags: string[];\n projectId: string | null;\n /** When the change was committed. */\n at: string;\n /** When the server flushed this frame — `at`→`sentAt` is its own cost. */\n sentAt?: string;\n /**\n * The finished delivery payload. Absent on `unpublish`, and when the server could not hydrate\n * it (over quota, deleted, larger than the frame cap): then the client refetches.\n */\n doc?: T;\n}\n\n// One EventSource per URL, refcounted, because HTTP/1.1 browsers cap ~6 sockets per host: a page\n// with a handful of live components would otherwise spend its whole connection budget on this\n// stream and stall its own image loads.\ntype Listener = (e: BcmsChangeEvent) => void;\nconst pools = new Map<string, { es: EventSource; listeners: Set<Listener> }>();\n\n/** Listen to the live stream at `src`. Returns the function that stops listening. */\nexport function subscribeLive(src: string, fn: Listener): () => void {\n let pool = pools.get(src);\n if (!pool) {\n const es = new EventSource(src);\n pool = { es, listeners: new Set() };\n es.addEventListener(\"change\", (e) => {\n let parsed: BcmsChangeEvent;\n try {\n parsed = JSON.parse((e as MessageEvent).data) as BcmsChangeEvent;\n } catch {\n return; // malformed frame — ignore, the next one will do\n }\n for (const l of pools.get(src)?.listeners ?? []) l(parsed);\n });\n pools.set(src, pool);\n }\n pool.listeners.add(fn);\n return () => {\n const p = pools.get(src);\n if (!p) return;\n p.listeners.delete(fn);\n if (p.listeners.size === 0) {\n p.es.close();\n pools.delete(src);\n }\n };\n}\n\n/**\n * Answer the canvas's soft-refresh request with `refresh`. The editor — not the page — decides\n * which of its writes are structural; the page must never re-render on draft events itself, which\n * fire on every autosave, including the inline edit the author is in the middle of.\n *\n * Accepted only from the page's own origin AND from the parent frame (the editor serves the site\n * through a same-origin proxy), so a third-party page framing the live site can trigger nothing.\n * The ack goes out BEFORE the refresh: after a reload this frame is gone.\n */\nexport function onCanvasRefresh(refresh: () => unknown): () => void {\n if (typeof window === \"undefined\" || window.parent === window) return () => {};\n const onMessage = (e: MessageEvent) => {\n if (e.origin !== window.location.origin || e.source !== window.parent) return;\n if ((e.data as { type?: unknown } | null)?.type !== \"bcms:refresh\") return;\n window.parent.postMessage({ type: \"bcms:refreshed\" }, e.origin);\n void refresh();\n };\n window.addEventListener(\"message\", onMessage);\n return () => window.removeEventListener(\"message\", onMessage);\n}\n\n/**\n * Load the click-to-edit overlay (`/bcms-visual-editing.js` on the studio origin). Served, never\n * bundled: a customer build is un-upgradable, so a copy baked into one could never be fixed. The\n * tag is its own guard; it is never removed, because removing it would not detach its listeners.\n */\nexport function loadVisualEditing(studioUrl = \"https://bettercms.ai\"): void {\n if (typeof document === \"undefined\") return;\n const src = `${studioUrl.replace(/\\/+$/, \"\")}/bcms-visual-editing.js`;\n if (document.querySelector(`script[src=\"${src}\"]`)) return;\n const el = document.createElement(\"script\");\n el.src = src;\n el.defer = true;\n el.dataset.bcmsStudio = studioUrl;\n document.head.appendChild(el);\n}\n\nexport interface StartBcmsLiveOptions {\n /** The page's own re-render: SvelteKit `invalidateAll`, Nuxt `refreshNuxtData`, a refetch. */\n refresh: () => unknown;\n /** The live SSE URL (a content:read key rides in it: EventSource cannot send headers). */\n src?: string;\n /** Only react to changes carrying one of these tags. Omit to react to all. */\n tags?: string[];\n /** Every matching change, with the pushed `doc` when there is one. */\n onChange?: (event: BcmsChangeEvent) => void;\n /** Where the click-to-edit overlay loads from in drafts. Default `https://bettercms.ai`. */\n studioUrl?: string;\n /** Drafts on? Default: the page's `<html data-bcms-draft>` marker, which the server stamps. */\n draft?: boolean;\n}\n\n/** Live stream + canvas soft refresh + (in drafts) the overlay. Returns the function that stops it. */\nexport function startBcmsLive(opts: StartBcmsLiveOptions): () => void {\n if (typeof window === \"undefined\") return () => {};\n if (opts.draft ?? document.documentElement.hasAttribute(\"data-bcms-draft\")) loadVisualEditing(opts.studioUrl);\n const stopRefresh = onCanvasRefresh(opts.refresh);\n const stopLive = opts.src\n ? subscribeLive(opts.src, (event) => {\n if (opts.tags?.length && !event.tags.some((t) => opts.tags!.includes(t))) return;\n opts.onChange?.(event);\n void opts.refresh();\n })\n : () => {};\n return () => {\n stopRefresh();\n stopLive();\n };\n}\n\n/** The standard tag Wappalyzer and BuiltWith read to name the CMS. */\nexport const GENERATOR_META = '<meta name=\"generator\" content=\"BetterCMS\">';\n\n/** The tag before the first `</head>`; unchanged without one, or when the page already has it. */\nexport function withGenerator(html: string): string {\n const at = html.search(/<\\/head>/i);\n return at < 0 || html.includes(GENERATOR_META) ? html : html.slice(0, at) + GENERATOR_META + html.slice(at);\n}\n\n/**\n * `<html data-bcms-draft=\"1\">`: the only thing the canvas trusts as proof that the frame really is\n * this site rendering a draft, not the published page it falls back to. Server renders stamp it.\n */\nexport function markDraft(html: string): string {\n return html.includes(\"data-bcms-draft=\") ? html : html.replace(/<html(?=[\\s>])/i, '<html data-bcms-draft=\"1\"');\n}\n\n// The other two halves of living inside the editor's canvas, browser-safe here too.\nexport { inEditor, EDITOR_FRAME_NAME } from \"./in-editor.js\";\nexport { onContentApplied, CONTENT_APPLIED, type ContentAppliedMessage } from \"./content-applied.js\";\n\nexport interface LiveSrcOptions {\n /** Backend base, e.g. `https://api.bettercms.ai`. */\n apiUrl: string;\n workspace: string;\n /** A content:read key — exposed to the browser in the URL (EventSource cannot send headers). */\n apiKey: string;\n /** Reference hydration depth of the pushed document; default 1, like the delivery API. */\n depth?: 0 | 1 | 2;\n /**\n * Stream draft autosaves too. Needs a `content:read:draft` key (the server ignores the flag for\n * any other key). Never on a public site: that key reads unpublished content.\n */\n drafts?: boolean;\n}\n\n/** The live SSE URL for `startBcmsLive({ src })`. */\nexport function liveSrc(opts: LiveSrcOptions): string {\n const q = new URLSearchParams({ key: opts.apiKey });\n if (opts.depth !== undefined) q.set(\"depth\", String(opts.depth));\n if (opts.drafts) q.set(\"drafts\", \"1\");\n return `${opts.apiUrl.replace(/\\/+$/, \"\")}/api/v1/delivery/${opts.workspace}/live?${q}`;\n}\n"],"mappings":";AAgBO,IAAM,oBAAoB;AAU1B,SAAS,SAAS,MAAiC,WAAyC,QAAiB;AAClH,MAAI;AACF,WAAO,CAAC,CAAC,OAAO,IAAI,SAAS,qBAAqB,IAAI,SAAS,IAAI;AAAA,EACrE,QAAQ;AACN,WAAO;AAA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