sanity-plugin-visual-editor 1.0.0 → 1.1.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/LICENSE +1 -1
- package/README.md +137 -16
- package/TESTING.md +133 -0
- package/dist/PreviewBar-D_rw0bhP.js +3503 -0
- package/dist/PreviewBar-D_rw0bhP.js.map +1 -0
- package/dist/bar.d.ts +22 -0
- package/dist/bar.js +67 -0
- package/dist/bar.js.map +1 -0
- package/dist/cloudflare.d.ts +76 -0
- package/dist/cloudflare.js +1071 -0
- package/dist/cloudflare.js.map +1 -0
- package/dist/data-D0qotTtt.d.ts +177 -0
- package/dist/host-DreYJEmR.js +615 -0
- package/dist/host-DreYJEmR.js.map +1 -0
- package/dist/host.d.ts +160 -0
- package/dist/host.js +3 -0
- package/dist/index-4Zm_NjhC.d.ts +221 -0
- package/dist/index.d.ts +18 -18
- package/dist/index.js +7 -8
- package/dist/link-search-JtZkxz4k.js +14 -0
- package/dist/link-search-JtZkxz4k.js.map +1 -0
- package/dist/link-session-Dr4YkKFy.js +52 -0
- package/dist/link-session-Dr4YkKFy.js.map +1 -0
- package/dist/next-client.d.ts +15 -0
- package/dist/next-client.js +78 -0
- package/dist/next-client.js.map +1 -0
- package/dist/next.d.ts +38 -0
- package/dist/next.js +117 -0
- package/dist/next.js.map +1 -0
- package/dist/node-labels-CDiW5rMq.js +122 -0
- package/dist/node-labels-CDiW5rMq.js.map +1 -0
- package/dist/page-documents-BFFcH8lD.d.ts +54 -0
- package/dist/page-documents-mGfw_flR.js +67 -0
- package/dist/page-documents-mGfw_flR.js.map +1 -0
- package/dist/perspective-BmS9TVtr.js +106 -0
- package/dist/perspective-BmS9TVtr.js.map +1 -0
- package/dist/preview-links-BZDZyIey.js +119 -0
- package/dist/preview-links-BZDZyIey.js.map +1 -0
- package/dist/preview-links-DM6BCiLV.d.ts +87 -0
- package/dist/protocol-BNO38gYy.js +280 -0
- package/dist/protocol-BNO38gYy.js.map +1 -0
- package/dist/protocol-BnRCy2wJ.d.ts +386 -0
- package/dist/server.d.ts +4 -0
- package/dist/server.js +495 -0
- package/dist/server.js.map +1 -0
- package/dist/shell-DZotxRXX.d.ts +37 -0
- package/dist/studio.d.ts +93 -0
- package/dist/studio.js +1263 -0
- package/dist/studio.js.map +1 -0
- package/dist/sveltekit.d.ts +281 -0
- package/dist/sveltekit.js +395 -0
- package/dist/sveltekit.js.map +1 -0
- package/package.json +120 -39
- package/dist/index.d.mts +0 -21
- package/dist/index.js.map +0 -1
- package/dist/index.mjs +0 -8
- package/dist/index.mjs.map +0 -1
- package/sanity.json +0 -8
- package/src/index.ts +0 -27
- package/v2-incompatible.js +0 -11
|
@@ -0,0 +1,1071 @@
|
|
|
1
|
+
import { DurableObject } from "cloudflare:workers";
|
|
2
|
+
import { evaluate, parse } from "groq-js";
|
|
3
|
+
/**
|
|
4
|
+
* Index emulation for `groq-js`, which scans every document for each `*[…]`. A filter over `*`
|
|
5
|
+
* whose condition has a top-level conjunct `_id == "…"`, `_type == "…"` or `_type in [...]`
|
|
6
|
+
* (params are already inlined at parse time) gets its `*` replaced by a hidden parameter that
|
|
7
|
+
* holds just those documents. The full condition still runs on that list, so the result is the
|
|
8
|
+
* same; only documents that could never match are skipped. Lists keep the dataset's order.
|
|
9
|
+
*/
|
|
10
|
+
function useIndexes(tree) {
|
|
11
|
+
let indexes = /* @__PURE__ */ new Map();
|
|
12
|
+
return {
|
|
13
|
+
tree: rewrite$1(tree, indexes),
|
|
14
|
+
indexes: [...indexes.values()]
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
function rewrite$1(node, indexes) {
|
|
18
|
+
let copy = { ...node };
|
|
19
|
+
for (let [key, value] of Object.entries(node)) Array.isArray(value) ? copy[key] = value.map((item) => isNode$1(item) ? rewrite$1(item, indexes) : item) : isNode$1(value) && (copy[key] = rewrite$1(value, indexes));
|
|
20
|
+
if (copy.type !== "Filter" || copy.base.type !== "Everything") return copy;
|
|
21
|
+
let spec = indexFor(conjuncts(copy.expr));
|
|
22
|
+
if (!spec) return copy;
|
|
23
|
+
let param = `__index_${spec.kind}_${spec.values.join("|")}`;
|
|
24
|
+
return indexes.set(param, {
|
|
25
|
+
param,
|
|
26
|
+
...spec
|
|
27
|
+
}), {
|
|
28
|
+
...copy,
|
|
29
|
+
base: {
|
|
30
|
+
type: "Parameter",
|
|
31
|
+
name: param
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/** Top-level `&&` operands, through groups. */
|
|
36
|
+
function conjuncts(node) {
|
|
37
|
+
return node.type === "And" ? [...conjuncts(node.left), ...conjuncts(node.right)] : node.type === "Group" ? conjuncts(node.base) : [node];
|
|
38
|
+
}
|
|
39
|
+
function indexFor(nodes) {
|
|
40
|
+
let byType = null;
|
|
41
|
+
for (let node of nodes) {
|
|
42
|
+
if (node.type !== "OpCall") continue;
|
|
43
|
+
let field = attributeName(node.left);
|
|
44
|
+
if (node.op === "==" && field === "_id") {
|
|
45
|
+
let value = stringValue(node.right);
|
|
46
|
+
if (value !== null) return {
|
|
47
|
+
kind: "id",
|
|
48
|
+
values: [value]
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
if (!(field !== "_type" || byType)) {
|
|
52
|
+
if (node.op === "==") {
|
|
53
|
+
let value = stringValue(node.right);
|
|
54
|
+
value !== null && (byType = {
|
|
55
|
+
kind: "type",
|
|
56
|
+
values: [value]
|
|
57
|
+
});
|
|
58
|
+
} else if (node.op === "in") {
|
|
59
|
+
let values = stringArray(node.right);
|
|
60
|
+
values && (byType = {
|
|
61
|
+
kind: "type",
|
|
62
|
+
values
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return byType;
|
|
68
|
+
}
|
|
69
|
+
/** The name of an implicit attribute access (`_type`, not `foo._type`). */
|
|
70
|
+
function attributeName(node) {
|
|
71
|
+
return node.type === "AccessAttribute" && node.base === void 0 ? node.name : null;
|
|
72
|
+
}
|
|
73
|
+
function stringValue(node) {
|
|
74
|
+
return node.type === "Value" && typeof node.value == "string" ? node.value : null;
|
|
75
|
+
}
|
|
76
|
+
function stringArray(node) {
|
|
77
|
+
if (node.type !== "Array") return null;
|
|
78
|
+
let values = [];
|
|
79
|
+
for (let element of node.elements) {
|
|
80
|
+
if (element.isSplat) return null;
|
|
81
|
+
let value = stringValue(element.value);
|
|
82
|
+
if (value === null) return null;
|
|
83
|
+
values.push(value);
|
|
84
|
+
}
|
|
85
|
+
return values;
|
|
86
|
+
}
|
|
87
|
+
function isNode$1(value) {
|
|
88
|
+
return !!value && typeof value == "object" && typeof value.type == "string";
|
|
89
|
+
}
|
|
90
|
+
/** Node fields that open a new `@` scope: implicit attribute access inside them is not ours. */
|
|
91
|
+
const SCOPED = /* @__PURE__ */ new Set([
|
|
92
|
+
"Projection",
|
|
93
|
+
"Filter",
|
|
94
|
+
"Map",
|
|
95
|
+
"FlatMap"
|
|
96
|
+
]);
|
|
97
|
+
/**
|
|
98
|
+
* Make `groq-js` match a Sanity query-engine behaviour (observed 2026-11-23): Sanity fetches
|
|
99
|
+
* only the sub-fields a projection names, so when none of them exist the parent object counts as
|
|
100
|
+
* missing and `seo{title, description, image}` returns `null`, even though `seo` is an object
|
|
101
|
+
* (here `{url: …}`). `groq-js` returns `{title: null, …}`.
|
|
102
|
+
*
|
|
103
|
+
* Each projection over a non-document base becomes
|
|
104
|
+
* `select(count(base) != null || defined(base._id) || defined(base.f1) || … => base, null){…}`,
|
|
105
|
+
* where `f1…` are the fields the projection reads from `@`. Arrays and documents pass through
|
|
106
|
+
* unchanged; projections over document sets (`*[…]`) are left alone. The hub's verification gate
|
|
107
|
+
* still compares every query with Sanity before trusting it.
|
|
108
|
+
*/
|
|
109
|
+
function emulateSanityPruning(tree) {
|
|
110
|
+
return rewrite(tree);
|
|
111
|
+
}
|
|
112
|
+
function rewrite(node) {
|
|
113
|
+
let copy = { ...node };
|
|
114
|
+
for (let [key, value] of Object.entries(node)) Array.isArray(value) ? copy[key] = value.map((item) => isNode(item) ? rewrite(item) : item) : isNode(value) && (copy[key] = rewrite(value));
|
|
115
|
+
if (copy.type !== "Projection") return copy;
|
|
116
|
+
let base = copy.base, expr = copy.expr;
|
|
117
|
+
if (expr.type !== "Object" || containsEverything(base)) return copy;
|
|
118
|
+
let attributes = expr.attributes;
|
|
119
|
+
if (attributes.some((attribute) => attribute.type !== "ObjectAttributeValue")) return copy;
|
|
120
|
+
let fields = /* @__PURE__ */ new Set(), usesThis = !1;
|
|
121
|
+
for (let attribute of attributes) usesThis = collectFields(attribute.value, fields) || usesThis;
|
|
122
|
+
if (usesThis || !fields.size) return copy;
|
|
123
|
+
let condition = [{
|
|
124
|
+
type: "OpCall",
|
|
125
|
+
op: "!=",
|
|
126
|
+
left: {
|
|
127
|
+
type: "FuncCall",
|
|
128
|
+
namespace: "global",
|
|
129
|
+
name: "count",
|
|
130
|
+
args: [base]
|
|
131
|
+
},
|
|
132
|
+
right: {
|
|
133
|
+
type: "Value",
|
|
134
|
+
value: null
|
|
135
|
+
}
|
|
136
|
+
}, ...["_id", ...fields].map((name) => ({
|
|
137
|
+
type: "FuncCall",
|
|
138
|
+
namespace: "global",
|
|
139
|
+
name: "defined",
|
|
140
|
+
args: [{
|
|
141
|
+
type: "AccessAttribute",
|
|
142
|
+
base,
|
|
143
|
+
name
|
|
144
|
+
}]
|
|
145
|
+
}))].reduce((left, right) => ({
|
|
146
|
+
type: "Or",
|
|
147
|
+
left,
|
|
148
|
+
right
|
|
149
|
+
}));
|
|
150
|
+
return {
|
|
151
|
+
...copy,
|
|
152
|
+
base: {
|
|
153
|
+
type: "Select",
|
|
154
|
+
alternatives: [{
|
|
155
|
+
type: "SelectAlternative",
|
|
156
|
+
condition,
|
|
157
|
+
value: base
|
|
158
|
+
}],
|
|
159
|
+
fallback: {
|
|
160
|
+
type: "Value",
|
|
161
|
+
value: null
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Root fields read from `@` (implicit attribute access), not descending into new scopes.
|
|
168
|
+
* Returns whether `@` itself is read.
|
|
169
|
+
*/
|
|
170
|
+
function collectFields(node, fields) {
|
|
171
|
+
if (node.type === "AccessAttribute" && node.base === void 0) return fields.add(node.name), !1;
|
|
172
|
+
if (node.type === "This") return !0;
|
|
173
|
+
let usesThis = !1;
|
|
174
|
+
for (let [key, value] of Object.entries(node)) if (!(SCOPED.has(node.type) && key === "expr")) {
|
|
175
|
+
if (Array.isArray(value)) for (let item of value) isNode(item) && (usesThis = collectFields(item, fields) || usesThis);
|
|
176
|
+
else isNode(value) && (usesThis = collectFields(value, fields) || usesThis);
|
|
177
|
+
}
|
|
178
|
+
return usesThis;
|
|
179
|
+
}
|
|
180
|
+
function containsEverything(node) {
|
|
181
|
+
return node.type === "Everything" || Object.values(node).some((value) => Array.isArray(value) ? value.some((item) => isNode(item) && containsEverything(item)) : isNode(value) && containsEverything(value));
|
|
182
|
+
}
|
|
183
|
+
function isNode(value) {
|
|
184
|
+
return !!value && typeof value == "object" && typeof value.type == "string";
|
|
185
|
+
}
|
|
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.
|
|
190
|
+
*/
|
|
191
|
+
const ON_DEMAND_TYPES = ["product", "productVariant"], BASE_QUERY = `*[!(_type in ${JSON.stringify(ON_DEMAND_TYPES)}) && !(_id in path("_.**"))]`;
|
|
192
|
+
/** Strip the `drafts.` or `versions.<release>.` prefix so every variant maps to one ID. */
|
|
193
|
+
function baseId(id) {
|
|
194
|
+
return id.replace(/^drafts\./, "").replace(/^versions\.[^.]+\./, "");
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* A local copy of the documents preview queries read (raw: published, `drafts.` and
|
|
198
|
+
* `versions.` IDs), kept current from `/listen` mutation results. It evaluates GROQ with
|
|
199
|
+
* `groq-js` against a perspective view built here, since `groq-js` has no perspectives.
|
|
200
|
+
*
|
|
201
|
+
* Production CPU is much slower than a laptop (2026-11-23: rebuilding the view took 0.2–0.55 s and
|
|
202
|
+
* a page query with a product scan ~3 s), so views update one document at a time, and scans
|
|
203
|
+
* filtered by `_type` or `_id` read precomputed lists instead of every document (`indexes.ts`).
|
|
204
|
+
*/
|
|
205
|
+
var Mirror = class {
|
|
206
|
+
#docs = /* @__PURE__ */ new Map();
|
|
207
|
+
/** Base ID → release name → version document. */
|
|
208
|
+
#versions = /* @__PURE__ */ new Map();
|
|
209
|
+
/** Base IDs of on-demand (product) documents the mirror tracks. */
|
|
210
|
+
#tracked = /* @__PURE__ */ new Set();
|
|
211
|
+
/** Base IDs known not to exist, so they are not fetched again for every evaluation. */
|
|
212
|
+
#missing = /* @__PURE__ */ new Set();
|
|
213
|
+
/**
|
|
214
|
+
* Unsaved Studio edits (LF-INIT-21), keyed by draft or version ID. They sit above the saved
|
|
215
|
+
* document until the saved content catches up, or until they go stale.
|
|
216
|
+
*/
|
|
217
|
+
#overlays = /* @__PURE__ */ new Map();
|
|
218
|
+
#trees = /* @__PURE__ */ new Map();
|
|
219
|
+
#views = /* @__PURE__ */ new Map();
|
|
220
|
+
#ready = null;
|
|
221
|
+
#fetchRaw;
|
|
222
|
+
#loaded = !1;
|
|
223
|
+
constructor(fetchRaw) {
|
|
224
|
+
this.#fetchRaw = fetchRaw;
|
|
225
|
+
}
|
|
226
|
+
get loaded() {
|
|
227
|
+
return this.#loaded;
|
|
228
|
+
}
|
|
229
|
+
/** Load every non-product document once. Concurrent callers share one load. */
|
|
230
|
+
ready() {
|
|
231
|
+
return this.#ready ??= (async () => {
|
|
232
|
+
let docs = await this.#fetchRaw(BASE_QUERY);
|
|
233
|
+
for (let doc of docs) this.#put(doc);
|
|
234
|
+
this.#views.clear(), this.#loaded = !0;
|
|
235
|
+
})().catch((error) => {
|
|
236
|
+
throw this.#ready = null, error;
|
|
237
|
+
}), this.#ready;
|
|
238
|
+
}
|
|
239
|
+
clear() {
|
|
240
|
+
this.#overlays.clear(), this.#docs.clear(), this.#versions.clear(), this.#tracked.clear(), this.#missing.clear(), this.#views.clear(), this.#ready = null, this.#loaded = !1;
|
|
241
|
+
}
|
|
242
|
+
/** Fetch the published and draft variants of any base IDs the mirror lacks. */
|
|
243
|
+
async ensure(ids) {
|
|
244
|
+
let wanted = ids.filter((id) => !this.#knows(id));
|
|
245
|
+
if (!wanted.length) return;
|
|
246
|
+
let docs = await this.#fetchRaw("*[_id in $ids]", { ids: wanted.flatMap((id) => [id, `drafts.${id}`]) }), found = /* @__PURE__ */ new Set();
|
|
247
|
+
for (let doc of docs) {
|
|
248
|
+
let base = baseId(doc._id);
|
|
249
|
+
found.add(base), this.#put(doc), doc._type && ON_DEMAND_TYPES.includes(doc._type) && this.#tracked.add(base);
|
|
250
|
+
}
|
|
251
|
+
for (let id of wanted) found.has(id) || this.#missing.add(id);
|
|
252
|
+
for (let base of found) this.#refresh(base);
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Apply one `/listen` mutation (`includeResult=true`). Returns whether the mirror changed.
|
|
256
|
+
* Products the mirror does not track are ignored.
|
|
257
|
+
*/
|
|
258
|
+
apply(documentId, result, transition) {
|
|
259
|
+
let base = baseId(documentId);
|
|
260
|
+
if (transition === "disappear" || !result) {
|
|
261
|
+
if (!this.#remove(documentId)) return !1;
|
|
262
|
+
} else {
|
|
263
|
+
if (result._type && ON_DEMAND_TYPES.includes(result._type) && !this.#tracked.has(base)) return !1;
|
|
264
|
+
this.#put(result), this.#missing.delete(base);
|
|
265
|
+
}
|
|
266
|
+
let overlay = this.#overlays.get(documentId);
|
|
267
|
+
return overlay && (!result || transition === "disappear" || sameContent(overlay.doc, result)) && this.#overlays.delete(documentId), this.#refresh(base), !0;
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Show an unsaved Studio edit in place of the saved draft or version. `seq` orders updates
|
|
271
|
+
* from one editor; an older one is ignored. Returns whether the mirror changed.
|
|
272
|
+
*/
|
|
273
|
+
overlay(doc, seq, now = Date.now()) {
|
|
274
|
+
if (!/^(drafts|versions)\./.test(doc._id)) return !1;
|
|
275
|
+
let base = baseId(doc._id);
|
|
276
|
+
if (doc._type && ON_DEMAND_TYPES.includes(doc._type) && !this.#tracked.has(base)) return !1;
|
|
277
|
+
let current = this.#overlays.get(doc._id);
|
|
278
|
+
return current && current.seq >= seq ? !1 : (this.#overlays.set(doc._id, {
|
|
279
|
+
doc,
|
|
280
|
+
seq,
|
|
281
|
+
at: now
|
|
282
|
+
}), this.#refresh(base), !0);
|
|
283
|
+
}
|
|
284
|
+
/** Drop overlays with no update for `ttl` ms. Returns the base IDs that changed. */
|
|
285
|
+
expireOverlays(ttl, now = Date.now()) {
|
|
286
|
+
let expired = [];
|
|
287
|
+
for (let [id, overlay] of this.#overlays) {
|
|
288
|
+
if (now - overlay.at < ttl) continue;
|
|
289
|
+
this.#overlays.delete(id);
|
|
290
|
+
let base = baseId(id);
|
|
291
|
+
this.#refresh(base), expired.push(base);
|
|
292
|
+
}
|
|
293
|
+
return expired;
|
|
294
|
+
}
|
|
295
|
+
get overlayCount() {
|
|
296
|
+
return this.#overlays.size;
|
|
297
|
+
}
|
|
298
|
+
/** Whether any of these base IDs currently show unsaved edits. */
|
|
299
|
+
overlaid(ids) {
|
|
300
|
+
if (!this.#overlays.size) return !1;
|
|
301
|
+
let bases = new Set([...this.#overlays.keys()].map(baseId));
|
|
302
|
+
return ids.some((id) => bases.has(id));
|
|
303
|
+
}
|
|
304
|
+
/** Base IDs referenced (`_ref`) by any variant of the given documents. */
|
|
305
|
+
referencesOf(ids) {
|
|
306
|
+
let found = /* @__PURE__ */ new Set(), walk = (value) => {
|
|
307
|
+
if (Array.isArray(value)) value.forEach(walk);
|
|
308
|
+
else if (value && typeof value == "object") for (let [field, child] of Object.entries(value)) field === "_ref" && typeof child == "string" ? found.add(baseId(child)) : walk(child);
|
|
309
|
+
};
|
|
310
|
+
for (let id of ids) for (let doc of this.#variants(id)) walk(doc);
|
|
311
|
+
return [...found];
|
|
312
|
+
}
|
|
313
|
+
/** Debug: rebuild one perspective view from scratch. */
|
|
314
|
+
benchView(perspective) {
|
|
315
|
+
this.#views.delete(perspective), this.#lists(this.#view(perspective));
|
|
316
|
+
}
|
|
317
|
+
/** Whether every ID is in the mirror (or known not to exist). */
|
|
318
|
+
covers(ids) {
|
|
319
|
+
return ids.every((id) => this.#knows(id));
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* 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.
|
|
324
|
+
*/
|
|
325
|
+
async evaluate(query, params, perspective) {
|
|
326
|
+
let { tree, indexes } = this.#parse(query, params), view = this.#view(perspective), lists = this.#lists(view), indexParams = {};
|
|
327
|
+
for (let index of indexes) if (index.kind === "id") {
|
|
328
|
+
let doc = view.byId.get(index.values[0]);
|
|
329
|
+
indexParams[index.param] = doc ? [doc] : [];
|
|
330
|
+
} else if (index.values.length === 1) indexParams[index.param] = lists.byType.get(index.values[0]) ?? [];
|
|
331
|
+
else {
|
|
332
|
+
let types = new Set(index.values);
|
|
333
|
+
indexParams[index.param] = lists.docs.filter((doc) => types.has(doc._type ?? ""));
|
|
334
|
+
}
|
|
335
|
+
return (await evaluate(tree, {
|
|
336
|
+
dataset: lists.docs,
|
|
337
|
+
params: {
|
|
338
|
+
...params,
|
|
339
|
+
...indexParams
|
|
340
|
+
},
|
|
341
|
+
dereference: async ({ _ref }) => {
|
|
342
|
+
let id = baseId(_ref), known = view.byId.get(id);
|
|
343
|
+
return known || this.#missing.has(id) ? known ?? null : (await this.ensure([id]), view.byId.get(id) ?? null);
|
|
344
|
+
}
|
|
345
|
+
})).get();
|
|
346
|
+
}
|
|
347
|
+
#parse(query, params) {
|
|
348
|
+
let key = JSON.stringify([query, params]), parsed = this.#trees.get(key);
|
|
349
|
+
return parsed || (parsed = useIndexes(emulateSanityPruning(parse(query, { params }))), this.#trees.size > 1e3 && this.#trees.clear(), this.#trees.set(key, parsed)), parsed;
|
|
350
|
+
}
|
|
351
|
+
#knows(id) {
|
|
352
|
+
return this.#missing.has(id) || this.#docs.has(id) || this.#docs.has(`drafts.${id}`);
|
|
353
|
+
}
|
|
354
|
+
#put(doc) {
|
|
355
|
+
if (this.#docs.set(doc._id, doc), doc._id.startsWith("versions.")) {
|
|
356
|
+
let base = baseId(doc._id), versions = this.#versions.get(base);
|
|
357
|
+
versions || this.#versions.set(base, versions = /* @__PURE__ */ new Map()), versions.set(doc._id.split(".")[1], doc);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
#remove(id) {
|
|
361
|
+
return this.#docs.delete(id) ? (id.startsWith("versions.") && this.#versions.get(baseId(id))?.delete(id.split(".")[1]), !0) : !1;
|
|
362
|
+
}
|
|
363
|
+
#variants(base) {
|
|
364
|
+
let docs = [], published = this.#docs.get(base), draft = this.#overlays.get(`drafts.${base}`)?.doc ?? this.#docs.get(`drafts.${base}`);
|
|
365
|
+
published && docs.push(published), draft && docs.push(draft);
|
|
366
|
+
for (let version of this.#versions.get(base)?.values() ?? []) docs.push(version);
|
|
367
|
+
for (let [id, overlay] of this.#overlays) id.startsWith("versions.") && baseId(id) === base && docs.push(overlay.doc);
|
|
368
|
+
return docs;
|
|
369
|
+
}
|
|
370
|
+
/** The document a perspective sees for one base ID, or `undefined`. */
|
|
371
|
+
#choose(base, stack) {
|
|
372
|
+
let chosen, versions = this.#versions.get(base);
|
|
373
|
+
for (let release of stack.releases) chosen ??= this.#overlays.get(`versions.${release}.${base}`)?.doc ?? versions?.get(release);
|
|
374
|
+
return stack.withDrafts && (chosen ??= this.#overlays.get(`drafts.${base}`)?.doc ?? this.#docs.get(`drafts.${base}`)), chosen ??= this.#docs.get(base), chosen && {
|
|
375
|
+
...chosen,
|
|
376
|
+
_id: base,
|
|
377
|
+
_originalId: chosen._id
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
/** Re-choose one base ID in every built view. */
|
|
381
|
+
#refresh(base) {
|
|
382
|
+
for (let view of this.#views.values()) {
|
|
383
|
+
let doc = this.#choose(base, view.stack);
|
|
384
|
+
doc ? view.byId.set(base, doc) : view.byId.delete(base), view.docs = null, view.byType = null;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* The documents as a perspective sees them: per base ID, the first of the release versions
|
|
389
|
+
* (in stack order), the draft (if `drafts` is in the stack) and the published document, with
|
|
390
|
+
* `_id` set to the base ID and `_originalId` to the document chosen.
|
|
391
|
+
*/
|
|
392
|
+
#view(perspective) {
|
|
393
|
+
let cached = this.#views.get(perspective);
|
|
394
|
+
if (cached) return cached;
|
|
395
|
+
let names = perspective.split(","), stack = {
|
|
396
|
+
releases: names.filter((name) => name !== "drafts" && name !== "published"),
|
|
397
|
+
withDrafts: names.includes("drafts")
|
|
398
|
+
}, view = {
|
|
399
|
+
stack,
|
|
400
|
+
byId: /* @__PURE__ */ new Map(),
|
|
401
|
+
docs: null,
|
|
402
|
+
byType: null
|
|
403
|
+
}, seen = /* @__PURE__ */ new Set();
|
|
404
|
+
for (let id of this.#docs.keys()) {
|
|
405
|
+
let base = baseId(id);
|
|
406
|
+
if (seen.has(base)) continue;
|
|
407
|
+
seen.add(base);
|
|
408
|
+
let doc = this.#choose(base, stack);
|
|
409
|
+
doc && view.byId.set(base, doc);
|
|
410
|
+
}
|
|
411
|
+
return this.#views.set(perspective, view), view;
|
|
412
|
+
}
|
|
413
|
+
#lists(view) {
|
|
414
|
+
if (!view.docs || !view.byType) {
|
|
415
|
+
view.docs = [...view.byId.values()], view.byType = /* @__PURE__ */ new Map();
|
|
416
|
+
for (let doc of view.docs) {
|
|
417
|
+
let type = doc._type ?? "", list = view.byType.get(type);
|
|
418
|
+
list || view.byType.set(type, list = []), list.push(doc);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
return {
|
|
422
|
+
docs: view.docs,
|
|
423
|
+
byType: view.byType
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
};
|
|
427
|
+
/** System fields that differ between the Studio's form value and the saved document. */
|
|
428
|
+
const SYSTEM_FIELDS = /* @__PURE__ */ new Set([
|
|
429
|
+
"_rev",
|
|
430
|
+
"_updatedAt",
|
|
431
|
+
"_createdAt",
|
|
432
|
+
"_system",
|
|
433
|
+
"_originalId"
|
|
434
|
+
]);
|
|
435
|
+
/** Whether two documents hold the same content, ignoring system fields and key order. */
|
|
436
|
+
function sameContent(a, b) {
|
|
437
|
+
let canonical = (doc) => JSON.stringify(Object.fromEntries(Object.entries(doc).filter(([key]) => !SYSTEM_FIELDS.has(key))), (_key, value) => value && typeof value == "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).sort(([x], [y]) => x < y ? -1 : +(x > y))) : value);
|
|
438
|
+
return canonical(a) === canonical(b);
|
|
439
|
+
}
|
|
440
|
+
/** Parse a `text/event-stream` body into events. Comments and `retry:` lines are skipped. */
|
|
441
|
+
async function* parseSse(body) {
|
|
442
|
+
let reader = body.pipeThrough(new TextDecoderStream()).getReader(), buffer = "";
|
|
443
|
+
try {
|
|
444
|
+
for (;;) {
|
|
445
|
+
let { done, value } = await reader.read();
|
|
446
|
+
if (done) return;
|
|
447
|
+
buffer += value.replace(/\r\n?/g, "\n");
|
|
448
|
+
let boundary;
|
|
449
|
+
for (; (boundary = buffer.indexOf("\n\n")) !== -1;) {
|
|
450
|
+
let block = buffer.slice(0, boundary);
|
|
451
|
+
buffer = buffer.slice(boundary + 2);
|
|
452
|
+
let event = parseBlock(block);
|
|
453
|
+
event && (yield event);
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
} finally {
|
|
457
|
+
reader.releaseLock();
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
function parseBlock(block) {
|
|
461
|
+
let id, event = "message", data = [];
|
|
462
|
+
for (let line of block.split("\n")) {
|
|
463
|
+
if (!line || line.startsWith(":")) continue;
|
|
464
|
+
let colon = line.indexOf(":"), field = colon === -1 ? line : line.slice(0, colon), value = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "");
|
|
465
|
+
field === "id" ? id = value : field === "event" ? event = value : field === "data" && data.push(value);
|
|
466
|
+
}
|
|
467
|
+
return !data.length && !id && event === "message" ? null : {
|
|
468
|
+
id,
|
|
469
|
+
event,
|
|
470
|
+
data: data.join("\n")
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
var PreviewHub = class extends DurableObject {
|
|
474
|
+
#entries = /* @__PURE__ */ new Map();
|
|
475
|
+
#byTag = /* @__PURE__ */ new Map();
|
|
476
|
+
#inflight = /* @__PURE__ */ new Map();
|
|
477
|
+
#recentEvents = [];
|
|
478
|
+
#mirror = new Mirror((query, params) => this.#fetchRaw(query, params));
|
|
479
|
+
#lastMutationAt = 0;
|
|
480
|
+
#lastVerifyNote = "";
|
|
481
|
+
/** Upstream stream health, for diagnostics. */
|
|
482
|
+
#streamStatus = {};
|
|
483
|
+
/** Base IDs mutated since the last local flush. */
|
|
484
|
+
#editedDocs = /* @__PURE__ */ new Set();
|
|
485
|
+
#upstream = null;
|
|
486
|
+
#lastEventId = null;
|
|
487
|
+
#idleTimer = null;
|
|
488
|
+
#lastActive = Date.now();
|
|
489
|
+
#pendingTags = /* @__PURE__ */ new Set();
|
|
490
|
+
#flushTimer = null;
|
|
491
|
+
#localTimer = null;
|
|
492
|
+
/** Independent task chains, so local updates never wait behind Sanity fetches. */
|
|
493
|
+
#chains = {
|
|
494
|
+
local: Promise.resolve(),
|
|
495
|
+
sweep: Promise.resolve(),
|
|
496
|
+
verify: Promise.resolve()
|
|
497
|
+
};
|
|
498
|
+
/** Long polls waiting right now. */
|
|
499
|
+
#polling = 0;
|
|
500
|
+
/** Wakes the waiting long polls when the log grows. */
|
|
501
|
+
#waiters = /* @__PURE__ */ new Set();
|
|
502
|
+
/** Tabs following this hub over a WebSocket. */
|
|
503
|
+
#sockets = /* @__PURE__ */ new Set();
|
|
504
|
+
/** The storefront remote queries (labels) that read each held query, by key. */
|
|
505
|
+
#labels = /* @__PURE__ */ new Map();
|
|
506
|
+
#label(key, label) {
|
|
507
|
+
let labels = this.#labels.get(key);
|
|
508
|
+
labels || this.#labels.set(key, labels = /* @__PURE__ */ new Set()), labels.size < 32 && labels.add(label);
|
|
509
|
+
}
|
|
510
|
+
/** Changes on every instance start, so a `Last-Event-ID` from before a restart is recognised. */
|
|
511
|
+
#epoch = crypto.randomUUID().slice(0, 8);
|
|
512
|
+
#seq = 0;
|
|
513
|
+
#log = [];
|
|
514
|
+
/** The instance name is `<perspective>|<deployed version id>`; see the default export. */
|
|
515
|
+
get #perspective() {
|
|
516
|
+
return (this.ctx.id.name ?? "drafts").split("|")[0];
|
|
517
|
+
}
|
|
518
|
+
/** Run a GROQ query in this hub's perspective, from memory when the hub already holds it. */
|
|
519
|
+
async query(query, params = {}, label) {
|
|
520
|
+
this.#touch(), this.#ensureUpstream(), this.#mirror.loaded || this.#mirror.ready().catch(() => {}), this.#verifyPending.size && this.#scheduleVerify();
|
|
521
|
+
let key = await fingerprint(query, params);
|
|
522
|
+
label && this.#label(key, label);
|
|
523
|
+
let entry = this.#entries.get(key);
|
|
524
|
+
if (entry) return entry.usedAt = Date.now(), entry.result;
|
|
525
|
+
let pending = this.#inflight.get(key);
|
|
526
|
+
return pending || (pending = this.#load(key, query, params).finally(() => this.#inflight.delete(key)), this.#inflight.set(key, pending)), await pending;
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* - `POST /query` `{ query, params, label? }` → `{ result }`. `label` names the storefront's
|
|
530
|
+
* remote query reading it; events for the query carry it back. The storefront uses this rather than the
|
|
531
|
+
* `query()` RPC method because Vite dev's platform proxy cannot carry Durable Object RPC.
|
|
532
|
+
* - `GET /socket` (WebSocket upgrade) → invalidation events, pushed as they happen.
|
|
533
|
+
* - `GET /events` → the same events by long poll, for tabs without a WebSocket.
|
|
534
|
+
* - `GET /stats` → entry counts by local state and timings, for debugging.
|
|
535
|
+
*/
|
|
536
|
+
async fetch(request) {
|
|
537
|
+
let url = new URL(request.url);
|
|
538
|
+
if (url.pathname === "/query" && request.method === "POST") {
|
|
539
|
+
let { query, params, label } = await request.json(), name = typeof label == "string" && label.length <= 2e3 ? label : void 0;
|
|
540
|
+
return Response.json({ result: await this.query(query, params ?? {}, name) });
|
|
541
|
+
}
|
|
542
|
+
if (url.pathname === "/stats") {
|
|
543
|
+
let local = {
|
|
544
|
+
unknown: 0,
|
|
545
|
+
ok: 0,
|
|
546
|
+
off: 0
|
|
547
|
+
};
|
|
548
|
+
for (let entry of this.#entries.values()) local[entry.local]++;
|
|
549
|
+
return Response.json({
|
|
550
|
+
entries: this.#entries.size,
|
|
551
|
+
local,
|
|
552
|
+
polling: this.#polling,
|
|
553
|
+
sockets: this.#sockets.size,
|
|
554
|
+
mirror: this.#mirror.loaded,
|
|
555
|
+
lastLocalFlush: this.#lastLocalFlush,
|
|
556
|
+
upstream: this.#streamStatus,
|
|
557
|
+
lastVerifyNote: this.#lastVerifyNote
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
if (url.pathname === "/socket") return this.#socket(request);
|
|
561
|
+
if (url.pathname === "/events") return this.#poll(request);
|
|
562
|
+
if (url.pathname === "/overlay" && request.method === "POST") {
|
|
563
|
+
let { document, seq } = await request.json();
|
|
564
|
+
return Response.json({ applied: await this.#applyOverlay(document, seq) });
|
|
565
|
+
}
|
|
566
|
+
if (url.pathname === "/bench") {
|
|
567
|
+
let key = url.searchParams.get("key");
|
|
568
|
+
if (url.searchParams.has("view")) return await this.#mirror.ready(), this.#mirror.benchView(this.#perspective), Response.json({ view: !0 });
|
|
569
|
+
let entry = key ? this.#entries.get(key) : void 0;
|
|
570
|
+
if (!entry) return Response.json({ keys: [...this.#entries].map(([k, e]) => ({
|
|
571
|
+
key: k,
|
|
572
|
+
local: e.local,
|
|
573
|
+
query: e.query.length
|
|
574
|
+
})) });
|
|
575
|
+
let result = await this.#evaluateLocal(entry);
|
|
576
|
+
return Response.json({
|
|
577
|
+
key,
|
|
578
|
+
bytes: JSON.stringify(result)?.length ?? 0
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
return new Response("Not found", { status: 404 });
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* What a tab at cursor `after` has missed: `{ cursor, events }`, `reset` when the cursor is from
|
|
585
|
+
* another instance (the hub restarted or was redeployed) or older than the log (refresh
|
|
586
|
+
* everything), or `null` when it is up to date. Without a cursor, the current one, so a new tab
|
|
587
|
+
* starts from now.
|
|
588
|
+
*/
|
|
589
|
+
#since(after) {
|
|
590
|
+
let current = `${this.#epoch}:${this.#seq}`;
|
|
591
|
+
if (!after) return {
|
|
592
|
+
cursor: current,
|
|
593
|
+
events: []
|
|
594
|
+
};
|
|
595
|
+
let [epoch, raw] = after.split(":"), seq = Number(raw), oldest = this.#log[0]?.seq ?? this.#seq + 1;
|
|
596
|
+
if (epoch !== this.#epoch || !Number.isInteger(seq) || seq < this.#seq && seq + 1 < oldest) return {
|
|
597
|
+
cursor: current,
|
|
598
|
+
events: [],
|
|
599
|
+
reset: !0
|
|
600
|
+
};
|
|
601
|
+
let events = this.#log.filter((event) => event.seq > seq);
|
|
602
|
+
return events.length ? {
|
|
603
|
+
cursor: `${this.#epoch}:${events[events.length - 1].seq}`,
|
|
604
|
+
events: events.map((e) => e.chunk)
|
|
605
|
+
} : null;
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* WebSocket: `GET /socket?after=<cursor>` sends what the tab missed (or its starting cursor),
|
|
609
|
+
* then each event as {@link #publish} logs it, with no request to wait for. The tab sends
|
|
610
|
+
* `ping` every 20 s to keep the connection open through proxies; the hub answers `pong`.
|
|
611
|
+
*
|
|
612
|
+
* Plain `accept()` rather than hibernation: a hub with open sockets stays in memory with its
|
|
613
|
+
* caches and upstream streams, as it does for waiting long polls.
|
|
614
|
+
*/
|
|
615
|
+
#socket(request) {
|
|
616
|
+
if (request.headers.get("upgrade")?.toLowerCase() !== "websocket") return new Response("Expected a WebSocket", { status: 426 });
|
|
617
|
+
this.#touch();
|
|
618
|
+
let { 0: client, 1: server } = new WebSocketPair();
|
|
619
|
+
server.accept();
|
|
620
|
+
let edits = request.headers.get("x-live-edit") === "1";
|
|
621
|
+
edits || this.#sockets.add(server);
|
|
622
|
+
let close = () => {
|
|
623
|
+
this.#sockets.delete(server), this.#touch();
|
|
624
|
+
};
|
|
625
|
+
if (server.addEventListener("close", close), server.addEventListener("error", close), server.addEventListener("message", (event) => {
|
|
626
|
+
event.data === "ping" ? server.send("pong") : edits && typeof event.data == "string" && this.#receiveEdit(event.data);
|
|
627
|
+
}), !edits) {
|
|
628
|
+
let missed = this.#since(new URL(request.url).searchParams.get("after"));
|
|
629
|
+
server.send(JSON.stringify(missed ?? {
|
|
630
|
+
cursor: `${this.#epoch}:${this.#seq}`,
|
|
631
|
+
events: []
|
|
632
|
+
}));
|
|
633
|
+
}
|
|
634
|
+
return new Response(null, {
|
|
635
|
+
status: 101,
|
|
636
|
+
webSocket: client
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
/** An unsaved Studio edit sent over a live-edit socket: `{ document, seq }`, a draft. */
|
|
640
|
+
async #receiveEdit(data) {
|
|
641
|
+
if (!(data.length > 1e6 || this.#perspective !== "drafts")) try {
|
|
642
|
+
let { document, seq } = JSON.parse(data);
|
|
643
|
+
if (typeof document?._id != "string" || !document._id.startsWith("drafts.") || typeof seq != "number") return;
|
|
644
|
+
await this.#applyOverlay(document, seq);
|
|
645
|
+
} catch (error) {
|
|
646
|
+
console.warn("[preview-hub] live edit failed", error);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* Long poll: `GET /events?after=<cursor>` answers as soon as the log has events after the
|
|
651
|
+
* cursor (see {@link #since}), or with none after {@link POLL_TIMEOUT_MS}.
|
|
652
|
+
*
|
|
653
|
+
* The request stays inside this handler until {@link #publish} wakes it. A streaming response
|
|
654
|
+
* does not work here: once a handler has returned its `Response`, Workers did not run its
|
|
655
|
+
* timers or flush its writes promptly, and SSE events reached tabs 0.7–4 s late (2026-11-23).
|
|
656
|
+
*/
|
|
657
|
+
async #poll(request) {
|
|
658
|
+
this.#touch();
|
|
659
|
+
let after = new URL(request.url).searchParams.get("after"), json = (body) => Response.json(body, { headers: { "cache-control": "no-store, no-transform" } });
|
|
660
|
+
this.#polling++;
|
|
661
|
+
try {
|
|
662
|
+
let deadline = Date.now() + 25e3;
|
|
663
|
+
for (; !request.signal?.aborted;) {
|
|
664
|
+
let message = this.#since(after);
|
|
665
|
+
if (message) return json(message);
|
|
666
|
+
let left = deadline - Date.now();
|
|
667
|
+
if (left <= 0) break;
|
|
668
|
+
await new Promise((resolve) => {
|
|
669
|
+
let wake = () => {
|
|
670
|
+
clearTimeout(timer), this.#waiters.delete(wake), resolve();
|
|
671
|
+
}, timer = setTimeout(wake, left);
|
|
672
|
+
this.#waiters.add(wake), request.signal?.addEventListener("abort", wake, { once: !0 });
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
return json({
|
|
676
|
+
cursor: after,
|
|
677
|
+
events: []
|
|
678
|
+
});
|
|
679
|
+
} finally {
|
|
680
|
+
this.#polling--, this.#touch();
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
async #load(key, query, params) {
|
|
684
|
+
let startedAt = Date.now(), response = await this.#fetchSanity(query, params);
|
|
685
|
+
return this.#recentEvents.some((event) => event.at >= startedAt && event.tags.some((tag) => response.syncTags?.includes(tag))) && (response = await this.#fetchSanity(query, params)), await this.#store(key, query, params, response.result, response.syncTags), this.#verifyPending.add(key), this.#scheduleVerify(), response.result;
|
|
686
|
+
}
|
|
687
|
+
/** Store a result. Returns whether its hash changed. `tags` defaults to the previous ones. */
|
|
688
|
+
async #store(key, query, params, result, syncTags) {
|
|
689
|
+
let previous = this.#entries.get(key);
|
|
690
|
+
previous && this.#unindex(key, previous.tags);
|
|
691
|
+
let entry = {
|
|
692
|
+
query,
|
|
693
|
+
params,
|
|
694
|
+
result,
|
|
695
|
+
hash: await hashJson(result),
|
|
696
|
+
tags: syncTags ?? previous?.tags ?? [],
|
|
697
|
+
docs: documentIds(result, params),
|
|
698
|
+
local: previous?.local ?? "unknown",
|
|
699
|
+
usedAt: Date.now()
|
|
700
|
+
};
|
|
701
|
+
this.#entries.set(key, entry);
|
|
702
|
+
for (let tag of entry.tags) {
|
|
703
|
+
let keys = this.#byTag.get(tag);
|
|
704
|
+
keys || this.#byTag.set(tag, keys = /* @__PURE__ */ new Set()), keys.add(key);
|
|
705
|
+
}
|
|
706
|
+
return this.#evict(), previous?.hash !== entry.hash;
|
|
707
|
+
}
|
|
708
|
+
#unindex(key, tags) {
|
|
709
|
+
for (let tag of tags) {
|
|
710
|
+
let keys = this.#byTag.get(tag);
|
|
711
|
+
keys?.delete(key), keys && !keys.size && this.#byTag.delete(tag);
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
#evict() {
|
|
715
|
+
if (this.#entries.size <= 500) return;
|
|
716
|
+
let oldest = [...this.#entries].sort((a, b) => a[1].usedAt - b[1].usedAt);
|
|
717
|
+
for (let [key, entry] of oldest.slice(0, this.#entries.size - 500)) this.#unindex(key, entry.tags), this.#entries.delete(key);
|
|
718
|
+
}
|
|
719
|
+
/** Run hub work one task at a time per chain; the chains run independently. */
|
|
720
|
+
#queue(chain, task) {
|
|
721
|
+
this.#chains[chain] = this.#chains[chain].then(task).catch((error) => {
|
|
722
|
+
console.warn(`[preview-hub] ${chain} task failed`, error);
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
/** Evaluate a query locally; `null` when the mirror cannot answer it. */
|
|
726
|
+
async #evaluateLocal(entry) {
|
|
727
|
+
await this.#mirror.ready(), await this.#mirror.ensure(entry.docs), await this.#mirror.ensure(this.#mirror.referencesOf(entry.docs));
|
|
728
|
+
let result = await this.#mirror.evaluate(entry.query, entry.params, this.#perspective), ids = documentIds(result, entry.params);
|
|
729
|
+
return this.#mirror.covers(ids) || (await this.#mirror.ensure(ids), result = await this.#mirror.evaluate(entry.query, entry.params, this.#perspective)), result;
|
|
730
|
+
}
|
|
731
|
+
/** Trust a query's local evaluation only if it reproduces Sanity's result exactly. */
|
|
732
|
+
async #verify(key) {
|
|
733
|
+
let overlaid = this.#entries.get(key);
|
|
734
|
+
if (overlaid && this.#mirror.overlaid(overlaid.docs)) {
|
|
735
|
+
this.#verifyPending.add(key), this.#scheduleVerify();
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
if (this.env.LOCAL_EVAL === "off") return;
|
|
739
|
+
let entry = this.#entries.get(key);
|
|
740
|
+
if (entry && entry.local !== "ok") try {
|
|
741
|
+
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)));
|
|
743
|
+
} 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));
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
/**
|
|
748
|
+
* After mirror mutations: re-evaluate the trusted queries whose results name an edited
|
|
749
|
+
* document, and publish the ones that changed. Every other trusted query is re-evaluated
|
|
750
|
+
* {@link REST_DELAY_MS} after edits stop: some are slow (the Makers list takes ~600 ms of CPU),
|
|
751
|
+
* and running them now would make the tab's refresh requests, ~100 ms later, wait behind them.
|
|
752
|
+
* The Live API sweep checks them against Sanity too.
|
|
753
|
+
*/
|
|
754
|
+
async #flushLocal() {
|
|
755
|
+
let started = Date.now(), edited = this.#editedDocs;
|
|
756
|
+
this.#editedDocs = /* @__PURE__ */ new Set();
|
|
757
|
+
let evaluated = [];
|
|
758
|
+
for (let [key, entry] of this.#entries) entry.local === "ok" && (entry.docs.some((id) => edited.has(id)) ? (evaluated.push(key), this.#restPending.delete(key), await this.#reevaluate(key, entry) && await this.#publish([key], "local")) : this.#restPending.add(key));
|
|
759
|
+
this.#lastLocalFlush = {
|
|
760
|
+
queuedMs: started - this.#lastMutationAt,
|
|
761
|
+
firstMs: Date.now() - started,
|
|
762
|
+
evaluated
|
|
763
|
+
}, this.#restTimer && clearTimeout(this.#restTimer), this.#restTimer = setTimeout(() => {
|
|
764
|
+
this.#restTimer = null, this.#queue("local", () => this.#flushRest());
|
|
765
|
+
}, 400);
|
|
766
|
+
}
|
|
767
|
+
/** Re-evaluate the trusted queries the last edits did not name directly. */
|
|
768
|
+
async #flushRest() {
|
|
769
|
+
let keys = [...this.#restPending];
|
|
770
|
+
this.#restPending.clear();
|
|
771
|
+
let changed = [];
|
|
772
|
+
for (let key of keys) {
|
|
773
|
+
let entry = this.#entries.get(key);
|
|
774
|
+
entry && entry.local === "ok" && (await yieldToEventLoop(), await this.#reevaluate(key, entry) && changed.push(key));
|
|
775
|
+
}
|
|
776
|
+
await this.#publish(changed, "rest");
|
|
777
|
+
}
|
|
778
|
+
/** Evaluate one trusted query locally and store it. Returns whether its result changed. */
|
|
779
|
+
async #reevaluate(key, entry) {
|
|
780
|
+
try {
|
|
781
|
+
let result = await this.#evaluateLocal(entry);
|
|
782
|
+
return await this.#store(key, entry.query, entry.params, result);
|
|
783
|
+
} catch (error) {
|
|
784
|
+
return entry.local = "off", console.warn("[preview-hub] local evaluation failed", key, error), !1;
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
#restPending = /* @__PURE__ */ new Set();
|
|
788
|
+
#restTimer = null;
|
|
789
|
+
#lastLocalFlush = null;
|
|
790
|
+
async #fetchSanity(query, params) {
|
|
791
|
+
let url = this.#sanityUrl("query");
|
|
792
|
+
return url.searchParams.set("perspective", this.#perspective), url.searchParams.set("returnQuery", "false"), this.#lastEventId && url.searchParams.set("lastLiveEventId", this.#lastEventId), this.#post(url, query, params);
|
|
793
|
+
}
|
|
794
|
+
/** Raw perspective (published, drafts and versions as stored), for the mirror. */
|
|
795
|
+
async #fetchRaw(query, params = {}) {
|
|
796
|
+
let url = this.#sanityUrl("query");
|
|
797
|
+
return url.searchParams.set("perspective", "raw"), url.searchParams.set("returnQuery", "false"), (await this.#post(url, query, params)).result;
|
|
798
|
+
}
|
|
799
|
+
async #post(url, query, params) {
|
|
800
|
+
let response = await fetch(url, {
|
|
801
|
+
method: "POST",
|
|
802
|
+
headers: {
|
|
803
|
+
authorization: `Bearer ${this.env.SANITY_API_READ_TOKEN}`,
|
|
804
|
+
"content-type": "application/json"
|
|
805
|
+
},
|
|
806
|
+
body: JSON.stringify({
|
|
807
|
+
query,
|
|
808
|
+
params
|
|
809
|
+
})
|
|
810
|
+
});
|
|
811
|
+
if (!response.ok) throw Error(`Sanity query failed: HTTP ${response.status} ${await response.text()}`);
|
|
812
|
+
return response.json();
|
|
813
|
+
}
|
|
814
|
+
#sanityUrl(path) {
|
|
815
|
+
let { SANITY_PROJECT_ID, SANITY_DATASET, SANITY_API_VERSION } = this.env;
|
|
816
|
+
return new URL(`https://${SANITY_PROJECT_ID}.api.sanity.io/v${SANITY_API_VERSION}/data/${path}/${SANITY_DATASET}`);
|
|
817
|
+
}
|
|
818
|
+
#ensureUpstream() {
|
|
819
|
+
if (this.#upstream) return;
|
|
820
|
+
let controller = new AbortController();
|
|
821
|
+
this.#upstream = controller, this.#followListener(controller.signal), this.#followLive(controller.signal), this.#idleTimer ??= setInterval(() => this.#checkIdle(), 6e4);
|
|
822
|
+
}
|
|
823
|
+
/**
|
|
824
|
+
* Keep one Server-Sent Events stream from Sanity open until `signal` aborts, reconnecting with
|
|
825
|
+
* exponential backoff. `onEvent` returns `false` to drop the connection and reconnect.
|
|
826
|
+
*/
|
|
827
|
+
async #follow(name, signal, connect, onEvent) {
|
|
828
|
+
let backoff = 1e3, status = this.#streamStatus[name] = {
|
|
829
|
+
connects: 0,
|
|
830
|
+
events: 0,
|
|
831
|
+
error: ""
|
|
832
|
+
};
|
|
833
|
+
for (; !signal.aborted;) {
|
|
834
|
+
try {
|
|
835
|
+
status.connects++;
|
|
836
|
+
let { url, headers } = connect(), response = await fetch(url, {
|
|
837
|
+
headers: {
|
|
838
|
+
authorization: `Bearer ${this.env.SANITY_API_READ_TOKEN}`,
|
|
839
|
+
accept: "text/event-stream",
|
|
840
|
+
"accept-encoding": "identity",
|
|
841
|
+
...headers
|
|
842
|
+
},
|
|
843
|
+
signal
|
|
844
|
+
});
|
|
845
|
+
if (!response.ok || !response.body) throw Error(`HTTP ${response.status} ${(await response.text()).slice(0, 200)}`);
|
|
846
|
+
backoff = 1e3;
|
|
847
|
+
for await (let event of parseSse(response.body)) if (status.events++, event.event === "channelError" && (status.error = event.data.slice(0, 200)), onEvent(event) === !1) break;
|
|
848
|
+
} catch (error) {
|
|
849
|
+
if (signal.aborted) return;
|
|
850
|
+
status.error = String(error).slice(0, 200), console.warn(`[preview-hub] ${name} stream failed`, error);
|
|
851
|
+
}
|
|
852
|
+
if (signal.aborted) return;
|
|
853
|
+
await new Promise((resolve) => setTimeout(resolve, backoff)), backoff = Math.min(backoff * 2, 3e4);
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
/** Fast path: `/listen` mutation results, applied to the mirror as soon as they commit. */
|
|
857
|
+
#followListener(signal) {
|
|
858
|
+
let connected = !1;
|
|
859
|
+
return this.#follow("Listener", signal, () => {
|
|
860
|
+
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 };
|
|
862
|
+
}, (event) => {
|
|
863
|
+
if (event.event === "welcome") connected && this.#resetLocal(), connected = !0;
|
|
864
|
+
else if (event.event === "mutation") {
|
|
865
|
+
let { documentId, transition, result } = JSON.parse(event.data);
|
|
866
|
+
this.#mirror.loaded && this.#mirror.apply(documentId, result, transition) && (this.#lastMutationAt = Date.now(), this.#editedDocs.add(baseId(documentId)), this.#scheduleLocal());
|
|
867
|
+
} else if ([
|
|
868
|
+
"reconnect",
|
|
869
|
+
"disconnect",
|
|
870
|
+
"channelError"
|
|
871
|
+
].includes(event.event)) return event.event === "channelError" && console.warn("[preview-hub] Listener channel error", event.data), !1;
|
|
872
|
+
});
|
|
873
|
+
}
|
|
874
|
+
/** Authority: Live Content API sync tags, ~1 s after each write; replays from its event ID. */
|
|
875
|
+
#followLive(signal) {
|
|
876
|
+
return this.#follow("Live Content API", signal, () => {
|
|
877
|
+
let url = this.#sanityUrl("live/events");
|
|
878
|
+
return url.searchParams.set("includeDrafts", "true"), {
|
|
879
|
+
url,
|
|
880
|
+
headers: this.#lastEventId ? { "last-event-id": this.#lastEventId } : void 0
|
|
881
|
+
};
|
|
882
|
+
}, (event) => {
|
|
883
|
+
if (event.id && (this.#lastEventId = event.id), event.event === "message") {
|
|
884
|
+
let { tags } = JSON.parse(event.data);
|
|
885
|
+
tags?.length && this.#onTags(tags);
|
|
886
|
+
} else if (event.event === "restart") this.#onTags([...this.#byTag.keys()]);
|
|
887
|
+
else if (event.event === "reconnect") return !1;
|
|
888
|
+
});
|
|
889
|
+
}
|
|
890
|
+
/**
|
|
891
|
+
* Unsaved Studio edits (LF-INIT-21): the `live-edit` Studio plugin posts the open document's
|
|
892
|
+
* form value through the storefront. It shows in the mirror until the saved document catches
|
|
893
|
+
* up or it goes stale, and trusted queries re-evaluate at once.
|
|
894
|
+
*/
|
|
895
|
+
async #applyOverlay(doc, seq) {
|
|
896
|
+
return this.#touch(), this.#ensureUpstream(), await this.#mirror.ready(), this.#mirror.overlay(doc, seq) ? (this.#lastMutationAt = Date.now(), this.#editedDocs.add(baseId(doc._id)), this.#flushLocalNow(), this.#overlayTimer ??= setInterval(() => {
|
|
897
|
+
for (let base of this.#mirror.expireOverlays(5e3)) this.#editedDocs.add(base);
|
|
898
|
+
this.#editedDocs.size && this.#scheduleLocal(), !this.#mirror.overlayCount && this.#overlayTimer && (clearInterval(this.#overlayTimer), this.#overlayTimer = null);
|
|
899
|
+
}, 1e3), !0) : !1;
|
|
900
|
+
}
|
|
901
|
+
#overlayTimer = null;
|
|
902
|
+
#verifyPending = /* @__PURE__ */ new Set();
|
|
903
|
+
#verifyTimer = null;
|
|
904
|
+
/** Verify pending queries once reads have paused for VERIFY_DELAY_MS, yielding between them. */
|
|
905
|
+
#scheduleVerify() {
|
|
906
|
+
this.#verifyTimer && clearTimeout(this.#verifyTimer), this.#verifyTimer = setTimeout(() => {
|
|
907
|
+
this.#verifyTimer = null;
|
|
908
|
+
let keys = [...this.#verifyPending];
|
|
909
|
+
this.#verifyPending.clear(), this.#queue("verify", async () => {
|
|
910
|
+
for (let key of keys) await yieldToEventLoop(), await this.#verify(key);
|
|
911
|
+
});
|
|
912
|
+
}, 750);
|
|
913
|
+
}
|
|
914
|
+
#resetLocal() {
|
|
915
|
+
this.#mirror.clear();
|
|
916
|
+
for (let [key, entry] of this.#entries) entry.local = "unknown", this.#verifyPending.add(key);
|
|
917
|
+
this.#scheduleVerify();
|
|
918
|
+
}
|
|
919
|
+
#localQueued = !1;
|
|
920
|
+
/**
|
|
921
|
+
* Re-evaluate on the local chain's next turn, with no timer: an editor is typing, and on Workers
|
|
922
|
+
* a Durable Object's timers can fire late. Listener mutations keep {@link #scheduleLocal},
|
|
923
|
+
* which coalesces a save's burst of documents.
|
|
924
|
+
*/
|
|
925
|
+
#flushLocalNow() {
|
|
926
|
+
this.#localQueued || (this.#localQueued = !0, this.#queue("local", async () => {
|
|
927
|
+
this.#localQueued = !1, await this.#flushLocal();
|
|
928
|
+
}));
|
|
929
|
+
}
|
|
930
|
+
#scheduleLocal() {
|
|
931
|
+
this.#localTimer ||= setTimeout(() => {
|
|
932
|
+
this.#localTimer = null, this.#queue("local", () => this.#flushLocal());
|
|
933
|
+
}, 10);
|
|
934
|
+
}
|
|
935
|
+
#onTags(tags) {
|
|
936
|
+
this.#recentEvents.push({
|
|
937
|
+
at: Date.now(),
|
|
938
|
+
tags
|
|
939
|
+
}), this.#recentEvents.length > 50 && this.#recentEvents.shift();
|
|
940
|
+
for (let tag of tags) this.#pendingTags.add(tag);
|
|
941
|
+
this.#flushTimer ||= setTimeout(() => {
|
|
942
|
+
this.#flushTimer = null, this.#queue("sweep", () => this.#flush());
|
|
943
|
+
}, 25);
|
|
944
|
+
}
|
|
945
|
+
/** Refetch the results a Live event's sync tags name, from Sanity. */
|
|
946
|
+
async #flush() {
|
|
947
|
+
let tags = [...this.#pendingTags];
|
|
948
|
+
this.#pendingTags.clear();
|
|
949
|
+
let keys = /* @__PURE__ */ new Set();
|
|
950
|
+
for (let tag of tags) for (let key of this.#byTag.get(tag) ?? []) keys.add(key);
|
|
951
|
+
if (!keys.size) return;
|
|
952
|
+
let changed = [];
|
|
953
|
+
await Promise.all([...keys].map(async (key) => {
|
|
954
|
+
let entry = this.#entries.get(key);
|
|
955
|
+
if (entry && !(entry.local === "ok" && this.#mirror.overlaid(entry.docs))) try {
|
|
956
|
+
let response = await this.#fetchSanity(entry.query, entry.params);
|
|
957
|
+
await this.#store(key, entry.query, entry.params, response.result, response.syncTags) && changed.push(key);
|
|
958
|
+
} catch (error) {
|
|
959
|
+
console.warn("[preview-hub] refetch failed", key, error), this.#unindex(key, entry.tags), this.#entries.delete(key), changed.push(key);
|
|
960
|
+
}
|
|
961
|
+
})), await this.#publish(changed, "sweep");
|
|
962
|
+
}
|
|
963
|
+
async #publish(changed, source) {
|
|
964
|
+
if (!changed.length) return;
|
|
965
|
+
let chunk = {
|
|
966
|
+
keys: changed.sort(),
|
|
967
|
+
at: Date.now(),
|
|
968
|
+
source
|
|
969
|
+
}, seq = ++this.#seq;
|
|
970
|
+
if (this.#log.push({
|
|
971
|
+
seq,
|
|
972
|
+
chunk
|
|
973
|
+
}), this.#log.length > 200 && this.#log.shift(), !this.#sockets.size) {
|
|
974
|
+
for (let wake of [...this.#waiters]) wake();
|
|
975
|
+
return;
|
|
976
|
+
}
|
|
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
|
+
let message = JSON.stringify({
|
|
985
|
+
cursor: `${this.#epoch}:${seq}`,
|
|
986
|
+
events: [{
|
|
987
|
+
...chunk,
|
|
988
|
+
results,
|
|
989
|
+
labels
|
|
990
|
+
}]
|
|
991
|
+
});
|
|
992
|
+
for (let socket of this.#sockets) try {
|
|
993
|
+
socket.send(message);
|
|
994
|
+
} catch {
|
|
995
|
+
this.#sockets.delete(socket);
|
|
996
|
+
}
|
|
997
|
+
for (let wake of [...this.#waiters]) wake();
|
|
998
|
+
}
|
|
999
|
+
#touch() {
|
|
1000
|
+
this.#lastActive = Date.now();
|
|
1001
|
+
}
|
|
1002
|
+
#checkIdle() {
|
|
1003
|
+
this.#polling > 0 || this.#sockets.size > 0 || Date.now() - this.#lastActive < 18e5 || (this.#upstream?.abort(), this.#upstream = null, this.#idleTimer && clearInterval(this.#idleTimer), this.#idleTimer = null, this.#entries.clear(), this.#byTag.clear(), this.#labels.clear(), this.#mirror.clear());
|
|
1004
|
+
}
|
|
1005
|
+
};
|
|
1006
|
+
/**
|
|
1007
|
+
* Base IDs of every `_id` and `_ref` anywhere in a result, plus every string in the params
|
|
1008
|
+
* (`getSections({ id })` returns no `_id` of its own). A param that is not a document ID only
|
|
1009
|
+
* adds a name the mirror marks as missing.
|
|
1010
|
+
*/
|
|
1011
|
+
function documentIds(result, params) {
|
|
1012
|
+
let found = /* @__PURE__ */ new Set(), walk = (value) => {
|
|
1013
|
+
if (Array.isArray(value)) for (let item of value) walk(item);
|
|
1014
|
+
else if (value && typeof value == "object") for (let [field, child] of Object.entries(value)) (field === "_id" || field === "_ref") && typeof child == "string" ? found.add(baseId(child)) : walk(child);
|
|
1015
|
+
};
|
|
1016
|
+
walk(result);
|
|
1017
|
+
let walkParams = (value) => {
|
|
1018
|
+
typeof value == "string" ? found.add(baseId(value)) : Array.isArray(value) ? value.forEach(walkParams) : value && typeof value == "object" && Object.values(value).forEach(walkParams);
|
|
1019
|
+
};
|
|
1020
|
+
return walkParams(params), [...found];
|
|
1021
|
+
}
|
|
1022
|
+
/** The first path where two JSON values differ, for logging why a local result was rejected. */
|
|
1023
|
+
function firstDifference(a, b, path = "$") {
|
|
1024
|
+
if (canonicalJson(a) === canonicalJson(b)) return null;
|
|
1025
|
+
if (a && b && typeof a == "object" && typeof b == "object") {
|
|
1026
|
+
let keys = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)]);
|
|
1027
|
+
for (let key of keys) {
|
|
1028
|
+
let diff = firstDifference(a[key], b[key], `${path}.${key}`);
|
|
1029
|
+
if (diff) return diff;
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
let show = (value) => JSON.stringify(value)?.slice(0, 80);
|
|
1033
|
+
return `${path}: sanity=${show(a)} local=${show(b)}`;
|
|
1034
|
+
}
|
|
1035
|
+
function yieldToEventLoop() {
|
|
1036
|
+
return new Promise((resolve) => setTimeout(resolve, 0));
|
|
1037
|
+
}
|
|
1038
|
+
async function sha256Hex(input) {
|
|
1039
|
+
let digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(input)));
|
|
1040
|
+
return Array.from(digest.subarray(0, 8), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1041
|
+
}
|
|
1042
|
+
/** Stable key for a query and its params. */
|
|
1043
|
+
function fingerprint(query, params) {
|
|
1044
|
+
return sha256Hex(JSON.stringify([query, sortKeys(params)]));
|
|
1045
|
+
}
|
|
1046
|
+
/**
|
|
1047
|
+
* Hash of a result with object keys sorted. Sanity returns keys sorted and `groq-js` in projection
|
|
1048
|
+
* order, so a raw `JSON.stringify` would make every local result look different.
|
|
1049
|
+
*/
|
|
1050
|
+
function hashJson(value) {
|
|
1051
|
+
return sha256Hex(canonicalJson(value));
|
|
1052
|
+
}
|
|
1053
|
+
function canonicalJson(value) {
|
|
1054
|
+
return JSON.stringify(value, (_key, child) => child && typeof child == "object" && !Array.isArray(child) ? Object.fromEntries(Object.entries(child).sort(([a], [b]) => a < b ? -1 : +(a > b))) : child) ?? "undefined";
|
|
1055
|
+
}
|
|
1056
|
+
function sortKeys(params) {
|
|
1057
|
+
return Object.fromEntries(Object.entries(params).sort(([a], [b]) => a.localeCompare(b)));
|
|
1058
|
+
}
|
|
1059
|
+
/**
|
|
1060
|
+
* Entry point for the storefront's service binding (this Worker has no public URL). It picks the
|
|
1061
|
+
* hub for the request's perspective with `getByName()` here, inside this Worker, so the instance
|
|
1062
|
+
* can read its perspective from `ctx.id.name`. Through Vite dev's platform proxy, a Durable
|
|
1063
|
+
* Object stub reached directly from the storefront arrives without its name.
|
|
1064
|
+
*/
|
|
1065
|
+
var cloudflare_default = { fetch(request, env) {
|
|
1066
|
+
let perspective = request.headers.get("x-preview-perspective") ?? "drafts";
|
|
1067
|
+
return !/^[\w.,-]{1,256}$/.test(perspective) || ["raw", "published"].includes(perspective) ? new Response("Invalid perspective", { status: 400 }) : env.PREVIEW_HUB.getByName(`${perspective}|${env.CF_VERSION_METADATA.id}`).fetch(request);
|
|
1068
|
+
} };
|
|
1069
|
+
export { PreviewHub, cloudflare_default as default };
|
|
1070
|
+
|
|
1071
|
+
//# sourceMappingURL=cloudflare.js.map
|