sanity-plugin-visual-editor 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +263 -16
  3. package/TESTING.md +133 -0
  4. package/dist/PreviewBar-D_rw0bhP.js +3503 -0
  5. package/dist/PreviewBar-D_rw0bhP.js.map +1 -0
  6. package/dist/bar.d.ts +22 -0
  7. package/dist/bar.js +67 -0
  8. package/dist/bar.js.map +1 -0
  9. package/dist/cloudflare.d.ts +87 -0
  10. package/dist/cloudflare.js +1134 -0
  11. package/dist/cloudflare.js.map +1 -0
  12. package/dist/data-D0qotTtt.d.ts +177 -0
  13. package/dist/host-x2eXr-LJ.js +619 -0
  14. package/dist/host-x2eXr-LJ.js.map +1 -0
  15. package/dist/host.d.ts +162 -0
  16. package/dist/host.js +3 -0
  17. package/dist/index-hDzatlg7.d.ts +276 -0
  18. package/dist/index.d.ts +18 -18
  19. package/dist/index.js +7 -8
  20. package/dist/link-search-JtZkxz4k.js +14 -0
  21. package/dist/link-search-JtZkxz4k.js.map +1 -0
  22. package/dist/next-client.d.ts +22 -0
  23. package/dist/next-client.js +112 -0
  24. package/dist/next-client.js.map +1 -0
  25. package/dist/next.d.ts +135 -0
  26. package/dist/next.js +176 -0
  27. package/dist/next.js.map +1 -0
  28. package/dist/node-labels-CDiW5rMq.js +122 -0
  29. package/dist/node-labels-CDiW5rMq.js.map +1 -0
  30. package/dist/page-documents-BFFcH8lD.d.ts +54 -0
  31. package/dist/page-documents-mGfw_flR.js +67 -0
  32. package/dist/page-documents-mGfw_flR.js.map +1 -0
  33. package/dist/perspective-BmS9TVtr.js +106 -0
  34. package/dist/perspective-BmS9TVtr.js.map +1 -0
  35. package/dist/preview-links-BZDZyIey.js +119 -0
  36. package/dist/preview-links-BZDZyIey.js.map +1 -0
  37. package/dist/preview-links-DM6BCiLV.d.ts +87 -0
  38. package/dist/protocol-BNO38gYy.js +280 -0
  39. package/dist/protocol-BNO38gYy.js.map +1 -0
  40. package/dist/protocol-BnRCy2wJ.d.ts +386 -0
  41. package/dist/server-B8MqMyaN.js +748 -0
  42. package/dist/server-B8MqMyaN.js.map +1 -0
  43. package/dist/server.d.ts +4 -0
  44. package/dist/server.js +3 -0
  45. package/dist/shell-DZotxRXX.d.ts +37 -0
  46. package/dist/studio.d.ts +93 -0
  47. package/dist/studio.js +1263 -0
  48. package/dist/studio.js.map +1 -0
  49. package/dist/sveltekit.d.ts +281 -0
  50. package/dist/sveltekit.js +394 -0
  51. package/dist/sveltekit.js.map +1 -0
  52. package/package.json +120 -39
  53. package/dist/index.d.mts +0 -21
  54. package/dist/index.js.map +0 -1
  55. package/dist/index.mjs +0 -8
  56. package/dist/index.mjs.map +0 -1
  57. package/sanity.json +0 -8
  58. package/src/index.ts +0 -27
  59. package/v2-incompatible.js +0 -11
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2025 Dennis Regalado
3
+ Copyright (c) 2026 Dennis Regalado
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,35 +1,282 @@
1
1
  # sanity-plugin-visual-editor
2
2
 
3
- > This is a **Sanity Studio v3** plugin.
3
+ Visual Editor, preview bar, click-to-edit overlays, short preview links, and Cloudflare realtime live edits for **Sanity + SvelteKit** and **Next.js**.
4
4
 
5
- ## Installation
5
+ ## What you get
6
6
 
