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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # sanity-plugin-visual-editor
2
2
 
3
- Visual Editor, preview bar, click-to-edit overlays, short preview links, and Cloudflare realtime live edits for **Sanity + SvelteKit** (and Next.js).
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
5
  ## What you get
6
6
 
@@ -134,6 +134,132 @@ export const handle = sequence(handleSanity, visualEditor.handle)
134
134
  export {PreviewHub, default} from 'sanity-plugin-visual-editor/cloudflare'
135
135
  ```
136
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`)
156
+
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`).
158
+
159
+ ### 2. Server config (`lib/visual-editor.ts`)
160
+
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
+
137
263
  ## Subpath Exports
138
264
 
139
265
  | Subpath | Purpose |
@@ -141,7 +267,7 @@ export {PreviewHub, default} from 'sanity-plugin-visual-editor/cloudflare'
141
267
  | `sanity-plugin-visual-editor` | Core helpers (`sanityAttr`, `createSanityAttr`, `STUDIO_PREVIEW_PARAM`, protocol & path utilities) |
142
268
  | `sanity-plugin-visual-editor/studio` | Sanity Studio plugin (`visualEditor`, `liveEditPlugin`, `defineLocations`, `defineDocuments`) |
143
269
  | `sanity-plugin-visual-editor/sveltekit` | SvelteKit factory & hook (`createSvelteKitVisualEditor`, `handleVisualEditor`) |
144
- | `sanity-plugin-visual-editor/server` | Framework-agnostic server handlers, `createPreviewHubClient`, `kvStore`, `renderPreviewLinkErrorHtml` |
270
+ | `sanity-plugin-visual-editor/server` | Framework-agnostic server handlers, `createPreviewRoutes`, `createPreviewHubClient`, `kvStore` |
145
271
  | `sanity-plugin-visual-editor/host` | Storefront host, click-to-edit overlays, & realtime subscriber (`connectVisualEditor`, `subscribePreviewEvents`) |
146
272
  | `sanity-plugin-visual-editor/bar` | React + `@sanity/ui` bar UI (`mountPreviewBar`) |
147
273
  | `sanity-plugin-visual-editor/cloudflare` | Cloudflare Durable Object `PreviewHub` + Worker fetch handler |
@@ -28,14 +28,15 @@ export interface PreviewInvalidation {
28
28
  /** Which path found the change: local evaluation, the delayed re-evaluation or a refetch. */
29
29
  source: 'local' | 'rest' | 'sweep';
30
30
  /**
31
- * The changed results, by key, so a tab can show them without asking again. Only on WebSocket
32
- * messages (the log keeps keys alone), and only for results under {@link MAX_PUSH_BYTES}.
31
+ * The changed results, by key, so a tab can show them without asking again. Only for results
32
+ * under {@link MAX_PUSH_BYTES}. Events a tab catches up on (a long poll, or a reconnecting
33
+ * WebSocket) carry each key's current result, on the last event that names the key.
33
34
  */
34
35
  results?: Record<string, unknown>;
35
- /** The storefront remote queries that read each changed key (WebSocket messages only). */
36
+ /** The storefront remote queries that read each changed key. */
36
37
  labels?: Record<string, string[]>;
37
38
  }
38
- /** Required Cloudflare Worker bindings for the preview hub worker. */
39
+ /** Cloudflare Worker bindings and vars for the preview hub worker. */
39
40
  export interface PreviewHubEnv {
40
41
  CF_VERSION_METADATA: {
41
42
  id: string;
@@ -44,6 +45,16 @@ export interface PreviewHubEnv {
44
45
  SANITY_DATASET: string;
45
46
  SANITY_API_VERSION: string;
46
47
  SANITY_API_READ_TOKEN: string;
48
+ /**
49
+ * Comma-separated document types the mirror does not bulk-load; one is fetched only when a held
50
+ * result references it. Default `product,productVariant`; set to `""` to bulk-load every type.
51
+ */
52
+ PREVIEW_HUB_ON_DEMAND_TYPES?: string;
53
+ /**
54
+ * Comma-separated document types left out of the `/listen` stream (and so also on-demand).
55
+ * Default `productVariant`; set to `""` to listen to every type.
56
+ */
57
+ PREVIEW_HUB_LISTEN_EXCLUDED_TYPES?: string;
47
58
  PREVIEW_HUB: {
48
59
  getByName(name: string): {
49
60
  fetch(request: Request): Promise<Response>;
@@ -184,11 +184,20 @@ function isNode(value) {
184
184
  return !!value && typeof value == "object" && typeof value.type == "string";
185
185
  }
186
186
  /**
187
- * Shopify-synced types make up ~21 of the dataset's ~22 MB (2026-11-23: 17,235 variants, 2,701
188
- * products). The mirror holds every other document, and only the products that held results
189
- * reference.
187
+ * Default on-demand types: Shopify-synced types made up ~21 of one dataset's ~22 MB (2026-11-23:
188
+ * 17,235 variants, 2,701 products). The mirror holds every other document, and only the products
189
+ * that held results reference.
190
190
  */
191
- const ON_DEMAND_TYPES = ["product", "productVariant"], BASE_QUERY = `*[!(_type in ${JSON.stringify(ON_DEMAND_TYPES)}) && !(_id in path("_.**"))]`;
191
+ const DEFAULT_ON_DEMAND_TYPES = ["product", "productVariant"], DEFAULT_LISTEN_EXCLUDED_TYPES = ["productVariant"];
192
+ /** Parse a comma-separated type list (a Worker var). Unset → `undefined`, so defaults apply. */
193
+ function parseTypeList(value) {
194
+ if (value !== void 0) return value.split(",").map((type) => type.trim()).filter(Boolean);
195
+ }
196
+ /** `*[...]` over documents not of these types, leaving out system documents (`_.`). */
197
+ function filterQuery(excluded) {
198
+ let system = "!(_id in path(\"_.**\"))";
199
+ return excluded.length ? `*[!(_type in ${JSON.stringify(excluded)}) && ${system}]` : `*[${system}]`;
200
+ }
192
201
  /** Strip the `drafts.` or `versions.<release>.` prefix so every variant maps to one ID. */
193
202
  function baseId(id) {
194
203
  return id.replace(/^drafts\./, "").replace(/^versions\.[^.]+\./, "");
@@ -206,7 +215,7 @@ var Mirror = class {
206
215
  #docs = /* @__PURE__ */ new Map();
207
216
  /** Base ID → release name → version document. */
208
217
  #versions = /* @__PURE__ */ new Map();
209
- /** Base IDs of on-demand (product) documents the mirror tracks. */
218
+ /** Base IDs of on-demand documents the mirror tracks. */
210
219
  #tracked = /* @__PURE__ */ new Set();
211
220
  /** Base IDs known not to exist, so they are not fetched again for every evaluation. */
212
221
  #missing = /* @__PURE__ */ new Set();
@@ -220,16 +229,25 @@ var Mirror = class {
220
229
  #ready = null;
221
230
  #fetchRaw;
222
231
  #loaded = !1;
223
- constructor(fetchRaw) {
232
+ #onDemandTypes;
233
+ #baseQuery;
234
+ /** `/listen` filter: everything the mirror can hold. */
235
+ listenQuery;
236
+ constructor(fetchRaw, options = {}) {
224
237
  this.#fetchRaw = fetchRaw;
238
+ let excluded = options.listenExcludedTypes ?? DEFAULT_LISTEN_EXCLUDED_TYPES;
239
+ this.#onDemandTypes = /* @__PURE__ */ new Set([...options.onDemandTypes ?? DEFAULT_ON_DEMAND_TYPES, ...excluded]), this.#baseQuery = filterQuery([...this.#onDemandTypes]), this.listenQuery = filterQuery(excluded);
240
+ }
241
+ #onDemand(type) {
242
+ return type !== void 0 && this.#onDemandTypes.has(type);
225
243
  }
226
244
  get loaded() {
227
245
  return this.#loaded;
228
246
  }
229
- /** Load every non-product document once. Concurrent callers share one load. */
247
+ /** Load every document not of an on-demand type once. Concurrent callers share one load. */
230
248
  ready() {
231
249
  return this.#ready ??= (async () => {
232
- let docs = await this.#fetchRaw(BASE_QUERY);
250
+ let docs = await this.#fetchRaw(this.#baseQuery);
233
251
  for (let doc of docs) this.#put(doc);
234
252
  this.#views.clear(), this.#loaded = !0;
235
253
  })().catch((error) => {
@@ -246,21 +264,21 @@ var Mirror = class {
246
264
  let docs = await this.#fetchRaw("*[_id in $ids]", { ids: wanted.flatMap((id) => [id, `drafts.${id}`]) }), found = /* @__PURE__ */ new Set();
247
265
  for (let doc of docs) {
248
266
  let base = baseId(doc._id);
249
- found.add(base), this.#put(doc), doc._type && ON_DEMAND_TYPES.includes(doc._type) && this.#tracked.add(base);
267
+ found.add(base), this.#put(doc), this.#onDemand(doc._type) && this.#tracked.add(base);
250
268
  }
251
269
  for (let id of wanted) found.has(id) || this.#missing.add(id);
252
270
  for (let base of found) this.#refresh(base);
253
271
  }
254
272
  /**
255
273
  * Apply one `/listen` mutation (`includeResult=true`). Returns whether the mirror changed.
256
- * Products the mirror does not track are ignored.
274
+ * On-demand documents the mirror does not track are ignored.
257
275
  */
258
276
  apply(documentId, result, transition) {
259
277
  let base = baseId(documentId);
260
278
  if (transition === "disappear" || !result) {
261
279
  if (!this.#remove(documentId)) return !1;
262
280
  } else {
263
- if (result._type && ON_DEMAND_TYPES.includes(result._type) && !this.#tracked.has(base)) return !1;
281
+ if (this.#onDemand(result._type) && !this.#tracked.has(base)) return !1;
264
282
  this.#put(result), this.#missing.delete(base);
265
283
  }
266
284
  let overlay = this.#overlays.get(documentId);
@@ -273,7 +291,7 @@ var Mirror = class {
273
291
  overlay(doc, seq, now = Date.now()) {
274
292
  if (!/^(drafts|versions)\./.test(doc._id)) return !1;
275
293
  let base = baseId(doc._id);
276
- if (doc._type && ON_DEMAND_TYPES.includes(doc._type) && !this.#tracked.has(base)) return !1;
294
+ if (this.#onDemand(doc._type) && !this.#tracked.has(base)) return !1;
277
295
  let current = this.#overlays.get(doc._id);
278
296
  return current && current.seq >= seq ? !1 : (this.#overlays.set(doc._id, {
279
297
  doc,
@@ -320,7 +338,7 @@ var Mirror = class {
320
338
  }
321
339
  /**
322
340
  * Evaluate a GROQ query against the given perspective. `->` looks documents up by ID and
323
- * fetches any the mirror does not hold yet (products), so references resolve as on Sanity.
341
+ * fetches any the mirror does not hold yet (on-demand types), so references resolve as on Sanity.
324
342
  */
325
343
  async evaluate(query, params, perspective) {
326
344
  let { tree, indexes } = this.#parse(query, params), view = this.#view(perspective), lists = this.#lists(view), indexParams = {};
@@ -475,7 +493,10 @@ var PreviewHub = class extends DurableObject {
475
493
  #byTag = /* @__PURE__ */ new Map();
476
494
  #inflight = /* @__PURE__ */ new Map();
477
495
  #recentEvents = [];
478
- #mirror = new Mirror((query, params) => this.#fetchRaw(query, params));
496
+ #mirror = new Mirror((query, params) => this.#fetchRaw(query, params), {
497
+ onDemandTypes: parseTypeList(this.env.PREVIEW_HUB_ON_DEMAND_TYPES),
498
+ listenExcludedTypes: parseTypeList(this.env.PREVIEW_HUB_LISTEN_EXCLUDED_TYPES)
499
+ });
479
500
  #lastMutationAt = 0;
480
501
  #lastVerifyNote = "";
481
502
  /** Upstream stream health, for diagnostics. */
@@ -521,7 +542,7 @@ var PreviewHub = class extends DurableObject {
521
542
  let key = await fingerprint(query, params);
522
543
  label && this.#label(key, label);
523
544
  let entry = this.#entries.get(key);
524
- if (entry) return entry.usedAt = Date.now(), entry.result;
545
+ if (entry) return entry.usedAt = Date.now(), entry.local === "off" && entry.usedAt >= entry.retryAt && (this.#verifyPending.add(key), this.#scheduleVerify()), entry.result;
525
546
  let pending = this.#inflight.get(key);
526
547
  return pending || (pending = this.#load(key, query, params).finally(() => this.#inflight.delete(key)), this.#inflight.set(key, pending)), await pending;
527
548
  }
@@ -570,7 +591,8 @@ var PreviewHub = class extends DurableObject {
570
591
  if (!entry) return Response.json({ keys: [...this.#entries].map(([k, e]) => ({
571
592
  key: k,
572
593
  local: e.local,
573
- query: e.query.length
594
+ query: e.query.length,
595
+ mismatches: e.mismatches
574
596
  })) });
575
597
  let result = await this.#evaluateLocal(entry);
576
598
  return Response.json({
@@ -625,8 +647,8 @@ var PreviewHub = class extends DurableObject {
625
647
  if (server.addEventListener("close", close), server.addEventListener("error", close), server.addEventListener("message", (event) => {
626
648
  event.data === "ping" ? server.send("pong") : edits && typeof event.data == "string" && this.#receiveEdit(event.data);
627
649
  }), !edits) {
628
- let missed = this.#since(new URL(request.url).searchParams.get("after"));
629
- server.send(JSON.stringify(missed ?? {
650
+ let missed = this.#since(new URL(request.url).searchParams.get("after")), message = missed ? this.#withPayloads(missed) : null;
651
+ server.send(JSON.stringify(message ?? {
630
652
  cursor: `${this.#epoch}:${this.#seq}`,
631
653
  events: []
632
654
  }));
