sanity-plugin-visual-editor 1.0.0 → 1.2.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.
Files changed (59) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +263 -16
  3. package/TESTING.md +133 -0
  4. package/dist/PreviewBar-D_rw0bhP.js +3503 -0
  5. package/dist/PreviewBar-D_rw0bhP.js.map +1 -0
  6. package/dist/bar.d.ts +22 -0
  7. package/dist/bar.js +67 -0
  8. package/dist/bar.js.map +1 -0
  9. package/dist/cloudflare.d.ts +87 -0
  10. package/dist/cloudflare.js +1134 -0
  11. package/dist/cloudflare.js.map +1 -0
  12. package/dist/data-D0qotTtt.d.ts +177 -0
  13. package/dist/host-x2eXr-LJ.js +619 -0
  14. package/dist/host-x2eXr-LJ.js.map +1 -0
  15. package/dist/host.d.ts +162 -0
  16. package/dist/host.js +3 -0
  17. package/dist/index-hDzatlg7.d.ts +276 -0
  18. package/dist/index.d.ts +18 -18
  19. package/dist/index.js +7 -8
  20. package/dist/link-search-JtZkxz4k.js +14 -0
  21. package/dist/link-search-JtZkxz4k.js.map +1 -0
  22. package/dist/next-client.d.ts +22 -0
  23. package/dist/next-client.js +112 -0
  24. package/dist/next-client.js.map +1 -0
  25. package/dist/next.d.ts +135 -0
  26. package/dist/next.js +176 -0
  27. package/dist/next.js.map +1 -0
  28. package/dist/node-labels-CDiW5rMq.js +122 -0
  29. package/dist/node-labels-CDiW5rMq.js.map +1 -0
  30. package/dist/page-documents-BFFcH8lD.d.ts +54 -0
  31. package/dist/page-documents-mGfw_flR.js +67 -0
  32. package/dist/page-documents-mGfw_flR.js.map +1 -0
  33. package/dist/perspective-BmS9TVtr.js +106 -0
  34. package/dist/perspective-BmS9TVtr.js.map +1 -0
  35. package/dist/preview-links-BZDZyIey.js +119 -0
  36. package/dist/preview-links-BZDZyIey.js.map +1 -0
  37. package/dist/preview-links-DM6BCiLV.d.ts +87 -0
  38. package/dist/protocol-BNO38gYy.js +280 -0
  39. package/dist/protocol-BNO38gYy.js.map +1 -0
  40. package/dist/protocol-BnRCy2wJ.d.ts +386 -0
  41. package/dist/server-B8MqMyaN.js +748 -0
  42. package/dist/server-B8MqMyaN.js.map +1 -0
  43. package/dist/server.d.ts +4 -0
  44. package/dist/server.js +3 -0
  45. package/dist/shell-DZotxRXX.d.ts +37 -0
  46. package/dist/studio.d.ts +93 -0
  47. package/dist/studio.js +1263 -0
  48. package/dist/studio.js.map +1 -0
  49. package/dist/sveltekit.d.ts +281 -0
  50. package/dist/sveltekit.js +394 -0
  51. package/dist/sveltekit.js.map +1 -0
  52. package/package.json +120 -39
  53. package/dist/index.d.mts +0 -21
  54. package/dist/index.js.map +0 -1
  55. package/dist/index.mjs +0 -8
  56. package/dist/index.mjs.map +0 -1
  57. package/sanity.json +0 -8
  58. package/src/index.ts +0 -27
  59. package/v2-incompatible.js +0 -11
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host-x2eXr-LJ.js","names":["element"],"sources":["../src/host/overlay.ts","../src/host/preview-events.ts","../src/host/index.ts"],"sourcesContent":["/**\n * Click-to-edit: hovering an element marked with `data-sanity` outlines it and labels its field;\n * clicking it asks for that document and path in the Studio's document pane instead of following\n * a link. Framework-agnostic and dependency-free; `mountPreviewBarHost` (while the pane is open)\n * and `mountPreviewBarFrame` (always) run it.\n *\n * Unlike `@sanity/visual-editing`, nothing is registered up front: one passive `pointermove`\n * listener, coalesced to an animation frame, hit-tests at the pointer with\n * `target.closest('[data-sanity]')`. No MutationObserver, IntersectionObserver, ResizeObserver or\n * per-element listeners, so the page can re-render as often as it likes. Boxes are positioned in\n * viewport coordinates (`getBoundingClientRect` in a `position: fixed` layer), so they stay on\n * sticky and fixed content, and a frame loop runs only while a box shows and something moved\n * (pointer, scroll, resize), until the boxes have settled.\n *\n * Beyond the hover box:\n * - Labels: field titles come from the Studio's schema. The engine asks (`onDescribe`) for the\n * nodes it shows and the bar or tool answers (`setLabels`); until then, the humanized path.\n * - Focus: the field focused in the document pane (`setFocus`) is outlined on the page, scrolled\n * into view when none of its elements is on screen.\n * - Drift: while active, the page's nodes are listed when it's idle (one `querySelectorAll`, again\n * only when the set of annotations changed) and described; any whose path doesn't resolve in the\n * document gets a dashed red outline and a console warning.\n *\n * It's on only while the host says so (`setActive`): in the Visual Editor tool's frame, while the\n * bar's inspector is on. Holding Alt/Option hides the outlines and lets clicks through to the page;\n * Esc clears the hover until the pointer moves.\n */\nimport type {NodeLabel} from '../core/node-labels'\nimport {MAX_DESCRIBE_NODES} from '../core/protocol'\nimport {\n describeSanityPath,\n matchFocusedNodes,\n parseSanityNode,\n SANITY_NODE_ATTRIBUTE,\n type SanityNode,\n} from '../core/sanity-node'\n\nexport type ClickToEditOptions = {\n /** An editable element was clicked. */\n onEdit: (node: SanityNode) => void\n /**\n * Label these nodes and check their paths; answer with `setLabels`. Without it, labels are the\n * humanized path and there is no drift check.\n */\n onDescribe?: (nodes: SanityNode[]) => void\n /**\n * Whether click-to-edit is on to begin with (the Visual Editor: while the inspector is on).\n * Default `true`; see `setActive`.\n */\n active?: boolean\n /** The outline layer's z-index. Default just below the bar's frame. */\n zIndex?: number\n}\n\nexport type ClickToEdit = {\n /** Turn click-to-edit on or off for the context (the pane opened or closed). */\n setActive(active: boolean): void\n /** Field titles and drift for nodes asked about with `onDescribe`. */\n setLabels(labels: readonly NodeLabel[]): void\n /** The field focused in the document pane (`path` in URL form), or `null`. */\n setFocus(focus: {id: string; path: string} | null): void\n destroy(): void\n}\n\nexport type SanityTarget = {element: Element; node: SanityNode}\n\nconst SELECTOR = `[${SANITY_NODE_ATTRIBUTE}]`\n/** One below the bar's wrapper (`2147483000`). */\nconst OVERLAY_Z_INDEX = 2147482999\nconst OVERLAY_TAG = 'sanity-plugin-visual-editor-overlay'\n/** Frames the boxes must hold still before the loop stops (smooth scrolling, transitions). */\nconst SETTLE_FRAMES = 20\n/** Ancestors shown in the label's breadcrumb. */\nconst MAX_CRUMBS = 3\n/** How often, while active, the page is checked for new or changed annotations (when idle). */\nconst SCAN_INTERVAL_MS = 4000\n/** Most outlines drawn for focus or drift at once. */\nconst MAX_MARKS = 40\n\n/** The nearest element at or above `start` whose `data-sanity` parses. */\nexport function findSanityTarget(start: EventTarget | Node | null): SanityTarget | null {\n let element: Element | null = null\n if (start instanceof Element) element = start.closest(SELECTOR)\n else if (start instanceof Node) element = start.parentElement?.closest(SELECTOR) ?? null\n while (element) {\n const node = parseSanityNode(element.getAttribute(SANITY_NODE_ATTRIBUTE))\n if (node) return {element, node}\n element = element.parentElement?.closest(SELECTOR) ?? null\n }\n return null\n}\n\n/** The editable ancestors above `element`, outermost first. */\nfunction ancestors(element: Element) {\n const found: SanityTarget[] = []\n let current = element.parentElement?.closest(SELECTOR) ?? null\n while (current && found.length < MAX_CRUMBS) {\n const node = parseSanityNode(current.getAttribute(SANITY_NODE_ATTRIBUTE))\n if (node) found.unshift({element: current, node})\n current = current.parentElement?.closest(SELECTOR) ?? null\n }\n return found\n}\n\n/** Every node on the page, in document order. */\nfunction scanPage() {\n const targets: SanityTarget[] = []\n for (const element of document.querySelectorAll(SELECTOR)) {\n const node = parseSanityNode(element.getAttribute(SANITY_NODE_ATTRIBUTE))\n if (node) targets.push({element, node})\n }\n return targets\n}\n\nconst nodeKey = (node: {id: string; path: string}) => `${node.id}\\n${node.path}`\n\nfunction prefersReducedMotion() {\n return window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false\n}\n\nfunction onScreen(rect: DOMRect) {\n return (\n rect.bottom > 0 &&\n rect.right > 0 &&\n rect.top < window.innerHeight &&\n rect.left < window.innerWidth &&\n (rect.width > 0 || rect.height > 0)\n )\n}\n\nconst STYLE = `\n:host {\n all: initial;\n position: fixed;\n inset: 0;\n pointer-events: none;\n contain: strict;\n --accent: #2276fc;\n --drift: #e5484d;\n font: 500 11px/16px -apple-system, BlinkMacSystemFont, \"Inter\", \"Segoe UI\", system-ui, sans-serif;\n}\n.box, .mark {\n position: absolute;\n top: 0;\n left: 0;\n display: none;\n box-sizing: border-box;\n border-radius: 2px;\n}\n.box {\n border: 1px solid var(--accent);\n background: rgb(34 118 252 / 0.06);\n}\n.mark[data-kind=\"focus\"] { border: 2px solid var(--accent); }\n.mark[data-kind=\"drift\"] { border: 1px dashed var(--drift); background: rgb(229 72 77 / 0.05); }\n.tab {\n position: absolute;\n top: 0;\n left: 0;\n display: none;\n align-items: baseline;\n gap: 6px;\n box-sizing: border-box;\n max-width: min(480px, calc(100vw - 8px));\n padding: 2px 6px;\n border-radius: 3px 3px 0 0;\n background: var(--accent);\n color: #fff;\n white-space: nowrap;\n}\n.tab[data-place=\"inside\"] { border-radius: 0 0 3px 0; }\n.tab[data-place=\"below\"] { border-radius: 0 0 3px 3px; }\n.tab[data-missing] { background: var(--drift); }\n/* Square the box's corner where the tab joins it. */\n.box[data-tab=\"above\"] { border-top-left-radius: 0; }\n.box[data-tab=\"below\"] { border-bottom-left-radius: 0; }\n.crumbs {\n flex: 0 1 auto;\n min-width: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n opacity: 0.72;\n}\n.crumbs:empty { display: none; }\n.label { flex: none; font-weight: 600; }\n.note { flex: none; opacity: 0.85; }\n.note:empty { display: none; }\n`\n\nexport function mountClickToEdit(options: ClickToEditOptions): ClickToEdit {\n let available = options.active ?? true\n let destroyed = false\n\n /** The pointer's last position in the viewport, and what it was over. */\n let pointer: {x: number; y: number} | null = null\n let pointerTarget: EventTarget | null = null\n let needsResolve = false\n let altHeld = false\n /** Esc cleared the hover; it comes back when the pointer moves. */\n let dismissed = false\n\n let hovered: SanityTarget | null = null\n /** What the hover label was last drawn for (attribute and labels), to redraw only on change. */\n let labelFor: string | null = null\n let lastRects = ''\n let stableFrames = 0\n let frame = 0\n let tabWidth = 0\n let tabHeight = 0\n\n /** A press intercepted on `pointerdown`, posted on its `click`. */\n let pressed: SanityNode | null = null\n\n /** Labels from the bar or tool, and the nodes asked about but not answered yet. */\n const labels = new Map<string, {label: string; missing?: boolean}>()\n const asked = new Set<string>()\n let toAsk: SanityNode[] = []\n let askQueued = false\n const warned = new Set<string>()\n\n /** The page's nodes at the last scan, and its annotations as one string to spot changes. */\n let scanned: SanityTarget[] = []\n let scanSignature = ''\n let scanTimer: ReturnType<typeof setTimeout> | undefined\n let idleHandle: number | undefined\n\n let focus: {id: string; path: string} | null = null\n let focusTargets: SanityTarget[] = []\n let driftTargets: SanityTarget[] = []\n\n // The layer: one element with an open shadow root, so the page's styles can't reach it.\n const layer = document.createElement(OVERLAY_TAG)\n layer.setAttribute('aria-hidden', 'true')\n layer.style.zIndex = String(options.zIndex ?? OVERLAY_Z_INDEX)\n const shadow = layer.attachShadow({mode: 'open'})\n const style = document.createElement('style')\n style.textContent = STYLE\n const marks = document.createElement('div')\n const box = document.createElement('div')\n box.className = 'box'\n const tab = document.createElement('div')\n tab.className = 'tab'\n const crumbs = document.createElement('span')\n crumbs.className = 'crumbs'\n const label = document.createElement('span')\n label.className = 'label'\n const note = document.createElement('span')\n note.className = 'note'\n tab.append(crumbs, label, note)\n shadow.append(style, marks, box, tab)\n document.body.appendChild(layer)\n\n const isActive = () => available && !destroyed\n\n function schedule() {\n stableFrames = 0\n if (!frame && !destroyed) frame = requestAnimationFrame(tick)\n }\n\n function hideHover() {\n box.style.display = 'none'\n tab.style.display = 'none'\n }\n\n function clearHover() {\n hovered = null\n labelFor = null\n hideHover()\n }\n\n function hideAll() {\n clearHover()\n for (const mark of marks.children) (mark as HTMLElement).style.display = 'none'\n lastRects = ''\n }\n\n /** Hit-test again where the pointer is, on the next frame (a toggle, Alt released, a scroll). */\n function resolveAtPointer() {\n pointerTarget = null\n needsResolve = true\n }\n\n function elementAtPointer() {\n return pointer ? document.elementFromPoint(pointer.x, pointer.y) : null\n }\n\n // Labels.\n\n function ask(nodes: readonly SanityNode[]) {\n if (!options.onDescribe) return\n for (const node of nodes) {\n const key = nodeKey(node)\n if (labels.has(key) || asked.has(key)) continue\n asked.add(key)\n toAsk.push(node)\n }\n if (toAsk.length && !askQueued) {\n askQueued = true\n queueMicrotask(flushAsk)\n }\n }\n\n function flushAsk() {\n askQueued = false\n const nodes = toAsk\n toAsk = []\n if (destroyed) return\n for (let start = 0; start < nodes.length; start += MAX_DESCRIBE_NODES)\n options.onDescribe?.(nodes.slice(start, start + MAX_DESCRIBE_NODES))\n }\n\n function labelOf(node: SanityNode) {\n return labels.get(nodeKey(node))?.label || describeSanityPath(node.path)\n }\n\n function drawLabel(target: SanityTarget) {\n const above = ancestors(target.element)\n ask([...above.map((item) => item.node), target.node])\n crumbs.textContent = above.map((item) => labelOf(item.node)).join(' › ')\n label.textContent = labelOf(target.node)\n const missing = labels.get(nodeKey(target.node))?.missing\n note.textContent = missing ? 'not in the document' : ''\n tab.toggleAttribute('data-missing', Boolean(missing))\n tab.style.display = 'flex'\n tabWidth = tab.offsetWidth\n tabHeight = tab.offsetHeight\n }\n\n // Focus and drift outlines.\n\n function refreshFocus() {\n focusTargets = focus ? matchFocusedNodes(scanPage(), focus).slice(0, MAX_MARKS) : []\n }\n\n function refreshDrift() {\n driftTargets = scanned\n .filter((target) => labels.get(nodeKey(target.node))?.missing)\n .slice(0, MAX_MARKS)\n for (const target of driftTargets) {\n const key = nodeKey(target.node)\n if (warned.has(key)) continue\n warned.add(key)\n console.warn(\n `sanity-visual-editor: data-sanity path \"${target.node.path}\" not found in ${target.node.type} \"${target.node.id}\"`,\n target.element,\n )\n }\n }\n\n function scan() {\n idleHandle = undefined\n if (!isActive()) return\n const targets = scanPage()\n const signature = targets\n .map((target) => target.element.getAttribute(SANITY_NODE_ATTRIBUTE))\n .join('\\n')\n scanned = targets\n if (signature !== scanSignature) {\n scanSignature = signature\n ask(targets.map((target) => target.node))\n }\n // Re-rendered elements replace the ones outlined.\n refreshDrift()\n if (driftTargets.length) schedule()\n scanTimer = setTimeout(scanWhenIdle, SCAN_INTERVAL_MS)\n }\n\n function scanWhenIdle() {\n if (!isActive() || !options.onDescribe) return\n if ('requestIdleCallback' in window)\n idleHandle = window.requestIdleCallback(scan, {timeout: 2000})\n else scan()\n }\n\n function stopScanning() {\n clearTimeout(scanTimer)\n if (idleHandle !== undefined && 'cancelIdleCallback' in window)\n window.cancelIdleCallback(idleHandle)\n idleHandle = undefined\n }\n\n function markAt(index: number) {\n let mark = marks.children[index] as HTMLElement | undefined\n if (!mark) {\n mark = document.createElement('div')\n mark.className = 'mark'\n marks.appendChild(mark)\n }\n return mark\n }\n\n function placeBox(element: HTMLElement, rect: DOMRect) {\n Object.assign(element.style, {\n display: 'block',\n width: `${rect.width}px`,\n height: `${rect.height}px`,\n transform: `translate(${rect.left}px, ${rect.top}px)`,\n })\n }\n\n function placeTab(rect: DOMRect) {\n // The tab sits on the box's top edge, outside it; inside the top when there's no room above\n // (the viewport's edge or a box taller than the screen), and below a short box at the top.\n const viewportWidth = document.documentElement.clientWidth || window.innerWidth\n const left = Math.max(4, Math.min(rect.left, viewportWidth - tabWidth - 4))\n let top = rect.top - tabHeight\n let place = 'above'\n if (top < 0) {\n place = rect.height > tabHeight * 2 ? 'inside' : 'below'\n top = place === 'inside' ? Math.max(rect.top, 0) : rect.bottom\n }\n tab.dataset.place = place\n // The box's corner squares off only where the tab actually meets it.\n if (left === rect.left && place !== 'inside') box.dataset.tab = place\n else delete box.dataset.tab\n tab.style.display = 'flex'\n tab.style.transform = `translate(${left}px, ${top}px)`\n }\n\n function tick() {\n frame = 0\n if (!isActive() || altHeld) {\n hideAll()\n return\n }\n\n // Hover.\n if (dismissed) {\n clearHover()\n } else {\n if (needsResolve) {\n needsResolve = false\n hovered = findSanityTarget(pointerTarget ?? elementAtPointer())\n pointerTarget = null\n }\n // A live re-render replaced the hovered element: find what's under the pointer now.\n if (hovered && !hovered.element.isConnected) hovered = findSanityTarget(elementAtPointer())\n if (hovered) {\n // The same element can be re-rendered with another document or path.\n const attribute = hovered.element.getAttribute(SANITY_NODE_ATTRIBUTE)\n const node = parseSanityNode(attribute)\n if (!node) {\n clearHover()\n } else {\n hovered = {element: hovered.element, node}\n const known = labels.get(nodeKey(node))\n const drawnFor = `${attribute}\\n${known?.label ?? ''}\\n${known?.missing ?? ''}`\n if (drawnFor !== labelFor) {\n labelFor = drawnFor\n lastRects = ''\n drawLabel(hovered)\n }\n }\n } else {\n clearHover()\n }\n }\n\n // A re-render replaced focused elements: match again.\n if (focus && focusTargets.some((target) => !target.element.isConnected)) refreshFocus()\n driftTargets = driftTargets.filter((target) => target.element.isConnected)\n\n const outlined = [\n ...focusTargets.map((target) => ({target, kind: 'focus'})),\n ...driftTargets.map((target) => ({target, kind: 'drift'})),\n ]\n const hoverRect = hovered?.element.getBoundingClientRect()\n const rects = outlined.map(({target}) => target.element.getBoundingClientRect())\n const key = [hoverRect, ...rects]\n .map((rect) => (rect ? `${rect.left},${rect.top},${rect.width},${rect.height}` : '-'))\n .join(';')\n if (key !== lastRects) {\n lastRects = key\n stableFrames = 0\n if (hoverRect && (hoverRect.width > 0 || hoverRect.height > 0)) {\n placeBox(box, hoverRect)\n placeTab(hoverRect)\n } else {\n hideHover()\n }\n outlined.forEach(({kind}, index) => {\n const mark = markAt(index)\n mark.dataset.kind = kind\n const rect = rects[index]!\n if (rect.width > 0 || rect.height > 0) placeBox(mark, rect)\n else mark.style.display = 'none'\n })\n for (let index = outlined.length; index < marks.children.length; index++)\n (marks.children[index] as HTMLElement).style.display = 'none'\n } else {\n stableFrames++\n }\n if (stableFrames < SETTLE_FRAMES && (hovered || outlined.length))\n frame = requestAnimationFrame(tick)\n }\n\n function onPointerMove(event: PointerEvent) {\n pointer = {x: event.clientX, y: event.clientY}\n altHeld = event.altKey\n if (!isActive()) return\n pointerTarget = event.target\n needsResolve = true\n dismissed = false\n schedule()\n }\n\n // Leaving the window, or moving into a frame (the bar, the pane, an embed) whose events this\n // page doesn't get.\n function onPointerOut(event: PointerEvent) {\n const next = event.relatedTarget\n if (next && !(next instanceof HTMLIFrameElement)) return\n pointer = null\n pointerTarget = null\n needsResolve = false\n clearHover()\n if (isActive()) schedule()\n }\n\n // Scrolling moves the page under a still pointer: hit-test again as well as re-measure.\n function onViewportChange() {\n if (!isActive()) return\n if (pointer) resolveAtPointer()\n if (hovered || pointer || focusTargets.length || driftTargets.length) schedule()\n }\n\n function onKeyDown(event: KeyboardEvent) {\n if (event.key === 'Alt') {\n altHeld = true\n schedule()\n return\n }\n if (event.key === 'Escape') {\n if (!hovered || !isActive()) return\n dismissed = true\n schedule()\n return\n }\n }\n\n function onKeyUp(event: KeyboardEvent) {\n if (event.key !== 'Alt') return\n altHeld = false\n if (!isActive()) return\n resolveAtPointer()\n schedule()\n }\n\n function onBlur() {\n if (!altHeld) return\n altHeld = false\n schedule()\n }\n\n /** An unmodified primary press on an editable element, while click-to-edit is on. */\n function interceptable(event: MouseEvent) {\n if (!isActive() || event.button !== 0) return null\n if (event.altKey || event.metaKey || event.ctrlKey || event.shiftKey) return null\n return findSanityTarget(event.target)\n }\n\n function swallow(event: Event) {\n event.preventDefault()\n event.stopPropagation()\n event.stopImmediatePropagation()\n }\n\n function onPointerDown(event: PointerEvent) {\n pressed = null\n if (!event.isPrimary) return\n const target = interceptable(event)\n if (!target) return\n swallow(event)\n // Posted on `click`, with the node as it was pressed, in case the page re-renders between.\n pressed = target.node\n }\n\n function onPointerUp(event: PointerEvent) {\n if (pressed) swallow(event)\n }\n\n function onPointerCancel() {\n pressed = null\n }\n\n // Only clicks that started with an intercepted press: keyboard activation (Enter on a link)\n // still reaches the page.\n function onClick(event: MouseEvent) {\n const node = pressed\n if (!node) return\n pressed = null\n swallow(event)\n options.onEdit(node)\n }\n\n function onDragStart(event: DragEvent) {\n if (pressed || interceptable(event)) event.preventDefault()\n }\n\n /** On again (the inspector): hover where the pointer is, outline focus, rescan. */\n function activated() {\n pressed = null\n stopScanning()\n if (!isActive()) {\n hideAll()\n return\n }\n dismissed = false\n resolveAtPointer()\n refreshFocus()\n scanSignature = ''\n scanWhenIdle()\n schedule()\n }\n\n const capture = {capture: true}\n const passiveCapture = {capture: true, passive: true}\n window.addEventListener('pointermove', onPointerMove, {passive: true})\n window.addEventListener('pointerout', onPointerOut, passiveCapture)\n window.addEventListener('scroll', onViewportChange, passiveCapture)\n window.addEventListener('resize', onViewportChange, {passive: true})\n window.addEventListener('keydown', onKeyDown, capture)\n window.addEventListener('keyup', onKeyUp, capture)\n window.addEventListener('blur', onBlur)\n window.addEventListener('pointerdown', onPointerDown, capture)\n window.addEventListener('pointerup', onPointerUp, capture)\n window.addEventListener('pointercancel', onPointerCancel, capture)\n window.addEventListener('click', onClick, capture)\n window.addEventListener('dragstart', onDragStart, capture)\n if (isActive()) scanWhenIdle()\n\n return {\n setActive(next) {\n if (destroyed || next === available) return\n available = next\n activated()\n },\n setLabels(next) {\n if (destroyed) return\n for (const item of next) {\n const key = nodeKey(item)\n asked.delete(key)\n labels.set(key, item.missing ? {label: item.label, missing: true} : {label: item.label})\n }\n refreshDrift()\n labelFor = null\n if (isActive()) schedule()\n },\n setFocus(next) {\n if (destroyed) return\n focus = next && next.id && next.path ? next : null\n refreshFocus()\n if (!isActive()) return\n // Scroll a focused field into view only when none of its elements is on screen.\n const first = focusTargets[0]\n if (first && !focusTargets.some((target) => onScreen(target.element.getBoundingClientRect())))\n first.element.scrollIntoView({\n block: 'center',\n behavior: prefersReducedMotion() ? 'auto' : 'smooth',\n })\n schedule()\n },\n destroy() {\n if (destroyed) return\n destroyed = true\n stopScanning()\n cancelAnimationFrame(frame)\n window.removeEventListener('pointermove', onPointerMove)\n window.removeEventListener('pointerout', onPointerOut, passiveCapture)\n window.removeEventListener('scroll', onViewportChange, passiveCapture)\n window.removeEventListener('resize', onViewportChange)\n window.removeEventListener('keydown', onKeyDown, capture)\n window.removeEventListener('keyup', onKeyUp, capture)\n window.removeEventListener('blur', onBlur)\n window.removeEventListener('pointerdown', onPointerDown, capture)\n window.removeEventListener('pointerup', onPointerUp, capture)\n window.removeEventListener('pointercancel', onPointerCancel, capture)\n window.removeEventListener('click', onClick, capture)\n window.removeEventListener('dragstart', onDragStart, capture)\n layer.remove()\n },\n }\n}\n","/**\n * Storefront subscriber for the realtime preview hub: opens a WebSocket first (falling back to\n * long polling where upgrades cannot open, such as Vite dev), resumes from its cursor, and calls\n * `onChange` with changed query keys, pushed results, and remote-query labels.\n */\n\nexport const PREVIEW_SOCKET_PATH = '/api/preview/socket'\nexport const PREVIEW_EVENTS_PATH = '/api/preview/events'\n\nconst RETRY_MS = 2_000\n/** Keeps the socket open through proxies that close quiet connections. */\nconst PING_MS = 20_000\n/** An upgrade nothing answers (e.g. Vite dev) neither opens nor closes: give up on it. */\nconst SOCKET_OPEN_TIMEOUT_MS = 1_500\n/** Sockets that close before opening this many times in a row fall back to long polling. */\nconst SOCKET_ATTEMPTS = 2\n/** Consecutive long-poll failures before reporting `offline`. */\nconst POLL_FAILS_BEFORE_OFFLINE = 2\n\ninterface EventsMessage {\n cursor: string\n events: {\n keys: string[]\n results?: Record<string, unknown>\n labels?: Record<string, string[]>\n }[]\n reset?: boolean\n}\n\n/**\n * Changed query keys, with the new results the hub pushed for some of them and the storefront\n * remote queries (labels) that read each one.\n */\nexport type PreviewChange = {\n keys: string[]\n results: Record<string, unknown>\n labels: Record<string, string[]>\n}\n\n/**\n * How the storefront is following the preview hub:\n * - `connected` — WebSocket open\n * - `polling` — WebSocket unavailable; long-polling instead (degraded)\n * - `offline` — long poll failing; live updates paused while retrying\n */\nexport type PreviewLiveStatus = 'connected' | 'polling' | 'offline'\n\nexport type SubscribePreviewEventsOptions = {\n socketPath?: string\n eventsPath?: string\n /** Sent with the socket and every poll, e.g. a live ticket (`{ticket}`). */\n params?: Record<string, string>\n /** Called when the transport status changes (not on every retry tick). */\n onStatus?: (status: PreviewLiveStatus) => void\n}\n\n/**\n * Follow the realtime preview hub and call `onChange` with changed query keys and pushed results.\n * When the hub cannot tell what was missed (it restarted or was redeployed), `onChange` is called\n * with no keys (`keys: []`): refresh everything. Returns a function that stops following.\n */\nexport function subscribePreviewEvents(\n onChange: (change: PreviewChange) => void,\n options?: SubscribePreviewEventsOptions,\n): () => void {\n const socketPath = options?.socketPath ?? PREVIEW_SOCKET_PATH\n const eventsPath = options?.eventsPath ?? PREVIEW_EVENTS_PATH\n const onStatus = options?.onStatus\n const params = options?.params ?? {}\n /** `path` with the extra params, and the cursor when there is one. */\n const urlFor = (path: string) => {\n const url = new URL(path, location.href)\n for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value)\n if (cursor) url.searchParams.set('after', cursor)\n return url\n }\n const controller = new AbortController()\n let cursor = ''\n let socket: WebSocket | null = null\n let ping: ReturnType<typeof setInterval> | undefined\n let retry: ReturnType<typeof setTimeout> | undefined\n let wake: (() => void) | undefined\n let timer: ReturnType<typeof setTimeout> | undefined\n const pending = new Set<string>()\n let results: Record<string, unknown> = {}\n let labels: Record<string, string[]> = {}\n let status: PreviewLiveStatus | null = null\n\n const setStatus = (next: PreviewLiveStatus) => {\n if (status === next) return\n status = next\n onStatus?.(next)\n }\n\n const sleep = (ms: number) =>\n new Promise<void>((resolve) => {\n wake = resolve\n retry = setTimeout(() => {\n wake = undefined\n resolve()\n }, ms)\n })\n\n // Changes that arrive in the same task are handed over together.\n const flush = () => {\n timer = undefined\n const keys = [...pending]\n const change = {keys, results, labels}\n pending.clear()\n results = {}\n labels = {}\n if (keys.length) onChange(change)\n }\n\n const receive = (data: EventsMessage) => {\n // The first message only gives the cursor; a later reset means events were missed.\n if (data.reset && cursor) onChange({keys: [], results: {}, labels: {}})\n cursor = data.cursor\n for (const event of data.events) {\n for (const key of event.keys) {\n pending.add(key)\n // A later event without a result for the key supersedes an earlier pushed one.\n if (event.results && key in event.results) results[key] = event.results[key]\n else delete results[key]\n if (event.labels?.[key]) labels[key] = event.labels[key]\n }\n }\n if (pending.size && !timer) timer = setTimeout(flush, 0)\n }\n\n const openSocket = (failures: number) => {\n if (controller.signal.aborted) return\n const url = urlFor(socketPath)\n url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'\n let opened = false\n let timedOut = false\n const ws = new WebSocket(url)\n socket = ws\n const openTimeout = setTimeout(() => {\n timedOut = true\n ws.close()\n }, SOCKET_OPEN_TIMEOUT_MS)\n\n ws.addEventListener('open', () => {\n clearTimeout(openTimeout)\n opened = true\n setStatus('connected')\n ping = setInterval(() => ws.send('ping'), PING_MS)\n })\n ws.addEventListener('message', (event) => {\n if (typeof event.data !== 'string' || event.data === 'pong') return\n try {\n receive(JSON.parse(event.data) as EventsMessage)\n } catch {\n // Ignore malformed frames.\n }\n })\n ws.addEventListener('close', () => {\n clearTimeout(openTimeout)\n clearInterval(ping)\n if (socket === ws) socket = null\n if (controller.signal.aborted) return\n const nextFailures = opened ? 0 : failures + 1\n // An unanswered upgrade (Vite dev) won't answer a retry either: fall back to long polling right away.\n if (timedOut || nextFailures >= SOCKET_ATTEMPTS) {\n void poll()\n } else {\n void sleep(RETRY_MS).then(() => openSocket(nextFailures))\n }\n })\n }\n\n const poll = async () => {\n let fails = 0\n // Entering poll means the socket path failed; surface degraded once before the first request.\n setStatus('polling')\n while (!controller.signal.aborted) {\n try {\n const response = await fetch(urlFor(eventsPath), {\n credentials: 'same-origin',\n signal: controller.signal,\n })\n // 204: no hub for this perspective (e.g. Published); 403: not in preview mode. Stop.\n if (response.status === 204 || response.status === 403) return\n if (!response.ok) throw new Error(`HTTP ${response.status}`)\n fails = 0\n setStatus('polling')\n receive((await response.json()) as EventsMessage)\n } catch {\n if (controller.signal.aborted) return\n fails += 1\n if (fails >= POLL_FAILS_BEFORE_OFFLINE) setStatus('offline')\n await sleep(RETRY_MS)\n }\n }\n }\n\n openSocket(0)\n\n return () => {\n controller.abort()\n clearInterval(ping)\n clearTimeout(retry)\n clearTimeout(timer)\n wake?.()\n wake = undefined\n socket?.close()\n }\n}\n","/**\n * The site side of the bar, with no React or Sanity UI: a same-origin iframe framing the bar's\n * route, mounted only in preview mode. Framework adapters call `mountPreviewBarHost` with their own\n * `refresh` (rerun the page's data in place) and `navigate` (client-side navigation).\n *\n * Same layout as Shopify's theme preview bar: the frame is always a full viewport tall and pinned to\n * the bar's edge (bottom by default, or top) of a bar-height wrapper that clips it. Opening a menu only stops the clipping, so the\n * frame's viewport never changes and its popovers position once, with no relayout. The wrapper is a\n * manual popover, so it sits in the top layer above every stacking context.\n *\n * With the document pane open the wrapper grows to the full viewport and a `clip-path` cuts it to\n * an L: the pane's full-height column (on the left or right) plus the bar, which narrows to sit\n * beside it. Clipped-out areas take no pointer events, so the rest of the page stays clickable,\n * and the page gets padding on the pane's side so its content reflows beside the pane.\n *\n * Click-to-edit (`overlay.ts`) runs only in the Visual Editor tool's frame (`mountPreviewBarFrame`),\n * not on the site.\n */\nimport {\n isInspectorShortcut,\n isPreviewBarFrame,\n isPreviewBarMessage,\n PREVIEW_BAR_HEIGHT,\n PREVIEW_BAR_ROUTE,\n PREVIEW_BAR_POSITION_PARAM,\n PREVIEW_PANEL_MIN_PAGE_WIDTH,\n STUDIO_PREVIEW_PARAM,\n type PaneSide,\n type PreviewBarMessage,\n type PreviewBarPosition,\n} from '../core/protocol'\nimport type {SanityNode} from '../core/sanity-node'\nimport {mountClickToEdit} from './overlay'\nimport {\n subscribePreviewEvents,\n type PreviewChange,\n type PreviewLiveStatus,\n type SubscribePreviewEventsOptions,\n} from './preview-events'\n\nexport type PreviewBarHostOptions = {\n /** The bar's route. Default `/__visual-editor`. */\n basePath?: string\n /** Reruns the page's data in place, no reload (SvelteKit `refreshAll`, Next.js `router.refresh`). */\n refresh: () => unknown\n /** Client-side navigation to a root-relative href (SvelteKit `goto`, Next.js `router.push`). */\n navigate: (href: string) => unknown\n /** The current path and query. Default `location.pathname + location.search`. */\n path?: string\n /**\n * Which edge the bar sits on. Default `'bottom'`, which never covers the site's own header.\n * With `'top'` the page gets `padding-top`; fixed or sticky headers at `top: 0` don't move and\n * sit under the bar.\n */\n position?: PreviewBarPosition\n}\n\nexport type PreviewBarHost = {\n /** Tell the bar the page changed (call after every client-side navigation). */\n setPath(path: string): void\n /** Tell the bar how the storefront is following the preview hub (toasts). */\n setLiveStatus(status: PreviewLiveStatus): void\n destroy(): void\n}\n\n/**\n * Whether this window should show the bar: the top window only. The Studio's Visual Editor frames\n * the site with its own bar, and other embeds (thumbnails) shouldn't get one.\n */\nexport function isTopWindow() {\n return typeof window !== 'undefined' && window.self === window.top\n}\n\nfunction isEditable(target: EventTarget | null) {\n const element = target as HTMLElement | null\n return Boolean(\n element?.closest?.('input, textarea, select, [contenteditable=\"\"], [contenteditable=\"true\"]'),\n )\n}\n\nfunction editMessage(node: SanityNode): PreviewBarMessage {\n return {type: 'sanity-visual-editor:edit', id: node.id, documentType: node.type, path: node.path}\n}\n\nfunction currentPath() {\n return window.location.pathname + window.location.search\n}\n\n/** The bar's height including the safe area on its edge, as a CSS length. */\nfunction barHeight(position: PreviewBarPosition) {\n return `(${PREVIEW_BAR_HEIGHT}px + env(safe-area-inset-${position}, 0px))`\n}\n\n/**\n * The frame's clip while the pane is open: the union of the pane's full-height column (`side`) and\n * the bar's full-width strip (`position`), as a polygon in the wrapper's coordinates.\n */\nexport function panelClipPath(\n side: PaneSide,\n position: PreviewBarPosition,\n width: number,\n barHeightCss: string,\n) {\n const inner = side === 'right' ? `calc(100% - ${width}px)` : `${width}px`\n const strip = position === 'bottom' ? `calc(100% - ${barHeightCss})` : `calc${barHeightCss}`\n const points =\n position === 'bottom'\n ? side === 'right'\n ? [`0 ${strip}`, `${inner} ${strip}`, `${inner} 0`, '100% 0', '100% 100%', '0 100%']\n : ['0 0', `${inner} 0`, `${inner} ${strip}`, `100% ${strip}`, '100% 100%', '0 100%']\n : side === 'right'\n ? ['0 0', '100% 0', '100% 100%', `${inner} 100%`, `${inner} ${strip}`, `0 ${strip}`]\n : ['0 0', '100% 0', `100% ${strip}`, `${inner} ${strip}`, `${inner} 100%`, '0 100%']\n return `polygon(${points.join(', ')})`\n}\n\nexport function mountPreviewBarHost(options: PreviewBarHostOptions): PreviewBarHost {\n const basePath = options.basePath ?? PREVIEW_BAR_ROUTE\n const position: PreviewBarPosition = options.position === 'top' ? 'top' : 'bottom'\n const BAR_HEIGHT = barHeight(position)\n let path = options.path ?? currentPath()\n let destroyed = false\n /** Last hub transport status, resent when the bar signals `ready`. */\n let liveStatus: PreviewLiveStatus | null = null\n /** An overlay (menu, tooltip, dialog) is open: the whole frame shows and takes clicks. */\n let overlayOpen = false\n /** The document pane's width, or 0 while it's closed. */\n let panelWidth = 0\n /** Which edge the pane sits on. */\n let panelSide: 'left' | 'right' = 'left'\n\n const wrapper = document.createElement('div')\n wrapper.setAttribute('popover', 'manual')\n wrapper.dataset.sanityPreviewBar = ''\n // Overrides the UA popover box (centred, bordered, padded, opaque). `z-index` only matters in\n // browsers without the Popover API, where the wrapper is not in the top layer.\n Object.assign(wrapper.style, {\n position: 'fixed',\n inset: position === 'top' ? '0 0 auto 0' : 'auto 0 0 0',\n zIndex: '2147483000',\n boxSizing: 'border-box',\n width: '100%',\n height: `calc${BAR_HEIGHT}`,\n margin: '0',\n padding: '0',\n border: '0',\n overflow: 'hidden',\n background: 'transparent',\n } satisfies Partial<CSSStyleDeclaration>)\n\n const iframe = document.createElement('iframe')\n iframe.src = position === 'top' ? `${basePath}?${PREVIEW_BAR_POSITION_PARAM}=top` : basePath\n iframe.title = 'Sanity preview bar'\n iframe.allow = 'clipboard-write'\n iframe.setAttribute(\n 'sandbox',\n 'allow-same-origin allow-scripts allow-popups allow-popups-to-escape-sandbox allow-top-navigation',\n )\n Object.assign(iframe.style, {\n position: 'absolute',\n [position]: `env(safe-area-inset-${position}, 0px)`,\n left: '0',\n display: 'block',\n width: '100%',\n height: '100dvh',\n border: '0',\n colorScheme: 'normal',\n } satisfies Partial<CSSStyleDeclaration>)\n\n wrapper.appendChild(iframe)\n document.body.appendChild(wrapper)\n if ('showPopover' in wrapper) wrapper.showPopover()\n\n // Reserve room so the bar never covers the footer (or, at the top, the start of the page).\n const root = document.documentElement\n root.style.setProperty(`padding-${position}`, `${PREVIEW_BAR_HEIGHT}px`)\n\n /** Clipping for the current overlay and pane state. */\n function layout() {\n const panel = panelWidth > 0\n wrapper.style.height = panel ? '100dvh' : `calc${BAR_HEIGHT}`\n wrapper.style.overflow = overlayOpen ? 'visible' : 'hidden'\n wrapper.style.clipPath =\n panel && !overlayOpen ? panelClipPath(panelSide, position, panelWidth, BAR_HEIGHT) : ''\n root.style.removeProperty('padding-left')\n root.style.removeProperty('padding-right')\n if (panel && window.innerWidth - panelWidth >= PREVIEW_PANEL_MIN_PAGE_WIDTH) {\n root.style.setProperty(`padding-${panelSide}`, `${panelWidth}px`)\n }\n }\n\n function post(message: PreviewBarMessage) {\n iframe.contentWindow?.postMessage(message, window.location.origin)\n }\n\n function hide() {\n destroy()\n }\n\n function onMessage(event: MessageEvent) {\n if (event.origin !== window.location.origin || event.source !== iframe.contentWindow) return\n if (!isPreviewBarMessage(event.data)) return\n switch (event.data.type) {\n case 'sanity-visual-editor:ready':\n post({type: 'sanity-visual-editor:path', path})\n if (liveStatus) post({type: 'sanity-visual-editor:live-status', status: liveStatus})\n break\n case 'sanity-visual-editor:hide':\n hide()\n break\n // While a menu, tooltip or dialog is open the transparent frame stops being clipped so it\n // can draw above the bar; a click outside lands in the frame and closes it.\n case 'sanity-visual-editor:menu':\n overlayOpen = event.data.open\n layout()\n break\n case 'sanity-visual-editor:panel':\n panelWidth = event.data.open ? Math.min(event.data.width, window.innerWidth) : 0\n panelSide = event.data.side\n layout()\n break\n case 'sanity-visual-editor:navigate':\n void options.navigate(event.data.href)\n break\n case 'sanity-visual-editor:refresh':\n Promise.resolve()\n .then(() => options.refresh())\n .finally(() => post({type: 'sanity-visual-editor:refreshed'}))\n break\n }\n }\n\n // ⌘K / Ctrl+K on the page opens the bar's search, like the Studio's shortcut; `E` (not while\n // typing) toggles the document pane, when the bar has one.\n function onKeyDown(event: KeyboardEvent) {\n const key = event.key.toLowerCase()\n if ((event.metaKey || event.ctrlKey) && key === 'k') {\n event.preventDefault()\n post({type: 'sanity-visual-editor:search'})\n return\n }\n if (key !== 'e' || event.metaKey || event.ctrlKey || event.altKey) return\n if (event.repeat || event.isComposing || event.defaultPrevented || isEditable(event.target))\n return\n post({type: 'sanity-visual-editor:pane'})\n }\n\n function onResize() {\n if (panelWidth > 0) layout()\n }\n\n window.addEventListener('message', onMessage)\n window.addEventListener('keydown', onKeyDown)\n window.addEventListener('resize', onResize)\n\n function destroy() {\n if (destroyed) return\n destroyed = true\n window.removeEventListener('message', onMessage)\n window.removeEventListener('keydown', onKeyDown)\n window.removeEventListener('resize', onResize)\n root.style.removeProperty(`padding-${position}`)\n root.style.removeProperty('padding-left')\n root.style.removeProperty('padding-right')\n wrapper.remove()\n }\n\n return {\n setPath(next) {\n path = next\n // Before the bar's `ready` this posts into an empty frame and is dropped; `ready` resends it.\n post({type: 'sanity-visual-editor:path', path})\n },\n setLiveStatus(status) {\n liveStatus = status\n post({type: 'sanity-visual-editor:live-status', status})\n },\n destroy,\n }\n}\n\nexport type PreviewBarFrameOptions = {\n /** Reruns the page's data in place, no reload (SvelteKit `refreshAll`, Next.js `router.refresh`). */\n refresh: () => unknown\n /** Client-side navigation to a root-relative href (SvelteKit `goto`, Next.js `router.push`). */\n navigate: (href: string) => unknown\n /** The current path and query. Default `location.pathname + location.search`. */\n path?: string\n /**\n * Click-to-edit while the bar's inspector is on (its button or ⌘⇧I): hovering an element with\n * `data-sanity` outlines it, and clicking it opens that document and field in the tool's pane.\n * Default `true`; `false` leaves it out, and the inspector does nothing.\n */\n clickToEdit?: boolean\n}\n\n/**\n * The site's side when the Studio's Visual Editor tool frames it (`isPreviewBarFrame()`): no bar\n * here (the tool shows it above the frame), just the tool's messages. The page reports its path\n * on load and after every navigation (`setPath`), reruns its data when the bar switches\n * perspective, and navigates when a search result is picked. Only the parent window on this\n * origin is listened to. Click-to-edit follows the bar's inspector; ⌘⇧I on the page toggles it.\n */\nexport function mountPreviewBarFrame(options: PreviewBarFrameOptions): PreviewBarHost {\n let path = options.path ?? currentPath()\n let destroyed = false\n\n function post(message: PreviewBarMessage) {\n window.parent.postMessage(message, window.location.origin)\n }\n\n function onMessage(event: MessageEvent) {\n if (event.origin !== window.location.origin || event.source !== window.parent) return\n if (!isPreviewBarMessage(event.data)) return\n switch (event.data.type) {\n case 'sanity-visual-editor:ready':\n post({type: 'sanity-visual-editor:frame-path', path})\n break\n case 'sanity-visual-editor:navigate':\n void options.navigate(event.data.href)\n break\n case 'sanity-visual-editor:refresh':\n Promise.resolve()\n .then(() => options.refresh())\n .finally(() => post({type: 'sanity-visual-editor:refreshed'}))\n break\n case 'sanity-visual-editor:inspector':\n clickToEdit?.setActive(event.data.active)\n break\n case 'sanity-visual-editor:labels':\n clickToEdit?.setLabels(event.data.labels)\n break\n case 'sanity-visual-editor:focus':\n clickToEdit?.setFocus(event.data)\n break\n }\n }\n\n // ⌘⇧I / Ctrl+Shift+I on the page toggles the bar's inspector, as it does in the bar.\n function onKeyDown(event: KeyboardEvent) {\n if (!isInspectorShortcut(event)) return\n event.preventDefault()\n post({type: 'sanity-visual-editor:toggle-inspector'})\n }\n\n // Off until the tool says the inspector is on (it does after every page load).\n const clickToEdit =\n options.clickToEdit === false\n ? null\n : mountClickToEdit({\n active: false,\n onEdit: (node) => post(editMessage(node)),\n onDescribe: (nodes) => post({type: 'sanity-visual-editor:describe', nodes}),\n })\n\n window.addEventListener('message', onMessage)\n if (clickToEdit) window.addEventListener('keydown', onKeyDown)\n post({type: 'sanity-visual-editor:frame-path', path})\n\n return {\n setPath(next) {\n path = next\n if (!destroyed) post({type: 'sanity-visual-editor:frame-path', path})\n },\n setLiveStatus(status) {\n if (!destroyed) post({type: 'sanity-visual-editor:live-status', status})\n },\n destroy() {\n destroyed = true\n window.removeEventListener('message', onMessage)\n window.removeEventListener('keydown', onKeyDown)\n clickToEdit?.destroy()\n },\n }\n}\n\nexport type ConnectVisualEditorOptions = PreviewBarHostOptions &\n SubscribePreviewEventsOptions & {\n /** Whether preview mode is active on the current page. */\n enabled: boolean\n /** Set `false` to skip subscribing to realtime preview hub events. Default `true`. */\n live?: boolean\n /** Called when realtime hub events arrive; defaults to calling `refresh()`. */\n onLiveChange?: (change: PreviewChange) => void\n }\n\n/**\n * One-call storefront entry point: automatically skips non-preview pages, `?studio-preview`\n * thumbnails, and third-party iframes; mounts `mountPreviewBarFrame` inside the Studio Visual\n * Editor or `mountPreviewBarHost` in the top window; and subscribes to realtime preview events.\n */\nexport function connectVisualEditor(options: ConnectVisualEditorOptions): PreviewBarHost {\n const {\n enabled,\n live = true,\n onLiveChange,\n socketPath,\n eventsPath,\n onStatus,\n ...hostOptions\n } = options\n const frame = isPreviewBarFrame()\n const studioPreview =\n typeof window !== 'undefined' &&\n new URLSearchParams(window.location.search).has(STUDIO_PREVIEW_PARAM)\n if (!enabled || studioPreview || (!isTopWindow() && !frame)) {\n return {setPath() {}, setLiveStatus() {}, destroy() {}}\n }\n const host = frame ? mountPreviewBarFrame(hostOptions) : mountPreviewBarHost(hostOptions)\n const stopLive =\n live !== false\n ? subscribePreviewEvents(\n (change) => {\n if (onLiveChange) onLiveChange(change)\n else void hostOptions.refresh()\n },\n {\n socketPath,\n eventsPath,\n onStatus(status) {\n host.setLiveStatus(status)\n onStatus?.(status)\n },\n },\n )\n : undefined\n return {\n setPath(next) {\n host.setPath(next)\n },\n setLiveStatus(status) {\n host.setLiveStatus(status)\n },\n destroy() {\n stopLive?.()\n host.destroy()\n },\n }\n}\n\nexport {isPreviewBarFrame, STUDIO_PREVIEW_PARAM} from '../core/protocol'\nexport {\n findSanityTarget,\n mountClickToEdit,\n type ClickToEdit,\n type ClickToEditOptions,\n type SanityTarget,\n} from './overlay'\nexport {\n PREVIEW_EVENTS_PATH,\n PREVIEW_SOCKET_PATH,\n subscribePreviewEvents,\n type PreviewChange,\n type PreviewLiveStatus,\n type SubscribePreviewEventsOptions,\n} from './preview-events'\n"],"mappings":";AAkEA,MAAM,WAAW,IAAI,sBAAsB;;AAc3C,SAAgB,iBAAiB,OAAuD;CACtF,IAAI,UAA0B;CAG9B,KAFI,iBAAiB,UAAS,UAAU,MAAM,QAAQ,QAAQ,IACrD,iBAAiB,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Ac,QAAQ;GACpB,KAAK,cAAc,MAAM;EAC3B;EACA,UAAU;GACR,WAAW,GACX,KAAK,QAAQ;EACf;CACF;AACF"}
package/dist/host.d.ts ADDED
@@ -0,0 +1,162 @@
1
+ /**
2
+ * The site side of the bar, with no React or Sanity UI: a same-origin iframe framing the bar's
3
+ * route, mounted only in preview mode. Framework adapters call `mountPreviewBarHost` with their own
4
+ * `refresh` (rerun the page's data in place) and `navigate` (client-side navigation).
5
+ *
6
+ * Same layout as Shopify's theme preview bar: the frame is always a full viewport tall and pinned to
7
+ * the bar's edge (bottom by default, or top) of a bar-height wrapper that clips it. Opening a menu only stops the clipping, so the
8
+ * frame's viewport never changes and its popovers position once, with no relayout. The wrapper is a
9
+ * manual popover, so it sits in the top layer above every stacking context.
10
+ *
11
+ * With the document pane open the wrapper grows to the full viewport and a `clip-path` cuts it to
12
+ * an L: the pane's full-height column (on the left or right) plus the bar, which narrows to sit
13
+ * beside it. Clipped-out areas take no pointer events, so the rest of the page stays clickable,
14
+ * and the page gets padding on the pane's side so its content reflows beside the pane.
15
+ *
16
+ * Click-to-edit (`overlay.ts`) runs only in the Visual Editor tool's frame (`mountPreviewBarFrame`),
17
+ * not on the site.
18
+ */
19
+ import { P as SanityNode, _ as isPreviewBarFrame, c as PaneSide, f as PreviewBarPosition, h as STUDIO_PREVIEW_PARAM, w as NodeLabel } from "./protocol-BnRCy2wJ.js";
20
+ /**
21
+ * Storefront subscriber for the realtime preview hub: opens a WebSocket first (falling back to
22
+ * long polling where upgrades cannot open, such as Vite dev), resumes from its cursor, and calls
23
+ * `onChange` with changed query keys, pushed results, and remote-query labels.
24
+ */
25
+ export declare const PREVIEW_SOCKET_PATH = "/api/preview/socket";
26
+ export declare const PREVIEW_EVENTS_PATH = "/api/preview/events";
27
+ /**
28
+ * Changed query keys, with the new results the hub pushed for some of them and the storefront
29
+ * remote queries (labels) that read each one.
30
+ */
31
+ type PreviewChange = {
32
+ keys: string[];
33
+ results: Record<string, unknown>;
34
+ labels: Record<string, string[]>;
35
+ };
36
+ /**
37
+ * How the storefront is following the preview hub:
38
+ * - `connected` — WebSocket open
39
+ * - `polling` — WebSocket unavailable; long-polling instead (degraded)
40
+ * - `offline` — long poll failing; live updates paused while retrying
41
+ */
42
+ type PreviewLiveStatus = 'connected' | 'polling' | 'offline';
43
+ type SubscribePreviewEventsOptions = {
44
+ socketPath?: string;
45
+ eventsPath?: string;
46
+ /** Sent with the socket and every poll, e.g. a live ticket (`{ticket}`). */
47
+ params?: Record<string, string>;
48
+ /** Called when the transport status changes (not on every retry tick). */
49
+ onStatus?: (status: PreviewLiveStatus) => void;
50
+ };
51
+ /**
52
+ * Follow the realtime preview hub and call `onChange` with changed query keys and pushed results.
53
+ * When the hub cannot tell what was missed (it restarted or was redeployed), `onChange` is called
54
+ * with no keys (`keys: []`): refresh everything. Returns a function that stops following.
55
+ */
56
+ export declare function subscribePreviewEvents(onChange: (change: PreviewChange) => void, options?: SubscribePreviewEventsOptions): () => void;
57
+ type ClickToEditOptions = {
58
+ /** An editable element was clicked. */
59
+ onEdit: (node: SanityNode) => void;
60
+ /**
61
+ * Label these nodes and check their paths; answer with `setLabels`. Without it, labels are the
62
+ * humanized path and there is no drift check.
63
+ */
64
+ onDescribe?: (nodes: SanityNode[]) => void;
65
+ /**
66
+ * Whether click-to-edit is on to begin with (the Visual Editor: while the inspector is on).
67
+ * Default `true`; see `setActive`.
68
+ */
69
+ active?: boolean;
70
+ /** The outline layer's z-index. Default just below the bar's frame. */
71
+ zIndex?: number;
72
+ };
73
+ type ClickToEdit = {
74
+ /** Turn click-to-edit on or off for the context (the pane opened or closed). */
75
+ setActive(active: boolean): void;
76
+ /** Field titles and drift for nodes asked about with `onDescribe`. */
77
+ setLabels(labels: readonly NodeLabel[]): void;
78
+ /** The field focused in the document pane (`path` in URL form), or `null`. */
79
+ setFocus(focus: {
80
+ id: string;
81
+ path: string;
82
+ } | null): void;
83
+ destroy(): void;
84
+ };
85
+ type SanityTarget = {
86
+ element: Element;
87
+ node: SanityNode;
88
+ };
89
+ /** The nearest element at or above `start` whose `data-sanity` parses. */
90
+ export declare function findSanityTarget(start: EventTarget | Node | null): SanityTarget | null;
91
+ export declare function mountClickToEdit(options: ClickToEditOptions): ClickToEdit;
92
+ export type PreviewBarHostOptions = {
93
+ /** The bar's route. Default `/__visual-editor`. */
94
+ basePath?: string;
95
+ /** Reruns the page's data in place, no reload (SvelteKit `refreshAll`, Next.js `router.refresh`). */
96
+ refresh: () => unknown;
97
+ /** Client-side navigation to a root-relative href (SvelteKit `goto`, Next.js `router.push`). */
98
+ navigate: (href: string) => unknown;
99
+ /** The current path and query. Default `location.pathname + location.search`. */
100
+ path?: string;
101
+ /**
102
+ * Which edge the bar sits on. Default `'bottom'`, which never covers the site's own header.
103
+ * With `'top'` the page gets `padding-top`; fixed or sticky headers at `top: 0` don't move and
104
+ * sit under the bar.
105
+ */
106
+ position?: PreviewBarPosition;
107
+ };
108
+ export type PreviewBarHost = {
109
+ /** Tell the bar the page changed (call after every client-side navigation). */
110
+ setPath(path: string): void;
111
+ /** Tell the bar how the storefront is following the preview hub (toasts). */
112
+ setLiveStatus(status: PreviewLiveStatus): void;
113
+ destroy(): void;
114
+ };
115
+ /**
116
+ * Whether this window should show the bar: the top window only. The Studio's Visual Editor frames
117
+ * the site with its own bar, and other embeds (thumbnails) shouldn't get one.
118
+ */
119
+ export declare function isTopWindow(): boolean;
120
+ /**
121
+ * The frame's clip while the pane is open: the union of the pane's full-height column (`side`) and
122
+ * the bar's full-width strip (`position`), as a polygon in the wrapper's coordinates.
123
+ */
124
+ export declare function panelClipPath(side: PaneSide, position: PreviewBarPosition, width: number, barHeightCss: string): string;
125
+ export declare function mountPreviewBarHost(options: PreviewBarHostOptions): PreviewBarHost;
126
+ export type PreviewBarFrameOptions = {
127
+ /** Reruns the page's data in place, no reload (SvelteKit `refreshAll`, Next.js `router.refresh`). */
128
+ refresh: () => unknown;
129
+ /** Client-side navigation to a root-relative href (SvelteKit `goto`, Next.js `router.push`). */
130
+ navigate: (href: string) => unknown;
131
+ /** The current path and query. Default `location.pathname + location.search`. */
132
+ path?: string;
133
+ /**
134
+ * Click-to-edit while the bar's inspector is on (its button or ⌘⇧I): hovering an element with
135
+ * `data-sanity` outlines it, and clicking it opens that document and field in the tool's pane.
136
+ * Default `true`; `false` leaves it out, and the inspector does nothing.
137
+ */
138
+ clickToEdit?: boolean;
139
+ };
140
+ /**
141
+ * The site's side when the Studio's Visual Editor tool frames it (`isPreviewBarFrame()`): no bar
142
+ * here (the tool shows it above the frame), just the tool's messages. The page reports its path
143
+ * on load and after every navigation (`setPath`), reruns its data when the bar switches
144
+ * perspective, and navigates when a search result is picked. Only the parent window on this
145
+ * origin is listened to. Click-to-edit follows the bar's inspector; ⌘⇧I on the page toggles it.
146
+ */
147
+ export declare function mountPreviewBarFrame(options: PreviewBarFrameOptions): PreviewBarHost;
148
+ export type ConnectVisualEditorOptions = PreviewBarHostOptions & SubscribePreviewEventsOptions & {
149
+ /** Whether preview mode is active on the current page. */
150
+ enabled: boolean;
151
+ /** Set `false` to skip subscribing to realtime preview hub events. Default `true`. */
152
+ live?: boolean;
153
+ /** Called when realtime hub events arrive; defaults to calling `refresh()`. */
154
+ onLiveChange?: (change: PreviewChange) => void;
155
+ };
156
+ /**
157
+ * One-call storefront entry point: automatically skips non-preview pages, `?studio-preview`
158
+ * thumbnails, and third-party iframes; mounts `mountPreviewBarFrame` inside the Studio Visual
159
+ * Editor or `mountPreviewBarHost` in the top window; and subscribes to realtime preview events.
160
+ */
161
+ export declare function connectVisualEditor(options: ConnectVisualEditorOptions): PreviewBarHost;
162
+ export { type ClickToEdit, type ClickToEditOptions, type PreviewChange, type PreviewLiveStatus, STUDIO_PREVIEW_PARAM, type SanityTarget, type SubscribePreviewEventsOptions, isPreviewBarFrame };
package/dist/host.js ADDED
@@ -0,0 +1,3 @@
1
+ import { c as STUDIO_PREVIEW_PARAM, u as isPreviewBarFrame } from "./protocol-BNO38gYy.js";
2
+ import { a as panelClipPath, c as subscribePreviewEvents, i as mountPreviewBarHost, l as findSanityTarget, n as isTopWindow, o as PREVIEW_EVENTS_PATH, r as mountPreviewBarFrame, s as PREVIEW_SOCKET_PATH, t as connectVisualEditor, u as mountClickToEdit } from "./host-x2eXr-LJ.js";
3
+ export { PREVIEW_EVENTS_PATH, PREVIEW_SOCKET_PATH, STUDIO_PREVIEW_PARAM, connectVisualEditor, findSanityTarget, isPreviewBarFrame, isTopWindow, mountClickToEdit, mountPreviewBarFrame, mountPreviewBarHost, panelClipPath, subscribePreviewEvents };
@@ -0,0 +1,276 @@
1
+ import { C as SearchConfig, n as PreviewBarData, s as PreviewPerspective, t as PreviewBarBrand, u as ReleaseDocument } from "./data-D0qotTtt.js";
2
+ import { s as PreviewLinkStore } from "./preview-links-DM6BCiLV.js";
3
+ import { r as PageDocumentRule } from "./page-documents-BFFcH8lD.js";
4
+ import { validatePreviewUrl } from "@sanity/preview-url-secret";
5
+ /**
6
+ * Signed, expiring link-session cookies: what a `/p/<code>` link leaves in the browser instead of
7
+ * the site's preview secret. The value is `<expires>.<signature>`, where `expires` is in seconds
8
+ * since the epoch and the signature is HMAC-SHA-256 over it, keyed with the preview secret. It
9
+ * proves "opened a live share link, valid until `expires`" and nothing else, so copying it gains
10
+ * no more than the link itself gave.
11
+ */
12
+ /** The link-session cookie's default name. */
13
+ declare const LINK_SESSION_COOKIE = "__sanity_preview_link";
14
+ /** A link-session cookie value valid until `expiresAt` (ms since the epoch). */
15
+ declare function signLinkSession(secret: string, expiresAt: number): Promise<string>;
16
+ /**
17
+ * When a link-session cookie value expires (ms since the epoch), or `null` when it is malformed,
18
+ * forged or expired. The signature check is `crypto.subtle.verify`'s, which is constant-time.
19
+ */
20
+ declare function verifyLinkSession(secret: string, value: string | undefined | null, now?: number): Promise<number | null>;
21
+ /**
22
+ * Client for the Cloudflare realtime preview hub Worker/DO, plus signed HMAC session tokens for
23
+ * the Studio live-edit endpoints (`/api/preview/live-edit*`).
24
+ */
25
+ /** Minimal Cloudflare Worker `Fetcher` shape (no `@cloudflare/workers-types` required). */
26
+ type PreviewHubFetcher = {
27
+ fetch(input: string | Request, init?: RequestInit): Promise<Response>;
28
+ };
29
+ /** Minimal Sanity client shape for reading the active perspective. */
30
+ type PreviewHubClientLike = {
31
+ config(): {
32
+ perspective?: unknown;
33
+ };
34
+ };
35
+ /** The preview hub instance for one perspective. */
36
+ interface PreviewHub {
37
+ /** `label` names the remote query reading it; the hub echoes it in events. */
38
+ query<T = unknown>(query: string, params?: Record<string, unknown>, label?: string): Promise<T>;
39
+ /** Debug: forward a GET to the hub (`/stats`, `/bench`). */
40
+ debug(pathAndSearch: string): Promise<Response>;
41
+ /** Forward a long poll for invalidations (`?after=<cursor>`) to the hub. */
42
+ events(search: string, signal: AbortSignal): Promise<Response>;
43
+ /**
44
+ * Open a WebSocket to the hub for invalidations (`?after=<cursor>`). The `101` response carries
45
+ * the socket; return it to the browser as it is.
46
+ */
47
+ socket(search: string): Promise<Response>;
48
+ /**
49
+ * Open a WebSocket on which the Studio sends unsaved edits (`{ document, seq }`). Call only
50
+ * after checking the editor's live-edit session.
51
+ */
52
+ editSocket(): Promise<Response>;
53
+ /** Show an unsaved Studio edit. Returns whether the hub applied it. */
54
+ overlay(document: {
55
+ _id: string;
56
+ _type?: string;
57
+ }, seq: number): Promise<boolean>;
58
+ }
59
+ /**
60
+ * Wraps a Cloudflare service binding (`env.PREVIEW_HUB`) into typed `previewHub(client)` and
61
+ * `hubFor(name)` helpers.
62
+ */
63
+ declare function createPreviewHubClient(getService: () => PreviewHubFetcher | undefined): {
64
+ hubFor: (name: string) => PreviewHub | null;
65
+ previewHub: (client: PreviewHubClientLike) => PreviewHub | null;
66
+ };
67
+ /** Default cookie that authorises `/api/preview/live-edit`. */
68
+ declare const LIVE_EDIT_COOKIE = "sanity-live-edit";
69
+ declare const LIVE_EDIT_PATH = "/api/preview/live-edit";
70
+ /** A Studio session token lasts this long; the plugin asks for a new one on a 401. */
71
+ declare const LIVE_EDIT_TTL_S: number;
72
+ /** A signed `<expires>.<signature>` token for the live-edit cookie. */
73
+ declare function createLiveEditToken(secret: string, now?: number): Promise<string>;
74
+ /** Whether a live-edit cookie value is a valid, unexpired token. */
75
+ declare function verifyLiveEditToken(secret: string, token: string | undefined, now?: number): Promise<boolean>;
76
+ /** How long a live ticket opens sockets and polls. Pages hand out a fresh one on every render. */
77
+ declare const LIVE_TICKET_TTL_S: number;
78
+ /**
79
+ * The hub name for a preview perspective: `drafts`, or a release stack such as `rABC,drafts`.
80
+ * `null` for perspectives that have no hub (`published`, `raw`).
81
+ */
82
+ declare function previewHubName(perspective: unknown): string | null;
83
+ /**
84
+ * A live ticket: proof, signed by the site, that a page was rendered in preview mode for one hub
85
+ * (`<hub>.<expires>.<signature>`). The page hands it to its tab, which sends it with the socket
86
+ * and the long poll. A Worker entry can check it without the framework's preview cookie, which
87
+ * only the framework can read (Next.js's draft mode cookie is a per-build value).
88
+ */
89
+ declare function createLiveTicket(secret: string, hub: string, now?: number): Promise<string>;
90
+ /** The hub a live ticket opens, or `null` when it is missing, forged or expired. */
91
+ declare function verifyLiveTicket(secret: string, ticket: string | null | undefined, now?: number): Promise<string | null>;
92
+ /** Default base path of the hub's site routes. */
93
+ declare const PREVIEW_ROUTES_PATH = "/api/preview";
94
+ /** Query parameter carrying a tab's live ticket. */
95
+ declare const LIVE_TICKET_PARAM = "ticket";
96
+ type PreviewRoutesOptions = {
97
+ /**
98
+ * Signs live tickets and the live-edit cookie. Keep it secret; any long random string. Empty
99
+ * turns the routes off (refused, not errors).
100
+ */
101
+ secret: string | (() => string);
102
+ /** The hub Worker's service binding (`() => env.PREVIEW_HUB`); `undefined` turns the routes off. */
103
+ hub: () => PreviewHubFetcher | undefined;
104
+ /**
105
+ * A server Sanity client with a read token, to check the Studio's preview secret when a
106
+ * live-edit session starts. Without it, `live-edit/session` answers `404` (fine in a Worker
107
+ * entry, which only serves the WebSocket routes).
108
+ */
109
+ client?: Parameters<typeof validatePreviewUrl>[0];
110
+ /**
111
+ * The hub for a request without a ticket (e.g. Next.js draft mode plus the perspective cookie),
112
+ * so `hub/stats` opens from the address bar. Return `null` outside preview.
113
+ */
114
+ fallbackHub?: (request: Request) => Promise<string | null> | string | null;
115
+ /** Default `/api/preview`. */
116
+ basePath?: string;
117
+ /** Largest unsaved document accepted, in bytes. Default `1_000_000`. */
118
+ maxBytes?: number;
119
+ };
120
+ declare function createPreviewRoutes(options: PreviewRoutesOptions): {
121
+ basePath: string;
122
+ handle: (request: Request) => Promise<Response | null>;
123
+ /**
124
+ * For a Worker entry, ahead of the framework: answers the two WebSocket routes and returns
125
+ * `null` for everything else, which then goes to the framework.
126
+ */
127
+ upgrade(request: Request): Promise<Response | null>;
128
+ };
129
+ type PreviewRoutes = ReturnType<typeof createPreviewRoutes>;
130
+ type PreviewLinkErrorRenderContext = {
131
+ status: 404 | 503;
132
+ expired: boolean;
133
+ brand: PreviewBarBrand;
134
+ studioPath: string;
135
+ request: Request;
136
+ };
137
+ type PreviewLinkErrorRenderer = (context: PreviewLinkErrorRenderContext) => Response | string | Promise<Response | string>;
138
+ /**
139
+ * Default zero-JS HTML screen for expired or unavailable `/p/<code>` preview links.
140
+ * Matches Sanity Presentation's `ErrorCard` (`sanity@6.23` + `@sanity/ui@4` `buildTheme()`):
141
+ * flat full-height canvas, centered `Container width={0}` (320px), semibold `size={1}` title and
142
+ * muted message over a ghost "Open Studio" button. Override via `renderLinkError` to customize.
143
+ */
144
+ declare function renderPreviewLinkErrorHtml({ expired, brand, studioPath }: Pick<PreviewLinkErrorRenderContext, 'expired' | 'brand'> & {
145
+ studioPath?: string;
146
+ }): string;
147
+ type PreviewBarOptions = {
148
+ brand: PreviewBarBrand;
149
+ /** Where the embedded Studio lives. Default `/studio`. */
150
+ studioPath?: string;
151
+ /** The Sanity project ID for the workspace menu's links. Default: the client's `projectId`. */
152
+ projectId?: string;
153
+ /** The bar's route. Default `/__visual-editor`. */
154
+ basePath?: string;
155
+ /**
156
+ * Which document each page shows: the Studio Presentation tool's `resolve.mainDocuments` list
157
+ * (`defineDocuments([...])`). With it, signed-in editors see the page's document status.
158
+ */
159
+ pageDocuments?: PageDocumentRule[];
160
+ /** Link search; `false` or omitted hides the search button. */
161
+ search?: SearchConfig | false;
162
+ /** Short expiring links; `false` or omitted keeps Presentation's own shared link. */
163
+ links?: {
164
+ /** A store, or a function returning one per request (for runtime bindings such as KV). */
165
+ store: PreviewLinkStore | (() => PreviewLinkStore);
166
+ /** Route prefix the links open at. Default `/p/`. */
167
+ route?: string;
168
+ /** Link lifetime in seconds: a whole number, at least 60 (Workers KV's minimum). Default 2 days. */
169
+ ttlSeconds?: number;
170
+ } | false;
171
+ };
172
+ /**
173
+ * The slice of `@sanity/client`'s `SanityClient` the bar uses. Structural, so any client version
174
+ * fits and the package carries none of its types.
175
+ */
176
+ type PreviewClient = {
177
+ withConfig(config: {
178
+ apiVersion?: string;
179
+ perspective?: PreviewPerspective | 'raw';
180
+ useCdn?: boolean;
181
+ stega?: boolean;
182
+ }): PreviewClient;
183
+ fetch<R = unknown>(query: string, params?: Record<string, unknown>, options?: {
184
+ tag?: string;
185
+ }): Promise<R>;
186
+ /** `SanityClient#config()`, read for the project ID when `projectId` isn't set. */
187
+ config?(): {
188
+ projectId?: string;
189
+ };
190
+ };
191
+ /** The request's preview state, as the framework adapter knows it. */
192
+ type PreviewContext = {
193
+ request: Request;
194
+ /** Preview mode is on (the preview cookie, or Next.js draft mode, is valid). */
195
+ previewEnabled: boolean;
196
+ /**
197
+ * A server Sanity client with a read token. Its perspective doesn't matter: handlers set what
198
+ * they need per query.
199
+ */
200
+ client: PreviewClient;
201
+ /** The perspective the request applies (the parsed perspective cookie). */
202
+ perspective: PreviewPerspective;
203
+ /**
204
+ * Preview mode came from opening a short link rather than from an editor (the adapter's
205
+ * link-session cookie). Such sessions can't mint links of their own.
206
+ */
207
+ linkSession?: boolean;
208
+ };
209
+ /**
210
+ * Adds or removes the framework's preview cookie on a response (e.g. `__sanity_preview`). When
211
+ * opening a short link, `link.expiresAt` (ms since the epoch) is when the link stops opening: the
212
+ * preview cookie should not outlive it.
213
+ */
214
+ type PreviewModeSwitch = (headers: Headers, request: Request, link?: {
215
+ expiresAt: number;
216
+ }) => void | Promise<void>;
217
+ /**
218
+ * `handlePreviewMode`'s cookie attributes: `SameSite=None; Secure` so the cookies also work inside
219
+ * the Studio's Presentation iframe, `Lax` on plain-HTTP local development.
220
+ */
221
+ declare function previewCookieAttributes(request: Request): "Path=/; HttpOnly; SameSite=None; Secure" | "Path=/; HttpOnly; SameSite=Lax";
222
+ declare function setCookieHeader(request: Request, name: string, value: string): string;
223
+ declare function deleteCookieHeader(request: Request, name: string): string;
224
+ /**
225
+ * Every content release, read like the Studio's releases store: raw perspective, the API version
226
+ * that introduced releases, no stega or CDN. The client's token needs read access to
227
+ * `system.release` documents.
228
+ */
229
+ declare function fetchReleases(client: PreviewClient): Promise<ReleaseDocument[]>;
230
+ declare function createPreviewBar(options: PreviewBarOptions): {
231
+ options: {
232
+ studioPath: string;
233
+ basePath: string;
234
+ linkRoute: string;
235
+ brand: PreviewBarBrand;
236
+ /** The Sanity project ID for the workspace menu's links. Default: the client's `projectId`. */
237
+ projectId?: string;
238
+ /**
239
+ * Which document each page shows: the Studio Presentation tool's `resolve.mainDocuments` list
240
+ * (`defineDocuments([...])`). With it, signed-in editors see the page's document status.
241
+ */
242
+ pageDocuments?: PageDocumentRule[];
243
+ /** Link search; `false` or omitted hides the search button. */
244
+ search?: SearchConfig | false;
245
+ /** Short expiring links; `false` or omitted keeps Presentation's own shared link. */
246
+ links?: {
247
+ /** A store, or a function returning one per request (for runtime bindings such as KV). */
248
+ store: PreviewLinkStore | (() => PreviewLinkStore);
249
+ /** Route prefix the links open at. Default `/p/`. */
250
+ route?: string;
251
+ /** Link lifetime in seconds: a whole number, at least 60 (Workers KV's minimum). Default 2 days. */
252
+ ttlSeconds?: number;
253
+ } | false;
254
+ };
255
+ resolveLink: (code: string) => Promise<{
256
+ status: 200;
257
+ link: {
258
+ pathname: string;
259
+ perspective: PreviewPerspective;
260
+ expiresAt: number;
261
+ };
262
+ } | {
263
+ status: 404 | 503;
264
+ }>;
265
+ loadBar: (ctx: PreviewContext) => Promise<PreviewBarData | null>;
266
+ perspective: (ctx: PreviewContext) => Promise<Response>;
267
+ exit: (ctx: Pick<PreviewContext, "request">, disablePreview: PreviewModeSwitch) => Promise<Response>;
268
+ resolveHref: (ctx: PreviewContext) => Promise<Response>;
269
+ pageDocument: (ctx: PreviewContext) => Promise<Response>;
270
+ share: (ctx: PreviewContext) => Promise<Response>;
271
+ openLink: (request: Request, code: string, enablePreview: PreviewModeSwitch) => Promise<Response>;
272
+ };
273
+ type PreviewBar = ReturnType<typeof createPreviewBar>;
274
+ declare const createVisualEditor: typeof createPreviewBar;
275
+ type VisualEditor = PreviewBar;
276
+ export { createPreviewHubClient as A, LIVE_EDIT_TTL_S as C, PreviewHubFetcher as D, PreviewHubClientLike as E, signLinkSession as F, verifyLinkSession as I, verifyLiveEditToken as M, verifyLiveTicket as N, createLiveEditToken as O, LINK_SESSION_COOKIE as P, LIVE_EDIT_PATH as S, PreviewHub as T, PREVIEW_ROUTES_PATH as _, PreviewModeSwitch as a, createPreviewRoutes as b, createVisualEditor as c, previewCookieAttributes as d, setCookieHeader as f, LIVE_TICKET_PARAM as g, renderPreviewLinkErrorHtml as h, PreviewContext as i, previewHubName as j, createLiveTicket as k, deleteCookieHeader as l, PreviewLinkErrorRenderer as m, PreviewBarOptions as n, VisualEditor as o, PreviewLinkErrorRenderContext as p, PreviewClient as r, createPreviewBar as s, PreviewBar as t, fetchReleases as u, PreviewRoutes as v, LIVE_TICKET_TTL_S as w, LIVE_EDIT_COOKIE as x, PreviewRoutesOptions as y };