@sanity/sdk 3.12.0 → 3.13.0-next.20261106104949

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1072 @@
1
+ import { c as getEnv, f as setCleanupTimeout, l as isReleasePerspective, n as bindActionByResource, o as UPSTREAM_CLOSE_DELAY_MS, s as defineStore, t as createStateSourceAction } from "./createStateSourceAction-BdcaQ2os.js";
2
+ import { M as getClientErrorApiBody, N as getClientErrorApiProjectId, P as getClientErrorApiType, a as getClientAuthState, b as retryWithCredential, l as getTokenState, nt as randomUuid, o as getCurrentUserState, tt as randomId, y as retryRead } from "./authStore-A65hzFu3.js";
3
+ import { n as defineFetcher, r as defineMutation } from "./commentFieldPath-BbKsoQiW.js";
4
+ import { r as omitProperty } from "./object-CxXlSVg7.js";
5
+ import { r as getClientState } from "./clientStore-C20oRB2w.js";
6
+ import { t as getNodeState } from "./getNodeState-C_9DqJzy.js";
7
+ import { ClientError, ConnectionFailedError, CorsOriginError, DisconnectError } from "@sanity/client";
8
+ import { BehaviorSubject, EMPTY, NEVER, Observable, catchError, combineLatest, defer, distinctUntilChanged, filter, first, firstValueFrom, from, groupBy, map, mergeMap, of, pairwise, race, share, startWith, switchMap, tap, timer } from "rxjs";
9
+ import { SDK_CHANNEL_NAME, SDK_NODE_NAME } from "@sanity/message-protocol";
10
+ import { isKeySegment, isKeyedObject } from "@sanity/types";
11
+ import { createSelector } from "reselect";
12
+ import { getIndexForKey, jsonMatch, slicePath, stringifyPath } from "@sanity/json-match";
13
+ import { evaluateSync } from "groq-js";
14
+ import { applyPatches, parsePatch } from "@sanity/diff-match-patch";
15
+ import { diffValue } from "@sanity/diff-patch";
16
+ function findClientError(error) {
17
+ return error instanceof ClientError ? error : error instanceof Error && error.cause instanceof ClientError ? error.cause : null;
18
+ }
19
+ function stringOrUndefined(value) {
20
+ return typeof value == "string" && value ? value : void 0;
21
+ }
22
+ /**
23
+ * Reads the identifiers from the 401 `projectUserNotFoundError` that the
24
+ * Content Lake returns when the signed-in user is not a member of the project.
25
+ * Accepts the `ClientError` itself or an error that wraps it as its `cause`,
26
+ * such as the React package's `AuthError`.
27
+ *
28
+ * @returns The identifiers, or `null` when the error is not a
29
+ * `projectUserNotFoundError`.
30
+ * @internal
31
+ */
32
+ function getProjectAccessErrorDetails(error) {
33
+ let clientError = findClientError(error);
34
+ if (!clientError || clientError.statusCode !== 401 || getClientErrorApiType(clientError) !== "projectUserNotFoundError") return null;
35
+ let body = getClientErrorApiBody(clientError)?.error;
36
+ return {
37
+ projectId: getClientErrorApiProjectId(clientError),
38
+ userId: stringOrUndefined(body?.userID),
39
+ traceId: stringOrUndefined(clientError.traceId)
40
+ };
41
+ }
42
+ /**
43
+ * Returns the ID of the project that rejected a request because the signed-in
44
+ * user isn't a member of it. The Content Lake reports this as a 401
45
+ * `projectUserNotFoundError`. It usually means the user signed in with a
46
+ * different account than the one that has access, for example Google instead
47
+ * of SSO with the same email address.
48
+ *
49
+ * When this error reaches the SDK's `AuthBoundary`, the boundary replaces the
50
+ * whole app with a screen that explains the problem. An app-level error
51
+ * boundary inside `AuthBoundary` catches the error first, so it decides where
52
+ * the error goes. Rethrow it when the app can't work without the rejected
53
+ * project. Handle it in place when only part of the app reads from that
54
+ * project, so a user who can access the app's other projects can keep using
55
+ * them.
56
+ *
57
+ * @param error - The value to inspect. A `ClientError`, or an error that wraps
58
+ * one as its `cause`.
59
+ * @returns The rejected project's ID, or `null` when the error isn't a
60
+ * `projectUserNotFoundError` or the response doesn't name the project.
61
+ *
62
+ * @example Rethrowing only for the project the whole app needs
63
+ * ```tsx
64
+ * const MAIN_PROJECT_ID = 'abc123'
65
+ *
66
+ * function Fallback({error}: FallbackProps) {
67
+ * const projectId = getProjectAccessErrorProjectId(error)
68
+ * // The app can't work without its main project, so let AuthBoundary
69
+ * // replace it with the project access screen.
70
+ * if (projectId === MAIN_PROJECT_ID) throw error
71
+ * if (projectId) return <p>You don't have access to project {projectId}.</p>
72
+ * return <p>Something went wrong.</p>
73
+ * }
74
+ * ```
75
+ *
76
+ * @category Authentication
77
+ * @public
78
+ */
79
+ function getProjectAccessErrorProjectId(error) {
80
+ return getProjectAccessErrorDetails(error)?.projectId ?? null;
81
+ }
82
+ const SIGN_IN_METHOD_LABELS = {
83
+ google: "Google",
84
+ github: "GitHub",
85
+ sanity: "email and password",
86
+ vercel: "Vercel"
87
+ };
88
+ /**
89
+ * Returns a user-facing name for a `/users/me` `provider` value, such as
90
+ * `Google` for `google` or `SSO` for any `saml-*` provider.
91
+ *
92
+ * @returns The label, or `undefined` for an unknown or missing provider.
93
+ * @internal
94
+ */
95
+ function getSignInMethodLabel(provider) {
96
+ if (provider) return provider.startsWith("saml-") ? "SSO" : SIGN_IN_METHOD_LABELS[provider];
97
+ }
98
+ function getProjectAccessErrorMessage(details, provider) {
99
+ let method = getSignInMethodLabel(provider);
100
+ return `${method ? `Your Sanity account (signed in with ${method})` : "Your Sanity account"} isn't a member of ${details.projectId ? `project ${details.projectId}` : "this project"}. Each sign-in method, such as Google or SSO, is a separate account. Sign out and sign in with the account that has access.${details.traceId ? ` (traceId: ${details.traceId})` : ""}`;
101
+ }
102
+ var ProjectAccessClientError = class extends ClientError {
103
+ constructor(error, message) {
104
+ super(error.response), this.message = message;
105
+ }
106
+ };
107
+ /**
108
+ * Replaces the API's `projectUserNotFoundError` message with one that tells
109
+ * the user what to do. Hooks throw store errors to the nearest error boundary,
110
+ * and most boundaries, including routers' default error screens, render
111
+ * `error.message`. Any other error is returned unchanged.
112
+ *
113
+ * @internal
114
+ */
115
+ function withProjectAccessMessage(instance, error) {
116
+ if (!(error instanceof ClientError) || error instanceof ProjectAccessClientError) return error;
117
+ let details = getProjectAccessErrorDetails(error);
118
+ if (!details) return error;
119
+ let provider = getCurrentUserState(instance).getCurrent()?.provider;
120
+ return new ProjectAccessClientError(error, getProjectAccessErrorMessage(details, provider));
121
+ }
122
+ function generateArrayKey(length = 12) {
123
+ let numBytes = Math.ceil(length / 2), bytes = crypto.getRandomValues(new Uint8Array(numBytes));
124
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("").slice(0, length);
125
+ }
126
+ function memoize(fn) {
127
+ let cache = /* @__PURE__ */ new WeakMap();
128
+ return ((input) => {
129
+ if (!input || typeof input != "object") return fn(input);
130
+ let cached = cache.get(input);
131
+ if (cached) return cached;
132
+ let result = fn(input);
133
+ return cache.set(input, result), result;
134
+ });
135
+ }
136
+ /**
137
+ * Recursively traverse a value. When an array is encountered, ensure that
138
+ * each object item has a _key property. Memoized such that sub-objects that
139
+ * have not changed aren't re-computed.
140
+ */
141
+ const ensureArrayKeysDeep = memoize((input) => {
142
+ if (!input || typeof input != "object") return input;
143
+ if (Array.isArray(input)) return !input.length || typeof input[0] != "object" || input.every(isKeyedObject) ? input : input.map((item) => !item || typeof item != "object" ? item : isKeyedObject(item) ? ensureArrayKeysDeep(item) : {
144
+ ...ensureArrayKeysDeep(item),
145
+ _key: generateArrayKey()
146
+ });
147
+ let entries = Object.entries(input).map(([key, value]) => [key, ensureArrayKeysDeep(value)]);
148
+ return entries.every(([key, value]) => input[key] === value) ? input : Object.fromEntries(entries);
149
+ });
150
+ /**
151
+ * Whether every array-addressing segment (keyed `[_key=="…"]` or numeric
152
+ * index) in the given match path resolves to an existing array item.
153
+ *
154
+ * This mirrors Content Lake, which auto-creates missing *object* properties
155
+ * when setting but never creates *array items*:
156
+ *
157
+ * ```js
158
+ * // object properties are created, even nested ones:
159
+ * set({}, {'meta.author.name': 'Ada'})
160
+ * // -> {meta: {author: {name: 'Ada'}}} (applies)
161
+ *
162
+ * // array items are not:
163
+ * set({items: [{_key: 'a'}]}, {'items[_key=="b"].title': 'x'})
164
+ * // -> {items: [{_key: 'a'}]} (no-op)
165
+ * ```
166
+ *
167
+ * Without this filter, the second example fabricated a degenerate item
168
+ * (`{title: 'x'}`, no `_key`) that would never exist on the server, which
169
+ * is how concurrent Portable Text edits grew phantom span-less children.
170
+ */
171
+ function resolvesArraySegments(input, path) {
172
+ let current = input;
173
+ for (let segment of path) if (typeof segment == "string") current = typeof current == "object" && current && !Array.isArray(current) ? current[segment] : void 0;
174
+ else {
175
+ if (!Array.isArray(current)) return !1;
176
+ if (isKeySegment(segment)) {
177
+ let index = getIndexForKey(current, segment._key);
178
+ if (index === void 0) return !1;
179
+ current = current[index];
180
+ } else {
181
+ let index = segment < 0 ? current.length + segment : segment;
182
+ if (!(index in current)) return !1;
183
+ current = current[index];
184
+ }
185
+ }
186
+ return !0;
187
+ }
188
+ function set(input, pathExpressionValues) {
189
+ let result = Object.entries(pathExpressionValues).flatMap(([pathExpression, replacementValue]) => Array.from(jsonMatch(input, pathExpression)).map((matchEntry) => ({
190
+ ...matchEntry,
191
+ replacementValue
192
+ }))).filter(({ path }) => resolvesArraySegments(input, path)).reduce((acc, { path, replacementValue }) => setDeep(acc, path, replacementValue), input);
193
+ return ensureArrayKeysDeep(result);
194
+ }
195
+ function setIfMissing(input, pathExpressionValues) {
196
+ let result = Object.entries(pathExpressionValues).flatMap(([pathExpression, replacementValue]) => Array.from(jsonMatch(input, pathExpression)).map((matchEntry) => ({
197
+ ...matchEntry,
198
+ replacementValue
199
+ }))).filter((matchEntry) => matchEntry.value === null || matchEntry.value === void 0).filter(({ path }) => resolvesArraySegments(input, path)).reduce((acc, { path, replacementValue }) => setDeep(acc, path, replacementValue), input);
200
+ return ensureArrayKeysDeep(result);
201
+ }
202
+ function unset(input, pathExpressions) {
203
+ let result = pathExpressions.flatMap((pathExpression) => Array.from(jsonMatch(input, pathExpression))).reverse().reduce((acc, { path }) => unsetDeep(acc, path), input);
204
+ return ensureArrayKeysDeep(result);
205
+ }
206
+ function insert(input, { items, ...insertPatch }) {
207
+ let operation, pathExpression;
208
+ if ("before" in insertPatch ? (operation = "before", pathExpression = insertPatch.before) : "after" in insertPatch ? (operation = "after", pathExpression = insertPatch.after) : "replace" in insertPatch && (operation = "replace", pathExpression = insertPatch.replace), !operation || typeof pathExpression != "string" || !pathExpression.length) return input;
209
+ let arrayPath = slicePath(pathExpression, 0, -1), positionPath = slicePath(pathExpression, -1), result = input;
210
+ for (let { path, value } of jsonMatch(input, arrayPath)) {
211
+ if (!Array.isArray(value)) continue;
212
+ let arr = value;
213
+ switch (operation) {
214
+ case "replace": {
215
+ let indexesToRemove = /* @__PURE__ */ new Set(), position = Infinity;
216
+ for (let itemMatch of jsonMatch(arr, positionPath)) {
217
+ if (itemMatch.path.length !== 1) continue;
218
+ let [segment] = itemMatch.path;
219
+ if (typeof segment == "string") continue;
220
+ let index;
221
+ typeof segment == "number" && (index = segment), typeof index == "number" && index < 0 && (index = arr.length + index), isKeySegment(segment) && (index = getIndexForKey(arr, segment._key)), typeof index == "number" && (index < 0 && (index = arr.length + index), indexesToRemove.add(index), index < position && (position = index));
222
+ }
223
+ if (position === Infinity) continue;
224
+ arr = arr.map((item, index) => ({
225
+ item,
226
+ index
227
+ })).filter(({ index }) => !indexesToRemove.has(index)).map(({ item }) => item), arr = [
228
+ ...arr.slice(0, position),
229
+ ...items,
230
+ ...arr.slice(position, arr.length)
231
+ ];
232
+ break;
233
+ }
234
+ case "before": {
235
+ let position = Infinity;
236
+ for (let itemMatch of jsonMatch(arr, positionPath)) {
237
+ if (itemMatch.path.length !== 1) continue;
238
+ let [segment] = itemMatch.path;
239
+ if (typeof segment == "string") continue;
240
+ let index;
241
+ typeof segment == "number" && (index = segment), typeof index == "number" && index < 0 && (index = arr.length + index), isKeySegment(segment) && (index = getIndexForKey(arr, segment._key)), typeof index == "number" && (index < 0 && (index = arr.length - index), index < position && (position = index));
242
+ }
243
+ if (position === Infinity) continue;
244
+ arr = [
245
+ ...arr.slice(0, position),
246
+ ...items,
247
+ ...arr.slice(position, arr.length)
248
+ ];
249
+ break;
250
+ }
251
+ case "after": {
252
+ let position = -Infinity;
253
+ for (let itemMatch of jsonMatch(arr, positionPath)) {
254
+ if (itemMatch.path.length !== 1) continue;
255
+ let [segment] = itemMatch.path;
256
+ if (typeof segment == "string") continue;
257
+ let index;
258
+ typeof segment == "number" && (index = segment), typeof index == "number" && index < 0 && (index = arr.length + index), isKeySegment(segment) && (index = getIndexForKey(arr, segment._key)), typeof index == "number" && index > position && (position = index);
259
+ }
260
+ if (position === -Infinity) continue;
261
+ arr = [
262
+ ...arr.slice(0, position + 1),
263
+ ...items,
264
+ ...arr.slice(position + 1, arr.length)
265
+ ];
266
+ break;
267
+ }
268
+ default: continue;
269
+ }
270
+ result = setDeep(result, path, arr);
271
+ }
272
+ return ensureArrayKeysDeep(result);
273
+ }
274
+ function inc(input, pathExpressionValues) {
275
+ let result = Object.entries(pathExpressionValues).flatMap(([pathExpression, valueToAdd]) => Array.from(jsonMatch(input, pathExpression)).map((matchEntry) => ({
276
+ ...matchEntry,
277
+ valueToAdd
278
+ }))).filter((matchEntry) => typeof matchEntry.value == "number").reduce((acc, { path, value, valueToAdd }) => setDeep(acc, path, value + valueToAdd), input);
279
+ return ensureArrayKeysDeep(result);
280
+ }
281
+ function dec(input, pathExpressionValues) {
282
+ let result = inc(input, Object.fromEntries(Object.entries(pathExpressionValues).filter(([, value]) => typeof value == "number").map(([key, value]) => [key, -value])));
283
+ return ensureArrayKeysDeep(result);
284
+ }
285
+ function diffMatchPatch(input, pathExpressionValues) {
286
+ let result = Object.entries(pathExpressionValues).flatMap(([pathExpression, dmp]) => Array.from(jsonMatch(input, pathExpression)).map((m) => ({
287
+ ...m,
288
+ dmp
289
+ }))).filter((i) => i.value !== void 0).map(({ path, value, dmp }) => {
290
+ if (typeof value != "string") throw Error(`Can't diff-match-patch \`${JSON.stringify(value)}\` at path \`${stringifyPath(path)}\`, because it is not a string`);
291
+ let [nextValue] = applyPatches(parsePatch(dmp), value, { allowExceedingIndices: !0 });
292
+ return {
293
+ path,
294
+ value: nextValue
295
+ };
296
+ }).reduce((acc, { path, value }) => setDeep(acc, path, value), input);
297
+ return ensureArrayKeysDeep(result);
298
+ }
299
+ function ifRevisionID(input, revisionId) {
300
+ let inputRev = typeof input == "object" && input && "_rev" in input && typeof input._rev == "string" ? input._rev : void 0;
301
+ if (typeof inputRev != "string") throw Error("Patch specified `ifRevisionID` but could not find document's revision ID.");
302
+ if (revisionId !== inputRev) throw Error(`Patch's \`ifRevisionID\` \`${revisionId}\` does not match document's revision ID \`${inputRev}\``);
303
+ return input;
304
+ }
305
+ function setDeep(input, path, value) {
306
+ let [currentSegment, ...restOfPath] = path;
307
+ if (currentSegment === void 0) return value;
308
+ if (typeof input != "object" || !input) {
309
+ if (typeof currentSegment == "string") return { [currentSegment]: setDeep(null, restOfPath, value) };
310
+ let index;
311
+ if (isKeySegment(currentSegment)) index = 0;
312
+ else if (typeof currentSegment == "number" && currentSegment >= 0) index = currentSegment;
313
+ else return input;
314
+ return [...Array.from({ length: index }).fill(null), setDeep(null, restOfPath, value)];
315
+ }
316
+ if (Array.isArray(input)) {
317
+ let index;
318
+ return isKeySegment(currentSegment) ? index = getIndexForKey(input, currentSegment._key) ?? input.length : typeof currentSegment == "number" && (index = currentSegment < 0 ? input.length + currentSegment : currentSegment), index === void 0 ? input : index in input ? input.map((nestedInput, i) => i === index ? setDeep(nestedInput, restOfPath, value) : nestedInput) : [
319
+ ...input,
320
+ ...Array.from({ length: index - input.length }).fill(null),
321
+ setDeep(null, restOfPath, value)
322
+ ];
323
+ }
324
+ return typeof currentSegment == "object" ? input : currentSegment in input ? Object.fromEntries(Object.entries(input).map(([key, nestedInput]) => key === currentSegment ? [key, setDeep(nestedInput, restOfPath, value)] : [key, nestedInput])) : {
325
+ ...input,
326
+ [currentSegment]: setDeep(null, restOfPath, value)
327
+ };
328
+ }
329
+ function unsetDeep(input, path) {
330
+ let [currentSegment, ...restOfPath] = path;
331
+ if (currentSegment === void 0 || typeof input != "object" || !input) return input;
332
+ let _segment;
333
+ if (isKeySegment(currentSegment) ? _segment = getIndexForKey(input, currentSegment._key) : (typeof currentSegment == "string" || typeof currentSegment == "number") && (_segment = currentSegment), _segment === void 0) return input;
334
+ let segment = _segment;
335
+ return typeof segment == "number" && Array.isArray(input) && (segment = segment < 0 ? input.length + segment : segment), segment in input ? restOfPath.length ? Array.isArray(input) ? input.map((nestedInput, index) => index === segment ? unsetDeep(nestedInput, restOfPath) : nestedInput) : Object.fromEntries(Object.entries(input).map(([key, value]) => key === segment ? [key, unsetDeep(value, restOfPath)] : [key, value])) : Array.isArray(input) ? input.filter((_nestedInput, index) => index !== segment) : Object.fromEntries(Object.entries(input).filter(([key]) => key !== segment.toString())) : input;
336
+ }
337
+ /**
338
+ * Exposes the patch operations used by {@link processMutations}.
339
+ *
340
+ * @remarks
341
+ * Property order determines execution order in {@link processMutations}:
342
+ * `ifRevisionID`, `set`, `setIfMissing`, `unset`, `inc`, `dec`, `insert`,
343
+ * then `diffMatchPatch`. Reordering the properties changes mutation results.
344
+ * Freezes the collection to prevent callers from replacing the functions
345
+ * used by the SDK's mutation evaluator.
346
+ *
347
+ * @see https://www.sanity.io/docs/http-mutations#5b4db1396e56
348
+ *
349
+ * @example
350
+ * ```ts
351
+ * const document = {items: [{_key: 'a', title: 'Before'}]}
352
+ * const updated = patchOperations.set<typeof document>(document, {
353
+ * 'items[_key=="a"].title': 'After',
354
+ * })
355
+ * ```
356
+ *
357
+ * @internal
358
+ */
359
+ const patchOperations = Object.freeze({
360
+ ifRevisionID,
361
+ set,
362
+ setIfMissing,
363
+ unset,
364
+ inc,
365
+ dec,
366
+ insert,
367
+ diffMatchPatch
368
+ });
369
+ /**
370
+ * Implements ID generation:
371
+ *
372
+ * A create mutation creates a new document. It takes the literal document
373
+ * content as its argument. The rules for the new document's identifier are as
374
+ * follows:
375
+ *
376
+ * - If the `_id` attribute is missing, then a new, random, unique ID is
377
+ * generated.
378
+ * - If the `_id` attribute is present but ends with `.`, then it is used as a
379
+ * prefix for a new, random, unique ID.
380
+ * - If the _id attribute is present, it is used as-is.
381
+ *
382
+ * [- source](https://www.sanity.io/docs/http-mutations#c732f27330a4)
383
+ */
384
+ function getId(id) {
385
+ return !id || typeof id != "string" ? randomUuid() : id.endsWith(".") ? `${id}${randomUuid()}` : id;
386
+ }
387
+ function getDocumentIds(selection) {
388
+ if ("id" in selection) {
389
+ let ids = (Array.isArray(selection.id) ? selection.id : [selection.id]).filter((id) => typeof id == "string");
390
+ return Array.from(new Set(ids));
391
+ }
392
+ if ("query" in selection) throw Error("'query' in mutations is not supported.");
393
+ return [];
394
+ }
395
+ /**
396
+ * Applies mutations to an in-memory set of Sanity documents.
397
+ * Deleted documents remain in the returned set with a value of `null`.
398
+ *
399
+ * Include every document affected by `mutations` in `documents`, using `null`
400
+ * for documents that do not exist.
401
+ *
402
+ * Returns `documents` itself when `mutations` is empty. Otherwise, returns a
403
+ * shallow copy of that object. The result can reuse document objects and
404
+ * nested objects from `documents`. Mutating a reused object through the
405
+ * result also changes the input.
406
+ *
407
+ * Sets `_rev` to `transactionId` on created, replaced, and patched documents.
408
+ * Uses `timestamp` for timestamps unless the mutation preserves them.
409
+ * Ignores `merge` patches; `inc` and `dec` skip values that are not numbers.
410
+ * Generates document IDs when omitted or ending in `.`.
411
+ * Patch operations can generate missing array keys.
412
+ *
413
+ * Does not persist documents or run Content Lake's server validation.
414
+ *
415
+ * @throws If a selection uses a query, a `create` targets an existing document,
416
+ * or a `patch` targets a document that does not exist.
417
+ * @throws If a patch operation fails, including a revision check failure or
418
+ * `diffMatchPatch` applied to a value other than a string or `undefined`.
419
+ *
420
+ * @internal
421
+ */
422
+ function processMutations({ documents, mutations, transactionId, timestamp }) {
423
+ if (!mutations.length) return documents;
424
+ let dataset = { ...documents }, now = timestamp || (/* @__PURE__ */ new Date()).toISOString();
425
+ for (let mutation of mutations) if ("create" in mutation) {
426
+ let id = getId(mutation.create._id);
427
+ if (dataset[id]) throw Error(`Cannot create document with \`_id\` \`${id}\` because another document with the same ID already exists.`);
428
+ dataset[id] = {
429
+ _createdAt: now,
430
+ _updatedAt: now,
431
+ ...mutation.create,
432
+ _rev: transactionId,
433
+ _id: id
434
+ };
435
+ } else if ("createOrReplace" in mutation) {
436
+ let id = getId(mutation.createOrReplace._id), prev = dataset[id];
437
+ dataset[id] = {
438
+ ...mutation.createOrReplace,
439
+ _createdAt: prev?._createdAt || typeof mutation.createOrReplace._createdAt == "string" && mutation.createOrReplace._createdAt || now,
440
+ _updatedAt: prev ? now : typeof mutation.createOrReplace._updatedAt == "string" && mutation.createOrReplace._updatedAt || now,
441
+ _rev: transactionId,
442
+ _id: id
443
+ };
444
+ } else if ("createIfNotExists" in mutation) {
445
+ let id = getId(mutation.createIfNotExists._id);
446
+ if (dataset[id]) continue;
447
+ dataset[id] = {
448
+ _createdAt: now,
449
+ _updatedAt: now,
450
+ ...mutation.createIfNotExists,
451
+ _rev: transactionId,
452
+ _id: id
453
+ };
454
+ } else if ("delete" in mutation) for (let id of getDocumentIds(mutation.delete)) dataset[id] = null;
455
+ else if ("patch" in mutation) {
456
+ let { patch } = mutation, patched = getDocumentIds(patch).map((id) => {
457
+ if (!dataset[id]) throw Error(`Cannot patch document with ID \`${id}\` because it was not found.`);
458
+ return Object.entries(patchOperations).reduce((acc, [type, operation]) => patch[type] ? operation(acc, patch[type]) : acc, dataset[id]);
459
+ });
460
+ for (let result of patched) dataset[result._id] = {
461
+ ...result,
462
+ _rev: transactionId,
463
+ _updatedAt: now
464
+ };
465
+ }
466
+ return dataset;
467
+ }
468
+ function checkGrant(grantExpr, document, identity) {
469
+ let value = evaluateSync(grantExpr, {
470
+ params: { document },
471
+ identity
472
+ });
473
+ return value.type === "boolean" && value.data;
474
+ }
475
+ /**
476
+ * Thrown when a precondition for an action failed.
477
+ */
478
+ var ActionError = class extends Error {
479
+ documentId;
480
+ transactionId;
481
+ constructor(options) {
482
+ super(options.message), Object.assign(this, options);
483
+ }
484
+ }, PermissionActionError = class extends ActionError {};
485
+ /**
486
+ * Creates a `processMutations` wrapper that surfaces application failures as
487
+ * `ActionError`s when the caller asked to preserve their patch operations.
488
+ * With preserved operations, patches can legitimately fail to apply (e.g.
489
+ * re-applied onto a diverged document during a rebase), so wrapping lets a
490
+ * rebase skip the transaction instead of failing the store. Without
491
+ * `preserveOperations`, errors are rethrown untouched.
492
+ */
493
+ function createMutationApplier(options) {
494
+ let { documentId, transactionId, timestamp, preserveOperations } = options;
495
+ return (documents, mutations, documentSetName) => {
496
+ try {
497
+ return processMutations({
498
+ documents,
499
+ transactionId,
500
+ mutations,
501
+ timestamp
502
+ });
503
+ } catch (error) {
504
+ throw preserveOperations ? new ActionError({
505
+ documentId,
506
+ transactionId,
507
+ message: `Failed to apply patches to the ${documentSetName} document: ${error instanceof Error ? error.message : "Unknown error"}`
508
+ }) : error;
509
+ }
510
+ };
511
+ }
512
+ /**
513
+ * Re-applies the operational intent of user-supplied `inc`/`dec` patches to a
514
+ * set of snapshot-diffed patches.
515
+ *
516
+ * The outgoing patches sent to Content Lake are re-derived by diffing the
517
+ * base document before and after the user's patches were applied. That diff
518
+ * collapses an `inc` into a `set` of the resulting number, which turns
519
+ * concurrent increments from different clients into last-write-wins. This
520
+ * helper finds diffed `set` operations that are exactly explained by the
521
+ * user's `inc`/`dec` operations and swaps them back, so the server applies
522
+ * the increment against whatever value is current at commit time.
523
+ *
524
+ * A `set` is only swapped when its value equals the base value plus the
525
+ * accumulated user deltas for that exact path; anything else (e.g. an `inc`
526
+ * combined with a `set` of the same field) keeps the diffed `set`.
527
+ *
528
+ * Content Lake fails the whole transaction when `inc`/`dec` targets a missing
529
+ * path (unlike `set`, which always succeeds). To avoid turning a concurrent
530
+ * field removal into a transaction revert, the emitted patch seeds the target
531
+ * with a `setIfMissing` of the base value; the server executes `setIfMissing`
532
+ * before `inc`/`dec` within a single patch, so a concurrently removed field
533
+ * degrades to the same result the diffed `set` would have produced. A path
534
+ * into a concurrently removed keyed array item can still fail the
535
+ * transaction (`setIfMissing` cannot create array items); the transaction is
536
+ * then reverted and reported, which is preferable to silently resurrecting
537
+ * the item.
538
+ */
539
+ function preserveNumericOperations(baseBefore, userPatches, diffedPatches) {
540
+ if (!baseBefore || !userPatches?.length) return diffedPatches;
541
+ let targets = /* @__PURE__ */ new Map();
542
+ for (let patch of userPatches) for (let [op, sign] of [["inc", 1], ["dec", -1]]) {
543
+ let record = patch[op];
544
+ if (record) {
545
+ for (let [pathExpression, amount] of Object.entries(record)) if (typeof amount == "number") for (let match of jsonMatch(baseBefore, pathExpression)) {
546
+ let path = stringifyPath(match.path), existing = targets.get(path);
547
+ existing ? (existing.expectedValue += sign * amount, existing.delta += sign * amount) : typeof match.value == "number" && targets.set(path, {
548
+ baseValue: match.value,
549
+ expectedValue: match.value + sign * amount,
550
+ delta: sign * amount
551
+ });
552
+ }
553
+ }
554
+ }
555
+ if (!targets.size) return diffedPatches;
556
+ let preserved = /* @__PURE__ */ new Map(), next = diffedPatches.flatMap((patch) => {
557
+ if (!patch.set) return [patch];
558
+ let keptSet = {};
559
+ for (let [path, value] of Object.entries(patch.set)) {
560
+ let target = targets.get(path);
561
+ target && typeof value == "number" && value === target.expectedValue ? preserved.set(path, {
562
+ delta: target.delta,
563
+ baseValue: target.baseValue
564
+ }) : keptSet[path] = value;
565
+ }
566
+ if (Object.keys(keptSet).length === Object.keys(patch.set).length) return [patch];
567
+ let { set: _set, ...rest } = patch, withKept = Object.keys(keptSet).length ? {
568
+ ...rest,
569
+ set: keptSet
570
+ } : rest;
571
+ return Object.keys(withKept).length ? [withKept] : [];
572
+ });
573
+ if (!preserved.size) return next;
574
+ let setIfMissing = {}, inc = {}, dec = {};
575
+ for (let [path, { delta, baseValue }] of preserved) setIfMissing[path] = baseValue, delta >= 0 ? inc[path] = delta : dec[path] = -delta;
576
+ return [...next, {
577
+ setIfMissing,
578
+ ...Object.keys(inc).length && { inc },
579
+ ...Object.keys(dec).length && { dec }
580
+ }];
581
+ }
582
+ /**
583
+ * Shared logic for applying user-provided patches to a single document that
584
+ * is identified by an exact ID (no draft/published wrapping). Used by the
585
+ * liveEdit branch of `document.edit` and by `release.edit`.
586
+ *
587
+ * Returns the updated base + working sets, plus the diffed patches in both
588
+ * raw and mutation form so the caller can decide what to send to the server.
589
+ */
590
+ function applySingleDocPatch({ base: initialBase, working: initialWorking, documentId, patches, transactionId, timestamp, grants, identity, notFoundMessage = "Cannot edit document because it does not exist.", permissionMessage = `You do not have permission to edit document "${documentId}".`, preserveOperations }) {
591
+ let base = initialBase, working = initialWorking, userPatches = patches?.map((patch) => ({ patch: {
592
+ id: documentId,
593
+ ...patch
594
+ } }));
595
+ if (!userPatches?.length) return {
596
+ base,
597
+ working,
598
+ diffedPatches: [],
599
+ workingMutations: []
600
+ };
601
+ if (!working[documentId] || !base[documentId]) throw new ActionError({
602
+ documentId,
603
+ transactionId,
604
+ message: notFoundMessage
605
+ });
606
+ let applyMutations = createMutationApplier({
607
+ documentId,
608
+ transactionId,
609
+ timestamp,
610
+ preserveOperations
611
+ }), baseBefore = base[documentId];
612
+ base = applyMutations(base, userPatches, "base");
613
+ let baseAfter = base[documentId], diffedPatches = preserveOperations ? patches : preserveNumericOperations(baseBefore, patches, diffValue(baseBefore, baseAfter)), workingBefore = working[documentId];
614
+ if (!checkGrant(grants.update, workingBefore, identity)) throw new PermissionActionError({
615
+ documentId,
616
+ transactionId,
617
+ message: permissionMessage
618
+ });
619
+ let workingMutations = diffedPatches.map((patch) => ({ patch: {
620
+ id: documentId,
621
+ ...patch
622
+ } }));
623
+ return working = applyMutations(working, workingMutations, "working"), {
624
+ base,
625
+ working,
626
+ diffedPatches,
627
+ workingMutations
628
+ };
629
+ }
630
+ /**
631
+ * The `document` a favorite write addresses over Comlink.
632
+ *
633
+ * @internal
634
+ */
635
+ function toFavoriteDocument(context) {
636
+ return {
637
+ id: context.documentId,
638
+ type: context.documentType,
639
+ resource: {
640
+ id: context.resourceId,
641
+ type: context.resourceType,
642
+ ...context.schemaName ? { schemaName: context.schemaName } : {}
643
+ }
644
+ };
645
+ }
646
+ function createFavoriteKey(context) {
647
+ return `${context.documentId}:${context.documentType}:${context.resourceId}:${context.resourceType}${context.schemaName ? `:${context.schemaName}` : ""}`;
648
+ }
649
+ /**
650
+ * Fetcher for a document's favorite status, read from the dashboard over
651
+ * comlink, on the shared fetcher cache.
652
+ *
653
+ * @internal
654
+ */
655
+ const favorites = defineFetcher({
656
+ name: "favorites",
657
+ getKey: (_instance, context) => createFavoriteKey(context),
658
+ tags: (_data, context) => [{
659
+ type: "favorite",
660
+ id: createFavoriteKey(context)
661
+ }],
662
+ fetch: (instance) => (context) => {
663
+ let nodeStateSource = getNodeState(instance, {
664
+ name: SDK_NODE_NAME,
665
+ connectTo: SDK_CHANNEL_NAME
666
+ }), payload = { document: toFavoriteDocument(context) };
667
+ return nodeStateSource.observable.pipe(first((nodeState) => !!nodeState), switchMap((nodeState) => {
668
+ let node = nodeState.node;
669
+ return from(node.fetch("dashboard/v1/events/favorite/query", payload)).pipe(map((response) => ({ isFavorited: response.isFavorited })), catchError((err) => (console.error("Favorites service connection error", err), of({ isFavorited: !1 }))));
670
+ }));
671
+ }
672
+ }), setFavorite = defineMutation({
673
+ name: "setFavorite",
674
+ mutationFn: (instance) => ({ isFavorited, ...context }) => {
675
+ let nodeStateSource = getNodeState(instance, {
676
+ name: SDK_NODE_NAME,
677
+ connectTo: SDK_CHANNEL_NAME
678
+ }), payload = {
679
+ eventType: isFavorited ? "added" : "removed",
680
+ document: toFavoriteDocument(context)
681
+ };
682
+ return nodeStateSource.observable.pipe(first((nodeState) => !!nodeState), switchMap((nodeState) => {
683
+ let node = nodeState.node;
684
+ return from(node.fetch("dashboard/v1/events/favorite/mutate", payload)).pipe(map((response) => {
685
+ if (!response.success) throw Error("Failed to update favorite status");
686
+ return { isFavorited };
687
+ }));
688
+ }));
689
+ },
690
+ onMutate: (write, { isFavorited, ...context }) => write(favorites, [context], { isFavorited }),
691
+ invalidates: (_result, input) => [{
692
+ type: "favorite",
693
+ id: createFavoriteKey(input)
694
+ }]
695
+ }), PROJECT_API_VERSION = "2025-07-18", USERS_STATE_CLEAR_DELAY = 5e3, getUsersKey = (instance, { resourceType, organizationId, batchSize = 100, projectId = instance.config.projectId, userId } = {}) => JSON.stringify({
696
+ resourceType,
697
+ organizationId,
698
+ batchSize,
699
+ projectId,
700
+ userId
701
+ }), parseUsersKey = (key) => JSON.parse(key), addSubscription = (subscriptionId, key) => (prev) => {
702
+ let group = prev.users[key], subscriptions = [...group?.subscriptions ?? [], subscriptionId];
703
+ return {
704
+ ...prev,
705
+ users: {
706
+ ...prev.users,
707
+ [key]: {
708
+ ...group,
709
+ subscriptions
710
+ }
711
+ }
712
+ };
713
+ }, removeSubscription = (subscriptionId, key) => (prev) => {
714
+ let group = prev.users[key];
715
+ if (!group) return prev;
716
+ let subscriptions = group.subscriptions.filter((id) => id !== subscriptionId);
717
+ return subscriptions.length ? {
718
+ ...prev,
719
+ users: {
720
+ ...prev.users,
721
+ [key]: {
722
+ ...group,
723
+ subscriptions
724
+ }
725
+ }
726
+ } : {
727
+ ...prev,
728
+ users: omitProperty(prev.users, key)
729
+ };
730
+ }, setUsersData = (key, { data, nextCursor, totalCount }) => (prev) => {
731
+ let group = prev.users[key];
732
+ if (!group) return prev;
733
+ let users = [...group.users ?? [], ...data];
734
+ return {
735
+ ...prev,
736
+ users: {
737
+ ...prev.users,
738
+ [key]: {
739
+ ...group,
740
+ users,
741
+ totalCount,
742
+ nextCursor
743
+ }
744
+ }
745
+ };
746
+ }, updateLastLoadMoreRequest = (timestamp, key) => (prev) => {
747
+ let group = prev.users[key];
748
+ return group ? {
749
+ ...prev,
750
+ users: {
751
+ ...prev.users,
752
+ [key]: {
753
+ ...group,
754
+ lastLoadMoreRequest: timestamp
755
+ }
756
+ }
757
+ } : prev;
758
+ }, setUsersError = (key, error) => (prev) => {
759
+ let group = prev.users[key];
760
+ return group ? {
761
+ ...prev,
762
+ users: {
763
+ ...prev.users,
764
+ [key]: {
765
+ ...group,
766
+ error
767
+ }
768
+ }
769
+ } : prev;
770
+ }, cancelRequest = (key) => (prev) => {
771
+ let group = prev.users[key];
772
+ return !group || group.subscriptions.length ? prev : {
773
+ ...prev,
774
+ users: omitProperty(prev.users, key)
775
+ };
776
+ }, initializeRequest = (key) => (prev) => prev.users[key] ? prev : {
777
+ ...prev,
778
+ users: {
779
+ ...prev.users,
780
+ [key]: { subscriptions: [] }
781
+ }
782
+ };
783
+ /**
784
+ * Emits Live Content API messages for a dataset so consumers can invalidate
785
+ * fetched data via sync tags.
786
+ *
787
+ * All consumers observe the same underlying EventSource connection:
788
+ * `@sanity/client` caches the live-events stream per URL and connection
789
+ * options, and every subscription made through this function uses the same
790
+ * API version and request tag.
791
+ *
792
+ * @internal
793
+ */
794
+ function observeLiveEvents(instance, { resource, onCorsError }) {
795
+ let hasToken$ = getTokenState(instance).observable.pipe(map(Boolean), distinctUntilChanged());
796
+ return getClientState(instance, {
797
+ apiVersion: "v2025-05-06",
798
+ resource
799
+ }).observable.pipe(switchMap((client) => (client.config().auth ? hasToken$ : of(!!client.config().token)).pipe(map((includeDrafts) => [client, includeDrafts])))).pipe(switchMap(([client, includeDrafts]) => retryWithCredential(defer(() => client.live.events({
800
+ includeDrafts,
801
+ tag: "live-events"
802
+ })), getClientAuthState(instance), (error, _, credentialChanged) => error instanceof CorsOriginError ? (onCorsError(error), EMPTY) : error instanceof DisconnectError ? EMPTY : error instanceof ConnectionFailedError && typeof error.status == "number" && error.status >= 400 && error.status < 500 ? credentialChanged : timer(1e3))), filter((e) => e.type === "message"));
803
+ }
804
+ /**
805
+ * Emits every release document (including archived and published), refetching
806
+ * whenever a Live Content API event matches the query's sync tags.
807
+ *
808
+ * This fetches directly through the client store — deliberately not via the
809
+ * query store — because release data is itself an input to query perspective
810
+ * resolution (`getPerspectiveState`); fetching through the query store would
811
+ * make the two stores mutually dependent.
812
+ *
813
+ * @internal
814
+ */
815
+ function observeReleases(instance, { resource, onCorsError, onError }) {
816
+ return getClientState(instance, {
817
+ apiVersion: "v2025-05-06",
818
+ resource
819
+ }).observable.pipe(switchMap((client) => {
820
+ let syncTags$ = new BehaviorSubject(void 0);
821
+ return combineLatest([observeLiveEvents(instance, {
822
+ resource,
823
+ onCorsError
824
+ }).pipe(startWith(void 0)), syncTags$]).pipe(filter(([message, syncTags]) => message === void 0 || message.tags.some((tag) => syncTags?.includes(tag))), map(([message]) => message?.id), distinctUntilChanged()).pipe(switchMap((lastLiveEventId) => client.observable.fetch("releases::all()", {}, {
825
+ perspective: "raw",
826
+ filterResponse: !1,
827
+ returnQuery: !1,
828
+ lastLiveEventId,
829
+ tag: "releases"
830
+ })), tap((response) => {
831
+ syncTags$.next(response.syncTags);
832
+ }), map((response) => response.result));
833
+ }), retryRead(getClientAuthState(instance), onError));
834
+ }
835
+ function sortReleases(releases = []) {
836
+ return [...releases].sort((a, b) => {
837
+ let aType = a.metadata?.releaseType, bType = b.metadata?.releaseType;
838
+ if (aType === "undecided" && bType !== "undecided") return -1;
839
+ if (aType !== "undecided" && bType === "undecided") return 1;
840
+ if (aType === "undecided" && bType === "undecided") return new Date(b._createdAt).getTime() - new Date(a._createdAt).getTime();
841
+ if (aType === "scheduled" && bType === "scheduled") {
842
+ let aPublishAt = a.publishAt || a.metadata?.intendedPublishAt;
843
+ if (!aPublishAt) return 1;
844
+ let bPublishAt = b.publishAt || b.metadata?.intendedPublishAt;
845
+ return bPublishAt ? new Date(bPublishAt).getTime() - new Date(aPublishAt).getTime() : -1;
846
+ }
847
+ return aType === "asap" && bType !== "asap" ? 1 : aType !== "asap" && bType === "asap" ? -1 : aType === "asap" && bType === "asap" ? new Date(b._createdAt).getTime() - new Date(a._createdAt).getTime() : 0;
848
+ });
849
+ }
850
+ const ARCHIVED_RELEASE_STATES = ["archived", "published"], STABLE_EMPTY_RELEASES = [], releasesStore = defineStore({
851
+ name: "Releases",
852
+ getInitialState: () => ({
853
+ activeReleases: STABLE_EMPTY_RELEASES,
854
+ allReleases: STABLE_EMPTY_RELEASES
855
+ }),
856
+ upstream: (context) => subscribeToReleases(context)
857
+ }), _getActiveReleasesState = bindActionByResource(releasesStore, createStateSourceAction({ selector: ({ state }) => {
858
+ if (state.error ?? state.fetchError) throw state.error ?? state.fetchError;
859
+ return state.activeReleases;
860
+ } })), getActiveReleasesState = (instance, options) => _getActiveReleasesState(instance, options ?? {}), _getAllReleasesState = bindActionByResource(releasesStore, createStateSourceAction({ selector: ({ state }) => {
861
+ if (state.error ?? state.fetchError) throw state.error ?? state.fetchError;
862
+ return state.allReleases;
863
+ } })), getAllReleasesState = (instance, options) => _getAllReleasesState(instance, options ?? {}), subscribeToReleases = ({ instance, state, key: { resource } }) => observeReleases(instance, {
864
+ resource,
865
+ onCorsError: (error) => state.set("setError", { error }),
866
+ onError: (fetchError) => state.set("setFetchError", { fetchError })
867
+ }).pipe(map((releases) => {
868
+ let sorted = sortReleases(releases ?? STABLE_EMPTY_RELEASES).reverse();
869
+ state.set("setReleases", {
870
+ allReleases: sorted,
871
+ activeReleases: sorted.filter((release) => !ARCHIVED_RELEASE_STATES.includes(release.state)),
872
+ fetchError: void 0
873
+ });
874
+ })).subscribe({ error: (error) => state.set("setError", { error }) }), optionsCache = /* @__PURE__ */ new Map(), selectInstancePerspective = (context, _) => context.instance.config.perspective, selectActiveReleases = (context) => context.state.activeReleases, selectOptions = (_context, options) => options, memoizedOptionsSelector = createSelector([selectActiveReleases, selectOptions], (activeReleases, options) => {
875
+ if (!options || !activeReleases) return options;
876
+ let releaseIds = activeReleases.map((release) => release._id).join(","), nestedCache = optionsCache.get(releaseIds);
877
+ nestedCache || (nestedCache = /* @__PURE__ */ new Map(), optionsCache.set(releaseIds, nestedCache));
878
+ let optionsKey = JSON.stringify(options), cachedOptions = nestedCache.get(optionsKey);
879
+ return cachedOptions || (cachedOptions = options, nestedCache.set(optionsKey, cachedOptions)), cachedOptions;
880
+ }), _getPerspectiveStateSelector = createStateSourceAction({ selector: createSelector([
881
+ selectInstancePerspective,
882
+ selectActiveReleases,
883
+ memoizedOptionsSelector
884
+ ], (instancePerspective, activeReleases, memoizedOptions) => {
885
+ let perspective = memoizedOptions?.perspective ?? instancePerspective ?? "drafts";
886
+ if (!isReleasePerspective(perspective)) return perspective;
887
+ if (!activeReleases || activeReleases.length === 0) return;
888
+ let releaseNames = sortReleases(activeReleases).map((release) => release.name), index = releaseNames.findIndex((name) => name === perspective.releaseName);
889
+ if (index < 0) throw Error(`Release "${perspective.releaseName}" not found in active releases`);
890
+ return ["drafts", ...releaseNames.slice(0, index + 1)].filter((name) => !perspective.excludedPerspectives?.includes(name)).reverse();
891
+ }) }), _boundGetPerspectiveState = bindActionByResource(releasesStore, _getPerspectiveStateSelector), getPerspectiveState = (instance, ...rest) => _boundGetPerspectiveState(instance, ...rest.length ? rest : [{}]), QUERY_STATE_CLEAR_DELAY = UPSTREAM_CLOSE_DELAY_MS, setQueryError = (key, error) => (prev) => {
892
+ let prevQuery = prev.queries[key];
893
+ return prevQuery ? {
894
+ ...prev,
895
+ queries: {
896
+ ...prev.queries,
897
+ [key]: {
898
+ ...prevQuery,
899
+ error
900
+ }
901
+ }
902
+ } : prev;
903
+ }, setQueryData = (key, result, syncTags) => (prev) => {
904
+ let prevQuery = prev.queries[key];
905
+ return prevQuery ? {
906
+ ...prev,
907
+ queries: {
908
+ ...prev.queries,
909
+ [key]: {
910
+ ...prevQuery,
911
+ result: result ?? null,
912
+ syncTags
913
+ }
914
+ }
915
+ } : prev;
916
+ }, setLastLiveEventId = (key, lastLiveEventId) => (prev) => {
917
+ let prevQuery = prev.queries[key];
918
+ return prevQuery ? {
919
+ ...prev,
920
+ queries: {
921
+ ...prev.queries,
922
+ [key]: {
923
+ ...prevQuery,
924
+ lastLiveEventId
925
+ }
926
+ }
927
+ } : prev;
928
+ }, addSubscriber = (key, subscriptionId) => (prev) => {
929
+ let prevQuery = prev.queries[key], subscribers = [...prevQuery?.subscribers ?? [], subscriptionId];
930
+ return {
931
+ ...prev,
932
+ queries: {
933
+ ...prev.queries,
934
+ [key]: {
935
+ ...prevQuery,
936
+ subscribers
937
+ }
938
+ }
939
+ };
940
+ }, removeSubscriber = (key, subscriptionId) => (prev) => {
941
+ let prevQuery = prev.queries[key];
942
+ if (!prevQuery) return prev;
943
+ let subscribers = prevQuery.subscribers.filter((id) => id !== subscriptionId);
944
+ return subscribers.length ? {
945
+ ...prev,
946
+ queries: {
947
+ ...prev.queries,
948
+ [key]: {
949
+ ...prevQuery,
950
+ subscribers
951
+ }
952
+ }
953
+ } : {
954
+ ...prev,
955
+ queries: omitProperty(prev.queries, key)
956
+ };
957
+ }, EMPTY_ARRAY = [], getQueryKey = (instance, options) => JSON.stringify(normalizeOptionsWithPerspective(instance, options)), parseQueryKey = (key) => JSON.parse(key);
958
+ /**
959
+ * Ensures the query key includes an effective perspective so that
960
+ * implicit differences (e.g. different instance.config.perspective)
961
+ * don't collide in the dataset-scoped store.
962
+ *
963
+ * Since perspectives are unique, we can depend on the release stacks
964
+ * to be correct when we retrieve the results.
965
+ *
966
+ */
967
+ function normalizeOptionsWithPerspective(instance, options) {
968
+ if (options.perspective !== void 0) return options;
969
+ let instancePerspective = instance.config.perspective;
970
+ return {
971
+ ...options,
972
+ perspective: instancePerspective === void 0 ? "drafts" : instancePerspective
973
+ };
974
+ }
975
+ const queryStore = defineStore({
976
+ name: "QueryStore",
977
+ getInitialState: () => ({ queries: {} }),
978
+ initialize(context) {
979
+ let subscription = listenForNewSubscribersAndFetch(context);
980
+ return () => subscription.unsubscribe();
981
+ },
982
+ upstream: (context) => listenToLiveClientAndSetLastLiveEventIds(context)
983
+ }), errorHandler = (state) => (error) => state.set("setError", { error }), listenForNewSubscribersAndFetch = ({ state, instance }) => state.observable.pipe(map((s) => new Set(Object.keys(s.queries))), distinctUntilChanged((curr, next) => curr.size === next.size && Array.from(next).every((i) => curr.has(i))), startWith(/* @__PURE__ */ new Set()), pairwise(), mergeMap(([curr, next]) => {
984
+ let added = Array.from(next).filter((i) => !curr.has(i)), removed = Array.from(curr).filter((i) => !next.has(i));
985
+ return [...added.map((key) => ({
986
+ key,
987
+ added: !0
988
+ })), ...removed.map((key) => ({
989
+ key,
990
+ added: !1
991
+ }))];
992
+ }), groupBy((i) => i.key), mergeMap((group$) => group$.pipe(switchMap((e) => {
993
+ if (!e.added) return EMPTY;
994
+ let lastLiveEventId$ = state.observable.pipe(map((s) => s.queries[group$.key]?.lastLiveEventId), distinctUntilChanged()), { query, params, projectId, dataset, tag, resource, perspective: perspectiveFromOptions, ...restOptions } = parseQueryKey(group$.key), perspective$ = isReleasePerspective(perspectiveFromOptions) ? getPerspectiveState(instance, {
995
+ perspective: perspectiveFromOptions,
996
+ resource
997
+ }).observable.pipe(filter(Boolean)) : of(perspectiveFromOptions ?? "drafts"), client$ = getClientState(instance, {
998
+ apiVersion: "v2025-05-06",
999
+ projectId,
1000
+ dataset,
1001
+ resource
1002
+ }).observable;
1003
+ return combineLatest({
1004
+ lastLiveEventId: lastLiveEventId$,
1005
+ client: client$,
1006
+ perspective: perspective$
1007
+ }).pipe(switchMap(({ lastLiveEventId, client, perspective }) => client.observable.fetch(query, params, {
1008
+ ...restOptions,
1009
+ perspective,
1010
+ filterResponse: !1,
1011
+ returnQuery: !1,
1012
+ lastLiveEventId,
1013
+ tag
1014
+ })), tap(({ result, syncTags }) => {
1015
+ state.set("setQueryData", setQueryData(group$.key, result, syncTags));
1016
+ }), retryRead(getClientAuthState(instance), (error) => state.set("setQueryError", setQueryError(group$.key, withProjectAccessMessage(instance, error)))));
1017
+ })))).subscribe({ error: errorHandler(state) }), listenToLiveClientAndSetLastLiveEventIds = ({ state, instance, key: { resource } }) => {
1018
+ let liveMessages$ = observeLiveEvents(instance, {
1019
+ resource,
1020
+ onCorsError: (error) => state.set("setError", { error })
1021
+ }).pipe(share());
1022
+ return state.observable.pipe(mergeMap((s) => Object.entries(s.queries)), groupBy(([key]) => key), mergeMap((group$) => {
1023
+ let syncTags$ = group$.pipe(map(([, queryState]) => queryState), map((i) => i?.syncTags ?? EMPTY_ARRAY), distinctUntilChanged());
1024
+ return combineLatest([liveMessages$, syncTags$]).pipe(filter(([message, syncTags]) => message.tags.some((tag) => syncTags.includes(tag))), tap(([message]) => {
1025
+ state.set("setLastLiveEventId", setLastLiveEventId(group$.key, message.id));
1026
+ }));
1027
+ })).subscribe({ error: errorHandler(state) });
1028
+ };
1029
+ /** @beta */
1030
+ function getQueryState(...args) {
1031
+ return _getQueryState(...args);
1032
+ }
1033
+ const _getQueryState = bindActionByResource(queryStore, createStateSourceAction({
1034
+ selector: ({ state, instance }, options) => {
1035
+ if (state.error) throw state.error;
1036
+ let key = getQueryKey(instance, options), queryState = state.queries[key];
1037
+ if (queryState?.error) throw queryState.error;
1038
+ return queryState?.result;
1039
+ },
1040
+ onSubscribe: ({ state, instance }, options) => {
1041
+ let subscriptionId = randomId(16), key = getQueryKey(instance, options);
1042
+ return state.set("addSubscriber", addSubscriber(key, subscriptionId)), () => {
1043
+ setCleanupTimeout(() => state.set("removeSubscriber", removeSubscriber(key, subscriptionId)), QUERY_STATE_CLEAR_DELAY);
1044
+ };
1045
+ }
1046
+ }));
1047
+ /** @beta */
1048
+ function resolveQuery(...args) {
1049
+ return _resolveQuery(...args);
1050
+ }
1051
+ const _resolveQuery = bindActionByResource(queryStore, ({ state, instance }, { signal, ...options }) => {
1052
+ let normalized = normalizeOptionsWithPerspective(instance, options), { getCurrent } = getQueryState(instance, normalized), key = getQueryKey(instance, normalized), subscriptionId = randomId(16);
1053
+ state.set("addSubscriber", addSubscriber(key, subscriptionId));
1054
+ let aborted$ = signal ? new Observable((observer) => {
1055
+ let cleanup = () => {
1056
+ signal.removeEventListener("abort", listener);
1057
+ }, listener = () => {
1058
+ observer.error(new DOMException("The operation was aborted.", "AbortError")), observer.complete(), cleanup();
1059
+ };
1060
+ return signal.addEventListener("abort", listener), cleanup;
1061
+ }).pipe(catchError((error) => {
1062
+ throw error instanceof Error && error.name === "AbortError" && state.set("removeSubscriber", removeSubscriber(key, subscriptionId)), error;
1063
+ })) : NEVER, resolved$ = state.observable.pipe(map(getCurrent), first((i) => i !== void 0)), promise = firstValueFrom(race([resolved$, aborted$])), releaseSubscriber = () => {
1064
+ setCleanupTimeout(() => {
1065
+ state.set("removeSubscriber", removeSubscriber(key, subscriptionId));
1066
+ }, QUERY_STATE_CLEAR_DELAY);
1067
+ };
1068
+ return promise.then(releaseSubscriber, releaseSubscriber), promise;
1069
+ }), CORE_SDK_VERSION = getEnv("PKG_VERSION") || "3.13.0-next.20261106104949-development";
1070
+ export { patchOperations as A, ActionError as C, createMutationApplier as D, checkGrant as E, getProjectAccessErrorDetails as M, getProjectAccessErrorProjectId as N, preserveNumericOperations as O, getSignInMethodLabel as P, toFavoriteDocument as S, applySingleDocPatch as T, updateLastLoadMoreRequest as _, resolveQuery as a, favorites as b, getAllReleasesState as c, getUsersKey as d, initializeRequest as f, setUsersError as g, setUsersData as h, parseQueryKey as i, processMutations as j, getId as k, addSubscription as l, removeSubscription as m, getQueryKey as n, getPerspectiveState as o, parseUsersKey as p, getQueryState as r, getActiveReleasesState as s, CORE_SDK_VERSION as t, cancelRequest as u, PROJECT_API_VERSION as v, PermissionActionError as w, setFavorite as x, USERS_STATE_CLEAR_DELAY as y };
1071
+
1072
+ //# sourceMappingURL=version-DRnj2zr5.js.map