sanity-plugin-visual-editor 1.1.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.
@@ -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,SAAM,UAAU,MAAM,eAAe,QAAQ,QAAQ,KAAK,OAC7E,UAAS;EACd,IAAM,OAAO,gBAAgB,QAAQ,aAAa,qBAAqB,CAAC;EACxE,IAAI,MAAM,OAAO;GAAC;GAAS;EAAI;EAC/B,UAAU,QAAQ,eAAe,QAAQ,QAAQ,KAAK;CACxD;CACA,OAAO;AACT;;AAGA,SAAS,UAAU,SAAkB;CACnC,IAAM,QAAwB,CAAC,GAC3B,UAAU,QAAQ,eAAe,QAAQ,QAAQ,KAAK;CAC1D,OAAO,WAAW,MAAM,SAAS,IAAY;EAC3C,IAAM,OAAO,gBAAgB,QAAQ,aAAa,qBAAqB,CAAC;EACpE,QAAM,MAAM,QAAQ;GAAC,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ACzE;EACA,UAAU;GACR,YAAY,IACZ,OAAO,oBAAoB,WAAW,SAAS,GAC/C,OAAO,oBAAoB,WAAW,SAAS,GAC/C,aAAa,QAAQ;EACvB;CACF;AACF;;;;;;AAiBA,SAAgB,oBAAoB,SAAqD;CACvF,IAAM,EACJ,SACA,OAAO,IACP,cACA,YACA,YACA,UACA,GAAG,gBACD,SACE,QAAQ,kBAAkB,GAC1B,gBACJ,OAAO,SAAW,OAClB,IAAI,gBAAgB,OAAO,SAAS,MAAM,CAAC,CAAC,IAAA,gBAAwB;CACtE,IAAI,CAAC,WAAW,iBAAkB,CAAC,YAAY,KAAK,CAAC,OACnD,OAAO;EAAC,UAAU,CAAC;EAAG,gBAAgB,CAAC;EAAG,UAAU,CAAC;CAAC;CAExD,IAAM,OAAO,QAAQ,qBAAqB,WAAW,IAAI,oBAAoB,WAAW,GAClF,WACJ,SAAS,KAeL,KAAA,IAdA,wBACG,WAAW;EACN,eAAc,aAAa,MAAM,IAC3B,YAAY,QAAQ;CAChC,GACA;EACE;EACA;EACA,SAAS,QAAQ;GACf,KAAK,cAAc,MAAM,GACzB,WAAW,MAAM;EACnB;CACF,CACF;CAEN,OAAO;EACL,QAAQ,MAAM;GACZ,KAAK,QAAQ,IAAI;EACnB;EACA,cAAc,QAAQ;GACpB,KAAK,cAAc,MAAM;EAC3B;EACA,UAAU;GACR,WAAW,GACX,KAAK,QAAQ;EACf;CACF;AACF"}
package/dist/host.d.ts CHANGED
@@ -43,6 +43,8 @@ type PreviewLiveStatus = 'connected' | 'polling' | 'offline';
43
43
  type SubscribePreviewEventsOptions = {
44
44
  socketPath?: string;
45
45
  eventsPath?: string;
46
+ /** Sent with the socket and every poll, e.g. a live ticket (`{ticket}`). */
47
+ params?: Record<string, string>;
46
48
  /** Called when the transport status changes (not on every retry tick). */
47
49
  onStatus?: (status: PreviewLiveStatus) => void;
48
50
  };
package/dist/host.js CHANGED
@@ -1,3 +1,3 @@
1
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-DreYJEmR.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
3
  export { PREVIEW_EVENTS_PATH, PREVIEW_SOCKET_PATH, STUDIO_PREVIEW_PARAM, connectVisualEditor, findSanityTarget, isPreviewBarFrame, isTopWindow, mountClickToEdit, mountPreviewBarFrame, mountPreviewBarHost, panelClipPath, subscribePreviewEvents };
@@ -1,6 +1,7 @@
1
1
  import { C as SearchConfig, n as PreviewBarData, s as PreviewPerspective, t as PreviewBarBrand, u as ReleaseDocument } from "./data-D0qotTtt.js";
2
2
  import { s as PreviewLinkStore } from "./preview-links-DM6BCiLV.js";
3
3
  import { r as PageDocumentRule } from "./page-documents-BFFcH8lD.js";