@@ -662,7 +684,7 @@ var PreviewHub = class extends DurableObject {
662
684
  let deadline = Date.now() + 25e3;
663
685
  for (; !request.signal?.aborted;) {
664
686
  let message = this.#since(after);
665
- if (message) return json(message);
687
+ if (message) return json(this.#withPayloads(message));
666
688
  let left = deadline - Date.now();
667
689
  if (left <= 0) break;
668
690
  await new Promise((resolve) => {
@@ -696,6 +718,8 @@ var PreviewHub = class extends DurableObject {
696
718
  tags: syncTags ?? previous?.tags ?? [],
697
719
  docs: documentIds(result, params),
698
720
  local: previous?.local ?? "unknown",
721
+ mismatches: previous?.mismatches ?? 0,
722
+ retryAt: previous?.retryAt ?? 0,
699
723
  usedAt: Date.now()
700
724
  };
701
725
  this.#entries.set(key, entry);
@@ -703,7 +727,9 @@ var PreviewHub = class extends DurableObject {
703
727
  let keys = this.#byTag.get(tag);
704
728
  keys || this.#byTag.set(tag, keys = /* @__PURE__ */ new Set()), keys.add(key);
705
729
  }
706
- return this.#evict(), previous?.hash !== entry.hash;
730
+ this.#evict();
731
+ let changed = previous?.hash !== entry.hash;
732
+ return changed && entry.local === "off" && Date.now() >= entry.retryAt && (this.#verifyPending.add(key), this.#scheduleVerify()), changed;
707
733
  }
708
734
  #unindex(key, tags) {
709
735
  for (let tag of tags) {
@@ -739,9 +765,13 @@ var PreviewHub = class extends DurableObject {
739
765
  let entry = this.#entries.get(key);
740
766
  if (entry && entry.local !== "ok") try {
741
767
  let local = await this.#evaluateLocal(entry), matches = await hashJson(local) === entry.hash;
742
- entry.local = matches ? "ok" : "off", matches || (this.#lastVerifyNote = `${key} ${firstDifference(entry.result, local)}`.slice(0, 300), console.log("[preview-hub] local result differs; refetch only", key, firstDifference(entry.result, local)));
768
+ if (this.#entries.get(key) !== entry) {
769
+ this.#verifyPending.add(key), this.#scheduleVerify();
770
+ return;
771
+ }
772
+ matches ? (entry.local = "ok", entry.mismatches = 0, entry.retryAt = 0) : (markOff(entry), this.#lastVerifyNote = `${key} ${firstDifference(entry.result, local)}`.slice(0, 300), console.log("[preview-hub] local result differs; refetch only", key, firstDifference(entry.result, local)));
743
773
  } catch (error) {
744
- entry.local = "off", this.#lastVerifyNote = `${key} error ${String(error)}`.slice(0, 300), console.log("[preview-hub] local evaluation unsupported; refetch only", key, String(error));
774
+ markOff(entry), this.#lastVerifyNote = `${key} error ${String(error)}`.slice(0, 300), console.log("[preview-hub] local evaluation unsupported; refetch only", key, String(error));
745
775
  }
746
776
  }
747
777
  /**
@@ -781,7 +811,7 @@ var PreviewHub = class extends DurableObject {
781
811
  let result = await this.#evaluateLocal(entry);
782
812
  return await this.#store(key, entry.query, entry.params, result);
783
813
  } catch (error) {
784
- return entry.local = "off", console.warn("[preview-hub] local evaluation failed", key, error), !1;
814
+ return markOff(entry), console.warn("[preview-hub] local evaluation failed", key, error), !1;
785
815
  }
786
816
  }
787
817
  #restPending = /* @__PURE__ */ new Set();
@@ -858,7 +888,7 @@ var PreviewHub = class extends DurableObject {
858
888
  let connected = !1;
859
889
  return this.#follow("Listener", signal, () => {
860
890
  let url = this.#sanityUrl("listen");
861
- return url.searchParams.set("query", "*[_type != \"productVariant\" && !(_id in path(\"_.**\"))]"), url.searchParams.set("includeResult", "true"), url.searchParams.set("visibility", "transaction"), url.searchParams.set("includeAllVersions", "true"), url.searchParams.set("tag", "preview-hub"), { url };
891
+ return url.searchParams.set("query", this.#mirror.listenQuery), url.searchParams.set("includeResult", "true"), url.searchParams.set("visibility", "transaction"), url.searchParams.set("includeAllVersions", "true"), url.searchParams.set("tag", "preview-hub"), { url };
862
892
  }, (event) => {
863
893
  if (event.event === "welcome") connected && this.#resetLocal(), connected = !0;
864
894
  else if (event.event === "mutation") {
@@ -913,7 +943,7 @@ var PreviewHub = class extends DurableObject {
913
943
  }
914
944
  #resetLocal() {
915
945
  this.#mirror.clear();
916
- for (let [key, entry] of this.#entries) entry.local = "unknown", this.#verifyPending.add(key);
946
+ for (let [key, entry] of this.#entries) entry.local = "unknown", entry.mismatches = 0, entry.retryAt = 0, this.#verifyPending.add(key);
917
947
  this.#scheduleVerify();
918
948
  }
919
949
  #localQueued = !1;
@@ -974,19 +1004,11 @@ var PreviewHub = class extends DurableObject {
974
1004
  for (let wake of [...this.#waiters]) wake();
975
1005
  return;
976
1006
  }
977
- let results = {}, labels = {};
978
- for (let key of changed) {
979
- let names = this.#labels.get(key);
980
- names?.size && (labels[key] = [...names]);
981
- let entry = this.#entries.get(key);
982
- entry && JSON.stringify(entry.result ?? null).length <= 256e3 && (results[key] = entry.result ?? null);
983
- }
984
1007
  let message = JSON.stringify({
985
1008
  cursor: `${this.#epoch}:${seq}`,
986
1009
  events: [{
987
1010
  ...chunk,
988
- results,
989
- labels
1011
+ ...this.#payload(changed)
990
1012
  }]
991
1013
  });
992
1014
  for (let socket of this.#sockets) try {
@@ -996,6 +1018,40 @@ var PreviewHub = class extends DurableObject {
996
1018
  }
997
1019
  for (let wake of [...this.#waiters]) wake();
998
1020
  }
1021
+ /** The current results (under {@link MAX_PUSH_BYTES}) and labels of changed keys. */
1022
+ #payload(keys) {
1023
+ let results = {}, labels = {};
1024
+ for (let key of keys) {
1025
+ let names = this.#labels.get(key);
1026
+ names?.size && (labels[key] = [...names]);
1027
+ let entry = this.#entries.get(key);
1028
+ entry && JSON.stringify(entry.result ?? null).length <= 256e3 && (results[key] = entry.result ?? null);
1029
+ }
1030
+ return {
1031
+ results,
1032
+ labels
1033
+ };
1034
+ }
1035
+ /**
1036
+ * Logged events (keys alone) with payloads, for a tab catching up. Each key's current result
1037
+ * and labels go on the last event that names it: a tab applies events in order, and a later
1038
+ * event supersedes an earlier one. The log's events are not modified.
1039
+ */
1040
+ #withPayloads(message) {
1041
+ let seen = /* @__PURE__ */ new Set(), events = [];
1042
+ for (let i = message.events.length - 1; i >= 0; i--) {
1043
+ let event = message.events[i], keys = event.keys.filter((key) => !seen.has(key));
1044
+ for (let key of keys) seen.add(key);
1045
+ events.unshift({
1046
+ ...event,
1047
+ ...this.#payload(keys)
1048
+ });
1049
+ }
1050
+ return {
1051
+ ...message,
1052
+ events
1053
+ };
1054
+ }
999
1055
  #touch() {
1000
1056
  this.#lastActive = Date.now();
1001
1057
  }
@@ -1004,6 +1060,13 @@ var PreviewHub = class extends DurableObject {
1004
1060
  }
1005
1061
  };
1006
1062
  /**
1063
+ * Stop trusting a query's local evaluation (it differed from Sanity's result, or failed), and
1064
+ * back off before checking it again: {@link RETRY_BASE_MS}, doubling per miss.
1065
+ */
1066
+ function markOff(entry) {
1067
+ entry.local = "off", entry.mismatches++, entry.retryAt = Date.now() + Math.min(5e3 * 2 ** (entry.mismatches - 1), 3e5);
1068
+ }
1069
+ /**
1007
1070
  * Base IDs of every `_id` and `_ref` anywhere in a result, plus every string in the params
1008
1071
  * (`getSections({ id })` returns no `_id` of its own). A param that is not a document ID only
1009
1072
  * adds a name the mirror marks as missing.