7
- ```sh
8
- npm install sanity-plugin-visual-editor
7
+ - **Studio Visual Editor (`sanity-plugin-visual-editor/studio`)**: Replaces Presentation with a unified toolbar, desktop/tablet/mobile viewport switcher, document pane, `defineLocations` / `defineDocuments`, and automatic keystroke-level **live edits** (including Portable Text).
8
+ - **One-stop server handler (`sanity-plugin-visual-editor/sveltekit`)**: One `createSvelteKitVisualEditor(config)` + `visualEditor.handle` in `hooks.server.ts` handles perspective cookies, `?studio-preview` bypass, `/__visual-editor/*` endpoints, `/p/<code>` short preview links (with customizable error HTML), `/api/preview/*` live-edit sessions, and Cloudflare WebSocket `101` upgrades.
9
+ - **One-call storefront client (`sanity-plugin-visual-editor/host`)**: `connectVisualEditor(...)` mounts the preview bar or Visual Editor click-to-edit overlay and subscribes to realtime hub invalidations.
10
+ - **Zero-dependency annotations (`sanity-plugin-visual-editor`)**: `sanityAttr(doc, path, { enabled })` and `createSanityAttr(doc, { enabled })` emit `data-sanity` attributes for click-to-edit overlays.
11
+ - **Cloudflare Realtime Hub (`sanity-plugin-visual-editor/cloudflare`)**: Drop-in `PreviewHub` Durable Object + Worker entry for sub-second draft updates across all tabs.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ bun add sanity-plugin-visual-editor
9
17
  ```
10
18
 
11
- ## Usage
19
+ ## Quick Start (SvelteKit × Sanity × Cloudflare)
12
20
 
13
- Add it as a plugin in `sanity.config.ts` (or .js):
21
+ ### 1. Sanity Studio (`sanity.studio.ts`)
14
22
 
15
23
  ```ts
16
24
  import {defineConfig} from 'sanity'
17
- import {myPlugin} from 'sanity-plugin-visual-editor'
25
+ import {defineDocuments, defineLocations, visualEditor} from 'sanity-plugin-visual-editor/studio'
18
26
 
19
27
  export default defineConfig({
20
- //...
21
- plugins: [myPlugin({})],
28
+ // ...
29
+ plugins: [
30
+ visualEditor({
31
+ previewUrl: {initial: '/', previewMode: {enable: '/preview/enable'}},
32
+ resolve: {
33
+ mainDocuments: defineDocuments([
34
+ {route: '/', type: 'homepage'},
35
+ {route: '/pages/:slug', type: 'page'},
36
+ ]),
37
+ locations: {
38
+ page: defineLocations({
39
+ select: {title: 'title', slug: 'slug.current'},
40
+ resolve: (doc) => ({
41
+ locations: [{title: doc?.title || 'Untitled', href: `/pages/${doc?.slug}`}],
42
+ }),
43
+ }),
44
+ },
45
+ },
46
+ // Live edits are enabled by default; pass `liveEdit: false` to disable.
47
+ }),
48
+ ],
22
49
  })
23
50
  ```
24
51
 
25
- ## License
52
+ ### 2. Server Config (`src/lib/server/visual-editor.ts`)
53
+
54
+ ```ts
55
+ import {env} from 'cloudflare:workers'
56
+ import {SANITY_PREVIEW_SECRET} from '$app/env/private'
57
+ import {serverClient} from '$sanity/client.server'
58
+ import {kvStore, type PreviewHubFetcher} from 'sanity-plugin-visual-editor/server'
59
+ import {createSvelteKitVisualEditor} from 'sanity-plugin-visual-editor/sveltekit'
60
+
61
+ export const visualEditor = createSvelteKitVisualEditor({
62
+ secret: () => SANITY_PREVIEW_SECRET,
63
+ client: serverClient,
64
+ brand: {title: 'My Store'},
65
+ studioPath: '/studio',
66
+ pageDocuments: MAIN_DOCUMENTS,
67
+ search: {routes, types},
68
+ links: {store: () => kvStore(env.PREVIEW_LINKS)},
69
+ hub: () => env.PREVIEW_HUB as PreviewHubFetcher | undefined,
70
+ // Optional: customize expired / unavailable `/p/<code>` HTML screens
71
+ // renderLinkError: ({expired, brand}) => `<html>...</html>`,
72
+ })
73
+ ```
74
+
75
+ ### 3. Server Hook (`src/hooks.server.ts`)
76
+
77
+ ```ts
78
+ import {sequence} from '@sveltejs/kit/hooks'
79
+ import {visualEditor} from '$lib/server/visual-editor'
80
+
81
+ export const handle = sequence(handleSanity, visualEditor.handle)
82
+ ```
83
+
84
+ ### 4. Storefront Layout (`src/routes/+layout.svelte`)
85
+
86
+ ```svelte
87
+ <script lang="ts">
88
+ import {goto, refreshAll} from '$app/navigation'
89
+ import {page} from '$app/state'
90
+ import type {PreviewBarHost} from 'sanity-plugin-visual-editor/host'
91
+
92
+ let host: PreviewBarHost | undefined = $state.raw()
93
+ $effect(() => {
94
+ if (!preview) return
95
+ let cancelled = false
96
+ import('sanity-plugin-visual-editor/host').then(({connectVisualEditor}) => {
97
+ if (cancelled) return
98
+ host = connectVisualEditor({
99
+ enabled: true,
100
+ position: 'top',
101
+ refresh: refreshAll,
102
+ navigate: (href) => goto(href),
103
+ })
104
+ })
105
+ return () => {
106
+ cancelled = true
107
+ host?.destroy()
108
+ host = undefined
109
+ }
110
+ })
111
+ $effect(() => host?.setPath(page.url.pathname + page.url.search))
112
+ </script>
113
+ ```
114
+
115
+ ### 5. Click-to-Edit Annotations
116
+
117
+ ```svelte
118
+ <script lang="ts">
119
+ import {sanityAttr} from 'sanity-plugin-visual-editor'
120
+ </script>
121
+
122
+ <h1 {...sanityAttr(pageDoc, 'heading', {enabled: preview})}>
123
+ {pageDoc.heading}
124
+ </h1>
125
+
126
+ <section {...sanityAttr(pageDoc, ['sections', {_key: section._key}, 'title'], {enabled: preview})}>
127
+ ...
128
+ </section>
129
+ ```
130
+
131
+ ### 6. Cloudflare Realtime Preview Hub Worker (`workers/preview-hub/src/index.ts`)
132
+
133
+ ```ts
134
+ export {PreviewHub, default} from 'sanity-plugin-visual-editor/cloudflare'
135
+ ```
136
+
137
+ The hub keeps a local copy of your dataset for instant updates. Large document types that preview pages rarely read can stay out of it, set as Worker vars (comma-separated):
138
+
139
+ | Var | Default | Effect |
140
+ | ----------------------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------ |
141
+ | `PREVIEW_HUB_ON_DEMAND_TYPES` | `product,productVariant` | Not bulk-loaded; a document is fetched only when a held result references it. `""` loads every type. |
142
+ | `PREVIEW_HUB_LISTEN_EXCLUDED_TYPES` | `productVariant` | Left out of the `/listen` stream (so also on demand). For types no preview reads. `""` listens to all. |
143
+
144
+ ```jsonc
145
+ // wrangler.jsonc
146
+ "vars": {"PREVIEW_HUB_ON_DEMAND_TYPES": "formSubmission", "PREVIEW_HUB_LISTEN_EXCLUDED_TYPES": "formSubmission"}
147
+ ```
148
+
149
+ ## Quick Start (Next.js App Router × Sanity × Cloudflare)
150
+
151
+ For `next-sanity` sites on Cloudflare Workers through OpenNext.
152
+
153
+ **How live preview works.** Nothing new to learn: Server Components fetch, as always. In draft mode, Next skips every cache, so each render reads fresh data. The site reads it through the preview hub, which keeps each result in memory with the Studio's unsaved edits applied. The tab follows the hub over a WebSocket and calls `router.refresh()` when a result the page read changes. Then the Server Components run again and read the new result. There's no client-side data and no `revalidateTag`: the cache is for published visitors, and draft requests never touch it.
154
+
155
+ ### 1. Sanity Studio (`sanity.config.ts`)
26
156
 
27
- [MIT](LICENSE) © Dennis Regalado
157
+ The same `visualEditor({...})` as above, with `previewMode.enable` set to your `next-sanity` draft-mode route (e.g. `/api/draft-mode/enable` from `defineEnableDraftMode`).
28
158
 
29
- ## Develop & test
159
+ ### 2. Server config (`lib/visual-editor.ts`)
30
160
 
31
- This plugin uses [@sanity/plugin-kit](https://github.com/sanity-io/plugin-kit)
32
- with default configuration for build & watch scripts.
161
+ ```ts
162
+ import {getCloudflareContext} from '@opennextjs/cloudflare'
163
+ import {createNextVisualEditor} from 'sanity-plugin-visual-editor/next'
164
+ import {kvStore} from 'sanity-plugin-visual-editor/server'
165
+
166
+ const env = () => getCloudflareContext().env
167
+
168
+ export const visualEditor = createNextVisualEditor({
169
+ client: client.withConfig({token}),
170
+ brand: {title: 'My Store'},
171
+ pageDocuments: MAIN_DOCUMENTS, // the Studio's `resolve.mainDocuments`
172
+ links: {store: () => kvStore(env().PREVIEW_LINKS)},
173
+ secret: () => process.env.VISUAL_EDITOR_SECRET ?? '', // any long random string
174
+ hub: () => env().PREVIEW_HUB,
175
+ })
176
+ ```
177
+
178
+ ### 3. Routes
179
+
180
+ ```ts
181
+ // app/%5F_visual-editor/[action]/route.ts (`%5F` escapes Next's `_private` folders)
182
+ export const {GET, POST} = visualEditor.handlers
183
+ // app/%5F_visual-editor/open/[code]/route.ts
184
+ export const GET = visualEditor.openLink
185
+ // app/%5F_visual-editor/page.tsx
186
+ export default async function Page() {
187
+ return <PreviewBarFrame data={await visualEditor.loadBar()} />
188
+ }
189
+ // app/p/[code]/page.tsx (+ not-found.tsx rendering <PreviewLinkErrorFrame expired />)
190
+ export default async function Page({params}) {
191
+ await visualEditor.checkLink((await params).code)
192
+ return <PreviewLinkErrorFrame brand={brand} expired={false} />
193
+ }
194
+ // app/api/preview/[...path]/route.ts: the hub's long poll, stats and the Studio's live edits
195
+ export const {GET, POST} = visualEditor.routes
196
+ ```
197
+
198
+ ### 4. Reads: through the hub in draft mode
199
+
200
+ Wrap the fetch helper your Server Components already use:
201
+
202
+ ```ts
203
+ export async function fetchSanity(options) {
204
+ if (options.perspective !== 'published') {
205
+ const hub = await visualEditor.hub() // null outside draft mode or without a hub
206
+ if (hub) return {data: await hub.query(options.query, options.params ?? {})}
207
+ }
208
+ return sanityFetch(options)
209
+ }
210
+ ```
211
+
212
+ ### 5. Root layout
213
+
214
+ ```tsx
215
+ import {PreviewBarHost} from 'sanity-plugin-visual-editor/next/client'
216
+
217
+ const isDraft = (await draftMode()).isEnabled
218
+ const live = isDraft ? await visualEditor.live() : null // a signed ticket for this page's hub
219
+
220
+ {
221
+ isDraft && <PreviewBarHost live={live} />
222
+ }
223
+ {
224
+ isDraft && !live && <SanityLive includeDrafts />
225
+ }
226
+ {
227
+ /* no hub: refresh after each save */
228
+ }
229
+ ```
230
+
231
+ ### 6. Worker entry (`worker.ts`, `main` in `wrangler.jsonc`)
232
+
233
+ A Next route handler can't answer a WebSocket upgrade, so the two socket routes are answered ahead of Next:
234
+
235
+ ```ts
236
+ import {createPreviewRoutes} from 'sanity-plugin-visual-editor/server'
237
+ // @ts-ignore generated by `opennextjs-cloudflare build`
238
+ import {default as handler} from './.open-next/worker.js'
239
+ // @ts-ignore
240
+ export {DOQueueHandler, DOShardedTagCache, BucketCachePurge} from './.open-next/worker.js'
241
+
242
+ export default {
243
+ async fetch(request, env, ctx) {
244
+ if (env.VISUAL_EDITOR_SECRET && env.PREVIEW_HUB) {
245
+ const routes = createPreviewRoutes({
246
+ secret: env.VISUAL_EDITOR_SECRET,
247
+ hub: () => env.PREVIEW_HUB,
248
+ })
249
+ const upgrade = await routes.upgrade(request)
250
+ if (upgrade) return upgrade
251
+ }
252
+ return handler.fetch(request, env, ctx)
253
+ },
254
+ }
255
+ ```
256
+
257
+ ### 7. The hub Worker and bindings
258
+
259
+ Deploy the hub Worker from step 6 of the SvelteKit guide (`export {PreviewHub, default} from 'sanity-plugin-visual-editor/cloudflare'`, with a `PREVIEW_HUB` Durable Object binding, a `CF_VERSION_METADATA` version-metadata binding, `SANITY_PROJECT_ID`, `SANITY_DATASET`, `SANITY_API_VERSION` vars and a `SANITY_API_READ_TOKEN` secret). Deploy it **before** the site: the site binds it as a service (`"services": [{"binding": "PREVIEW_HUB", "service": "<hub worker>"}]`), and add the `VISUAL_EDITOR_SECRET` secret to the site.
260
+
261
+ For `next dev`, call `initOpenNextCloudflareForDev({configPath: './wrangler.dev.jsonc'})` in `next.config.ts` with a config holding the same service binding, and run the hub with `wrangler dev` alongside. `next dev` can't upgrade WebSockets, so tabs long-poll (`/api/preview/events`) and the Studio sends edits as POSTs. Both fall back automatically.
262
+
263
+ ## Subpath Exports
264
+
265
+ | Subpath | Purpose |
266
+ | --------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
267
+ | `sanity-plugin-visual-editor` | Core helpers (`sanityAttr`, `createSanityAttr`, `STUDIO_PREVIEW_PARAM`, protocol & path utilities) |
268
+ | `sanity-plugin-visual-editor/studio` | Sanity Studio plugin (`visualEditor`, `liveEditPlugin`, `defineLocations`, `defineDocuments`) |
269
+ | `sanity-plugin-visual-editor/sveltekit` | SvelteKit factory & hook (`createSvelteKitVisualEditor`, `handleVisualEditor`) |
270
+ | `sanity-plugin-visual-editor/server` | Framework-agnostic server handlers, `createPreviewRoutes`, `createPreviewHubClient`, `kvStore` |
271
+ | `sanity-plugin-visual-editor/host` | Storefront host, click-to-edit overlays, & realtime subscriber (`connectVisualEditor`, `subscribePreviewEvents`) |
272
+ | `sanity-plugin-visual-editor/bar` | React + `@sanity/ui` bar UI (`mountPreviewBar`) |
273
+ | `sanity-plugin-visual-editor/cloudflare` | Cloudflare Durable Object `PreviewHub` + Worker fetch handler |
274
+ | `sanity-plugin-visual-editor/next` & `/next/client` | Next.js App Router adapter |
275
+
276
+ ## Verification
277
+
278
+ After setup or upgrades, follow [TESTING.md](./TESTING.md) (designed for both humans and AI agents) to verify `/p/<code>` links, Visual Editor, click-to-edit overlays, keystroke live edits, Preview Hub stats, and Cloudflare WebSocket `101` upgrades end-to-end.
279
+
280
+ ## License
33
281
 
34
- See [Testing a plugin in Sanity Studio](https://github.com/sanity-io/plugin-kit#testing-a-plugin-in-sanity-studio)
35
- on how to run this plugin with hotreload in the studio.
282
+ MIT
package/TESTING.md ADDED
@@ -0,0 +1,133 @@
1
+ # Agent Verification Playbook (`TESTING.md`)
2
+
3
+ Run this checklist after completing `README.md` setup (or upgrading `sanity-plugin-visual-editor`) on any **SvelteKit × Sanity × Cloudflare** or **Next.js × Sanity × Cloudflare** project.
4
+
5
+ Every check below has concrete pass/fail criteria so an AI agent or developer can verify the full stack in ~2 minutes without leaving dirty edits in Sanity.
6
+
7
+ ---
8
+
9
+ ## 0. Start Local Services
10
+
11
+ Run both the app dev server and the local Cloudflare Preview Hub worker:
12
+
13
+ ```bash
14
+ # Terminal 1: Storefront + embedded Studio (e.g. http://localhost:5173 or http://localhost:3000)
15
+ bun run dev
16
+
17
+ # Terminal 2: Realtime Preview Hub Durable Object (http://localhost:8787)
18
+ cd workers/preview-hub && bun run dev
19
+ ```
20
+
21
+ Set `BASE_URL` to your app's local origin (`http://localhost:5173` for SvelteKit, `http://localhost:3000` for Next.js).
22
+
23
+ > **Note on WebSockets in dev:** `vite dev` and `next dev` do not forward WebSocket `upgrade` requests to app hooks/routes. In dev mode, `subscribePreviewEvents` and `liveEditPlugin` automatically fall back to `GET /api/preview/events` (`polling >= 1`) and `POST /api/preview/live-edit`. To verify real `101` WebSockets (`sockets >= 1`), run Check 7b against `wrangler dev` (`bun run build && bun run preview`).
24
+
25
+ ---
26
+
27
+ ## 1. Expired Short Preview Link (`/p/<code>`)
28
+
29
+ 1. Navigate to `${BASE_URL}/p/nonexistent-e2e-check`.
30
+ 2. **Pass criteria:**
31
+ - HTTP status is **404** (not a framework 500 or generic storefront 404).
32
+ - Response is the styled HTML error screen (custom `renderLinkError` or default `"Preview link expired"` with brand title) and includes `<meta name="robots" content="noindex" />`.
33
+ - Zero console errors.
34
+
35
+ ---
36
+
37
+ ## 2. Studio Visual Editor (`/studio/visual-editor`)
38
+
39
+ 1. Navigate to `${BASE_URL}/studio/visual-editor?preview=/` (sign in to Sanity Studio if prompted).
40
+ 2. **Pass criteria:**
41
+ - Top toolbar renders: Workspace menu, Perspective/Releases menu, Page picker, Search, Viewport toggle, Inspector toggle, Share button, Exit.
42
+ - Center `iframe[title="Preview"]` loads `/` (`200`) and the right-hand Studio Document Pane opens the page's document.
43
+ - Network shows `POST /api/preview/live-edit/session?sanity-preview-secret=...` → **204 No Content**.
44
+ - Zero console errors or 404/500 responses on `/__visual-editor/*` or `/api/preview/*`.
45
+
46
+ ---
47
+
48
+ ## 3. Click-to-Edit Overlays (`sanityAttr`)
49
+
50
+ 1. Inside `/studio/visual-editor?preview=/`, ensure the **Inspector** button is active (`Deactivate inspector` / `[aria-pressed="true"]`).
51
+ 2. Inspect `iframe[title="Preview"]` for `[data-sanity]` attributes.
52
+ 3. Hover an annotated element (e.g. a hero heading) and click it.
53
+ 4. **Pass criteria:**
54
+ - At least one `[data-sanity]` element is present inside the preview iframe (`id=...;type=...;path=...`).
55
+ - Hovering draws the blue overlay bounding box and field label pill.
56
+ - Clicking opens/focuses the matching field in the Studio Document Pane.
57
+
58
+ ---
59
+
60
+ ## 4. Keystroke Live-Edit Round-Trip (Non-Destructive)
61
+
62
+ 1. Wait ~2–3 seconds after `/studio/visual-editor?preview=/` loads so the storefront subscriber connects (`polling >= 1` in dev, or `sockets >= 1` in Workers).
63
+ 2. Pick a visible text field in the focused Document Pane (e.g. a heading). Record its exact original value.
64
+ 3. Append `" E2E"` to the input (**do not publish**).
65
+ 4. **Pass criteria:**
66
+ - `POST /api/preview/live-edit` returns **202 Accepted** (never `401` or `503`).
67
+ - Within ~1 second, the matching element inside `iframe[title="Preview"]` updates live to include `" E2E"`.
68
+ 5. **Cleanup (mandatory):** Immediately revert the input to its exact original value, wait ~2 seconds, and confirm both the input and the storefront iframe match the original text.
69
+
70
+ ---
71
+
72
+ ## 5. Standalone Preview Bar (`/__visual-editor`)
73
+
74
+ 1. With preview mode active, navigate to `${BASE_URL}/`.
75
+ 2. **Pass criteria:**
76
+ - `iframe[title="Sanity preview bar"][src*="/__visual-editor"]` mounts cleanly.
77
+ - `GET /__visual-editor/document?path=%2F` returns **200**.
78
+ - **Search** (signed in) opens the Studio's own search, filtered to your configured document types; picking a result opens its page.
79
+ - **Perspective** menu opens and lists Drafts / Published / Releases.
80
+ - **Share** opens, calls `POST /__visual-editor/share` (**200**), and displays a `/p/<code>` link + QR code. Save that `/p/<code>` URL for Check 6.
81
+
82
+ ---
83
+
84
+ ## 6. Valid Short Preview Link Round-Trip (`/p/<code>`)
85
+
86
+ 1. In the standalone preview bar's menu, click **Exit preview** (`POST /__visual-editor/exit` → **204**).
87
+ 2. Reload `${BASE_URL}/` and confirm `iframe[title="Sanity preview bar"]` is gone (`count === 0`) and `[data-sanity]` count is `0`.
88
+ 3. Navigate to the `/p/<code>` URL minted in Check 5.
89
+ 4. **Pass criteria:**
90
+ - Redirects (`307`) to `/` and sets the preview + perspective cookies (`Set-Cookie` headers).
91
+ - Preview bar re-mounts on `/` with the shared perspective active.
92
+
93
+ ---
94
+
95
+ ## 7. Realtime Preview Hub & WebSocket Check (`/api/preview/hub/stats`)
96
+
97
+ ### 7a. Local Dev (`vite dev` / `next dev`)
98
+
99
+ While `${BASE_URL}/` is open in preview mode, fetch `${BASE_URL}/api/preview/hub/stats` in another tab:
100
+
101
+ - **Pass criteria (`200 OK` JSON):**
102
+ - `mirror: true`
103
+ - `entries > 0` and `local.ok > 0`
104
+ - `polling >= 1` (HTTP long-poll fallback active)
105
+ - `upstream.Listener.error === ""` and `upstream["Live Content API"].error === ""`
106
+
107
+ ### 7b. Cloudflare Worker (`wrangler dev` or Deployed Preview)
108
+
109
+ Build and run the Worker locally (SvelteKit: `bun run build && bun run preview`; Next.js: `opennextjs-cloudflare build && wrangler dev` with custom `worker.ts`), open a `/p/<code>` preview tab, and fetch `/api/preview/hub/stats`:
110
+
111
+ - **Pass criteria:**
112
+ - **`sockets >= 1`** and `polling === 0` (confirms real `101 Switching Protocols` WebSocket upgrade to `PreviewHub`).
113
+
114
+ ---
115
+
116
+ ## 8. Studio Thumbnail & Production Isolation
117
+
118
+ 1. While preview mode is active, navigate to `${BASE_URL}/?studio-preview`.
119
+ - **Pass:** Preview bar does **not** mount; published content is served (no drafts).
120
+ 2. Exit preview mode and inspect `${BASE_URL}/`.
121
+ - **Pass:** `0` `[data-sanity]` attributes in the DOM; `/__visual-editor` and `/api/preview/hub/stats` reject non-preview requests (`403` / `404`).
122
+
123
+ ---
124
+
125
+ ## Common Failure Signatures
126
+
127
+ | Symptom | Likely Cause |
128
+ | -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
129
+ | `POST /api/preview/live-edit/session` returns `204`, followed by `401 POST /api/preview/live-edit` | Server handler used `event.cookies.set(...)` on a direct `new Response(...)` instead of appending `Set-Cookie` headers directly on the `Response`. |
130
+ | `HTTP 503 Worker "...-preview-hub" not found` | Local `workers/preview-hub` (`wrangler dev`) is not running, or `PREVIEW_HUB` service binding name in `wrangler.jsonc` does not match. |
131
+ | `polling: 0` and `sockets: 0` in `vite dev` / `next dev` | Preview hub subscriber did not mount (`connectVisualEditor`), or WebSocket open-timeout is missing. |
132
+ | `sockets: 0` on Cloudflare Worker (`wrangler dev` / prod) | In SvelteKit: `visualEditor.handle` must run **before** other hooks that wrap responses. In Next.js: WebSocket upgrades must be intercepted in the OpenNext custom `worker.ts` before `openNextHandler.fetch()`. |
133
+ | `0` `[data-sanity]` elements in Check 3 | Storefront components have not wired `{...sanityAttr(doc, path, { enabled: preview })}` yet, or `enabled` is `false`. |