4
+ import { validatePreviewUrl } from "@sanity/preview-url-secret";
4
5
  /**
5
6
  * Signed, expiring link-session cookies: what a `/p/<code>` link leaves in the browser instead of
6
7
  * the site's preview secret. The value is `<expires>.<signature>`, where `expires` is in seconds
@@ -72,6 +73,60 @@ declare const LIVE_EDIT_TTL_S: number;
72
73
  declare function createLiveEditToken(secret: string, now?: number): Promise<string>;
73
74
  /** Whether a live-edit cookie value is a valid, unexpired token. */
74
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>;
75
130
  type PreviewLinkErrorRenderContext = {
76
131
  status: 404 | 503;
77
132
  expired: boolean;
@@ -218,4 +273,4 @@ declare function createPreviewBar(options: PreviewBarOptions): {
218
273
  type PreviewBar = ReturnType<typeof createPreviewBar>;
219
274
  declare const createVisualEditor: typeof createPreviewBar;
220
275
  type VisualEditor = PreviewBar;
221
- export { createPreviewHubClient as C, verifyLinkSession as D, signLinkSession as E, createLiveEditToken as S, LINK_SESSION_COOKIE as T, LIVE_EDIT_PATH as _, PreviewModeSwitch as a, PreviewHubClientLike as b, createVisualEditor as c, previewCookieAttributes as d, setCookieHeader as f, LIVE_EDIT_COOKIE as g, renderPreviewLinkErrorHtml as h, PreviewContext as i, 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, LIVE_EDIT_TTL_S as v, verifyLiveEditToken as w, PreviewHubFetcher as x, PreviewHub as y };
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 };
@@ -1,11 +1,18 @@
1
1
  import { n as PreviewBarData, r as PreviewLinkErrorData } from "./data-D0qotTtt.js";
2
+ import { LiveTicket } from "./next.js";
2
3
  /**
3
4
  * Mounts the bar's frame in the top window while draft mode is on. In the Studio's Visual Editor
4
5
  * tool's frame (`isPreviewBarFrame()`), it answers the tool instead (`mountPreviewBarFrame`): the
5
6
  * tool shows its own bar above the page. Other frames are skipped.
7
+ *
8
+ * With `live` (`await visualEditor.live()`), it follows the realtime preview hub and calls
9
+ * `router.refresh()` when a result the page read changes: the Server Components run again and
10
+ * read the new result from the hub. One refresh at a time; changes that arrive meanwhile are
11
+ * picked up by one more.
6
12
  */
7
- export declare function PreviewBarHost({ basePath }: {
13
+ export declare function PreviewBarHost({ basePath, live }: {
8
14
  basePath?: string;
15
+ live?: LiveTicket | null;
9
16
  }): null;
10
17
  /** The bar itself, for `app/__visual-editor/page.tsx`. */
11
18
  export declare function PreviewBarFrame({ data }: {
@@ -1,23 +1,57 @@
1
1
  "use client";
2
2
  import { u as isPreviewBarFrame } from "./protocol-BNO38gYy.js";
3
- import { n as isTopWindow } from "./host-DreYJEmR.js";
4
- import { useEffect, useRef, useState } from "react";
3
+ import { n as isTopWindow } from "./host-x2eXr-LJ.js";
4
+ import { useCallback, useEffect, useRef, useState, useTransition } from "react";
5
5
  import { jsx } from "react/jsx-runtime";
6
6
  import { usePathname, useRouter } from "next/navigation";
7
7
  /**
8
8
  * Next.js client components. `PreviewBarHost` goes in the site's root layout (rendered only in
9
- * draft mode); `PreviewBarFrame` and `PreviewLinkErrorFrame` render the bar's page and the
10
- * expired-link page. React and Sanity UI load only from the frames' dynamic imports, so the host
9
+ * draft mode) and follows the realtime preview hub when given a live ticket; `PreviewBarFrame` and
10
+ * `PreviewLinkErrorFrame` render the bar's page and the expired-link page. React and Sanity UI load only from the frames' dynamic imports, so the host
11
11
  * stays a few KB.
12
12
  */
13
+ /** The hub a ticket names (`<hub>.<expires>.<signature>`), to tell when the tab must move. */
14
+ function ticketHub(ticket) {
15
+ if (!ticket) return null;
16
+ let last = ticket.lastIndexOf("."), middle = ticket.lastIndexOf(".", last - 1);
17
+ return middle > 0 ? ticket.slice(0, middle) : null;
18
+ }
13
19
  /**
14
20
  * Mounts the bar's frame in the top window while draft mode is on. In the Studio's Visual Editor
15
21
  * tool's frame (`isPreviewBarFrame()`), it answers the tool instead (`mountPreviewBarFrame`): the
16
22
  * tool shows its own bar above the page. Other frames are skipped.
23
+ *
24
+ * With `live` (`await visualEditor.live()`), it follows the realtime preview hub and calls
25
+ * `router.refresh()` when a result the page read changes: the Server Components run again and
26
+ * read the new result from the hub. One refresh at a time; changes that arrive meanwhile are
27
+ * picked up by one more.
17
28
  */
18
- function PreviewBarHost({ basePath }) {
19
- let router = useRouter(), pathname = usePathname(), [host, setHost] = useState(null);
20
- return useEffect(() => {
29
+ function PreviewBarHost({ basePath, live }) {
30
+ let router = useRouter(), pathname = usePathname(), [host, setHost] = useState(null), [refreshing, startRefresh] = useTransition(), refreshingRef = useRef(!1), stale = useRef(!1);
31
+ refreshingRef.current = refreshing;
32
+ let refresh = useCallback(() => {
33
+ refreshingRef.current ? stale.current = !0 : startRefresh(() => router.refresh());
34
+ }, [router]);
35
+ useEffect(() => {
36
+ !refreshing && stale.current && (stale.current = !1, startRefresh(() => router.refresh()));
37
+ }, [refreshing, router]);
38
+ let hub = ticketHub(live?.ticket), ticket = useRef(live?.ticket);
39
+ return ticket.current = live?.ticket, useEffect(() => {
40
+ if (!host || !hub || !ticket.current) return;
41
+ let cancelled = !1, stop, params = { ticket: ticket.current };
42
+ return import("./host.js").then(({ subscribePreviewEvents }) => {
43
+ cancelled || (stop = subscribePreviewEvents(refresh, {
44
+ params,
45
+ onStatus: (status) => host.setLiveStatus(status)
46
+ }));
47
+ }), () => {
48
+ cancelled = !0, stop?.();
49
+ };
50
+ }, [
51
+ host,
52
+ hub,
53
+ refresh
54
+ ]), useEffect(() => {
21
55
  let frame = isPreviewBarFrame();
22
56
  if (!frame && !isTopWindow()) return;
23
57
  let cancelled = !1, mounted;
@@ -1 +1 @@
1
- {"version":3,"file":"next-client.js","names":[],"sources":["../src/next/client.tsx"],"sourcesContent":["'use client'\n/**\n * Next.js client components. `PreviewBarHost` goes in the site's root layout (rendered only in\n * draft mode); `PreviewBarFrame` and `PreviewLinkErrorFrame` render the bar's page and the\n * expired-link page. React and Sanity UI load only from the frames' dynamic imports, so the host\n * stays a few KB.\n */\nimport {usePathname, useRouter} from 'next/navigation'\nimport {useEffect, useRef, useState} from 'react'\n\nimport type {PreviewBarData, PreviewLinkErrorData} from '../core/data'\nimport {isPreviewBarFrame} from '../core/protocol'\nimport {isTopWindow, type PreviewBarHost as Host} from '../host'\n\n/**\n * Mounts the bar's frame in the top window while draft mode is on. In the Studio's Visual Editor\n * tool's frame (`isPreviewBarFrame()`), it answers the tool instead (`mountPreviewBarFrame`): the\n * tool shows its own bar above the page. Other frames are skipped.\n */\nexport function PreviewBarHost({basePath}: {basePath?: string}) {\n const router = useRouter()\n const pathname = usePathname()\n const [host, setHost] = useState<Host | null>(null)\n\n useEffect(() => {\n const frame = isPreviewBarFrame()\n if (!frame && !isTopWindow()) return\n let cancelled = false\n let mounted: Host | undefined\n import('../host').then(({mountPreviewBarHost, mountPreviewBarFrame}) => {\n if (cancelled) return\n const options = {\n // Server components rerun with the new perspective cookie; client state stays.\n refresh: () => router.refresh(),\n navigate: (href: string) => router.push(href),\n }\n mounted = frame ? mountPreviewBarFrame(options) : mountPreviewBarHost({...options, basePath})\n setHost(mounted)\n })\n return () => {\n cancelled = true\n mounted?.destroy()\n setHost(null)\n }\n }, [basePath, router])\n\n // Keep the bar's path current after client-side navigation.\n useEffect(() => {\n host?.setPath(window.location.pathname + window.location.search)\n }, [host, pathname])\n\n return null\n}\n\ntype BarModule = typeof import('../bar')\n\n/**\n * Mounts a React root from the lazily loaded bar module into this component's element. The\n * cancellation check runs before mounting, so React's development double-run of effects never\n * mounts two roots on one element.\n */\nfunction useMounted(mount: (bar: BarModule, element: HTMLElement) => () => void, deps: unknown[]) {\n const ref = useRef<HTMLDivElement>(null)\n useEffect(() => {\n const element = ref.current\n if (!element) return\n let unmount: (() => void) | undefined\n let cancelled = false\n import('../bar').then((bar) => {\n if (!cancelled) unmount = mount(bar, element)\n })\n return () => {\n cancelled = true\n unmount?.()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps)\n return ref\n}\n\n/** The bar itself, for `app/__visual-editor/page.tsx`. */\nexport function PreviewBarFrame({data}: {data: PreviewBarData}) {\n const ref = useMounted(({mountPreviewBar}, element) => mountPreviewBar(element, data), [data])\n return <div ref={ref} style={{height: '100%'}} />\n}\n\n/** The expired-link page, for `/p/[code]` and its `not-found.tsx`. */\nexport function PreviewLinkErrorFrame(props: PreviewLinkErrorData) {\n const ref = useMounted(\n ({mountPreviewLinkError}, element) => mountPreviewLinkError(element, props),\n [props.expired, props.brand, props.studioPath],\n )\n return <div ref={ref} />\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmBA,SAAgB,eAAe,EAAC,YAAgC;CAC9D,IAAM,SAAS,UAAU,GACnB,WAAW,YAAY,GACvB,CAAC,MAAM,WAAW,SAAsB,IAAI;CA6BlD,OA3BA,gBAAgB;EACd,IAAM,QAAQ,kBAAkB;EAChC,IAAI,CAAC,SAAS,CAAC,YAAY,GAAG;EAC9B,IAAI,YAAY,IACZ;EAWJ,OAVA,OAAO,YAAU,CAAC,MAAM,EAAC,qBAAqB,2BAA0B;GACtE,IAAI,WAAW;GACf,IAAM,UAAU;IAEd,eAAe,OAAO,QAAQ;IAC9B,WAAW,SAAiB,OAAO,KAAK,IAAI;GAC9C;GACA,UAAU,QAAQ,qBAAqB,OAAO,IAAI,oBAAoB;IAAC,GAAG;IAAS;GAAQ,CAAC,GAC5F,QAAQ,OAAO;EACjB,CAAC,SACY;GACX,YAAY,IACZ,SAAS,QAAQ,GACjB,QAAQ,IAAI;EACd;CACF,GAAG,CAAC,UAAU,MAAM,CAAC,GAGrB,gBAAgB;EACd,MAAM,QAAQ,OAAO,SAAS,WAAW,OAAO,SAAS,MAAM;CACjE,GAAG,CAAC,MAAM,QAAQ,CAAC,GAEZ;AACT;;;;;;AASA,SAAS,WAAW,OAA6D,MAAiB;CAChG,IAAM,MAAM,OAAuB,IAAI;CAevC,OAdA,gBAAgB;EACd,IAAM,UAAU,IAAI;EACpB,IAAI,CAAC,SAAS;EACd,IAAI,SACA,YAAY;EAIhB,OAHA,OAAO,WAAS,CAAC,MAAM,QAAQ;GACxB,cAAW,UAAU,MAAM,KAAK,OAAO;EAC9C,CAAC,SACY;GACX,YAAY,IACZ,UAAU;EACZ;CAEF,GAAG,IAAI,GACA;AACT;;AAGA,SAAgB,gBAAgB,EAAC,QAA+B;CAC9D,IAAM,MAAM,YAAY,EAAC,mBAAkB,YAAY,gBAAgB,SAAS,IAAI,GAAG,CAAC,IAAI,CAAC;CAC7F,OAAO,oBAAC,OAAD;EAAU;EAAK,OAAO,EAAC,QAAQ,OAAM;CAAI,CAAA;AAClD;;AAGA,SAAgB,sBAAsB,OAA6B;CACjE,IAAM,MAAM,YACT,EAAC,yBAAwB,YAAY,sBAAsB,SAAS,KAAK,GAC1E;EAAC,MAAM;EAAS,MAAM;EAAO,MAAM;CAAU,CAC/C;CACA,OAAO,oBAAC,OAAD,EAAU,IAAM,CAAA;AACzB"}
1
+ {"version":3,"file":"next-client.js","names":[],"sources":["../src/next/client.tsx"],"sourcesContent":["'use client'\n/**\n * Next.js client components. `PreviewBarHost` goes in the site's root layout (rendered only in\n * draft mode) and follows the realtime preview hub when given a live ticket; `PreviewBarFrame` and\n * `PreviewLinkErrorFrame` render the bar's page and the expired-link page. React and Sanity UI load only from the frames' dynamic imports, so the host\n * stays a few KB.\n */\nimport {usePathname, useRouter} from 'next/navigation'\nimport {useCallback, useEffect, useRef, useState, useTransition} from 'react'\n\nimport type {PreviewBarData, PreviewLinkErrorData} from '../core/data'\nimport {isPreviewBarFrame} from '../core/protocol'\nimport {isTopWindow, type PreviewBarHost as Host} from '../host'\nimport type {LiveTicket} from './index'\n\n/** The hub a ticket names (`<hub>.<expires>.<signature>`), to tell when the tab must move. */\nfunction ticketHub(ticket: string | undefined) {\n if (!ticket) return null\n const last = ticket.lastIndexOf('.')\n const middle = ticket.lastIndexOf('.', last - 1)\n return middle > 0 ? ticket.slice(0, middle) : null\n}\n\n/**\n * Mounts the bar's frame in the top window while draft mode is on. In the Studio's Visual Editor\n * tool's frame (`isPreviewBarFrame()`), it answers the tool instead (`mountPreviewBarFrame`): the\n * tool shows its own bar above the page. Other frames are skipped.\n *\n * With `live` (`await visualEditor.live()`), it follows the realtime preview hub and calls\n * `router.refresh()` when a result the page read changes: the Server Components run again and\n * read the new result from the hub. One refresh at a time; changes that arrive meanwhile are\n * picked up by one more.\n */\nexport function PreviewBarHost({basePath, live}: {basePath?: string; live?: LiveTicket | null}) {\n const router = useRouter()\n const pathname = usePathname()\n const [host, setHost] = useState<Host | null>(null)\n const [refreshing, startRefresh] = useTransition()\n const refreshingRef = useRef(false)\n const stale = useRef(false)\n refreshingRef.current = refreshing\n\n const refresh = useCallback(() => {\n if (refreshingRef.current) {\n stale.current = true\n return\n }\n startRefresh(() => router.refresh())\n }, [router])\n\n useEffect(() => {\n if (refreshing || !stale.current) return\n stale.current = false\n startRefresh(() => router.refresh())\n }, [refreshing, router])\n\n // The ticket changes hourly (and with the perspective); the socket only moves with its hub.\n const hub = ticketHub(live?.ticket)\n const ticket = useRef(live?.ticket)\n ticket.current = live?.ticket\n\n useEffect(() => {\n if (!host || !hub || !ticket.current) return\n let cancelled = false\n let stop: (() => void) | undefined\n const params = {ticket: ticket.current}\n import('../host').then(({subscribePreviewEvents}) => {\n if (cancelled) return\n stop = subscribePreviewEvents(refresh, {\n params,\n onStatus: (status) => host.setLiveStatus(status),\n })\n })\n return () => {\n cancelled = true\n stop?.()\n }\n }, [host, hub, refresh])\n\n useEffect(() => {\n const frame = isPreviewBarFrame()\n if (!frame && !isTopWindow()) return\n let cancelled = false\n let mounted: Host | undefined\n import('../host').then(({mountPreviewBarHost, mountPreviewBarFrame}) => {\n if (cancelled) return\n const options = {\n // Server components rerun with the new perspective cookie; client state stays.\n refresh: () => router.refresh(),\n navigate: (href: string) => router.push(href),\n }\n mounted = frame ? mountPreviewBarFrame(options) : mountPreviewBarHost({...options, basePath})\n setHost(mounted)\n })\n return () => {\n cancelled = true\n mounted?.destroy()\n setHost(null)\n }\n }, [basePath, router])\n\n // Keep the bar's path current after client-side navigation.\n useEffect(() => {\n host?.setPath(window.location.pathname + window.location.search)\n }, [host, pathname])\n\n return null\n}\n\ntype BarModule = typeof import('../bar')\n\n/**\n * Mounts a React root from the lazily loaded bar module into this component's element. The\n * cancellation check runs before mounting, so React's development double-run of effects never\n * mounts two roots on one element.\n */\nfunction useMounted(mount: (bar: BarModule, element: HTMLElement) => () => void, deps: unknown[]) {\n const ref = useRef<HTMLDivElement>(null)\n useEffect(() => {\n const element = ref.current\n if (!element) return\n let unmount: (() => void) | undefined\n let cancelled = false\n import('../bar').then((bar) => {\n if (!cancelled) unmount = mount(bar, element)\n })\n return () => {\n cancelled = true\n unmount?.()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps)\n return ref\n}\n\n/** The bar itself, for `app/__visual-editor/page.tsx`. */\nexport function PreviewBarFrame({data}: {data: PreviewBarData}) {\n const ref = useMounted(({mountPreviewBar}, element) => mountPreviewBar(element, data), [data])\n return <div ref={ref} style={{height: '100%'}} />\n}\n\n/** The expired-link page, for `/p/[code]` and its `not-found.tsx`. */\nexport function PreviewLinkErrorFrame(props: PreviewLinkErrorData) {\n const ref = useMounted(\n ({mountPreviewLinkError}, element) => mountPreviewLinkError(element, props),\n [props.expired, props.brand, props.studioPath],\n )\n return <div ref={ref} />\n}\n"],"m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A;AACzB"}
package/dist/next.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { n as PreviewBarData } from "./data-D0qotTtt.js";
2
- import { r as PreviewClient, t as PreviewBar } from "./index-4Zm_NjhC.js";
2
+ import { D as PreviewHubFetcher, T as PreviewHub, n as PreviewBarOptions, r as PreviewClient, t as PreviewBar } from "./index-hDzatlg7.js";
3
+ import { validatePreviewUrl } from "@sanity/preview-url-secret";
3
4
  export type NextPreviewBarOptions = {
4
5
  /** From `createPreviewBar` (`sanity-plugin-visual-editor/server`). */
5
6
  bar: PreviewBar;
@@ -35,4 +36,100 @@ export declare function createNextPreviewBar(options: NextPreviewBarOptions): {
35
36
  */
36
37
  openLink(request: Request, { params }: RouteContext): Promise<Response>;
37
38
  };
39
+ export type NextPreviewBar = ReturnType<typeof createNextPreviewBar>;
40
+ /** What a draft-mode page hands its tab to follow the hub: see `PreviewBarHost`'s `live`. */
41
+ export type LiveTicket = {
42
+ ticket: string;
43
+ };
44
+ export type NextVisualEditorOptions = PreviewBarOptions & {
45
+ /** A server Sanity client with a read token (e.g. `client.withConfig({token})`). */
46
+ client: PreviewClient & Parameters<typeof validatePreviewUrl>[0];
47
+ /**
48
+ * The realtime preview hub's service binding, e.g. `() => getCloudflareContext().env.PREVIEW_HUB`.
49
+ * Without it (or when it returns `undefined`), there is no live preview: `live()` and `hub()`
50
+ * return `null` and the site reads Sanity directly.
51
+ */
52
+ hub?: () => PreviewHubFetcher | undefined;
53
+ /**
54
+ * Signs live tickets and the Studio's live-edit cookie; without it there is no live preview,
55
+ * as without `hub`. The Worker entry (`createPreviewRoutes(...).upgrade`) must use the same value.
56
+ */
57
+ secret?: string | (() => string);
58
+ /** The hub routes' base path. Default `/api/preview`. */
59
+ routesPath?: string;
60
+ };
61
+ /**
62
+ * One-stop Next.js setup: the preview bar (`createPreviewBar` + `createNextPreviewBar`) and the
63
+ * realtime preview hub. Route files re-export its handlers; see the README.
64
+ */
65
+ export declare function createNextVisualEditor(options: NextVisualEditorOptions): {
66
+ bar: {
67
+ /** `app/__visual-editor/[action]/route.ts`: `export const {GET, POST} = previewBar.handlers`. */
68
+ handlers: {
69
+ GET: (request: Request, { params }: RouteContext) => Promise<Response>;
70
+ POST: (request: Request, { params }: RouteContext) => Promise<Response>;
71
+ };
72
+ /**
73
+ * `app/__visual-editor/page.tsx`: the bar's data, or a 404 outside draft mode. Pass it to
74
+ * `<PreviewBarFrame data={…} />`.
75
+ */
76
+ loadBar(): Promise<PreviewBarData>;
77
+ /**
78
+ * `app/p/[code]/page.tsx`: redirects a live link to the open handler; calls `notFound()` for
79
+ * an unknown, malformed or expired one (render `<PreviewLinkErrorFrame expired />` in that
80
+ * segment's `not-found.tsx`). Returns `'unavailable'` when the store can't be read, for the
81
+ * page to render `<PreviewLinkErrorFrame expired={false} />`.
82
+ */
83
+ checkLink(code: string): Promise<"unavailable">;
84
+ /**
85
+ * `app/__visual-editor/open/[code]/route.ts`: `export const GET = previewBar.openLink`. Turns
86
+ * draft mode on until the link expires, marks the session as opened from a link (so it can't
87
+ * mint links), sets the stored perspective and redirects to the stored page; a link that has
88
+ * gone meanwhile goes back to `/p/<code>` for the expired page.
89
+ */
90
+ openLink(request: Request, { params }: RouteContext): Promise<Response>;
91
+ };
92
+ /** `app/api/preview/[...path]/route.ts`: `export const {GET, POST} = visualEditor.routes`. */
93
+ routes: {
94
+ GET: (request: Request) => Promise<Response>;
95
+ POST: (request: Request) => Promise<Response>;
96
+ };
97
+ /**
98
+ * For the root layout, in draft mode: `<PreviewBarHost live={await visualEditor.live()} />`.
99
+ * A signed ticket for this request's hub, or `null` when there is nothing to follow
100
+ * (no hub binding, draft mode off, or the Published perspective). Fresh on every render, so a
101
+ * perspective switch (which refreshes the page) moves the tab to the new hub.
102
+ */
103
+ live(): Promise<LiveTicket | null>;
104
+ /**
105
+ * For Server Components' reads in draft mode: this request's hub, or `null` (read Sanity as
106
+ * usual). `await hub.query(query, params)` returns the result, unsaved Studio edits included.
107
+ */
108
+ hub(): Promise<PreviewHub | null>;
109
+ /** `app/__visual-editor/[action]/route.ts`: `export const {GET, POST} = previewBar.handlers`. */
110
+ handlers: {
111
+ GET: (request: Request, { params }: RouteContext) => Promise<Response>;
112
+ POST: (request: Request, { params }: RouteContext) => Promise<Response>;
113
+ };
114
+ /**
115
+ * `app/__visual-editor/page.tsx`: the bar's data, or a 404 outside draft mode. Pass it to
116
+ * `<PreviewBarFrame data={…} />`.
117
+ */
118
+ loadBar(): Promise<PreviewBarData>;
119
+ /**
120
+ * `app/p/[code]/page.tsx`: redirects a live link to the open handler; calls `notFound()` for
121
+ * an unknown, malformed or expired one (render `<PreviewLinkErrorFrame expired />` in that
122
+ * segment's `not-found.tsx`). Returns `'unavailable'` when the store can't be read, for the
123
+ * page to render `<PreviewLinkErrorFrame expired={false} />`.
124
+ */
125
+ checkLink(code: string): Promise<"unavailable">;
126
+ /**
127
+ * `app/__visual-editor/open/[code]/route.ts`: `export const GET = previewBar.openLink`. Turns
128
+ * draft mode on until the link expires, marks the session as opened from a link (so it can't
129
+ * mint links), sets the stored perspective and redirects to the stored page; a link that has
130
+ * gone meanwhile goes back to `/p/<code>` for the expired page.
131
+ */
132
+ openLink(request: Request, { params }: RouteContext): Promise<Response>;
133
+ };
134
+ export type NextVisualEditor = ReturnType<typeof createNextVisualEditor>;
38
135
  export {};
package/dist/next.js CHANGED
@@ -1,11 +1,17 @@
1
1
  import { c as parsePerspective, m as serializePerspective, n as PERSPECTIVE_COOKIE } from "./perspective-BmS9TVtr.js";
2
- import { t as LINK_SESSION_COOKIE } from "./link-session-Dr4YkKFy.js";
2
+ import { _ as createPreviewHubClient, g as createLiveTicket, t as createPreviewBar, u as createPreviewRoutes, v as previewHubName, x as LINK_SESSION_COOKIE } from "./server-B8MqMyaN.js";
3
3
  import { cookies, draftMode, headers } from "next/headers";
4
4
  import { notFound, redirect } from "next/navigation";
5
5
  /**
6
6
  * Next.js (App Router) adapter, for sites using `next-sanity`'s draft mode. Server side: route
7
- * handlers, the bar page's data and the short-link checks. The client components live in
8
- * `sanity-plugin-visual-editor/next/client`. See the README for the routes.
7
+ * handlers, the bar page's data, the short-link checks and the realtime preview hub. The client
8
+ * components live in `sanity-plugin-visual-editor/next/client`. See the README for the routes.
9
+ *
10
+ * Live preview keeps Next's own model: Server Components fetch, and draft mode skips every cache.
11
+ * In draft mode they read through the hub (`visualEditor.hub()`), which holds each result in
12
+ * memory, Studio keystrokes included. The tab follows the hub over a WebSocket and calls
13
+ * `router.refresh()` when a result it shows changes, so the Server Components run again and read
14
+ * the new result. No `revalidateTag`: draft requests never touch the cache.
9
15
  *
10
16
  * Opening a short link takes two steps because a page can't set cookies while it renders:
11
17
  * `/p/[code]` checks the link (rendering the expired page with a 404 when it's gone) and redirects
@@ -112,6 +118,59 @@ function createNextPreviewBar(options) {
112
118
  }
113
119
  };
114
120
  }
115
- export { createNextPreviewBar };
121
+ /**
122
+ * One-stop Next.js setup: the preview bar (`createPreviewBar` + `createNextPreviewBar`) and the
123
+ * realtime preview hub. Route files re-export its handlers; see the README.
124
+ */
125
+ function createNextVisualEditor(options) {
126
+ let { client, hub: hubBinding, secret, routesPath, ...barOptions } = options, bar = createNextPreviewBar({
127
+ bar: createPreviewBar(barOptions),
128
+ client
129
+ }), getService = () => hubBinding?.(), { hubFor } = createPreviewHubClient(getService), getSecret = () => (typeof secret == "function" ? secret() : secret) ?? "";
130
+ /** This request's hub name: draft mode on, a preview perspective, a hub binding and a secret. */
131
+ async function requestHub() {
132
+ if (!hubBinding || !getService() || !getSecret() || !(await draftMode()).isEnabled) return null;
133
+ let perspective = parsePerspective((await cookies()).get(PERSPECTIVE_COOKIE)?.value);
134
+ return previewHubName(perspective);
135
+ }
136
+ let routes = createPreviewRoutes({
137
+ secret: getSecret,
138
+ hub: getService,
139
+ client,
140
+ basePath: routesPath,
141
+ fallbackHub: requestHub
142
+ });
143
+ async function handleRoute(request) {
144
+ return await routes.handle(request) ?? new Response("Not found", { status: 404 });
145
+ }
146
+ return {
147
+ ...bar,
148
+ bar,
149
+ /** `app/api/preview/[...path]/route.ts`: `export const {GET, POST} = visualEditor.routes`. */
150
+ routes: {
151
+ GET: handleRoute,
152
+ POST: handleRoute
153
+ },
154
+ /**
155
+ * For the root layout, in draft mode: `<PreviewBarHost live={await visualEditor.live()} />`.
156
+ * A signed ticket for this request's hub, or `null` when there is nothing to follow
157
+ * (no hub binding, draft mode off, or the Published perspective). Fresh on every render, so a
158
+ * perspective switch (which refreshes the page) moves the tab to the new hub.
159
+ */
160
+ async live() {
161
+ let name = await requestHub();
162
+ return name ? { ticket: await createLiveTicket(getSecret(), name) } : null;
163
+ },
164
+ /**
165
+ * For Server Components' reads in draft mode: this request's hub, or `null` (read Sanity as
166
+ * usual). `await hub.query(query, params)` returns the result, unsaved Studio edits included.
167
+ */
168
+ async hub() {
169
+ let name = await requestHub();
170
+ return name ? hubFor(name) : null;
171
+ }
172
+ };
173
+ }
174
+ export { createNextPreviewBar, createNextVisualEditor };
116
175
 
117
176
  //# sourceMappingURL=next.js.map