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.
- package/README.md +128 -2
- package/dist/cloudflare.d.ts +15 -4
- package/dist/cloudflare.js +97 -34
- package/dist/cloudflare.js.map +1 -1
- package/dist/{host-DreYJEmR.js → host-x2eXr-LJ.js} +9 -5
- package/dist/host-x2eXr-LJ.js.map +1 -0
- package/dist/host.d.ts +2 -0
- package/dist/host.js +1 -1
- package/dist/{index-4Zm_NjhC.d.ts → index-hDzatlg7.d.ts} +56 -1
- package/dist/next-client.d.ts +8 -1
- package/dist/next-client.js +41 -7
- package/dist/next-client.js.map +1 -1
- package/dist/next.d.ts +98 -1
- package/dist/next.js +63 -4
- package/dist/next.js.map +1 -1
- package/dist/server-B8MqMyaN.js +748 -0
- package/dist/server-B8MqMyaN.js.map +1 -0
- package/dist/server.d.ts +2 -2
- package/dist/server.js +3 -495
- package/dist/sveltekit.d.ts +2 -2
- package/dist/sveltekit.js +2 -3
- package/dist/sveltekit.js.map +1 -1
- package/package.json +1 -1
- package/dist/host-DreYJEmR.js.map +0 -1
- package/dist/link-session-Dr4YkKFy.js +0 -52
- package/dist/link-session-Dr4YkKFy.js.map +0 -1
- package/dist/server.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-B8MqMyaN.js","names":[],"sources":["../src/server/link-session.ts","../src/server/preview-hub.ts","../src/server/preview-routes.ts","../src/server/link-error-html.ts","../src/server/index.ts"],"sourcesContent":["/**\n * Signed, expiring link-session cookies: what a `/p/<code>` link leaves in the browser instead of\n * the site's preview secret. The value is `<expires>.<signature>`, where `expires` is in seconds\n * since the epoch and the signature is HMAC-SHA-256 over it, keyed with the preview secret. It\n * proves \"opened a live share link, valid until `expires`\" and nothing else, so copying it gains\n * no more than the link itself gave.\n */\n\n/** The link-session cookie's default name. */\nexport const LINK_SESSION_COOKIE = '__sanity_preview_link'\n\nconst encoder = new TextEncoder()\nconst LABEL = 'sanity-preview-bar/link-session/v1:'\n\nfunction key(secret: string) {\n if (!secret) throw new Error('sanity-visual-editor: the preview secret is empty')\n return crypto.subtle.importKey(\n 'raw',\n encoder.encode(secret),\n {name: 'HMAC', hash: 'SHA-256'},\n false,\n ['sign', 'verify'],\n )\n}\n\nfunction toBase64Url(bytes: ArrayBuffer) {\n let binary = ''\n for (const byte of new Uint8Array(bytes)) binary += String.fromCharCode(byte)\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\nfunction fromBase64Url(value: string) {\n if (!/^[A-Za-z0-9_-]+$/.test(value)) return null\n try {\n const binary = atob(value.replace(/-/g, '+').replace(/_/g, '/'))\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n return bytes\n } catch {\n return null\n }\n}\n\n/** A link-session cookie value valid until `expiresAt` (ms since the epoch). */\nexport async function signLinkSession(secret: string, expiresAt: number) {\n const expires = String(Math.floor(expiresAt / 1000))\n const signature = await crypto.subtle.sign(\n 'HMAC',\n await key(secret),\n encoder.encode(LABEL + expires),\n )\n return `${expires}.${toBase64Url(signature)}`\n}\n\n/**\n * When a link-session cookie value expires (ms since the epoch), or `null` when it is malformed,\n * forged or expired. The signature check is `crypto.subtle.verify`'s, which is constant-time.\n */\nexport async function verifyLinkSession(\n secret: string,\n value: string | undefined | null,\n now = Date.now(),\n): Promise<number | null> {\n if (!value || value.length > 128) return null\n const match = /^(\\d{1,12})\\.([A-Za-z0-9_-]+)$/.exec(value)\n if (!match) return null\n const expiresAt = Number(match[1]) * 1000\n if (!(expiresAt > now)) return null\n const signature = fromBase64Url(match[2])\n if (!signature) return null\n const valid = await crypto.subtle.verify(\n 'HMAC',\n await key(secret),\n signature,\n encoder.encode(LABEL + match[1]),\n )\n return valid ? expiresAt : null\n}\n","/**\n * Client for the Cloudflare realtime preview hub Worker/DO, plus signed HMAC session tokens for\n * the Studio live-edit endpoints (`/api/preview/live-edit*`).\n */\n\nconst HUB_ORIGIN = 'https://preview-hub.internal'\n/** Must match `PERSPECTIVE_HEADER` in the preview hub worker. */\nconst PERSPECTIVE_HEADER = 'x-preview-perspective'\n/** Must match `LIVE_EDIT_HEADER` in the preview hub worker. */\nconst LIVE_EDIT_HEADER = 'x-live-edit'\n\n/** Minimal Cloudflare Worker `Fetcher` shape (no `@cloudflare/workers-types` required). */\nexport type PreviewHubFetcher = {\n fetch(input: string | Request, init?: RequestInit): Promise<Response>\n}\n\n/** Minimal Sanity client shape for reading the active perspective. */\nexport type PreviewHubClientLike = {\n config(): {perspective?: unknown}\n}\n\n/** The preview hub instance for one perspective. */\nexport interface PreviewHub {\n /** `label` names the remote query reading it; the hub echoes it in events. */\n query<T = unknown>(query: string, params?: Record<string, unknown>, label?: string): Promise<T>\n /** Debug: forward a GET to the hub (`/stats`, `/bench`). */\n debug(pathAndSearch: string): Promise<Response>\n /** Forward a long poll for invalidations (`?after=<cursor>`) to the hub. */\n events(search: string, signal: AbortSignal): Promise<Response>\n /**\n * Open a WebSocket to the hub for invalidations (`?after=<cursor>`). The `101` response carries\n * the socket; return it to the browser as it is.\n */\n socket(search: string): Promise<Response>\n /**\n * Open a WebSocket on which the Studio sends unsaved edits (`{ document, seq }`). Call only\n * after checking the editor's live-edit session.\n */\n editSocket(): Promise<Response>\n /** Show an unsaved Studio edit. Returns whether the hub applied it. */\n overlay(document: {_id: string; _type?: string}, seq: number): Promise<boolean>\n}\n\n/**\n * Wraps a Cloudflare service binding (`env.PREVIEW_HUB`) into typed `previewHub(client)` and\n * `hubFor(name)` helpers.\n */\nexport function createPreviewHubClient(getService: () => PreviewHubFetcher | undefined) {\n function hubFor(name: string): PreviewHub | null {\n const service = getService()\n if (!service) return null\n // `raw` and `published` are not preview perspectives; never give them a hub.\n if (name === 'raw' || name === 'published') return null\n\n return {\n async query<T>(query: string, params: Record<string, unknown> = {}, label?: string) {\n const response = await service.fetch(`${HUB_ORIGIN}/query`, {\n method: 'POST',\n headers: {'content-type': 'application/json', [PERSPECTIVE_HEADER]: name},\n body: JSON.stringify({query, params, label}),\n })\n if (!response.ok) {\n throw new Error(`Preview hub: HTTP ${response.status} ${await response.text()}`)\n }\n const {result} = (await response.json()) as {result: T}\n return result\n },\n debug(pathAndSearch) {\n return service.fetch(`${HUB_ORIGIN}${pathAndSearch}`, {\n headers: {[PERSPECTIVE_HEADER]: name},\n })\n },\n async overlay(document, seq) {\n const response = await service.fetch(`${HUB_ORIGIN}/overlay`, {\n method: 'POST',\n headers: {'content-type': 'application/json', [PERSPECTIVE_HEADER]: name},\n body: JSON.stringify({document, seq}),\n })\n if (!response.ok) throw new Error(`Preview hub: HTTP ${response.status}`)\n return ((await response.json()) as {applied: boolean}).applied\n },\n events(search, signal) {\n return service.fetch(`${HUB_ORIGIN}/events${search}`, {\n headers: {[PERSPECTIVE_HEADER]: name},\n signal,\n })\n },\n socket(search) {\n return service.fetch(`${HUB_ORIGIN}/socket${search}`, {\n headers: {upgrade: 'websocket', [PERSPECTIVE_HEADER]: name},\n })\n },\n editSocket() {\n return service.fetch(`${HUB_ORIGIN}/socket`, {\n headers: {upgrade: 'websocket', [PERSPECTIVE_HEADER]: name, [LIVE_EDIT_HEADER]: '1'},\n })\n },\n }\n }\n\n function previewHub(client: PreviewHubClientLike): PreviewHub | null {\n const name = previewHubName(client.config().perspective)\n return name ? hubFor(name) : null\n }\n\n return {hubFor, previewHub}\n}\n\n/** Default cookie that authorises `/api/preview/live-edit`. */\nexport const LIVE_EDIT_COOKIE = 'sanity-live-edit'\nexport const LIVE_EDIT_PATH = '/api/preview/live-edit'\n/** A Studio session token lasts this long; the plugin asks for a new one on a 401. */\nexport const LIVE_EDIT_TTL_S = 12 * 60 * 60\n\nasync function hmac(secret: string, message: string): Promise<string> {\n const key = await crypto.subtle.importKey(\n 'raw',\n new TextEncoder().encode(secret),\n {name: 'HMAC', hash: 'SHA-256'},\n false,\n ['sign'],\n )\n const signature = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(message))\n return btoa(String.fromCharCode(...new Uint8Array(signature)))\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '')\n}\n\nfunction sign(secret: string, expires: number): Promise<string> {\n return hmac(secret, `live-edit:${expires}`)\n}\n\nfunction sameString(a: string, b: string) {\n if (a.length !== b.length) return false\n let diff = 0\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n return diff === 0\n}\n\n/** A signed `<expires>.<signature>` token for the live-edit cookie. */\nexport async function createLiveEditToken(secret: string, now = Date.now()): Promise<string> {\n const expires = Math.floor(now / 1000) + LIVE_EDIT_TTL_S\n return `${expires}.${await sign(secret, expires)}`\n}\n\n/** Whether a live-edit cookie value is a valid, unexpired token. */\nexport async function verifyLiveEditToken(\n secret: string,\n token: string | undefined,\n now = Date.now(),\n): Promise<boolean> {\n if (!token) return false\n const [raw, signature] = token.split('.')\n const expires = Number(raw)\n if (!Number.isInteger(expires) || expires < now / 1000 || !signature) return false\n return sameString(await sign(secret, expires), signature)\n}\n\n/** How long a live ticket opens sockets and polls. Pages hand out a fresh one on every render. */\nexport const LIVE_TICKET_TTL_S = 12 * 60 * 60\n\nconst HUB_NAME = /^[\\w.,-]{1,256}$/\n\n/**\n * The hub name for a preview perspective: `drafts`, or a release stack such as `rABC,drafts`.\n * `null` for perspectives that have no hub (`published`, `raw`).\n */\nexport function previewHubName(perspective: unknown): string | null {\n const name = Array.isArray(perspective)\n ? perspective.join(',')\n : typeof perspective === 'string' && perspective\n ? perspective\n : 'drafts'\n if (name === 'published' || name === 'raw' || !HUB_NAME.test(name)) return null\n return name\n}\n\n/**\n * A live ticket: proof, signed by the site, that a page was rendered in preview mode for one hub\n * (`<hub>.<expires>.<signature>`). The page hands it to its tab, which sends it with the socket\n * and the long poll. A Worker entry can check it without the framework's preview cookie, which\n * only the framework can read (Next.js's draft mode cookie is a per-build value).\n */\nexport async function createLiveTicket(\n secret: string,\n hub: string,\n now = Date.now(),\n): Promise<string> {\n if (!HUB_NAME.test(hub)) throw new Error(`Invalid preview hub name: ${hub}`)\n // Rounded up to the hour, so every render within an hour hands out the same ticket and a page\n // refresh doesn't look like a new one to the tab.\n const expires = Math.ceil(now / 1000 / 3600) * 3600 + LIVE_TICKET_TTL_S\n return `${hub}.${expires}.${await hmac(secret, `live:${hub}:${expires}`)}`\n}\n\n/** The hub a live ticket opens, or `null` when it is missing, forged or expired. */\nexport async function verifyLiveTicket(\n secret: string,\n ticket: string | null | undefined,\n now = Date.now(),\n): Promise<string | null> {\n if (!ticket) return null\n const last = ticket.lastIndexOf('.')\n const middle = ticket.lastIndexOf('.', last - 1)\n if (middle <= 0) return null\n const hub = ticket.slice(0, middle)\n const expires = Number(ticket.slice(middle + 1, last))\n const signature = ticket.slice(last + 1)\n if (!HUB_NAME.test(hub) || !Number.isInteger(expires) || expires < now / 1000 || !signature) {\n return null\n }\n return sameString(await hmac(secret, `live:${hub}:${expires}`), signature) ? hub : null\n}\n","/**\n * The realtime preview hub's site routes (`/api/preview/*`), framework-neutral: a web `Request`\n * in, a web `Response` out, or `null` for a path that isn't one of them.\n *\n * - `GET socket` tab → hub invalidations over a WebSocket (`101`)\n * - `GET events` the same as a long poll, where a socket can't open\n * - `GET hub/stats|bench` debug output of the tab's hub\n * - `POST live-edit/session` trades a Studio preview secret for the live-edit cookie\n * - `POST live-edit` one unsaved Studio edit\n * - `GET live-edit/socket` unsaved Studio edits over a WebSocket (`101`)\n *\n * Tabs prove they are in preview with a live ticket (`createLiveTicket`), which names their hub;\n * the Studio proves an editor with the live-edit cookie. Neither needs the framework, so the\n * WebSocket routes also run in a Worker entry ahead of the framework, which can't return a `101`.\n */\nimport {validatePreviewUrl} from '@sanity/preview-url-secret'\n\nimport {\n createLiveEditToken,\n createPreviewHubClient,\n LIVE_EDIT_COOKIE,\n LIVE_EDIT_PATH,\n LIVE_EDIT_TTL_S,\n type PreviewHubFetcher,\n verifyLiveEditToken,\n verifyLiveTicket,\n} from './preview-hub'\n\n/** Default base path of the hub's site routes. */\nexport const PREVIEW_ROUTES_PATH = '/api/preview'\n/** Query parameter carrying a tab's live ticket. */\nexport const LIVE_TICKET_PARAM = 'ticket'\n\nexport type PreviewRoutesOptions = {\n /**\n * Signs live tickets and the live-edit cookie. Keep it secret; any long random string. Empty\n * turns the routes off (refused, not errors).\n */\n secret: string | (() => string)\n /** The hub Worker's service binding (`() => env.PREVIEW_HUB`); `undefined` turns the routes off. */\n hub: () => PreviewHubFetcher | undefined\n /**\n * A server Sanity client with a read token, to check the Studio's preview secret when a\n * live-edit session starts. Without it, `live-edit/session` answers `404` (fine in a Worker\n * entry, which only serves the WebSocket routes).\n */\n client?: Parameters<typeof validatePreviewUrl>[0]\n /**\n * The hub for a request without a ticket (e.g. Next.js draft mode plus the perspective cookie),\n * so `hub/stats` opens from the address bar. Return `null` outside preview.\n */\n fallbackHub?: (request: Request) => Promise<string | null> | string | null\n /** Default `/api/preview`. */\n basePath?: string\n /** Largest unsaved document accepted, in bytes. Default `1_000_000`. */\n maxBytes?: number\n}\n\nconst NO_STORE = {'cache-control': 'private, no-store', 'x-robots-tag': 'noindex'}\n\nfunction text(body: string, status: number) {\n return new Response(body, {status, headers: NO_STORE})\n}\n\nfunction readCookie(request: Request, name: string): string | undefined {\n for (const part of (request.headers.get('cookie') ?? '').split(';')) {\n const index = part.indexOf('=')\n if (index < 0 || part.slice(0, index).trim() !== name) continue\n try {\n return decodeURIComponent(part.slice(index + 1).trim())\n } catch {\n return undefined\n }\n }\n return undefined\n}\n\nfunction isUpgrade(request: Request) {\n return request.headers.get('upgrade')?.toLowerCase() === 'websocket'\n}\n\n/** `?after=<cursor>` alone: the ticket stays on this side of the hub. */\nfunction cursorSearch(url: URL) {\n const after = url.searchParams.get('after')\n return after ? `?${new URLSearchParams({after})}` : ''\n}\n\nexport function createPreviewRoutes(options: PreviewRoutesOptions) {\n const basePath = (options.basePath ?? PREVIEW_ROUTES_PATH).replace(/\\/+$/, '')\n const maxBytes = options.maxBytes ?? 1_000_000\n const secret = () => (typeof options.secret === 'function' ? options.secret() : options.secret)\n const {hubFor} = createPreviewHubClient(options.hub)\n const liveEditPath = `${basePath}${LIVE_EDIT_PATH.slice(PREVIEW_ROUTES_PATH.length)}`\n\n // Without a secret nothing verifies: tabs and the Studio are refused, never an error.\n async function tabHub(request: Request, url: URL): Promise<string | null> {\n const ticket = url.searchParams.get(LIVE_TICKET_PARAM)\n if (ticket) return secret() ? verifyLiveTicket(secret(), ticket) : null\n return (await options.fallbackHub?.(request)) ?? null\n }\n\n async function editor(request: Request) {\n if (!secret()) return false\n return verifyLiveEditToken(secret(), readCookie(request, LIVE_EDIT_COOKIE))\n }\n\n /** Answers a hub route, or returns `null` for any other path. */\n async function handle(request: Request): Promise<Response | null> {\n const url = new URL(request.url)\n if (!url.pathname.startsWith(`${basePath}/`)) return null\n const route = url.pathname.slice(basePath.length + 1).replace(/\\/+$/, '')\n const method = request.method\n\n if (route === 'socket' || route === 'live-edit/socket') {\n if (method !== 'GET') return null\n if (!isUpgrade(request)) return text('Expected a WebSocket', 426)\n if (route === 'live-edit/socket') {\n if (!(await editor(request))) return text('No live-edit session', 401)\n const hub = hubFor('drafts')\n return hub ? hub.editSocket() : text('No preview hub', 503)\n }\n const name = await tabHub(request, url)\n if (!name) return text('Preview mode only', 403)\n const hub = hubFor(name)\n // 204: nothing to follow (no hub binding). The tab stops trying.\n return hub\n ? hub.socket(cursorSearch(url))\n : new Response(null, {status: 204, headers: NO_STORE})\n }\n\n if (route === 'events' && method === 'GET') {\n const name = await tabHub(request, url)\n if (!name) return text('Preview mode only', 403)\n const hub = hubFor(name)\n if (!hub) return new Response(null, {status: 204, headers: NO_STORE})\n const upstream = await hub.events(cursorSearch(url), request.signal)\n return new Response(await upstream.text(), {\n status: upstream.status,\n headers: {'content-type': 'application/json', ...NO_STORE},\n })\n }\n\n if ((route === 'hub/stats' || route === 'hub/bench') && method === 'GET') {\n const name = await tabHub(request, url)\n if (!name) return text('Preview mode only', 403)\n const hub = hubFor(name)\n if (!hub) {\n return Response.json(\n {hub: null, perspective: name, reason: 'No preview hub binding.'},\n {headers: NO_STORE},\n )\n }\n const search = new URLSearchParams(url.search)\n search.delete(LIVE_TICKET_PARAM)\n const query = search.size ? `?${search}` : ''\n const upstream = await hub.debug(`/${route.slice('hub/'.length)}${query}`)\n return new Response(await upstream.text(), {\n status: upstream.status,\n headers: {'content-type': 'application/json', ...NO_STORE},\n })\n }\n\n if (route === 'live-edit/session' && method === 'POST') {\n if (!options.client) return null\n if (!secret()) return text('Live edits are off: no secret', 503)\n const {isValid} = await validatePreviewUrl(options.client, request.url)\n if (!isValid) return text('Invalid preview secret', 401)\n const token = await createLiveEditToken(secret())\n const cookie = [\n `${LIVE_EDIT_COOKIE}=${encodeURIComponent(token)}`,\n `Path=${liveEditPath}`,\n `Max-Age=${LIVE_EDIT_TTL_S}`,\n 'HttpOnly',\n ...(url.protocol === 'https:' ? ['Secure'] : []),\n 'SameSite=Strict',\n ].join('; ')\n return new Response(null, {status: 204, headers: {...NO_STORE, 'set-cookie': cookie}})\n }\n\n if (route === 'live-edit' && method === 'POST') {\n if (!(await editor(request))) return text('No live-edit session', 401)\n const body = await request.text()\n if (body.length > maxBytes) return text('Document too large', 413)\n let parsed: {document?: {_id?: unknown; _type?: unknown}; seq?: unknown}\n try {\n parsed = JSON.parse(body) as typeof parsed\n } catch {\n return text('Invalid JSON', 400)\n }\n const {document, seq} = parsed\n if (\n !document ||\n typeof document._id !== 'string' ||\n !document._id.startsWith('drafts.') ||\n typeof seq !== 'number'\n ) {\n return text('Expected { document: draft, seq }', 400)\n }\n const hub = hubFor('drafts')\n if (!hub) return Response.json({applied: false}, {status: 503, headers: NO_STORE})\n const applied = await hub.overlay(document as {_id: string; _type?: string}, seq)\n return Response.json({applied}, {status: 202, headers: NO_STORE})\n }\n\n return null\n }\n\n return {\n basePath,\n handle,\n /**\n * For a Worker entry, ahead of the framework: answers the two WebSocket routes and returns\n * `null` for everything else, which then goes to the framework.\n */\n async upgrade(request: Request): Promise<Response | null> {\n if (!isUpgrade(request)) return null\n const {pathname} = new URL(request.url)\n if (pathname !== `${basePath}/socket` && pathname !== `${liveEditPath}/socket`) return null\n return handle(request)\n },\n }\n}\n\nexport type PreviewRoutes = ReturnType<typeof createPreviewRoutes>\n","import type {PreviewBarBrand} from '../core/data'\nimport {PREVIEW_LINK_TTL_SECONDS} from '../core/preview-links'\n\nexport type PreviewLinkErrorRenderContext = {\n status: 404 | 503\n expired: boolean\n brand: PreviewBarBrand\n studioPath: string\n request: Request\n}\n\nexport type PreviewLinkErrorRenderer = (\n context: PreviewLinkErrorRenderContext,\n) => Response | string | Promise<Response | string>\n\nconst TTL_DAYS = PREVIEW_LINK_TTL_SECONDS / (24 * 60 * 60)\n\nfunction escapeHtml(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n}\n\n/**\n * Default zero-JS HTML screen for expired or unavailable `/p/<code>` preview links.\n * Matches Sanity Presentation's `ErrorCard` (`sanity@6.23` + `@sanity/ui@4` `buildTheme()`):\n * flat full-height canvas, centered `Container width={0}` (320px), semibold `size={1}` title and\n * muted message over a ghost \"Open Studio\" button. Override via `renderLinkError` to customize.\n */\nexport function renderPreviewLinkErrorHtml({\n expired,\n brand,\n studioPath = '/studio',\n}: Pick<PreviewLinkErrorRenderContext, 'expired' | 'brand'> & {studioPath?: string}): string {\n const title = expired ? 'This preview link has expired' : 'This preview link couldn’t be opened'\n const message = expired\n ? `Preview links open for ${TTL_DAYS} days. Ask the person who shared it for a new link.`\n : 'Something went wrong on our side. Try the link again in a moment.'\n const pageTitle = expired ? 'Preview link expired' : 'Preview link error'\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<meta name=\"robots\" content=\"noindex\" />\n<title>${escapeHtml(pageTitle)} · ${escapeHtml(brand.title)}</title>\n<style>\n :root {\n color-scheme: light dark;\n --bg: #ffffff;\n --fg: #252837;\n --muted: #515870;\n --btn-bg: #f6f6f8;\n --btn-fg: #4e556d;\n --btn-border: #e6e6ea;\n --btn-hover-bg: #eeeef1;\n --btn-hover-fg: #353a4d;\n --btn-hover-border: #dedee4;\n --btn-active-bg: #e3e4e8;\n --btn-active-fg: #222533;\n --btn-active-border: #d4d5db;\n --focus-ring: #556bfc;\n }\n @media (prefers-color-scheme: dark) {\n :root {\n --bg: #13141b;\n --fg: #e4e5e9;\n --muted: #979cb0;\n --btn-bg: #191a24;\n --btn-fg: #999eb3;\n --btn-border: #262837;\n --btn-hover-bg: #21232f;\n --btn-hover-fg: #c1c3d0;\n --btn-hover-border: #2e3141;\n --btn-active-bg: #2a2d3f;\n --btn-active-fg: #e6e7ec;\n --btn-active-border: #363a50;\n --focus-ring: #596ffc;\n }\n }\n * { box-sizing: border-box; }\n html, body { height: 100%; margin: 0; }\n body {\n background: var(--bg);\n color: var(--fg);\n font-family: Inter, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", \"Liberation Sans\", Helvetica, Arial, system-ui, sans-serif;\n font-size: 13px;\n line-height: 19px;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n }\n main {\n min-height: 100dvh;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .container {\n width: 100%;\n max-width: 320px;\n padding: 20px;\n display: flex;\n flex-direction: column;\n gap: 20px;\n }\n .copy {\n display: flex;\n flex-direction: column;\n gap: 12px;\n }\n h1 {\n margin: 0;\n font-size: 13px;\n line-height: 19px;\n font-weight: 600;\n color: var(--fg);\n }\n p {\n margin: 0;\n font-size: 13px;\n line-height: 19px;\n font-weight: 400;\n color: var(--muted);\n }\n .actions { display: flex; }\n a.button {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n padding: 6px 10px;\n border-radius: 3px;\n font-size: 13px;\n line-height: 19px;\n font-weight: 500;\n text-decoration: none;\n background: var(--btn-bg);\n color: var(--btn-fg);\n box-shadow: inset 0 0 0 1px var(--btn-border);\n transition: background-color 100ms, color 100ms, box-shadow 100ms;\n }\n a.button:hover {\n background: var(--btn-hover-bg);\n color: var(--btn-hover-fg);\n box-shadow: inset 0 0 0 1px var(--btn-hover-border);\n }\n a.button:active {\n background: var(--btn-active-bg);\n color: var(--btn-active-fg);\n box-shadow: inset 0 0 0 1px var(--btn-active-border);\n }\n a.button:focus-visible {\n outline: none;\n box-shadow: inset 0 0 0 1px var(--btn-border), 0 0 0 1px var(--bg), 0 0 0 3px var(--focus-ring);\n }\n</style>\n</head>\n<body>\n <main>\n <div class=\"container\">\n <div class=\"copy\">\n <h1>${escapeHtml(title)}</h1>\n <p>${escapeHtml(message)}</p>\n </div>\n <div class=\"actions\">\n <a class=\"button\" href=\"${escapeHtml(studioPath)}\">Open Studio</a>\n </div>\n </div>\n </main>\n</body>\n</html>`\n}\n","/**\n * The bar's server side, framework-neutral: each handler takes a web `Request` plus the request's\n * preview state and returns a web `Response`. Framework adapters (`sanity-plugin-visual-editor/sveltekit`,\n * later `/next`) supply that state and the one thing that differs per framework: turning preview\n * mode on and off.\n */\nimport {fetchSharedAccessQuery} from '@sanity/preview-url-secret/constants'\n\nimport type {PreviewBarBrand, PreviewBarData} from '../core/data'\nimport {type SearchConfig, searchKinds} from '../core/link-search'\nimport {\n activeReleases,\n DRAFTS,\n PERSPECTIVE_COOKIE,\n perspectiveStack,\n type PreviewPerspective,\n PUBLISHED,\n RELEASES_QUERY,\n type ReleaseDocument,\n releaseIdOf,\n serializePerspective,\n parsePerspective,\n} from '../core/perspective'\nimport {\n assertLinkTtl,\n createPreviewLink,\n generatePreviewLinkCode,\n isPreviewLinkCode,\n normalizePreviewPathname,\n parsePreviewLinkValue,\n PREVIEW_LINK_ROUTE,\n previewLinkExpiry,\n PREVIEW_LINK_TTL_SECONDS,\n type PreviewLinkStore,\n previewLinkKey,\n} from '../core/preview-links'\nimport {findPageDocumentRule, type PageDocumentRule} from '../core/page-documents'\nimport {PREVIEW_BAR_ROUTE} from '../core/protocol'\n\nexport type PreviewBarOptions = {\n brand: PreviewBarBrand\n /** Where the embedded Studio lives. Default `/studio`. */\n studioPath?: string\n /** The Sanity project ID for the workspace menu's links. Default: the client's `projectId`. */\n projectId?: string\n /** The bar's route. Default `/__visual-editor`. */\n basePath?: string\n /**\n * Which document each page shows: the Studio Presentation tool's `resolve.mainDocuments` list\n * (`defineDocuments([...])`). With it, signed-in editors see the page's document status.\n */\n pageDocuments?: PageDocumentRule[]\n /** Link search; `false` or omitted hides the search button. */\n search?: SearchConfig | false\n /** Short expiring links; `false` or omitted keeps Presentation's own shared link. */\n links?:\n | {\n /** A store, or a function returning one per request (for runtime bindings such as KV). */\n store: PreviewLinkStore | (() => PreviewLinkStore)\n /** Route prefix the links open at. Default `/p/`. */\n route?: string\n /** Link lifetime in seconds: a whole number, at least 60 (Workers KV's minimum). Default 2 days. */\n ttlSeconds?: number\n }\n | false\n}\n\n/**\n * The slice of `@sanity/client`'s `SanityClient` the bar uses. Structural, so any client version\n * fits and the package carries none of its types.\n */\nexport type PreviewClient = {\n withConfig(config: {\n apiVersion?: string\n perspective?: PreviewPerspective | 'raw'\n useCdn?: boolean\n stega?: boolean\n }): PreviewClient\n fetch<R = unknown>(\n query: string,\n params?: Record<string, unknown>,\n options?: {tag?: string},\n ): Promise<R>\n /** `SanityClient#config()`, read for the project ID when `projectId` isn't set. */\n config?(): {projectId?: string}\n}\n\n/** The request's preview state, as the framework adapter knows it. */\nexport type PreviewContext = {\n request: Request\n /** Preview mode is on (the preview cookie, or Next.js draft mode, is valid). */\n previewEnabled: boolean\n /**\n * A server Sanity client with a read token. Its perspective doesn't matter: handlers set what\n * they need per query.\n */\n client: PreviewClient\n /** The perspective the request applies (the parsed perspective cookie). */\n perspective: PreviewPerspective\n /**\n * Preview mode came from opening a short link rather than from an editor (the adapter's\n * link-session cookie). Such sessions can't mint links of their own.\n */\n linkSession?: boolean\n}\n\n/**\n * Adds or removes the framework's preview cookie on a response (e.g. `__sanity_preview`). When\n * opening a short link, `link.expiresAt` (ms since the epoch) is when the link stops opening: the\n * preview cookie should not outlive it.\n */\nexport type PreviewModeSwitch = (\n headers: Headers,\n request: Request,\n link?: {expiresAt: number},\n) => void | Promise<void>\n\nconst PRIVATE_HEADERS = {'cache-control': 'private, no-store', 'x-robots-tag': 'noindex'}\n\nfunction json(body: unknown, init: ResponseInit = {}) {\n const headers = new Headers(init.headers)\n headers.set('content-type', 'application/json')\n for (const [key, value] of Object.entries(PRIVATE_HEADERS)) headers.set(key, value)\n return new Response(JSON.stringify(body), {...init, headers})\n}\n\nfunction status(code: number, message: string) {\n return json({message}, {status: code})\n}\n\nfunction sameOrigin(request: Request) {\n return request.headers.get('origin') === new URL(request.url).origin\n}\n\n/**\n * `handlePreviewMode`'s cookie attributes: `SameSite=None; Secure` so the cookies also work inside\n * the Studio's Presentation iframe, `Lax` on plain-HTTP local development.\n */\nexport function previewCookieAttributes(request: Request) {\n const secure = new URL(request.url).protocol === 'https:'\n return secure ? 'Path=/; HttpOnly; SameSite=None; Secure' : 'Path=/; HttpOnly; SameSite=Lax'\n}\n\nexport function setCookieHeader(request: Request, name: string, value: string) {\n return `${name}=${encodeURIComponent(value)}; ${previewCookieAttributes(request)}`\n}\n\nexport function deleteCookieHeader(request: Request, name: string) {\n return `${name}=; Max-Age=0; ${previewCookieAttributes(request)}`\n}\n\n/**\n * Every content release, read like the Studio's releases store: raw perspective, the API version\n * that introduced releases, no stega or CDN. The client's token needs read access to\n * `system.release` documents.\n */\nexport function fetchReleases(client: PreviewClient) {\n return client\n .withConfig({apiVersion: '2025-02-19', perspective: 'raw', useCdn: false, stega: false})\n .fetch<ReleaseDocument[] | null>(RELEASES_QUERY)\n .then((releases) => releases ?? [])\n}\n\nfunction rawClient(client: PreviewClient) {\n return client.withConfig({perspective: 'raw', useCdn: false, stega: false})\n}\n\nexport function createPreviewBar(options: PreviewBarOptions) {\n const studioPath = options.studioPath ?? '/studio'\n const basePath = options.basePath ?? PREVIEW_BAR_ROUTE\n const search = options.search || null\n const links = options.links || null\n const linkRoute = links ? (links.route ?? PREVIEW_LINK_ROUTE) : PREVIEW_LINK_ROUTE\n const ttlSeconds = links ? assertLinkTtl(links.ttlSeconds ?? PREVIEW_LINK_TTL_SECONDS) : 0\n\n function store() {\n if (!links) throw new Error('sanity-visual-editor: short links are not configured')\n return typeof links.store === 'function' ? links.store() : links.store\n }\n\n /** The bar page's data, or `null` outside preview (render a 404). */\n async function loadBar(ctx: PreviewContext): Promise<PreviewBarData | null> {\n if (!ctx.previewEnabled) return null\n const [releasesResult, shareSecretResult] = await Promise.allSettled([\n fetchReleases(ctx.client),\n // Presentation's \"Share this preview\" secret exists only while an editor has sharing on.\n // The bar only learns whether it exists; links are minted server-side.\n links\n ? rawClient(ctx.client).fetch<string | null>(fetchSharedAccessQuery)\n : Promise.resolve(null),\n ])\n if (releasesResult.status === 'rejected') {\n console.error('sanity-visual-editor: could not load content releases', releasesResult.reason)\n }\n if (shareSecretResult.status === 'rejected') {\n console.error(\n 'sanity-visual-editor: could not read the preview share secret',\n shareSecretResult.reason,\n )\n }\n return {\n brand: options.brand,\n studioPath,\n projectId: options.projectId ?? ctx.client.config?.().projectId ?? null,\n basePath,\n releases: releasesResult.status === 'fulfilled' ? activeReleases(releasesResult.value) : [],\n releasesError: releasesResult.status === 'rejected',\n sharing: shareSecretResult.status === 'fulfilled' && Boolean(shareSecretResult.value),\n links: Boolean(links),\n perspective: serializePerspective(ctx.perspective),\n search: search ? searchKinds(search) : null,\n pageDocuments: Boolean(options.pageDocuments),\n }\n }\n\n /**\n * POST `{ selected, excluded }`: sets the perspective cookie. The stack is built here from fresh\n * release data, so the client only names a layer to select and layers to hide.\n */\n async function perspective(ctx: PreviewContext): Promise<Response> {\n if (!ctx.previewEnabled) return status(404, 'Not found')\n if (!sameOrigin(ctx.request)) return status(403, 'Forbidden')\n const body = (await ctx.request.json().catch(() => ({}))) as {\n selected?: unknown\n excluded?: unknown\n }\n const selected = typeof body.selected === 'string' ? body.selected : DRAFTS\n // Published and Drafts are stacks of their own; only a release needs the release list (so a\n // token that can't read releases can still switch between the two).\n let releases: ReleaseDocument[] = []\n if (selected !== PUBLISHED && selected !== DRAFTS) {\n try {\n releases = activeReleases(await fetchReleases(ctx.client))\n } catch (error) {\n console.error('sanity-visual-editor: could not load content releases', error)\n return status(503, 'Could not load content releases')\n }\n }\n const releaseIds = releases.map(releaseIdOf)\n if (selected !== PUBLISHED && selected !== DRAFTS && !releaseIds.includes(selected)) {\n return status(400, 'Unknown perspective')\n }\n const excluded = Array.isArray(body.excluded)\n ? body.excluded.filter(\n (name): name is string =>\n typeof name === 'string' && (name === DRAFTS || releaseIds.includes(name)),\n )\n : []\n const stack = perspectiveStack({selected, releases, excluded})\n return json(\n {perspective: stack},\n {\n headers: {\n 'set-cookie': setCookieHeader(\n ctx.request,\n PERSPECTIVE_COOKIE,\n serializePerspective(stack),\n ),\n },\n },\n )\n }\n\n /**\n * POST: ends preview mode in place. Clears the perspective cookie; `disablePreview` clears the\n * framework's preview cookie. The bar then asks the host to rerun its data, so no reload.\n */\n async function exit(\n ctx: Pick<PreviewContext, 'request'>,\n disablePreview: PreviewModeSwitch,\n ): Promise<Response> {\n if (!sameOrigin(ctx.request)) return status(403, 'Forbidden')\n const headers = new Headers(PRIVATE_HEADERS)\n headers.append('set-cookie', deleteCookieHeader(ctx.request, PERSPECTIVE_COOKIE))\n await disablePreview(headers, ctx.request)\n return new Response(null, {status: 204, headers})\n }\n\n /**\n * GET `?type=&id=`: `{ href }`, the page a document opens, for search results picked in the\n * Studio's own search (Studio layer). 404 for a type without a page or a document without a slug.\n */\n async function resolveHref(ctx: PreviewContext): Promise<Response> {\n if (!ctx.previewEnabled || !search) return status(404, 'Not found')\n const url = new URL(ctx.request.url)\n const type = search.types?.find((candidate) => candidate.type === url.searchParams.get('type'))\n const id = (url.searchParams.get('id') ?? '')\n .replace(/^drafts\\./, '')\n .replace(/^versions\\.[^.]+\\./, '')\n if (!type || !/^[\\w.-]{1,128}$/.test(id)) return status(404, 'Not found')\n const client = ctx.client.withConfig({\n perspective: ctx.perspective,\n stega: false,\n useCdn: false,\n })\n // The type's own filter too, so a document the site doesn't show (an archived product) has no\n // page here either.\n const filter = type.filter ? ` && (${type.filter})` : ''\n const slug = await client.fetch<string | null>(\n `*[_id == $id${filter}][0]{\"slug\": ${type.fields.slug}}.slug`,\n {id},\n )\n if (!slug) return status(404, 'No page for this document')\n return json({href: type.href(slug)})\n }\n\n /**\n * GET `?path=`: `{ document: { _id, _type } | null }`, the document the page at `path` shows,\n * from `pageDocuments`. The ID is the published ID, whatever version the perspective shows.\n */\n async function pageDocument(ctx: PreviewContext): Promise<Response> {\n if (!ctx.previewEnabled || !options.pageDocuments) return status(404, 'Not found')\n const path = new URL(ctx.request.url).searchParams.get('path') ?? '/'\n const rule = findPageDocumentRule(options.pageDocuments, path)\n if (!rule) return json({document: null})\n const client = ctx.client.withConfig({\n perspective: ctx.perspective,\n stega: false,\n useCdn: false,\n })\n const document = await client.fetch<{_id: string; _type: string} | null>(\n `*[${rule.filter}][0]{_id, _type}`,\n rule.params,\n {tag: 'preview-bar.page-document'},\n )\n return json({\n document: document\n ? {\n _id: document._id.replace(/^drafts\\./, '').replace(/^versions\\.[^.]+\\./, ''),\n _type: document._type,\n }\n : null,\n })\n }\n\n /**\n * POST `{ pathname }`: mints a short link while Presentation's \"Share this preview\" is on (409\n * when it is off). The store holds the page and perspective, never a secret. 403 for a session\n * opened from a short link: recipients can't hand out links of their own.\n */\n async function share(ctx: PreviewContext): Promise<Response> {\n if (!ctx.previewEnabled || !links) return status(404, 'Not found')\n if (!sameOrigin(ctx.request)) return status(403, 'Forbidden')\n if (ctx.linkSession) return status(403, 'Preview links can’t be shared from a preview link')\n const body = (await ctx.request.json().catch(() => ({}))) as {pathname?: unknown}\n const pathname = normalizePreviewPathname(body?.pathname)\n if (!pathname) return status(400, 'Invalid pathname')\n const shareSecret = await rawClient(ctx.client).fetch<string | null>(fetchSharedAccessQuery)\n if (!shareSecret) return status(409, 'Preview sharing is off')\n const link = createPreviewLink({\n code: generatePreviewLinkCode(),\n pathname,\n perspective: serializePerspective(ctx.perspective),\n ttlSeconds,\n route: linkRoute,\n })\n try {\n await store().put(link.key, link.value, link.ttlSeconds)\n } catch (err) {\n console.error('sanity-visual-editor: could not store a preview link', err)\n return status(503, 'Preview links are not configured')\n }\n return json({url: new URL(link.path, ctx.request.url).href, expiresAt: link.expiresAt})\n }\n\n /**\n * Opens `/p/<code>`: a 307 to the stored page with the perspective cookie and, through\n * `enablePreview`, the framework's preview cookie. 404 for an unknown, malformed or expired\n * code; 503 when the store can't be read. Render your expired-link page for those two.\n */\n async function openLink(\n request: Request,\n code: string,\n enablePreview: PreviewModeSwitch,\n ): Promise<Response> {\n const result = await resolveLink(code)\n if (result.status !== 200) {\n return status(result.status, result.status === 404 ? 'Preview link not found' : 'Unavailable')\n }\n const {link} = result\n const headers = new Headers(PRIVATE_HEADERS)\n headers.set('location', link.pathname)\n headers.append(\n 'set-cookie',\n setCookieHeader(request, PERSPECTIVE_COOKIE, serializePerspective(link.perspective)),\n )\n await enablePreview(headers, request, {expiresAt: link.expiresAt})\n return new Response(null, {status: 307, headers})\n }\n\n /**\n * Looks a short link up: `200` with the stored page, perspective and expiry (ms since the\n * epoch), `404` for an unknown, malformed or expired code, `503` when the store can't be read.\n * Expiry is checked here too (`createdAt` + `ttlSeconds`), so a store that ignores the TTL\n * doesn't make links permanent. For adapters that set cookies through their framework's own\n * API; `openLink` builds the whole response.\n */\n async function resolveLink(code: string): Promise<\n | {\n status: 200\n link: {pathname: string; perspective: PreviewPerspective; expiresAt: number}\n }\n | {status: 404 | 503}\n > {\n if (!links || !isPreviewLinkCode(code)) return {status: 404}\n let stored: unknown\n try {\n stored = await store().get(previewLinkKey(code))\n } catch (err) {\n console.error('sanity-visual-editor: could not read a preview link', err)\n return {status: 503}\n }\n const link = parsePreviewLinkValue(stored)\n if (!link) return {status: 404}\n // A `createdAt` in the future (beyond a minute of clock skew) isn't one we wrote.\n const now = Date.now()\n const expiresAt = previewLinkExpiry(link, ttlSeconds)\n if (expiresAt === null || expiresAt <= now || expiresAt > now + ttlSeconds * 1000 + 60_000) {\n return {status: 404}\n }\n return {\n status: 200,\n link: {pathname: link.pathname, perspective: parsePerspective(link.perspective), expiresAt},\n }\n }\n\n return {\n options: {...options, studioPath, basePath, linkRoute},\n resolveLink,\n loadBar,\n perspective,\n exit,\n resolveHref,\n pageDocument,\n share,\n openLink,\n }\n}\n\nexport type PreviewBar = ReturnType<typeof createPreviewBar>\n\nexport const createVisualEditor = createPreviewBar\nexport type VisualEditor = PreviewBar\n\nexport {kvStore, memoryStore} from '../core/preview-links'\nexport {LINK_SESSION_COOKIE, signLinkSession, verifyLinkSession} from './link-session'\nexport type {KVNamespaceLike, PreviewLinkStore} from '../core/preview-links'\nexport type {SearchConfig, SearchDocumentType, SearchRoute} from '../core/link-search'\nexport type {PreviewBarBrand, PreviewBarData} from '../core/data'\nexport * from './preview-hub'\nexport * from './preview-routes'\nexport * from './link-error-html'\n"],"mappings":";;;;;;;;;;;;;;;AASA,MAAa,sBAAsB,yBAE7B,UAAU,IAAI,YAAY,GAC1B,QAAQ;AAEd,SAAS,IAAI,QAAgB;CAC3B,IAAI,CAAC,QAAQ,MAAU,MAAM,mDAAmD;CAChF,OAAO,OAAO,OAAO,UACnB,OACA,QAAQ,OAAO,MAAM,GACrB;EAAC,MAAM;EAAQ,MAAM;CAAS,GAC9B,IACA,CAAC,QAAQ,QAAQ,CACnB;AACF;AAEA,SAAS,YAAY,OAAoB;CACvC,IAAI,SAAS;CACb,KAAK,IAAM,QAAQ,IAAI,WAAW,KAAK,GAAG,UAAU,OAAO,aAAa,IAAI;CAC5E,OAAO,KAAK,MAAM,CAAC,CAAC,QAAQ,OAAO,GAAG,CAAC,C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GAAC,GAAG;GAAS;GAAY;GAAU;EAAS;EACrD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF;AAIA,MAAa,qBAAqB"}
|
package/dist/server.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { C as SearchConfig, D as SearchRoute, n as PreviewBarData, t as PreviewBarBrand, w as SearchDocumentType } from "./data-D0qotTtt.js";
|
|
2
2
|
import { m as memoryStore, p as kvStore, s as PreviewLinkStore, t as KVNamespaceLike } from "./preview-links-DM6BCiLV.js";
|
|
3
|
-
import {
|
|
4
|
-
export { type KVNamespaceLike, LINK_SESSION_COOKIE, LIVE_EDIT_COOKIE, LIVE_EDIT_PATH, LIVE_EDIT_TTL_S, PreviewBar, type PreviewBarBrand, type PreviewBarData, PreviewBarOptions, PreviewClient, PreviewContext, PreviewHub, PreviewHubClientLike, PreviewHubFetcher, PreviewLinkErrorRenderContext, PreviewLinkErrorRenderer, type PreviewLinkStore, PreviewModeSwitch, type SearchConfig, type SearchDocumentType, type SearchRoute, VisualEditor, createLiveEditToken, createPreviewBar, createPreviewHubClient, createVisualEditor, deleteCookieHeader, fetchReleases, kvStore, memoryStore, previewCookieAttributes, renderPreviewLinkErrorHtml, setCookieHeader, signLinkSession, verifyLinkSession, verifyLiveEditToken };
|
|
3
|
+
import { A as createPreviewHubClient, C as LIVE_EDIT_TTL_S, D as PreviewHubFetcher, E as PreviewHubClientLike, F as signLinkSession, I as verifyLinkSession, M as verifyLiveEditToken, N as verifyLiveTicket, O as createLiveEditToken, P as LINK_SESSION_COOKIE, S as LIVE_EDIT_PATH, T as PreviewHub, _ as PREVIEW_ROUTES_PATH, a as PreviewModeSwitch, b as createPreviewRoutes, c as createVisualEditor, d as previewCookieAttributes, f as setCookieHeader, g as LIVE_TICKET_PARAM, h as renderPreviewLinkErrorHtml, i as PreviewContext, j as previewHubName, k as createLiveTicket, l as deleteCookieHeader, m as PreviewLinkErrorRenderer, n as PreviewBarOptions, o as VisualEditor, p as PreviewLinkErrorRenderContext, r as PreviewClient, s as createPreviewBar, t as PreviewBar, u as fetchReleases, v as PreviewRoutes, w as LIVE_TICKET_TTL_S, x as LIVE_EDIT_COOKIE, y as PreviewRoutesOptions } from "./index-hDzatlg7.js";
|
|
4
|
+
export { type KVNamespaceLike, LINK_SESSION_COOKIE, LIVE_EDIT_COOKIE, LIVE_EDIT_PATH, LIVE_EDIT_TTL_S, LIVE_TICKET_PARAM, LIVE_TICKET_TTL_S, PREVIEW_ROUTES_PATH, PreviewBar, type PreviewBarBrand, type PreviewBarData, PreviewBarOptions, PreviewClient, PreviewContext, PreviewHub, PreviewHubClientLike, PreviewHubFetcher, PreviewLinkErrorRenderContext, PreviewLinkErrorRenderer, type PreviewLinkStore, PreviewModeSwitch, PreviewRoutes, PreviewRoutesOptions, type SearchConfig, type SearchDocumentType, type SearchRoute, VisualEditor, createLiveEditToken, createLiveTicket, createPreviewBar, createPreviewHubClient, createPreviewRoutes, createVisualEditor, deleteCookieHeader, fetchReleases, kvStore, memoryStore, previewCookieAttributes, previewHubName, renderPreviewLinkErrorHtml, setCookieHeader, signLinkSession, verifyLinkSession, verifyLiveEditToken, verifyLiveTicket };
|
package/dist/server.js
CHANGED
|
@@ -1,495 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { c as
|
|
3
|
-
|
|
4
|
-
import { t as findPageDocumentRule } from "./page-documents-mGfw_flR.js";
|
|
5
|
-
import "./protocol-BNO38gYy.js";
|
|
6
|
-
import { n as signLinkSession, r as verifyLinkSession, t as LINK_SESSION_COOKIE } from "./link-session-Dr4YkKFy.js";
|
|
7
|
-
import { fetchSharedAccessQuery } from "@sanity/preview-url-secret/constants";
|
|
8
|
-
/**
|
|
9
|
-
* Client for the Cloudflare realtime preview hub Worker/DO, plus signed HMAC session tokens for
|
|
10
|
-
* the Studio live-edit endpoints (`/api/preview/live-edit*`).
|
|
11
|
-
*/
|
|
12
|
-
const HUB_ORIGIN = "https://preview-hub.internal", PERSPECTIVE_HEADER = "x-preview-perspective";
|
|
13
|
-
/**
|
|
14
|
-
* Wraps a Cloudflare service binding (`env.PREVIEW_HUB`) into typed `previewHub(client)` and
|
|
15
|
-
* `hubFor(name)` helpers.
|
|
16
|
-
*/
|
|
17
|
-
function createPreviewHubClient(getService) {
|
|
18
|
-
function hubFor(name) {
|
|
19
|
-
let service = getService();
|
|
20
|
-
return !service || name === "raw" || name === "published" ? null : {
|
|
21
|
-
async query(query, params = {}, label) {
|
|
22
|
-
let response = await service.fetch(`${HUB_ORIGIN}/query`, {
|
|
23
|
-
method: "POST",
|
|
24
|
-
headers: {
|
|
25
|
-
"content-type": "application/json",
|
|
26
|
-
[PERSPECTIVE_HEADER]: name
|
|
27
|
-
},
|
|
28
|
-
body: JSON.stringify({
|
|
29
|
-
query,
|
|
30
|
-
params,
|
|
31
|
-
label
|
|
32
|
-
})
|
|
33
|
-
});
|
|
34
|
-
if (!response.ok) throw Error(`Preview hub: HTTP ${response.status} ${await response.text()}`);
|
|
35
|
-
let { result } = await response.json();
|
|
36
|
-
return result;
|
|
37
|
-
},
|
|
38
|
-
debug(pathAndSearch) {
|
|
39
|
-
return service.fetch(`${HUB_ORIGIN}${pathAndSearch}`, { headers: { [PERSPECTIVE_HEADER]: name } });
|
|
40
|
-
},
|
|
41
|
-
async overlay(document, seq) {
|
|
42
|
-
let response = await service.fetch(`${HUB_ORIGIN}/overlay`, {
|
|
43
|
-
method: "POST",
|
|
44
|
-
headers: {
|
|
45
|
-
"content-type": "application/json",
|
|
46
|
-
[PERSPECTIVE_HEADER]: name
|
|
47
|
-
},
|
|
48
|
-
body: JSON.stringify({
|
|
49
|
-
document,
|
|
50
|
-
seq
|
|
51
|
-
})
|
|
52
|
-
});
|
|
53
|
-
if (!response.ok) throw Error(`Preview hub: HTTP ${response.status}`);
|
|
54
|
-
return (await response.json()).applied;
|
|
55
|
-
},
|
|
56
|
-
events(search, signal) {
|
|
57
|
-
return service.fetch(`${HUB_ORIGIN}/events${search}`, {
|
|
58
|
-
headers: { [PERSPECTIVE_HEADER]: name },
|
|
59
|
-
signal
|
|
60
|
-
});
|
|
61
|
-
},
|
|
62
|
-
socket(search) {
|
|
63
|
-
return service.fetch(`${HUB_ORIGIN}/socket${search}`, { headers: {
|
|
64
|
-
upgrade: "websocket",
|
|
65
|
-
[PERSPECTIVE_HEADER]: name
|
|
66
|
-
} });
|
|
67
|
-
},
|
|
68
|
-
editSocket() {
|
|
69
|
-
return service.fetch(`${HUB_ORIGIN}/socket`, { headers: {
|
|
70
|
-
upgrade: "websocket",
|
|
71
|
-
[PERSPECTIVE_HEADER]: name,
|
|
72
|
-
"x-live-edit": "1"
|
|
73
|
-
} });
|
|
74
|
-
}
|
|
75
|
-
};
|
|
76
|
-
}
|
|
77
|
-
function previewHub(client) {
|
|
78
|
-
let { perspective } = client.config();
|
|
79
|
-
return hubFor(Array.isArray(perspective) ? perspective.join(",") : typeof perspective == "string" && perspective ? perspective : "drafts");
|
|
80
|
-
}
|
|
81
|
-
return {
|
|
82
|
-
hubFor,
|
|
83
|
-
previewHub
|
|
84
|
-
};
|
|
85
|
-
}
|
|
86
|
-
/** Default cookie that authorises `/api/preview/live-edit`. */
|
|
87
|
-
const LIVE_EDIT_COOKIE = "sanity-live-edit", LIVE_EDIT_PATH = "/api/preview/live-edit", LIVE_EDIT_TTL_S = 43200;
|
|
88
|
-
async function sign(secret, expires) {
|
|
89
|
-
let key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), {
|
|
90
|
-
name: "HMAC",
|
|
91
|
-
hash: "SHA-256"
|
|
92
|
-
}, !1, ["sign"]), signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`live-edit:${expires}`));
|
|
93
|
-
return btoa(String.fromCharCode(...new Uint8Array(signature))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
94
|
-
}
|
|
95
|
-
/** A signed `<expires>.<signature>` token for the live-edit cookie. */
|
|
96
|
-
async function createLiveEditToken(secret, now = Date.now()) {
|
|
97
|
-
let expires = Math.floor(now / 1e3) + LIVE_EDIT_TTL_S;
|
|
98
|
-
return `${expires}.${await sign(secret, expires)}`;
|
|
99
|
-
}
|
|
100
|
-
/** Whether a live-edit cookie value is a valid, unexpired token. */
|
|
101
|
-
async function verifyLiveEditToken(secret, token, now = Date.now()) {
|
|
102
|
-
if (!token) return !1;
|
|
103
|
-
let [raw, signature] = token.split("."), expires = Number(raw);
|
|
104
|
-
if (!Number.isInteger(expires) || expires < now / 1e3 || !signature) return !1;
|
|
105
|
-
let expected = await sign(secret, expires);
|
|
106
|
-
if (expected.length !== signature.length) return !1;
|
|
107
|
-
let diff = 0;
|
|
108
|
-
for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ signature.charCodeAt(i);
|
|
109
|
-
return diff === 0;
|
|
110
|
-
}
|
|
111
|
-
const TTL_DAYS = PREVIEW_LINK_TTL_SECONDS / 86400;
|
|
112
|
-
function escapeHtml(value) {
|
|
113
|
-
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
114
|
-
}
|
|
115
|
-
/**
|
|
116
|
-
* Default zero-JS HTML screen for expired or unavailable `/p/<code>` preview links.
|
|
117
|
-
* Matches Sanity Presentation's `ErrorCard` (`sanity@6.23` + `@sanity/ui@4` `buildTheme()`):
|
|
118
|
-
* flat full-height canvas, centered `Container width={0}` (320px), semibold `size={1}` title and
|
|
119
|
-
* muted message over a ghost "Open Studio" button. Override via `renderLinkError` to customize.
|
|
120
|
-
*/
|
|
121
|
-
function renderPreviewLinkErrorHtml({ expired, brand, studioPath = "/studio" }) {
|
|
122
|
-
let title = expired ? "This preview link has expired" : "This preview link couldn’t be opened", message = expired ? `Preview links open for ${TTL_DAYS} days. Ask the person who shared it for a new link.` : "Something went wrong on our side. Try the link again in a moment.";
|
|
123
|
-
return `<!doctype html>
|
|
124
|
-
<html lang="en">
|
|
125
|
-
<head>
|
|
126
|
-
<meta charset="utf-8" />
|
|
127
|
-
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
128
|
-
<meta name="robots" content="noindex" />
|
|
129
|
-
<title>${escapeHtml(expired ? "Preview link expired" : "Preview link error")} · ${escapeHtml(brand.title)}</title>
|
|
130
|
-
<style>
|
|
131
|
-
:root {
|
|
132
|
-
color-scheme: light dark;
|
|
133
|
-
--bg: #ffffff;
|
|
134
|
-
--fg: #252837;
|
|
135
|
-
--muted: #515870;
|
|
136
|
-
--btn-bg: #f6f6f8;
|
|
137
|
-
--btn-fg: #4e556d;
|
|
138
|
-
--btn-border: #e6e6ea;
|
|
139
|
-
--btn-hover-bg: #eeeef1;
|
|
140
|
-
--btn-hover-fg: #353a4d;
|
|
141
|
-
--btn-hover-border: #dedee4;
|
|
142
|
-
--btn-active-bg: #e3e4e8;
|
|
143
|
-
--btn-active-fg: #222533;
|
|
144
|
-
--btn-active-border: #d4d5db;
|
|
145
|
-
--focus-ring: #556bfc;
|
|
146
|
-
}
|
|
147
|
-
@media (prefers-color-scheme: dark) {
|
|
148
|
-
:root {
|
|
149
|
-
--bg: #13141b;
|
|
150
|
-
--fg: #e4e5e9;
|
|
151
|
-
--muted: #979cb0;
|
|
152
|
-
--btn-bg: #191a24;
|
|
153
|
-
--btn-fg: #999eb3;
|
|
154
|
-
--btn-border: #262837;
|
|
155
|
-
--btn-hover-bg: #21232f;
|
|
156
|
-
--btn-hover-fg: #c1c3d0;
|
|
157
|
-
--btn-hover-border: #2e3141;
|
|
158
|
-
--btn-active-bg: #2a2d3f;
|
|
159
|
-
--btn-active-fg: #e6e7ec;
|
|
160
|
-
--btn-active-border: #363a50;
|
|
161
|
-
--focus-ring: #596ffc;
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
* { box-sizing: border-box; }
|
|
165
|
-
html, body { height: 100%; margin: 0; }
|
|
166
|
-
body {
|
|
167
|
-
background: var(--bg);
|
|
168
|
-
color: var(--fg);
|
|
169
|
-
font-family: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Liberation Sans", Helvetica, Arial, system-ui, sans-serif;
|
|
170
|
-
font-size: 13px;
|
|
171
|
-
line-height: 19px;
|
|
172
|
-
-webkit-font-smoothing: antialiased;
|
|
173
|
-
-moz-osx-font-smoothing: grayscale;
|
|
174
|
-
}
|
|
175
|
-
main {
|
|
176
|
-
min-height: 100dvh;
|
|
177
|
-
display: flex;
|
|
178
|
-
align-items: center;
|
|
179
|
-
justify-content: center;
|
|
180
|
-
}
|
|
181
|
-
.container {
|
|
182
|
-
width: 100%;
|
|
183
|
-
max-width: 320px;
|
|
184
|
-
padding: 20px;
|
|
185
|
-
display: flex;
|
|
186
|
-
flex-direction: column;
|
|
187
|
-
gap: 20px;
|
|
188
|
-
}
|
|
189
|
-
.copy {
|
|
190
|
-
display: flex;
|
|
191
|
-
flex-direction: column;
|
|
192
|
-
gap: 12px;
|
|
193
|
-
}
|
|
194
|
-
h1 {
|
|
195
|
-
margin: 0;
|
|
196
|
-
font-size: 13px;
|
|
197
|
-
line-height: 19px;
|
|
198
|
-
font-weight: 600;
|
|
199
|
-
color: var(--fg);
|
|
200
|
-
}
|
|
201
|
-
p {
|
|
202
|
-
margin: 0;
|
|
203
|
-
font-size: 13px;
|
|
204
|
-
line-height: 19px;
|
|
205
|
-
font-weight: 400;
|
|
206
|
-
color: var(--muted);
|
|
207
|
-
}
|
|
208
|
-
.actions { display: flex; }
|
|
209
|
-
a.button {
|
|
210
|
-
display: inline-flex;
|
|
211
|
-
align-items: center;
|
|
212
|
-
justify-content: center;
|
|
213
|
-
gap: 8px;
|
|
214
|
-
padding: 6px 10px;
|
|
215
|
-
border-radius: 3px;
|
|
216
|
-
font-size: 13px;
|
|
217
|
-
line-height: 19px;
|
|
218
|
-
font-weight: 500;
|
|
219
|
-
text-decoration: none;
|
|
220
|
-
background: var(--btn-bg);
|
|
221
|
-
color: var(--btn-fg);
|
|
222
|
-
box-shadow: inset 0 0 0 1px var(--btn-border);
|
|
223
|
-
transition: background-color 100ms, color 100ms, box-shadow 100ms;
|
|
224
|
-
}
|
|
225
|
-
a.button:hover {
|
|
226
|
-
background: var(--btn-hover-bg);
|
|
227
|
-
color: var(--btn-hover-fg);
|
|
228
|
-
box-shadow: inset 0 0 0 1px var(--btn-hover-border);
|
|
229
|
-
}
|
|
230
|
-
a.button:active {
|
|
231
|
-
background: var(--btn-active-bg);
|
|
232
|
-
color: var(--btn-active-fg);
|
|
233
|
-
box-shadow: inset 0 0 0 1px var(--btn-active-border);
|
|
234
|
-
}
|
|
235
|
-
a.button:focus-visible {
|
|
236
|
-
outline: none;
|
|
237
|
-
box-shadow: inset 0 0 0 1px var(--btn-border), 0 0 0 1px var(--bg), 0 0 0 3px var(--focus-ring);
|
|
238
|
-
}
|
|
239
|
-
</style>
|
|
240
|
-
</head>
|
|
241
|
-
<body>
|
|
242
|
-
<main>
|
|
243
|
-
<div class="container">
|
|
244
|
-
<div class="copy">
|
|
245
|
-
<h1>${escapeHtml(title)}</h1>
|
|
246
|
-
<p>${escapeHtml(message)}</p>
|
|
247
|
-
</div>
|
|
248
|
-
<div class="actions">
|
|
249
|
-
<a class="button" href="${escapeHtml(studioPath)}">Open Studio</a>
|
|
250
|
-
</div>
|
|
251
|
-
</div>
|
|
252
|
-
</main>
|
|
253
|
-
</body>
|
|
254
|
-
</html>`;
|
|
255
|
-
}
|
|
256
|
-
/**
|
|
257
|
-
* The bar's server side, framework-neutral: each handler takes a web `Request` plus the request's
|
|
258
|
-
* preview state and returns a web `Response`. Framework adapters (`sanity-plugin-visual-editor/sveltekit`,
|
|
259
|
-
* later `/next`) supply that state and the one thing that differs per framework: turning preview
|
|
260
|
-
* mode on and off.
|
|
261
|
-
*/
|
|
262
|
-
const PRIVATE_HEADERS = {
|
|
263
|
-
"cache-control": "private, no-store",
|
|
264
|
-
"x-robots-tag": "noindex"
|
|
265
|
-
};
|
|
266
|
-
function json(body, init = {}) {
|
|
267
|
-
let headers = new Headers(init.headers);
|
|
268
|
-
headers.set("content-type", "application/json");
|
|
269
|
-
for (let [key, value] of Object.entries(PRIVATE_HEADERS)) headers.set(key, value);
|
|
270
|
-
return new Response(JSON.stringify(body), {
|
|
271
|
-
...init,
|
|
272
|
-
headers
|
|
273
|
-
});
|
|
274
|
-
}
|
|
275
|
-
function status(code, message) {
|
|
276
|
-
return json({ message }, { status: code });
|
|
277
|
-
}
|
|
278
|
-
function sameOrigin(request) {
|
|
279
|
-
return request.headers.get("origin") === new URL(request.url).origin;
|
|
280
|
-
}
|
|
281
|
-
/**
|
|
282
|
-
* `handlePreviewMode`'s cookie attributes: `SameSite=None; Secure` so the cookies also work inside
|
|
283
|
-
* the Studio's Presentation iframe, `Lax` on plain-HTTP local development.
|
|
284
|
-
*/
|
|
285
|
-
function previewCookieAttributes(request) {
|
|
286
|
-
return new URL(request.url).protocol === "https:" ? "Path=/; HttpOnly; SameSite=None; Secure" : "Path=/; HttpOnly; SameSite=Lax";
|
|
287
|
-
}
|
|
288
|
-
function setCookieHeader(request, name, value) {
|
|
289
|
-
return `${name}=${encodeURIComponent(value)}; ${previewCookieAttributes(request)}`;
|
|
290
|
-
}
|
|
291
|
-
function deleteCookieHeader(request, name) {
|
|
292
|
-
return `${name}=; Max-Age=0; ${previewCookieAttributes(request)}`;
|
|
293
|
-
}
|
|
294
|
-
/**
|
|
295
|
-
* Every content release, read like the Studio's releases store: raw perspective, the API version
|
|
296
|
-
* that introduced releases, no stega or CDN. The client's token needs read access to
|
|
297
|
-
* `system.release` documents.
|
|
298
|
-
*/
|
|
299
|
-
function fetchReleases(client) {
|
|
300
|
-
return client.withConfig({
|
|
301
|
-
apiVersion: "2025-02-19",
|
|
302
|
-
perspective: "raw",
|
|
303
|
-
useCdn: !1,
|
|
304
|
-
stega: !1
|
|
305
|
-
}).fetch(RELEASES_QUERY).then((releases) => releases ?? []);
|
|
306
|
-
}
|
|
307
|
-
function rawClient(client) {
|
|
308
|
-
return client.withConfig({
|
|
309
|
-
perspective: "raw",
|
|
310
|
-
useCdn: !1,
|
|
311
|
-
stega: !1
|
|
312
|
-
});
|
|
313
|
-
}
|
|
314
|
-
function createPreviewBar(options) {
|
|
315
|
-
let studioPath = options.studioPath ?? "/studio", basePath = options.basePath ?? "/__visual-editor", search = options.search || null, links = options.links || null, linkRoute = links ? links.route ?? "/p/" : "/p/", ttlSeconds = links ? assertLinkTtl(links.ttlSeconds ?? 172800) : 0;
|
|
316
|
-
function store() {
|
|
317
|
-
if (!links) throw Error("sanity-visual-editor: short links are not configured");
|
|
318
|
-
return typeof links.store == "function" ? links.store() : links.store;
|
|
319
|
-
}
|
|
320
|
-
/** The bar page's data, or `null` outside preview (render a 404). */
|
|
321
|
-
async function loadBar(ctx) {
|
|
322
|
-
if (!ctx.previewEnabled) return null;
|
|
323
|
-
let [releasesResult, shareSecretResult] = await Promise.allSettled([fetchReleases(ctx.client), links ? rawClient(ctx.client).fetch(fetchSharedAccessQuery) : Promise.resolve(null)]);
|
|
324
|
-
return releasesResult.status === "rejected" && console.error("sanity-visual-editor: could not load content releases", releasesResult.reason), shareSecretResult.status === "rejected" && console.error("sanity-visual-editor: could not read the preview share secret", shareSecretResult.reason), {
|
|
325
|
-
brand: options.brand,
|
|
326
|
-
studioPath,
|
|
327
|
-
projectId: options.projectId ?? ctx.client.config?.().projectId ?? null,
|
|
328
|
-
basePath,
|
|
329
|
-
releases: releasesResult.status === "fulfilled" ? activeReleases(releasesResult.value) : [],
|
|
330
|
-
releasesError: releasesResult.status === "rejected",
|
|
331
|
-
sharing: shareSecretResult.status === "fulfilled" && !!shareSecretResult.value,
|
|
332
|
-
links: !!links,
|
|
333
|
-
perspective: serializePerspective(ctx.perspective),
|
|
334
|
-
search: search ? searchKinds(search) : null,
|
|
335
|
-
pageDocuments: !!options.pageDocuments
|
|
336
|
-
};
|
|
337
|
-
}
|
|
338
|
-
/**
|
|
339
|
-
* POST `{ selected, excluded }`: sets the perspective cookie. The stack is built here from fresh
|
|
340
|
-
* release data, so the client only names a layer to select and layers to hide.
|
|
341
|
-
*/
|
|
342
|
-
async function perspective(ctx) {
|
|
343
|
-
if (!ctx.previewEnabled) return status(404, "Not found");
|
|
344
|
-
if (!sameOrigin(ctx.request)) return status(403, "Forbidden");
|
|
345
|
-
let body = await ctx.request.json().catch(() => ({})), selected = typeof body.selected == "string" ? body.selected : DRAFTS, releases = [];
|
|
346
|
-
if (selected !== "published" && selected !== "drafts") try {
|
|
347
|
-
releases = activeReleases(await fetchReleases(ctx.client));
|
|
348
|
-
} catch (error) {
|
|
349
|
-
return console.error("sanity-visual-editor: could not load content releases", error), status(503, "Could not load content releases");
|
|
350
|
-
}
|
|
351
|
-
let releaseIds = releases.map(releaseIdOf);
|
|
352
|
-
if (selected !== "published" && selected !== "drafts" && !releaseIds.includes(selected)) return status(400, "Unknown perspective");
|
|
353
|
-
let excluded = Array.isArray(body.excluded) ? body.excluded.filter((name) => typeof name == "string" && (name === "drafts" || releaseIds.includes(name))) : [], stack = perspectiveStack({
|
|
354
|
-
selected,
|
|
355
|
-
releases,
|
|
356
|
-
excluded
|
|
357
|
-
});
|
|
358
|
-
return json({ perspective: stack }, { headers: { "set-cookie": setCookieHeader(ctx.request, PERSPECTIVE_COOKIE, serializePerspective(stack)) } });
|
|
359
|
-
}
|
|
360
|
-
/**
|
|
361
|
-
* POST: ends preview mode in place. Clears the perspective cookie; `disablePreview` clears the
|
|
362
|
-
* framework's preview cookie. The bar then asks the host to rerun its data, so no reload.
|
|
363
|
-
*/
|
|
364
|
-
async function exit(ctx, disablePreview) {
|
|
365
|
-
if (!sameOrigin(ctx.request)) return status(403, "Forbidden");
|
|
366
|
-
let headers = new Headers(PRIVATE_HEADERS);
|
|
367
|
-
return headers.append("set-cookie", deleteCookieHeader(ctx.request, PERSPECTIVE_COOKIE)), await disablePreview(headers, ctx.request), new Response(null, {
|
|
368
|
-
status: 204,
|
|
369
|
-
headers
|
|
370
|
-
});
|
|
371
|
-
}
|
|
372
|
-
/**
|
|
373
|
-
* GET `?type=&id=`: `{ href }`, the page a document opens, for search results picked in the
|
|
374
|
-
* Studio's own search (Studio layer). 404 for a type without a page or a document without a slug.
|
|
375
|
-
*/
|
|
376
|
-
async function resolveHref(ctx) {
|
|
377
|
-
if (!ctx.previewEnabled || !search) return status(404, "Not found");
|
|
378
|
-
let url = new URL(ctx.request.url), type = search.types?.find((candidate) => candidate.type === url.searchParams.get("type")), id = (url.searchParams.get("id") ?? "").replace(/^drafts\./, "").replace(/^versions\.[^.]+\./, "");
|
|
379
|
-
if (!type || !/^[\w.-]{1,128}$/.test(id)) return status(404, "Not found");
|
|
380
|
-
let client = ctx.client.withConfig({
|
|
381
|
-
perspective: ctx.perspective,
|
|
382
|
-
stega: !1,
|
|
383
|
-
useCdn: !1
|
|
384
|
-
}), filter = type.filter ? ` && (${type.filter})` : "", slug = await client.fetch(`*[_id == $id${filter}][0]{"slug": ${type.fields.slug}}.slug`, { id });
|
|
385
|
-
return slug ? json({ href: type.href(slug) }) : status(404, "No page for this document");
|
|
386
|
-
}
|
|
387
|
-
/**
|
|
388
|
-
* GET `?path=`: `{ document: { _id, _type } | null }`, the document the page at `path` shows,
|
|
389
|
-
* from `pageDocuments`. The ID is the published ID, whatever version the perspective shows.
|
|
390
|
-
*/
|
|
391
|
-
async function pageDocument(ctx) {
|
|
392
|
-
if (!ctx.previewEnabled || !options.pageDocuments) return status(404, "Not found");
|
|
393
|
-
let path = new URL(ctx.request.url).searchParams.get("path") ?? "/", rule = findPageDocumentRule(options.pageDocuments, path);
|
|
394
|
-
if (!rule) return json({ document: null });
|
|
395
|
-
let document = await ctx.client.withConfig({
|
|
396
|
-
perspective: ctx.perspective,
|
|
397
|
-
stega: !1,
|
|
398
|
-
useCdn: !1
|
|
399
|
-
}).fetch(`*[${rule.filter}][0]{_id, _type}`, rule.params, { tag: "preview-bar.page-document" });
|
|
400
|
-
return json({ document: document ? {
|
|
401
|
-
_id: document._id.replace(/^drafts\./, "").replace(/^versions\.[^.]+\./, ""),
|
|
402
|
-
_type: document._type
|
|
403
|
-
} : null });
|
|
404
|
-
}
|
|
405
|
-
/**
|
|
406
|
-
* POST `{ pathname }`: mints a short link while Presentation's "Share this preview" is on (409
|
|
407
|
-
* when it is off). The store holds the page and perspective, never a secret. 403 for a session
|
|
408
|
-
* opened from a short link: recipients can't hand out links of their own.
|
|
409
|
-
*/
|
|
410
|
-
async function share(ctx) {
|
|
411
|
-
if (!ctx.previewEnabled || !links) return status(404, "Not found");
|
|
412
|
-
if (!sameOrigin(ctx.request)) return status(403, "Forbidden");
|
|
413
|
-
if (ctx.linkSession) return status(403, "Preview links can’t be shared from a preview link");
|
|
414
|
-
let body = await ctx.request.json().catch(() => ({})), pathname = normalizePreviewPathname(body?.pathname);
|
|
415
|
-
if (!pathname) return status(400, "Invalid pathname");
|
|
416
|
-
if (!await rawClient(ctx.client).fetch(fetchSharedAccessQuery)) return status(409, "Preview sharing is off");
|
|
417
|
-
let link = createPreviewLink({
|
|
418
|
-
code: generatePreviewLinkCode(),
|
|
419
|
-
pathname,
|
|
420
|
-
perspective: serializePerspective(ctx.perspective),
|
|
421
|
-
ttlSeconds,
|
|
422
|
-
route: linkRoute
|
|
423
|
-
});
|
|
424
|
-
try {
|
|
425
|
-
await store().put(link.key, link.value, link.ttlSeconds);
|
|
426
|
-
} catch (err) {
|
|
427
|
-
return console.error("sanity-visual-editor: could not store a preview link", err), status(503, "Preview links are not configured");
|
|
428
|
-
}
|
|
429
|
-
return json({
|
|
430
|
-
url: new URL(link.path, ctx.request.url).href,
|
|
431
|
-
expiresAt: link.expiresAt
|
|
432
|
-
});
|
|
433
|
-
}
|
|
434
|
-
/**
|
|
435
|
-
* Opens `/p/<code>`: a 307 to the stored page with the perspective cookie and, through
|
|
436
|
-
* `enablePreview`, the framework's preview cookie. 404 for an unknown, malformed or expired
|
|
437
|
-
* code; 503 when the store can't be read. Render your expired-link page for those two.
|
|
438
|
-
*/
|
|
439
|
-
async function openLink(request, code, enablePreview) {
|
|
440
|
-
let result = await resolveLink(code);
|
|
441
|
-
if (result.status !== 200) return status(result.status, result.status === 404 ? "Preview link not found" : "Unavailable");
|
|
442
|
-
let { link } = result, headers = new Headers(PRIVATE_HEADERS);
|
|
443
|
-
return headers.set("location", link.pathname), headers.append("set-cookie", setCookieHeader(request, PERSPECTIVE_COOKIE, serializePerspective(link.perspective))), await enablePreview(headers, request, { expiresAt: link.expiresAt }), new Response(null, {
|
|
444
|
-
status: 307,
|
|
445
|
-
headers
|
|
446
|
-
});
|
|
447
|
-
}
|
|
448
|
-
/**
|
|
449
|
-
* Looks a short link up: `200` with the stored page, perspective and expiry (ms since the
|
|
450
|
-
* epoch), `404` for an unknown, malformed or expired code, `503` when the store can't be read.
|
|
451
|
-
* Expiry is checked here too (`createdAt` + `ttlSeconds`), so a store that ignores the TTL
|
|
452
|
-
* doesn't make links permanent. For adapters that set cookies through their framework's own
|
|
453
|
-
* API; `openLink` builds the whole response.
|
|
454
|
-
*/
|
|
455
|
-
async function resolveLink(code) {
|
|
456
|
-
if (!links || !isPreviewLinkCode(code)) return { status: 404 };
|
|
457
|
-
let stored;
|
|
458
|
-
try {
|
|
459
|
-
stored = await store().get(previewLinkKey(code));
|
|
460
|
-
} catch (err) {
|
|
461
|
-
return console.error("sanity-visual-editor: could not read a preview link", err), { status: 503 };
|
|
462
|
-
}
|
|
463
|
-
let link = parsePreviewLinkValue(stored);
|
|
464
|
-
if (!link) return { status: 404 };
|
|
465
|
-
let now = Date.now(), expiresAt = previewLinkExpiry(link, ttlSeconds);
|
|
466
|
-
return expiresAt === null || expiresAt <= now || expiresAt > now + ttlSeconds * 1e3 + 6e4 ? { status: 404 } : {
|
|
467
|
-
status: 200,
|
|
468
|
-
link: {
|
|
469
|
-
pathname: link.pathname,
|
|
470
|
-
perspective: parsePerspective(link.perspective),
|
|
471
|
-
expiresAt
|
|
472
|
-
}
|
|
473
|
-
};
|
|
474
|
-
}
|
|
475
|
-
return {
|
|
476
|
-
options: {
|
|
477
|
-
...options,
|
|
478
|
-
studioPath,
|
|
479
|
-
basePath,
|
|
480
|
-
linkRoute
|
|
481
|
-
},
|
|
482
|
-
resolveLink,
|
|
483
|
-
loadBar,
|
|
484
|
-
perspective,
|
|
485
|
-
exit,
|
|
486
|
-
resolveHref,
|
|
487
|
-
pageDocument,
|
|
488
|
-
share,
|
|
489
|
-
openLink
|
|
490
|
-
};
|
|
491
|
-
}
|
|
492
|
-
const createVisualEditor = createPreviewBar;
|
|
493
|
-
export { LINK_SESSION_COOKIE, LIVE_EDIT_COOKIE, LIVE_EDIT_PATH, LIVE_EDIT_TTL_S, createLiveEditToken, createPreviewBar, createPreviewHubClient, createVisualEditor, deleteCookieHeader, fetchReleases, kvStore, memoryStore, previewCookieAttributes, renderPreviewLinkErrorHtml, setCookieHeader, signLinkSession, verifyLinkSession, verifyLiveEditToken };
|
|
494
|
-
|
|
495
|
-
//# sourceMappingURL=server.js.map
|
|
1
|
+
import { d as memoryStore, u as kvStore } from "./preview-links-BZDZyIey.js";
|
|
2
|
+
import { C as verifyLinkSession, S as signLinkSession, _ as createPreviewHubClient, a as previewCookieAttributes, b as verifyLiveTicket, c as LIVE_TICKET_PARAM, d as LIVE_EDIT_COOKIE, f as LIVE_EDIT_PATH, g as createLiveTicket, h as createLiveEditToken, i as fetchReleases, l as PREVIEW_ROUTES_PATH, m as LIVE_TICKET_TTL_S, n as createVisualEditor, o as setCookieHeader, p as LIVE_EDIT_TTL_S, r as deleteCookieHeader, s as renderPreviewLinkErrorHtml, t as createPreviewBar, u as createPreviewRoutes, v as previewHubName, x as LINK_SESSION_COOKIE, y as verifyLiveEditToken } from "./server-B8MqMyaN.js";
|
|
3
|
+
export { LINK_SESSION_COOKIE, LIVE_EDIT_COOKIE, LIVE_EDIT_PATH, LIVE_EDIT_TTL_S, LIVE_TICKET_PARAM, LIVE_TICKET_TTL_S, PREVIEW_ROUTES_PATH, createLiveEditToken, createLiveTicket, createPreviewBar, createPreviewHubClient, createPreviewRoutes, createVisualEditor, deleteCookieHeader, fetchReleases, kvStore, memoryStore, previewCookieAttributes, previewHubName, renderPreviewLinkErrorHtml, setCookieHeader, signLinkSession, verifyLinkSession, verifyLiveEditToken, verifyLiveTicket };
|