@sanity/sdk 3.15.0 → 3.16.0-next.20261120142616

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/_exports/_internal.d.ts +5 -5
  2. package/dist/_exports/_internal.js +2 -2
  3. package/dist/_exports/agent.d.ts +1 -1
  4. package/dist/_exports/collaboration.d.ts +3 -3
  5. package/dist/_exports/collaboration.js +2 -2
  6. package/dist/_exports/comlink.d.ts +2 -2
  7. package/dist/_exports/dashboard.d.ts +2 -2
  8. package/dist/{applications-DV6XreC6.d.ts → applications-D84Jz932.d.ts} +10 -3
  9. package/dist/applications-D84Jz932.d.ts.map +1 -0
  10. package/dist/{buildCommentThreads-C1hKJdCg.js → buildCommentThreads-C_XIm6jE.js} +2 -2
  11. package/dist/{buildCommentThreads-C1hKJdCg.js.map → buildCommentThreads-C_XIm6jE.js.map} +1 -1
  12. package/dist/{bus-BsPCAXk3.d.ts → bus-CdYznZ0s.d.ts} +2 -2
  13. package/dist/{bus-BsPCAXk3.d.ts.map → bus-CdYznZ0s.d.ts.map} +1 -1
  14. package/dist/{types-Dp4-_rxL.js → commentFieldPath-32Sd8yky.js} +17 -9
  15. package/dist/commentFieldPath-32Sd8yky.js.map +1 -0
  16. package/dist/{commentsOptions-DuLgrFc5.d.ts → commentsOptions-ChZhk8mb.d.ts} +2 -2
  17. package/dist/{commentsOptions-DuLgrFc5.d.ts.map → commentsOptions-ChZhk8mb.d.ts.map} +1 -1
  18. package/dist/{createSanityInstance-BtgGknwT.d.ts → createSanityInstance-C1wD7RmA.d.ts} +13 -1
  19. package/dist/{createSanityInstance-BtgGknwT.d.ts.map → createSanityInstance-C1wD7RmA.d.ts.map} +1 -1
  20. package/dist/createStateSourceAction-Bn0po7Z3.js.map +1 -1
  21. package/dist/{createStateSourceAction-CzAwbNjw.d.ts → createStateSourceAction-Cb7ZjAd8.d.ts} +2 -2
  22. package/dist/{createStateSourceAction-CzAwbNjw.d.ts.map → createStateSourceAction-Cb7ZjAd8.d.ts.map} +1 -1
  23. package/dist/index.d.ts +3 -3
  24. package/dist/index.js +1207 -6
  25. package/dist/index.js.map +1 -1
  26. package/dist/{version-BbLOOPMX.js → version-CiC6TBKI.js} +7 -1208
  27. package/dist/version-CiC6TBKI.js.map +1 -0
  28. package/package.json +1 -1
  29. package/src/config/sanityConfig.ts +12 -0
  30. package/src/store/fetcherStore.test.ts +129 -2
  31. package/src/store/fetcherStore.ts +45 -10
  32. package/dist/applications-DV6XreC6.d.ts.map +0 -1
  33. package/dist/types-Dp4-_rxL.js.map +0 -1
  34. package/dist/version-BbLOOPMX.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import { c as cleanupTimer, f as isReleasePerspective, h as isMediaLibraryResource, i as bindActionGlobally, m as isDatasetResource, n as bindActionByResource, o as UPSTREAM_CLOSE_DELAY_MS, p as isCanvasResource, r as bindActionByResourceAndPerspective, s as defineStore, t as createStateSourceAction, u as setCleanupTimeout } from "./createStateSourceAction-Bn0po7Z3.js";
2
- import { A as SUBMISSION_RETRY_MAX_DELAY, B as getTokenFromLocation, C as OutOfSyncError, E as API_VERSION$8, G as createLogger, H as getAuthLogger, J as DEFAULT_API_VERSION, M as createLoggedInAuthState, N as getAuthCode, O as INITIAL_OUTGOING_THROTTLE_TIME, P as getCleanedUrl, R as getDefaultLocation, T as ACL_RETRY_MAX_DELAY, V as AuthStateType, W as configureLogging$1, X as REQUEST_TAG_PREFIX, Y as DEFAULT_BASE, _ as toOAuthTokens, a as getClientAuthState, b as retryRead, c as getLoginUrlState, d as runOAuthTokenRefresh, f as appendResourceIndicator, g as serializeTokens, h as postTokenRequest, i as getAuthState, k as SUBMISSION_RETRY_BASE_DELAY, l as getTokenState, m as getOAuthOptions, o as getCurrentUserState, p as createOAuthClient, s as getIsInDashboardState, t as authStore, u as setAuthToken, w as DocumentInaccessibleError, x as retryWithCredential, y as retryOnCredentialChange, z as getDefaultStorage } from "./authStore-BW6CPIWb.js";
2
+ import { A as SUBMISSION_RETRY_MAX_DELAY, B as getTokenFromLocation, C as OutOfSyncError, D as DOCUMENT_STATE_CLEAR_DELAY, E as API_VERSION$8, G as createLogger, H as getAuthLogger, J as DEFAULT_API_VERSION, M as createLoggedInAuthState, N as getAuthCode, O as INITIAL_OUTGOING_THROTTLE_TIME, P as getCleanedUrl, R as getDefaultLocation, T as ACL_RETRY_MAX_DELAY, V as AuthStateType, W as configureLogging$1, X as REQUEST_TAG_PREFIX, Y as DEFAULT_BASE, _ as toOAuthTokens, a as getClientAuthState, b as retryRead, c as getLoginUrlState, d as runOAuthTokenRefresh, f as appendResourceIndicator, g as serializeTokens, h as postTokenRequest, i as getAuthState, j as UNVERIFIED_REVISION_RETENTION_TIME, k as SUBMISSION_RETRY_BASE_DELAY, l as getTokenState, m as getOAuthOptions, o as getCurrentUserState, p as createOAuthClient, s as getIsInDashboardState, t as authStore, u as setAuthToken, w as DocumentInaccessibleError, x as retryWithCredential, y as retryOnCredentialChange, z as getDefaultStorage } from "./authStore-BW6CPIWb.js";
3
3
  import { a as getDashboardMessageBus, h as randomUuid, m as randomId, n as getDashboardOrganizationId, r as getTopicState } from "./topicStore-B3dYW015.js";
4
4
  import { n as isObject, r as omitProperty, t as isDeepEqual } from "./object-CxXlSVg7.js";
5
5
  import { n as getClient, r as getClientState } from "./clientStore-C7pmeImZ.js";
6
- import { i as definePagedFetcher, n as defineFetcher, r as defineMutation, t as toCommentFieldPath } from "./types-Dp4-_rxL.js";
7
- import { a as compareProjectOrganization, i as projects, n as threadComments, o as observeAppOrganizationId, r as project, s as buildQuery } from "./buildCommentThreads-C1hKJdCg.js";
8
- import { A as getDocumentIdsFromHandleLikes, B as patchOperations, D as applyFirstQueuedTransaction, F as throwDocumentError, G as getProjectAccessErrorProjectId, H as getReleaseDocumentId, I as transitionAppliedTransactionsToOutgoing, L as calculatePermissions, M as queueTransaction, N as removeQueuedTransaction, O as applyRemoteDocument, P as revertOutgoingTransaction, R as createGrantsLookup, S as toPreferenceError, T as setFavorite, U as isReleaseAction, V as processMutations, _ as setUsersError, b as USERS_STATE_CLEAR_DELAY, c as getActiveReleasesState, d as cancelRequest, f as getUsersKey, g as setUsersData, h as removeSubscription, i as getQueryState, j as manageSubscriberIds, k as cleanupOutgoingTransaction, l as getAllReleasesState, m as parseUsersKey, o as resolveQuery, p as initializeRequest, s as getPerspectiveState, t as CORE_SDK_VERSION, u as addSubscription, v as updateLastLoadMoreRequest, w as favorites, x as PreferenceError, y as PROJECT_API_VERSION, z as ActionError } from "./version-BbLOOPMX.js";
6
+ import { i as definePagedFetcher, n as defineFetcher, r as defineMutation, t as toCommentFieldPath } from "./commentFieldPath-32Sd8yky.js";
7
+ import { a as compareProjectOrganization, i as projects, n as threadComments, o as observeAppOrganizationId, r as project, s as buildQuery } from "./buildCommentThreads-C_XIm6jE.js";
8
+ import { A as checkGrant, D as ActionError, F as processMutations, L as getProjectAccessErrorProjectId, M as preserveNumericOperations, N as getId, O as PermissionActionError, P as patchOperations, S as toPreferenceError, T as setFavorite, _ as setUsersError, b as USERS_STATE_CLEAR_DELAY, c as getActiveReleasesState, d as cancelRequest, f as getUsersKey, g as setUsersData, h as removeSubscription, i as getQueryState, j as createMutationApplier, k as applySingleDocPatch, l as getAllReleasesState, m as parseUsersKey, o as resolveQuery, p as initializeRequest, s as getPerspectiveState, t as CORE_SDK_VERSION, u as addSubscription, v as updateLastLoadMoreRequest, w as favorites, x as PreferenceError, y as PROJECT_API_VERSION } from "./version-CiC6TBKI.js";
9
9
  import { ClientError, CorsOriginError } from "@sanity/client";
10
10
  import { BehaviorSubject, EMPTY, NEVER, Observable, ReplaySubject, Subject, Subscription, auditTime, catchError, combineLatest, concat, concatMap, debounceTime, defer, distinctUntilChanged, filter, first, firstValueFrom, from, fromEvent, groupBy, map, merge, mergeMap, of, pairwise, partition, race, share, skip, startWith, switchMap, take, takeUntil, tap, throttle, throwError, timer, withLatestFrom } from "rxjs";
11
11
  import "@sanity/types";
@@ -14,8 +14,9 @@ import { DocumentId, getDraftId, getPublishedId, getVersionId, isDraftId, isPubl
14
14
  import { getIndexForKey, getPathDepth, joinPaths, jsonMatch, jsonMatch as jsonMatch$1, slicePath, stringifyPath } from "@sanity/json-match";
15
15
  import { SanityEncoder } from "@sanity/mutate";
16
16
  import { createDocumentLoaderFromClient } from "@sanity/mutate/_unstable_store";
17
- import "groq-js";
17
+ import { parse } from "groq-js";
18
18
  import { catchError as catchError$1, distinctUntilChanged as distinctUntilChanged$1, map as map$1, mergeMap as mergeMap$1, retry as retry$1, scan, share as share$1, switchMap as switchMap$1 } from "rxjs/operators";
19
+ import { diffValue } from "@sanity/diff-patch";
19
20
  import { fromUrl } from "@sanity/bifur-client";
20
21
  /**
21
22
  * Creates a new Sanity resource instance
@@ -1742,6 +1743,27 @@ function deleteRelease(handle) {
1742
1743
  ...handle
1743
1744
  };
1744
1745
  }
1746
+ /**
1747
+ * Returns the full release document ID for the given release name.
1748
+ * e.g. `getReleaseDocumentId('my-release') === '_.releases.my-release'`
1749
+ * @beta
1750
+ */
1751
+ function getReleaseDocumentId(releaseId) {
1752
+ return `_.releases.${releaseId}`;
1753
+ }
1754
+ const RELEASE_ACTION_TYPES = /* @__PURE__ */ new Set([
1755
+ "release.create",
1756
+ "release.edit",
1757
+ "release.publish",
1758
+ "release.schedule",
1759
+ "release.unschedule",
1760
+ "release.archive",
1761
+ "release.unarchive",
1762
+ "release.delete"
1763
+ ]);
1764
+ function isReleaseAction(action) {
1765
+ return RELEASE_ACTION_TYPES.has(action.type);
1766
+ }
1745
1767
  var DeadlineExceededError = class extends OutOfSyncError {
1746
1768
  constructor(message, state) {
1747
1769
  super(message, state), this.name = "DeadlineExceededError";
@@ -1861,7 +1883,1186 @@ const listen = ({ state }, documentId) => {
1861
1883
  ...previousRev && { previousRev }
1862
1884
  };
1863
1885
  }));
1864
- }, actionMap = {
1886
+ };
1887
+ var MultiKeyWeakMap = class MultiKeyWeakMap {
1888
+ #rootMap = /* @__PURE__ */ new WeakMap();
1889
+ static #globalIdCounter = 0;
1890
+ #idCache = /* @__PURE__ */ new WeakMap();
1891
+ /**
1892
+ * Assigns a numeric ID to the key.
1893
+ */
1894
+ #assignId(key) {
1895
+ let cachedId = this.#idCache.get(key);
1896
+ if (cachedId !== void 0) return cachedId;
1897
+ let id = MultiKeyWeakMap.#globalIdCounter;
1898
+ return this.#idCache.set(key, id), MultiKeyWeakMap.#globalIdCounter++, id;
1899
+ }
1900
+ /**
1901
+ * Remove duplicate keys and arrange them in a consistent order
1902
+ * by sorting according to their assigned IDs.
1903
+ */
1904
+ #arrangeKeys(keys) {
1905
+ let keyed = Array.from(new Set(keys)).map((key) => [this.#assignId(key), key]);
1906
+ return keyed.sort((a, b) => a[0] - b[0]), keyed.map(([, key]) => key);
1907
+ }
1908
+ /**
1909
+ * Recursively search the nested WeakMap structure for the value.
1910
+ */
1911
+ #getDeep(keys, map) {
1912
+ if (keys.length === 0) return;
1913
+ let [firstKey, ...restKeys] = keys, node = map.get(firstKey);
1914
+ if (node) return restKeys.length === 0 ? node.value : this.#getDeep(restKeys, node.next);
1915
+ }
1916
+ /**
1917
+ * Recursively create nodes along the key chain until the final key
1918
+ * is reached, then assign the value.
1919
+ */
1920
+ #setDeep(keys, map, value) {
1921
+ if (keys.length === 0) return;
1922
+ let [firstKey, ...restKeys] = keys, node = map.get(firstKey);
1923
+ node || (node = {
1924
+ value: void 0,
1925
+ next: /* @__PURE__ */ new WeakMap()
1926
+ }, map.set(firstKey, node)), restKeys.length === 0 ? node.value = value : this.#setDeep(restKeys, node.next, value);
1927
+ }
1928
+ /**
1929
+ * Retrieves the value associated with the array of keys.
1930
+ * The keys are de-duplicated and sorted so that the order does not matter.
1931
+ */
1932
+ get(keys) {
1933
+ let arrangedKeys = this.#arrangeKeys(keys);
1934
+ return this.#getDeep(arrangedKeys, this.#rootMap);
1935
+ }
1936
+ /**
1937
+ * Associates the value with the given array of keys.
1938
+ */
1939
+ set(keys, value) {
1940
+ let arrangedKeys = this.#arrangeKeys(keys);
1941
+ this.#setDeep(arrangedKeys, this.#rootMap, value);
1942
+ }
1943
+ };
1944
+ function createGrantsLookup(datasetAcl) {
1945
+ let filtersByGrant = {
1946
+ create: /* @__PURE__ */ new Set(),
1947
+ history: /* @__PURE__ */ new Set(),
1948
+ read: /* @__PURE__ */ new Set(),
1949
+ update: /* @__PURE__ */ new Set()
1950
+ };
1951
+ for (let entry of datasetAcl) for (let grant of entry.permissions) {
1952
+ let set = filtersByGrant[grant];
1953
+ set && (set.add(entry.filter), filtersByGrant[grant] = set);
1954
+ }
1955
+ return Object.fromEntries(Object.entries(filtersByGrant).map(([grant, filters]) => {
1956
+ let combinedFilter = Array.from(filters).map((i) => `(${i})`).join("||");
1957
+ return combinedFilter ? [grant, parse(`$document {"_": ${combinedFilter}}._`)] : [grant, parse("false")];
1958
+ }));
1959
+ }
1960
+ const documentsCache = new MultiKeyWeakMap(), actionsCache = /* @__PURE__ */ new WeakMap(), nullReplacer = {}, documentsSelector = createSelector([({ state: { documentStates } }) => documentStates, (_context, { actions }) => actions], (documentStates, actions) => {
1961
+ let documentIds = new Set(actions.map((action) => {
1962
+ if (typeof action.documentId != "string") return [];
1963
+ if (action.liveEdit) return [action.documentId];
1964
+ let ids = [getPublishedId(DocumentId(action.documentId)), getDraftId(DocumentId(action.documentId))];
1965
+ return isReleasePerspective(action.perspective) && ids.push(getVersionId(DocumentId(action.documentId), action.perspective.releaseName)), ids;
1966
+ }).flat());
1967
+ throwDocumentError(documentStates, documentIds);
1968
+ let documents = {};
1969
+ for (let documentId of documentIds) {
1970
+ let local = documentStates[documentId]?.local;
1971
+ if (local === void 0) return;
1972
+ documents[documentId] = local;
1973
+ }
1974
+ let keys = Object.values(documents).map((doc) => doc === null ? nullReplacer : doc);
1975
+ return documentsCache.get(keys) || (documentsCache.set(keys, documents), documents);
1976
+ }), memoizedActionsSelector = createSelector([documentsSelector, (_state, { actions }) => actions], (documents, actions) => {
1977
+ if (!documents) return;
1978
+ let nestedCache = actionsCache.get(documents);
1979
+ nestedCache || (nestedCache = /* @__PURE__ */ new Map(), actionsCache.set(documents, nestedCache));
1980
+ let normalizedActions = Array.isArray(actions) ? actions : [actions], actionsKey = JSON.stringify(normalizedActions);
1981
+ return nestedCache.get(actionsKey) || (nestedCache.set(actionsKey, normalizedActions), normalizedActions);
1982
+ }), enNarrowConjunction = new Intl.ListFormat("en", {
1983
+ style: "narrow",
1984
+ type: "conjunction"
1985
+ });
1986
+ function calculatePermissions(...args) {
1987
+ return _calculatePermissions(...args);
1988
+ }
1989
+ const _calculatePermissions = createSelector([
1990
+ ({ state: { grants } }) => grants,
1991
+ ({ state: { identity } }) => identity,
1992
+ documentsSelector,
1993
+ memoizedActionsSelector
1994
+ ], (grants, identity, documents, actions) => {
1995
+ if (!documents || !grants || !actions) return;
1996
+ let timestamp = (/* @__PURE__ */ new Date()).toISOString(), reasons = [];
1997
+ try {
1998
+ processActions({
1999
+ actions,
2000
+ transactionId: randomId(16),
2001
+ working: documents,
2002
+ base: documents,
2003
+ timestamp,
2004
+ grants,
2005
+ identity
2006
+ });
2007
+ } catch (error) {
2008
+ if (error instanceof PermissionActionError) reasons.push({
2009
+ message: error.message,
2010
+ documentId: error.documentId,
2011
+ type: "access"
2012
+ });
2013
+ else if (error instanceof ActionError) reasons.push({
2014
+ message: error.message,
2015
+ documentId: error.documentId,
2016
+ type: "precondition"
2017
+ });
2018
+ else throw error;
2019
+ }
2020
+ for (let action of actions) if (action.type === "document.edit" && !action.patches?.length) {
2021
+ let docId = action.documentId, doc;
2022
+ doc = action.liveEdit ? documents[docId] : isReleasePerspective(action.perspective) ? documents[getVersionId(DocumentId(docId), action.perspective.releaseName)] : documents[getDraftId(DocumentId(docId))] ?? documents[getPublishedId(DocumentId(docId))], doc ? checkGrant(grants.update, doc, identity) || reasons.push({
2023
+ type: "access",
2024
+ message: `You are not allowed to edit the document with ID "${docId}".`,
2025
+ documentId: docId
2026
+ }) : isReleasePerspective(action.perspective) ? reasons.push({
2027
+ type: "precondition",
2028
+ message: `The version document with ID "${docId}" could not be found. Please create it or add it to the release first.`,
2029
+ documentId: docId
2030
+ }) : reasons.push({
2031
+ type: "precondition",
2032
+ message: `The document with ID "${docId}" could not be found. Please check that it exists before editing.`,
2033
+ documentId: docId
2034
+ });
2035
+ }
2036
+ let allowed = reasons.length === 0;
2037
+ if (allowed) return { allowed };
2038
+ let sortedReasons = reasons.map((reason, index) => ({
2039
+ ...reason,
2040
+ index
2041
+ })).sort((a, b) => a.type === b.type ? a.message.localeCompare(b.message, "en-US") : a.type === "access" ? -1 : 1).map(({ index: _index, ...reason }) => reason);
2042
+ return {
2043
+ allowed,
2044
+ reasons: sortedReasons,
2045
+ message: enNarrowConjunction.format(sortedReasons.map((i) => i.message))
2046
+ };
2047
+ });
2048
+ function handleCreate(action, ctx) {
2049
+ let { transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations } = ctx, { base, working } = ctx, documentId = getId(action.documentId);
2050
+ if (action.liveEdit) {
2051
+ if (working[documentId]) throw new ActionError({
2052
+ documentId,
2053
+ transactionId,
2054
+ message: "This document already exists."
2055
+ });
2056
+ let newDocBase = {
2057
+ _type: action.documentType,
2058
+ _id: documentId,
2059
+ ...action.initialValue
2060
+ }, mutations = [{ create: {
2061
+ _type: action.documentType,
2062
+ _id: documentId,
2063
+ ...action.initialValue
2064
+ } }];
2065
+ if (base = processMutations({
2066
+ documents: base,
2067
+ transactionId,
2068
+ mutations: [{ create: newDocBase }],
2069
+ timestamp
2070
+ }), working = processMutations({
2071
+ documents: working,
2072
+ transactionId,
2073
+ mutations,
2074
+ timestamp
2075
+ }), !checkGrant(grants.create, working[documentId], identity)) throw new PermissionActionError({
2076
+ documentId,
2077
+ transactionId,
2078
+ message: `You do not have permission to create document "${documentId}".`
2079
+ });
2080
+ return outgoingMutations.push(...mutations), {
2081
+ base,
2082
+ working
2083
+ };
2084
+ }
2085
+ let versionId = isReleasePerspective(action.perspective) ? getVersionId(DocumentId(documentId), action.perspective.releaseName) : void 0, draftId = getDraftId(DocumentId(documentId)), publishedId = getPublishedId(DocumentId(documentId));
2086
+ if (versionId ? working[versionId] : working[draftId]) {
2087
+ let errorDocType = versionId ? "release version" : "draft";
2088
+ throw new ActionError({
2089
+ documentId,
2090
+ transactionId,
2091
+ message: `A ${errorDocType} of this document already exists. Please use or discard the existing ${errorDocType} before creating a new one.`
2092
+ });
2093
+ }
2094
+ let newDocBase = {
2095
+ ...base[draftId] ?? base[publishedId],
2096
+ _type: action.documentType,
2097
+ _id: versionId ?? draftId,
2098
+ ...action.initialValue
2099
+ }, newDocWorking = {
2100
+ ...working[draftId] ?? working[publishedId],
2101
+ _type: action.documentType,
2102
+ _id: versionId ?? draftId,
2103
+ ...action.initialValue
2104
+ }, mutations = [{ create: newDocWorking }];
2105
+ if (base = processMutations({
2106
+ documents: base,
2107
+ transactionId,
2108
+ mutations: [{ create: newDocBase }],
2109
+ timestamp
2110
+ }), working = processMutations({
2111
+ documents: working,
2112
+ transactionId,
2113
+ mutations,
2114
+ timestamp
2115
+ }), versionId && !checkGrant(grants.create, working[versionId], identity)) throw new PermissionActionError({
2116
+ documentId,
2117
+ transactionId,
2118
+ message: `You do not have permission to create a release version for document "${documentId}".`
2119
+ });
2120
+ if (!versionId && !checkGrant(grants.create, working[draftId], identity)) throw new PermissionActionError({
2121
+ documentId,
2122
+ transactionId,
2123
+ message: `You do not have permission to create a draft for document "${documentId}".`
2124
+ });
2125
+ return outgoingMutations.push(...mutations), outgoingActions.push({
2126
+ actionType: "sanity.action.document.version.create",
2127
+ publishedId,
2128
+ attributes: newDocWorking
2129
+ }), {
2130
+ base,
2131
+ working
2132
+ };
2133
+ }
2134
+ function handleDelete(action, ctx) {
2135
+ let { transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations } = ctx, { base, working } = ctx, documentId = action.documentId;
2136
+ if (isReleasePerspective(action.perspective)) throw new ActionError({
2137
+ documentId,
2138
+ transactionId,
2139
+ message: "Cannot delete a version document. You may want to use the \"unpublish\" or \"discard\" actions instead."
2140
+ });
2141
+ if (action.liveEdit) {
2142
+ if (!working[documentId]) throw new ActionError({
2143
+ documentId,
2144
+ transactionId,
2145
+ message: "The document you are trying to delete does not exist."
2146
+ });
2147
+ if (!checkGrant(grants.update, working[documentId], identity)) throw new PermissionActionError({
2148
+ documentId,
2149
+ transactionId,
2150
+ message: "You do not have permission to delete this document."
2151
+ });
2152
+ let mutations = [{ delete: { id: documentId } }];
2153
+ return base = processMutations({
2154
+ documents: base,
2155
+ transactionId,
2156
+ mutations,
2157
+ timestamp
2158
+ }), working = processMutations({
2159
+ documents: working,
2160
+ transactionId,
2161
+ mutations,
2162
+ timestamp
2163
+ }), outgoingMutations.push(...mutations), {
2164
+ base,
2165
+ working
2166
+ };
2167
+ }
2168
+ let draftId = getDraftId(DocumentId(documentId)), publishedId = getPublishedId(DocumentId(documentId));
2169
+ if (!working[publishedId]) throw new ActionError({
2170
+ documentId,
2171
+ transactionId,
2172
+ message: working[draftId] ? "Cannot delete a document without a published version." : "The document you are trying to delete does not exist."
2173
+ });
2174
+ let cantDeleteDraft = working[draftId] && !checkGrant(grants.update, working[draftId], identity), cantDeletePublished = working[publishedId] && !checkGrant(grants.update, working[publishedId], identity);
2175
+ if (cantDeleteDraft || cantDeletePublished) throw new PermissionActionError({
2176
+ documentId,
2177
+ transactionId,
2178
+ message: "You do not have permission to delete this document."
2179
+ });
2180
+ let mutations = [{ delete: { id: publishedId } }, { delete: { id: draftId } }], includeDrafts = working[draftId] ? [draftId] : void 0;
2181
+ return base = processMutations({
2182
+ documents: base,
2183
+ transactionId,
2184
+ mutations,
2185
+ timestamp
2186
+ }), working = processMutations({
2187
+ documents: working,
2188
+ transactionId,
2189
+ mutations,
2190
+ timestamp
2191
+ }), outgoingMutations.push(...mutations), outgoingActions.push({
2192
+ actionType: "sanity.action.document.delete",
2193
+ publishedId,
2194
+ ...includeDrafts ? { includeDrafts } : {}
2195
+ }), {
2196
+ base,
2197
+ working
2198
+ };
2199
+ }
2200
+ function handleDiscard(action, ctx) {
2201
+ let { transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations } = ctx, { base, working } = ctx, documentId = getId(action.documentId);
2202
+ if (action.liveEdit) throw new ActionError({
2203
+ documentId,
2204
+ transactionId,
2205
+ message: `Cannot discard changes for liveEdit document "${documentId}". LiveEdit documents do not support drafts.`
2206
+ });
2207
+ let versionId = isReleasePerspective(action.perspective) ? getVersionId(DocumentId(documentId), action.perspective.releaseName) : getDraftId(DocumentId(documentId)), mutations = [{ delete: { id: versionId } }];
2208
+ if (!working[versionId]) throw new ActionError({
2209
+ documentId,
2210
+ transactionId,
2211
+ message: `There is no draft or version available to discard for document "${documentId}".`
2212
+ });
2213
+ if (!checkGrant(grants.update, working[versionId], identity)) throw new PermissionActionError({
2214
+ documentId,
2215
+ transactionId,
2216
+ message: `You do not have permission to discard changes for document "${documentId}".`
2217
+ });
2218
+ return base = processMutations({
2219
+ documents: base,
2220
+ transactionId,
2221
+ mutations,
2222
+ timestamp
2223
+ }), working = processMutations({
2224
+ documents: working,
2225
+ transactionId,
2226
+ mutations,
2227
+ timestamp
2228
+ }), outgoingMutations.push(...mutations), outgoingActions.push({
2229
+ actionType: "sanity.action.document.version.discard",
2230
+ versionId
2231
+ }), {
2232
+ base,
2233
+ working
2234
+ };
2235
+ }
2236
+ function handleEdit(action, ctx) {
2237
+ let { transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations } = ctx, { base, working } = ctx, documentId = getId(action.documentId);
2238
+ if (action.liveEdit) {
2239
+ let result = applySingleDocPatch({
2240
+ base,
2241
+ working,
2242
+ documentId,
2243
+ patches: action.patches,
2244
+ transactionId,
2245
+ timestamp,
2246
+ grants,
2247
+ identity,
2248
+ preserveOperations: action.preserveOperations
2249
+ });
2250
+ return outgoingMutations.push(...result.workingMutations), {
2251
+ base: result.base,
2252
+ working: result.working
2253
+ };
2254
+ }
2255
+ let versionId = isReleasePerspective(action.perspective) ? getVersionId(DocumentId(documentId), action.perspective.releaseName) : void 0, draftId = getDraftId(DocumentId(documentId)), publishedId = getPublishedId(DocumentId(documentId)), patchDocumentId = isReleasePerspective(action.perspective) ? versionId : draftId, userPatches = action.patches?.map((patch) => ({ patch: {
2256
+ id: patchDocumentId,
2257
+ ...patch
2258
+ } }));
2259
+ if (!userPatches?.length) return {
2260
+ base,
2261
+ working
2262
+ };
2263
+ if (isReleasePerspective(action.perspective)) {
2264
+ if (!working[versionId] && !base[versionId]) throw new ActionError({
2265
+ documentId,
2266
+ transactionId,
2267
+ message: "This document does not exist in the release. Please create it or add it to the release first."
2268
+ });
2269
+ } else if (!working[draftId] && !working[publishedId] || !base[draftId] && !base[publishedId]) throw new ActionError({
2270
+ documentId,
2271
+ transactionId,
2272
+ message: "Cannot edit document because it does not exist in draft or published form."
2273
+ });
2274
+ let applyMutations = createMutationApplier({
2275
+ documentId,
2276
+ transactionId,
2277
+ timestamp,
2278
+ preserveOperations: action.preserveOperations
2279
+ }), baseMutations = [];
2280
+ !isReleasePerspective(action.perspective) && !base[draftId] && base[publishedId] && baseMutations.push({ create: {
2281
+ ...base[publishedId],
2282
+ _id: draftId
2283
+ } });
2284
+ let baseBefore = base[patchDocumentId] ?? base[publishedId];
2285
+ userPatches && baseMutations.push(...userPatches), base = applyMutations(base, baseMutations, "base");
2286
+ let baseAfter = base[patchDocumentId], patches = action.preserveOperations ? action.patches ?? [] : preserveNumericOperations(baseBefore, action.patches, diffValue(baseBefore, baseAfter)), workingMutations = [];
2287
+ if (!isReleasePerspective(action.perspective) && !working[draftId] && working[publishedId]) {
2288
+ let newDraftFromPublished = {
2289
+ ...working[publishedId],
2290
+ _id: draftId
2291
+ };
2292
+ if (!checkGrant(grants.create, newDraftFromPublished, identity)) throw new PermissionActionError({
2293
+ documentId,
2294
+ transactionId,
2295
+ message: "You do not have permission to create a draft for editing this document."
2296
+ });
2297
+ workingMutations.push({ create: newDraftFromPublished });
2298
+ }
2299
+ let workingBefore = working[patchDocumentId] ?? working[publishedId];
2300
+ if (!checkGrant(grants.update, workingBefore, identity)) throw new PermissionActionError({
2301
+ documentId,
2302
+ transactionId,
2303
+ message: `You do not have permission to edit document "${documentId}".`
2304
+ });
2305
+ return workingMutations.push(...patches.map((patch) => ({ patch: {
2306
+ id: patchDocumentId,
2307
+ ...patch
2308
+ } }))), working = applyMutations(working, workingMutations, "working"), outgoingMutations.push(...workingMutations), outgoingActions.push(...patches.map((patch) => ({
2309
+ actionType: "sanity.action.document.edit",
2310
+ draftId: patchDocumentId,
2311
+ publishedId,
2312
+ patch
2313
+ }))), {
2314
+ base,
2315
+ working
2316
+ };
2317
+ }
2318
+ function handlePublish(action, ctx) {
2319
+ let { transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations } = ctx, { base, working } = ctx, documentId = getId(action.documentId);
2320
+ if (action.liveEdit || isReleasePerspective(action.perspective)) throw new ActionError({
2321
+ documentId,
2322
+ transactionId,
2323
+ message: "Cannot publish this document. Publishing is not supported for liveEdit or version (release) documents."
2324
+ });
2325
+ let draftId = getDraftId(DocumentId(documentId)), publishedId = getPublishedId(DocumentId(documentId)), workingDraft = working[draftId], baseDraft = base[draftId];
2326
+ if (!workingDraft || !baseDraft) throw new ActionError({
2327
+ documentId,
2328
+ transactionId,
2329
+ message: `Cannot publish because no draft version was found for document "${documentId}".`
2330
+ });
2331
+ if (!isDeepEqual(workingDraft, baseDraft)) throw new ActionError({
2332
+ documentId,
2333
+ transactionId,
2334
+ message: "Publish aborted: The document has changed elsewhere. Please try again."
2335
+ });
2336
+ let newPublishedFromDraft = {
2337
+ ...strengthenOnPublish(workingDraft),
2338
+ _id: publishedId
2339
+ }, mutations = [{ delete: { id: draftId } }, { createOrReplace: newPublishedFromDraft }];
2340
+ if (working[draftId] && !checkGrant(grants.update, working[draftId], identity)) throw new PermissionActionError({
2341
+ documentId,
2342
+ transactionId,
2343
+ message: `Publish failed: You do not have permission to update the draft for "${documentId}".`
2344
+ });
2345
+ if (working[publishedId] && !checkGrant(grants.update, newPublishedFromDraft, identity)) throw new PermissionActionError({
2346
+ documentId,
2347
+ transactionId,
2348
+ message: `Publish failed: You do not have permission to update the published version of "${documentId}".`
2349
+ });
2350
+ if (!working[publishedId] && !checkGrant(grants.create, newPublishedFromDraft, identity)) throw new PermissionActionError({
2351
+ documentId,
2352
+ transactionId,
2353
+ message: `Publish failed: You do not have permission to publish a new version of "${documentId}".`
2354
+ });
2355
+ return base = processMutations({
2356
+ documents: base,
2357
+ transactionId,
2358
+ mutations,
2359
+ timestamp
2360
+ }), working = processMutations({
2361
+ documents: working,
2362
+ transactionId,
2363
+ mutations,
2364
+ timestamp
2365
+ }), outgoingMutations.push(...mutations), outgoingActions.push({
2366
+ actionType: "sanity.action.document.publish",
2367
+ draftId,
2368
+ publishedId
2369
+ }), {
2370
+ base,
2371
+ working
2372
+ };
2373
+ }
2374
+ function strengthenOnPublish(draft) {
2375
+ let isStrengthenReference = (value) => "_strengthenOnPublish" in value;
2376
+ function strengthen(value) {
2377
+ if (typeof value != "object" || !value) return value;
2378
+ if (isStrengthenReference(value)) {
2379
+ let { _strengthenOnPublish, _weak, ...rest } = value;
2380
+ return {
2381
+ ...rest,
2382
+ ..._strengthenOnPublish.weak && { _weak: !0 }
2383
+ };
2384
+ }
2385
+ return Array.isArray(value) ? value.map(strengthen) : Object.fromEntries(Object.entries(value).map(([k, v]) => [k, strengthen(v)]));
2386
+ }
2387
+ return strengthen(draft);
2388
+ }
2389
+ function handleReleaseArchive(action, ctx) {
2390
+ let { base, working, grants, outgoingActions, transactionId, identity } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId), existing = working[releaseDocumentId] ?? base[releaseDocumentId];
2391
+ if (!existing) throw new ActionError({
2392
+ documentId: releaseDocumentId,
2393
+ transactionId,
2394
+ message: `Cannot archive release "${action.releaseId}" because it does not exist.`
2395
+ });
2396
+ if (!checkGrant(grants.update, existing, identity)) throw new PermissionActionError({
2397
+ documentId: releaseDocumentId,
2398
+ transactionId,
2399
+ message: `You do not have permission to archive release "${action.releaseId}".`
2400
+ });
2401
+ return outgoingActions.push({
2402
+ actionType: "sanity.action.release.archive",
2403
+ releaseId: action.releaseId
2404
+ }), {
2405
+ base,
2406
+ working
2407
+ };
2408
+ }
2409
+ function handleReleaseUnarchive(action, ctx) {
2410
+ let { base, working, grants, outgoingActions, transactionId, identity } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId), existing = working[releaseDocumentId] ?? base[releaseDocumentId];
2411
+ if (!existing) throw new ActionError({
2412
+ documentId: releaseDocumentId,
2413
+ transactionId,
2414
+ message: `Cannot unarchive release "${action.releaseId}" because it does not exist.`
2415
+ });
2416
+ if (!checkGrant(grants.update, existing, identity)) throw new PermissionActionError({
2417
+ documentId: releaseDocumentId,
2418
+ transactionId,
2419
+ message: `You do not have permission to unarchive release "${action.releaseId}".`
2420
+ });
2421
+ return outgoingActions.push({
2422
+ actionType: "sanity.action.release.unarchive",
2423
+ releaseId: action.releaseId
2424
+ }), {
2425
+ base,
2426
+ working
2427
+ };
2428
+ }
2429
+ function handleReleaseCreate(action, ctx) {
2430
+ let { transactionId, timestamp, grants, outgoingActions, outgoingMutations, identity } = ctx, { base, working } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId);
2431
+ if (working[releaseDocumentId] || base[releaseDocumentId]) throw new ActionError({
2432
+ documentId: releaseDocumentId,
2433
+ transactionId,
2434
+ message: `A release with id "${action.releaseId}" already exists.`
2435
+ });
2436
+ let mutations = [{ create: {
2437
+ _id: releaseDocumentId,
2438
+ _type: "system.release",
2439
+ name: action.releaseId,
2440
+ state: "active",
2441
+ metadata: action.metadata
2442
+ } }];
2443
+ if (base = processMutations({
2444
+ documents: base,
2445
+ transactionId,
2446
+ mutations,
2447
+ timestamp
2448
+ }), working = processMutations({
2449
+ documents: working,
2450
+ transactionId,
2451
+ mutations,
2452
+ timestamp
2453
+ }), !checkGrant(grants.create, working[releaseDocumentId], identity)) throw new PermissionActionError({
2454
+ documentId: releaseDocumentId,
2455
+ transactionId,
2456
+ message: `You do not have permission to create release "${action.releaseId}".`
2457
+ });
2458
+ return outgoingMutations.push(...mutations), outgoingActions.push({
2459
+ actionType: "sanity.action.release.create",
2460
+ releaseId: action.releaseId,
2461
+ metadata: action.metadata
2462
+ }), {
2463
+ base,
2464
+ working
2465
+ };
2466
+ }
2467
+ const DELETABLE_STATES = /* @__PURE__ */ new Set(["archived", "published"]);
2468
+ function handleReleaseDelete(action, ctx) {
2469
+ let { transactionId, timestamp, grants, outgoingActions, outgoingMutations, identity } = ctx, { base, working } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId), existing = working[releaseDocumentId] ?? base[releaseDocumentId];
2470
+ if (!existing) throw new ActionError({
2471
+ documentId: releaseDocumentId,
2472
+ transactionId,
2473
+ message: `Cannot delete release "${action.releaseId}" because it does not exist.`
2474
+ });
2475
+ let state = existing.state;
2476
+ if (state && typeof state == "string" && !DELETABLE_STATES.has(state)) throw new ActionError({
2477
+ documentId: releaseDocumentId,
2478
+ transactionId,
2479
+ message: `Cannot delete release "${action.releaseId}" while it is "${state}". Archive it first.`
2480
+ });
2481
+ if (!checkGrant(grants.update, existing, identity)) throw new PermissionActionError({
2482
+ documentId: releaseDocumentId,
2483
+ transactionId,
2484
+ message: `You do not have permission to delete release "${action.releaseId}".`
2485
+ });
2486
+ let mutations = [{ delete: { id: releaseDocumentId } }];
2487
+ return base = processMutations({
2488
+ documents: base,
2489
+ transactionId,
2490
+ mutations,
2491
+ timestamp
2492
+ }), working = processMutations({
2493
+ documents: working,
2494
+ transactionId,
2495
+ mutations,
2496
+ timestamp
2497
+ }), outgoingMutations.push(...mutations), outgoingActions.push({
2498
+ actionType: "sanity.action.release.delete",
2499
+ releaseId: action.releaseId
2500
+ }), {
2501
+ base,
2502
+ working
2503
+ };
2504
+ }
2505
+ function handleReleaseEdit(action, ctx) {
2506
+ let { transactionId, timestamp, grants, outgoingActions, outgoingMutations, identity } = ctx, { base, working } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId), result = applySingleDocPatch({
2507
+ base,
2508
+ working,
2509
+ documentId: releaseDocumentId,
2510
+ patches: [action.patch],
2511
+ transactionId,
2512
+ timestamp,
2513
+ grants,
2514
+ identity,
2515
+ notFoundMessage: `Cannot edit release "${action.releaseId}" because it does not exist.`,
2516
+ permissionMessage: `You do not have permission to edit release "${action.releaseId}".`
2517
+ });
2518
+ return outgoingMutations.push(...result.workingMutations), outgoingActions.push(...result.diffedPatches.map((patch) => ({
2519
+ actionType: "sanity.action.release.edit",
2520
+ releaseId: action.releaseId,
2521
+ patch
2522
+ }))), {
2523
+ base: result.base,
2524
+ working: result.working
2525
+ };
2526
+ }
2527
+ function handleReleasePublish(action, ctx) {
2528
+ let { base, working, grants, outgoingActions, transactionId, identity } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId), existing = working[releaseDocumentId] ?? base[releaseDocumentId];
2529
+ if (!existing) throw new ActionError({
2530
+ documentId: releaseDocumentId,
2531
+ transactionId,
2532
+ message: `Cannot publish release "${action.releaseId}" because it does not exist.`
2533
+ });
2534
+ if (!checkGrant(grants.update, existing, identity)) throw new PermissionActionError({
2535
+ documentId: releaseDocumentId,
2536
+ transactionId,
2537
+ message: `You do not have permission to publish release "${action.releaseId}".`
2538
+ });
2539
+ return outgoingActions.push({
2540
+ actionType: "sanity.action.release.publish",
2541
+ releaseId: action.releaseId
2542
+ }), {
2543
+ base,
2544
+ working
2545
+ };
2546
+ }
2547
+ function handleReleaseSchedule(action, ctx) {
2548
+ let { base, working, grants, outgoingActions, transactionId, identity } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId);
2549
+ if (Number.isNaN(Date.parse(action.publishAt))) throw new ActionError({
2550
+ documentId: releaseDocumentId,
2551
+ transactionId,
2552
+ message: `Cannot schedule release "${action.releaseId}": "publishAt" must be a valid ISO 8601 timestamp (received "${action.publishAt}").`
2553
+ });
2554
+ let existing = working[releaseDocumentId] ?? base[releaseDocumentId];
2555
+ if (!existing) throw new ActionError({
2556
+ documentId: releaseDocumentId,
2557
+ transactionId,
2558
+ message: `Cannot schedule release "${action.releaseId}" because it does not exist.`
2559
+ });
2560
+ if (!checkGrant(grants.update, existing, identity)) throw new PermissionActionError({
2561
+ documentId: releaseDocumentId,
2562
+ transactionId,
2563
+ message: `You do not have permission to schedule release "${action.releaseId}".`
2564
+ });
2565
+ return outgoingActions.push({
2566
+ actionType: "sanity.action.release.schedule",
2567
+ releaseId: action.releaseId,
2568
+ publishAt: action.publishAt
2569
+ }), {
2570
+ base,
2571
+ working
2572
+ };
2573
+ }
2574
+ function handleReleaseUnschedule(action, ctx) {
2575
+ let { base, working, grants, outgoingActions, transactionId, identity } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId), existing = working[releaseDocumentId] ?? base[releaseDocumentId];
2576
+ if (!existing) throw new ActionError({
2577
+ documentId: releaseDocumentId,
2578
+ transactionId,
2579
+ message: `Cannot unschedule release "${action.releaseId}" because it does not exist.`
2580
+ });
2581
+ if (!checkGrant(grants.update, existing, identity)) throw new PermissionActionError({
2582
+ documentId: releaseDocumentId,
2583
+ transactionId,
2584
+ message: `You do not have permission to unschedule release "${action.releaseId}".`
2585
+ });
2586
+ return outgoingActions.push({
2587
+ actionType: "sanity.action.release.unschedule",
2588
+ releaseId: action.releaseId
2589
+ }), {
2590
+ base,
2591
+ working
2592
+ };
2593
+ }
2594
+ function handleUnpublish(action, ctx) {
2595
+ let { transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations } = ctx, { base, working } = ctx, documentId = getId(action.documentId);
2596
+ if (action.liveEdit || isReleasePerspective(action.perspective)) throw new ActionError({
2597
+ documentId,
2598
+ transactionId,
2599
+ message: "Cannot unpublish this document. Unpublishing is not supported for liveEdit or version (release) documents."
2600
+ });
2601
+ let draftId = getDraftId(DocumentId(documentId)), publishedId = getPublishedId(DocumentId(documentId));
2602
+ if (!working[publishedId] && !base[publishedId]) throw new ActionError({
2603
+ documentId,
2604
+ transactionId,
2605
+ message: `Cannot unpublish because the document "${documentId}" is not currently published.`
2606
+ });
2607
+ let sourceDoc = working[publishedId] ?? base[publishedId], newDraftFromPublished = {
2608
+ ...sourceDoc,
2609
+ _id: draftId
2610
+ }, mutations = [{ delete: { id: publishedId } }, { createIfNotExists: newDraftFromPublished }];
2611
+ if (!checkGrant(grants.update, sourceDoc, identity)) throw new PermissionActionError({
2612
+ documentId,
2613
+ transactionId,
2614
+ message: `You do not have permission to unpublish the document "${documentId}".`
2615
+ });
2616
+ if (!working[draftId] && !checkGrant(grants.create, newDraftFromPublished, identity)) throw new PermissionActionError({
2617
+ documentId,
2618
+ transactionId,
2619
+ message: `You do not have permission to create a draft from the published version of "${documentId}".`
2620
+ });
2621
+ return base = processMutations({
2622
+ documents: base,
2623
+ transactionId,
2624
+ mutations: [{ delete: { id: publishedId } }, { createIfNotExists: {
2625
+ ...base[publishedId] ?? sourceDoc,
2626
+ _id: draftId
2627
+ } }],
2628
+ timestamp
2629
+ }), working = processMutations({
2630
+ documents: working,
2631
+ transactionId,
2632
+ mutations,
2633
+ timestamp
2634
+ }), outgoingMutations.push(...mutations), outgoingActions.push({
2635
+ actionType: "sanity.action.document.unpublish",
2636
+ draftId,
2637
+ publishedId
2638
+ }), {
2639
+ base,
2640
+ working
2641
+ };
2642
+ }
2643
+ /**
2644
+ * Applies the given set of actions to the working set of documents and converts
2645
+ * high-level actions into lower-level outgoing mutations/actions that respect
2646
+ * the current state of the working documents.
2647
+ *
2648
+ * Supports a "base" and "working" set of documents to allow actions to be
2649
+ * applied on top of a different working set of documents in a 3-way merge
2650
+ *
2651
+ * Actions are applied to the base set of documents first. The difference
2652
+ * between the base before and after is used to create a patch. This patch is
2653
+ * then applied to the working set of documents and is set as the outgoing patch
2654
+ * sent to the server.
2655
+ */
2656
+ function processActions({ actions, transactionId, working: initialWorking, base: initialBase, timestamp, grants, identity }) {
2657
+ let base = { ...initialBase }, working = { ...initialWorking }, outgoingActions = [], outgoingMutations = [], liveEditAction = actions.find((action) => !isReleaseAction(action) && action.liveEdit), otherAction = actions.find((action) => isReleaseAction(action) || !action.liveEdit);
2658
+ if (liveEditAction && otherAction) throw new ActionError({
2659
+ documentId: liveEditAction.documentId,
2660
+ transactionId,
2661
+ message: "Cannot combine liveEdit document actions with other actions in the same transaction. Submit them as separate transactions."
2662
+ });
2663
+ for (let action of actions) {
2664
+ let result = dispatch(action, {
2665
+ base,
2666
+ working,
2667
+ transactionId,
2668
+ timestamp,
2669
+ grants,
2670
+ identity,
2671
+ outgoingActions,
2672
+ outgoingMutations
2673
+ });
2674
+ base = result.base, working = result.working;
2675
+ }
2676
+ let previousRevs = Object.fromEntries(Object.entries(initialWorking).map(([id, doc]) => [id, doc?._rev]));
2677
+ return {
2678
+ working,
2679
+ outgoingActions,
2680
+ outgoingMutations,
2681
+ previous: initialWorking,
2682
+ previousRevs
2683
+ };
2684
+ }
2685
+ function dispatch(action, ctx) {
2686
+ switch (action.type) {
2687
+ case "document.create": return handleCreate(action, ctx);
2688
+ case "document.delete": return handleDelete(action, ctx);
2689
+ case "document.discard": return handleDiscard(action, ctx);
2690
+ case "document.edit": return handleEdit(action, ctx);
2691
+ case "document.publish": return handlePublish(action, ctx);
2692
+ case "document.unpublish": return handleUnpublish(action, ctx);
2693
+ case "release.create": return handleReleaseCreate(action, ctx);
2694
+ case "release.edit": return handleReleaseEdit(action, ctx);
2695
+ case "release.publish": return handleReleasePublish(action, ctx);
2696
+ case "release.schedule": return handleReleaseSchedule(action, ctx);
2697
+ case "release.unschedule": return handleReleaseUnschedule(action, ctx);
2698
+ case "release.archive": return handleReleaseArchive(action, ctx);
2699
+ case "release.unarchive": return handleReleaseUnarchive(action, ctx);
2700
+ case "release.delete": return handleReleaseDelete(action, ctx);
2701
+ default: throw Error(`Unknown action type: "${action.type}". Please contact support if this issue persists.`);
2702
+ }
2703
+ }
2704
+ const EMPTY_REVISIONS = {};
2705
+ function queueTransaction(prev, transaction) {
2706
+ let { transactionId, actions } = transaction;
2707
+ return {
2708
+ ...getDocumentIdsFromHandleLikes(actions).reduce((acc, id) => addSubscriptionIdToDocument(acc, id, transactionId), prev),
2709
+ queued: [...prev.queued, transaction]
2710
+ };
2711
+ }
2712
+ function removeQueuedTransaction(prev, transactionId) {
2713
+ let transaction = prev.queued.find((t) => t.transactionId === transactionId);
2714
+ return transaction ? {
2715
+ ...getDocumentIdsFromHandleLikes(transaction.actions).reduce((acc, id) => removeSubscriptionIdFromDocument(acc, id, transactionId), prev),
2716
+ queued: prev.queued.filter((t) => transactionId !== t.transactionId)
2717
+ } : prev;
2718
+ }
2719
+ function applyFirstQueuedTransaction(prev) {
2720
+ let queued = prev.queued.at(0);
2721
+ if (!queued || !prev.grants) return prev;
2722
+ let ids = getDocumentIdsFromHandleLikes(queued.actions);
2723
+ if (ids.some((id) => prev.documentStates[id]?.local === void 0)) return prev;
2724
+ let working = ids.reduce((acc, id) => (acc[id] = prev.documentStates[id]?.local, acc), {}), timestamp = (/* @__PURE__ */ new Date()).toISOString(), result = processActions({
2725
+ ...queued,
2726
+ working,
2727
+ base: working,
2728
+ timestamp,
2729
+ grants: prev.grants,
2730
+ identity: prev.identity
2731
+ }), applied = {
2732
+ ...queued,
2733
+ ...result,
2734
+ base: result.previous,
2735
+ timestamp
2736
+ };
2737
+ return {
2738
+ ...prev,
2739
+ applied: [...prev.applied, applied],
2740
+ queued: prev.queued.filter((t) => t.transactionId !== queued.transactionId),
2741
+ documentStates: Object.entries(result.working).reduce((acc, [id, next]) => {
2742
+ let prevDoc = acc[id];
2743
+ return prevDoc && (acc[id] = {
2744
+ ...prevDoc,
2745
+ local: next
2746
+ }), acc;
2747
+ }, { ...prev.documentStates })
2748
+ };
2749
+ }
2750
+ function batchAppliedTransactions([curr, ...rest]) {
2751
+ if (!curr) return;
2752
+ if (!curr.actions.length) return batchAppliedTransactions(rest);
2753
+ if (curr.actions.length > 1) return {
2754
+ ...curr,
2755
+ disableBatching: !0,
2756
+ batchedTransactionIds: [curr.transactionId]
2757
+ };
2758
+ let [action] = curr.actions;
2759
+ if (action.type !== "document.edit" || curr.disableBatching) return {
2760
+ ...curr,
2761
+ disableBatching: !0,
2762
+ batchedTransactionIds: [curr.transactionId]
2763
+ };
2764
+ let editAction = {
2765
+ ...curr,
2766
+ actions: [action],
2767
+ disableBatching: !1,
2768
+ batchedTransactionIds: [curr.transactionId]
2769
+ };
2770
+ if (!rest.length) return editAction;
2771
+ let next = batchAppliedTransactions(rest);
2772
+ if (!next) return;
2773
+ if (next.disableBatching) return editAction;
2774
+ let nextFirst = next.actions[0], nextLiveEdit = nextFirst && "liveEdit" in nextFirst ? nextFirst.liveEdit : !1;
2775
+ return !!action.liveEdit == !!nextLiveEdit ? {
2776
+ disableBatching: !1,
2777
+ transactionId: next.transactionId,
2778
+ actions: [action, ...next.actions],
2779
+ outgoingActions: [...curr.outgoingActions, ...next.outgoingActions],
2780
+ batchedTransactionIds: [curr.transactionId, ...next.batchedTransactionIds],
2781
+ outgoingMutations: [...curr.outgoingMutations, ...next.outgoingMutations],
2782
+ working: {
2783
+ ...curr.working,
2784
+ ...next.working
2785
+ },
2786
+ previousRevs: {
2787
+ ...next.previousRevs,
2788
+ ...curr.previousRevs
2789
+ },
2790
+ previous: {
2791
+ ...next.previous,
2792
+ ...curr.previous
2793
+ },
2794
+ base: {
2795
+ ...next.base,
2796
+ ...curr.base
2797
+ },
2798
+ timestamp: curr.timestamp ?? next.timestamp
2799
+ } : editAction;
2800
+ }
2801
+ function transitionAppliedTransactionsToOutgoing(prev) {
2802
+ if (prev.outgoing) return prev;
2803
+ let transaction = batchAppliedTransactions(prev.applied);
2804
+ if (!transaction) return prev;
2805
+ let { transactionId, previousRevs, working, batchedTransactionIds: consumedTransactions } = transaction, timestamp = (/* @__PURE__ */ new Date()).toISOString();
2806
+ return {
2807
+ ...prev,
2808
+ outgoing: transaction,
2809
+ applied: prev.applied.filter((i) => !consumedTransactions.includes(i.transactionId)),
2810
+ documentStates: Object.entries(previousRevs).reduce((acc, [documentId, previousRev]) => {
2811
+ if (working[documentId]?._rev === previousRev) return acc;
2812
+ let documentState = prev.documentStates[documentId];
2813
+ return documentState && (acc[documentId] = {
2814
+ ...documentState,
2815
+ unverifiedRevisions: {
2816
+ ...documentState.unverifiedRevisions,
2817
+ [transactionId]: {
2818
+ documentId,
2819
+ previousRev,
2820
+ transactionId,
2821
+ timestamp
2822
+ }
2823
+ },
2824
+ recentOwnTransactionIds: [...(documentState.recentOwnTransactionIds ?? []).slice(-49), transactionId]
2825
+ }), acc;
2826
+ }, { ...prev.documentStates })
2827
+ };
2828
+ }
2829
+ function cleanupOutgoingTransaction(prev) {
2830
+ let { outgoing } = prev;
2831
+ if (!outgoing) return prev;
2832
+ let next = prev, ids = getDocumentIdsFromHandleLikes(outgoing.actions);
2833
+ for (let transactionId of outgoing.batchedTransactionIds) for (let documentId of ids) next = removeSubscriptionIdFromDocument(next, documentId, transactionId);
2834
+ return {
2835
+ ...next,
2836
+ outgoing: void 0,
2837
+ documentStates: evictOrphanedDocumentStates(next.documentStates)
2838
+ };
2839
+ }
2840
+ function revertOutgoingTransaction(prev) {
2841
+ if (!prev.grants) return prev;
2842
+ let base = prev;
2843
+ if (prev.outgoing) {
2844
+ let ids = getDocumentIdsFromHandleLikes(prev.outgoing.actions);
2845
+ for (let transactionId of prev.outgoing.batchedTransactionIds) for (let documentId of ids) base = removeSubscriptionIdFromDocument(base, documentId, transactionId);
2846
+ }
2847
+ let working = Object.fromEntries(Object.entries(base.documentStates).map(([documentId, documentState]) => [documentId, documentState?.remote])), nextApplied = [];
2848
+ for (let t of prev.applied) try {
2849
+ let next = processActions({
2850
+ ...t,
2851
+ working,
2852
+ grants: prev.grants,
2853
+ identity: prev.identity
2854
+ });
2855
+ working = next.working, nextApplied.push({
2856
+ ...t,
2857
+ ...next
2858
+ });
2859
+ } catch (error) {
2860
+ if (error instanceof ActionError) continue;
2861
+ throw error;
2862
+ }
2863
+ return {
2864
+ ...base,
2865
+ applied: nextApplied,
2866
+ outgoing: void 0,
2867
+ documentStates: evictOrphanedDocumentStates(Object.fromEntries(Object.entries(base.documentStates).filter((e) => !!e[1]).map(([documentId, documentState]) => {
2868
+ let { unverifiedRevisions = {} } = documentState, next = {
2869
+ ...documentState,
2870
+ unverifiedRevisions: prev.outgoing && prev.outgoing.transactionId in unverifiedRevisions ? omitProperty(unverifiedRevisions, prev.outgoing.transactionId) : unverifiedRevisions
2871
+ };
2872
+ return !next.subscriptions.length && isAwaitingOwnEcho(next) ? [documentId, next] : [documentId, {
2873
+ ...next,
2874
+ local: documentId in working ? working[documentId] : next.local
2875
+ }];
2876
+ })))
2877
+ };
2878
+ }
2879
+ /**
2880
+ * Extracts the patch operations addressed to the given document from a set of
2881
+ * raw listener mutations, stripping the mutation-level `id` addressing so the
2882
+ * patches are rooted at the document. A transaction can carry mutations for
2883
+ * other documents, so anything not explicitly id-addressed to this document
2884
+ * (including query-addressed patches) is dropped.
2885
+ */
2886
+ function extractPatchOperations(mutations, documentId) {
2887
+ return mutations ? mutations.flatMap((mutation) => {
2888
+ if (!("patch" in mutation) || !mutation.patch) return [];
2889
+ let { id, ...operations } = mutation.patch;
2890
+ return id === documentId ? [operations] : [];
2891
+ }) : [];
2892
+ }
2893
+ function applyRemoteDocument(prev, { document, documentId, previousRev, revision, timestamp, type, mutations }, events) {
2894
+ if (!prev.grants) return prev;
2895
+ let prevDocState = prev.documentStates[documentId];
2896
+ if (!prevDocState) return prev;
2897
+ let prevUnverifiedRevisions = prevDocState.unverifiedRevisions, revisionToVerify = revision ? prevUnverifiedRevisions?.[revision] : void 0, unverifiedRevisions = prevUnverifiedRevisions ?? EMPTY_REVISIONS;
2898
+ if (revision && revisionToVerify && (unverifiedRevisions = omitProperty(prevUnverifiedRevisions, revision)), type === "mutation" && revision) {
2899
+ let patches = extractPatchOperations(mutations, documentId);
2900
+ if (patches.length) {
2901
+ let isOwnTransaction = !!revisionToVerify || (prevDocState.recentOwnTransactionIds?.includes(revision) ?? !1);
2902
+ events.next({
2903
+ type: "remote-patches",
2904
+ documentId,
2905
+ transactionId: revision,
2906
+ previousRev,
2907
+ timestamp,
2908
+ patches,
2909
+ origin: isOwnTransaction ? "local" : "remote"
2910
+ });
2911
+ }
2912
+ }
2913
+ if (type === "sync" && (unverifiedRevisions = Object.fromEntries(Object.entries(unverifiedRevisions).filter(([, unverifiedRevision]) => unverifiedRevision ? new Date(timestamp).getTime() <= new Date(unverifiedRevision.timestamp).getTime() : !1))), revisionToVerify && revisionToVerify.previousRev === previousRev) {
2914
+ let modifiesDocument = (transaction) => transaction.working[documentId]?._rev !== transaction.previousRevs[documentId], local = !prev.applied.some(modifiesDocument) && (!prev.outgoing || prev.outgoing.transactionId === revision || !modifiesDocument(prev.outgoing)) && !isDeepEqual(prevDocState.local, document) ? document : prevDocState.local;
2915
+ return {
2916
+ ...prev,
2917
+ documentStates: evictOrphanedDocumentStates({
2918
+ ...prev.documentStates,
2919
+ [documentId]: {
2920
+ ...prevDocState,
2921
+ remote: document,
2922
+ remoteRev: revision,
2923
+ local,
2924
+ unverifiedRevisions
2925
+ }
2926
+ })
2927
+ };
2928
+ }
2929
+ let working = {
2930
+ ...prev.applied.at(0)?.previous,
2931
+ [documentId]: document
2932
+ }, nextApplied = [];
2933
+ for (let curr of prev.applied) try {
2934
+ let next = processActions({
2935
+ ...curr,
2936
+ working,
2937
+ grants: prev.grants,
2938
+ identity: prev.identity
2939
+ });
2940
+ working = next.working, nextApplied.push({
2941
+ ...curr,
2942
+ ...next
2943
+ });
2944
+ } catch (error) {
2945
+ if (error instanceof ActionError) {
2946
+ events.next({
2947
+ type: "rebase-error",
2948
+ transactionId: error.transactionId,
2949
+ documentId: error.documentId,
2950
+ message: error.message,
2951
+ error
2952
+ });
2953
+ continue;
2954
+ }
2955
+ throw error;
2956
+ }
2957
+ let nextLocal = working[documentId], local = isDeepEqual(prevDocState.local, nextLocal) ? prevDocState.local : nextLocal;
2958
+ return {
2959
+ ...prev,
2960
+ applied: nextApplied,
2961
+ documentStates: evictOrphanedDocumentStates({
2962
+ ...prev.documentStates,
2963
+ [documentId]: {
2964
+ ...prevDocState,
2965
+ remote: document,
2966
+ remoteRev: revision,
2967
+ local,
2968
+ unverifiedRevisions
2969
+ }
2970
+ })
2971
+ };
2972
+ }
2973
+ function addSubscriptionIdToDocument(prev, documentId, subscriptionId) {
2974
+ let prevDocState = prev.documentStates?.[documentId], prevSubscriptions = prevDocState?.subscriptions ?? [];
2975
+ return {
2976
+ ...prev,
2977
+ documentStates: {
2978
+ ...prev.documentStates,
2979
+ [documentId]: {
2980
+ ...prevDocState,
2981
+ id: documentId,
2982
+ subscriptions: [...prevSubscriptions, subscriptionId]
2983
+ }
2984
+ }
2985
+ };
2986
+ }
2987
+ function removeSubscriptionIdFromDocument(prev, documentId, subscriptionId) {
2988
+ let prevDocState = prev.documentStates?.[documentId];
2989
+ if (!prevDocState) return prev;
2990
+ let subscriptions = prevDocState.subscriptions.filter((id) => id !== subscriptionId);
2991
+ return !subscriptions.length && !isAwaitingOwnEcho(prevDocState) ? {
2992
+ ...prev,
2993
+ documentStates: omitProperty(prev.documentStates, documentId)
2994
+ } : {
2995
+ ...prev,
2996
+ documentStates: {
2997
+ ...prev.documentStates,
2998
+ [documentId]: {
2999
+ ...prevDocState,
3000
+ subscriptions
3001
+ }
3002
+ }
3003
+ };
3004
+ }
3005
+ /**
3006
+ * Whether this document still expects the listener echo of one of its own
3007
+ * submitted transactions. That expectation is the only reason a document state
3008
+ * with no subscribers is kept around.
3009
+ *
3010
+ * Revisions stop counting after `UNVERIFIED_REVISION_RETENTION_TIME` because an
3011
+ * echo is not guaranteed to arrive at all: Content Lake records no transaction
3012
+ * when every operation resolves to a no-op (e.g. a keyed path that no longer
3013
+ * exists), while the client bumps `_rev` regardless and so tracks a revision
3014
+ * for it. Without the expiry, such a document (and the listener keyed off its
3015
+ * state) would be pinned for the lifetime of the store.
3016
+ *
3017
+ * `recentOwnTransactionIds` deliberately does not extend the wait: it is capped
3018
+ * rather than drained, so honoring it would keep every edited document alive.
3019
+ */
3020
+ function isAwaitingOwnEcho(documentState) {
3021
+ let expiresAfter = Date.now() - UNVERIFIED_REVISION_RETENTION_TIME;
3022
+ return Object.values(documentState.unverifiedRevisions ?? {}).some((revision) => !!revision && new Date(revision.timestamp).getTime() > expiresAfter);
3023
+ }
3024
+ /**
3025
+ * Removes every document state that has no subscribers left and no own
3026
+ * transaction still awaiting its echo.
3027
+ *
3028
+ * This is a sweep rather than a decision made where the last subscriber leaves
3029
+ * because `removeSubscriptionIdFromDocument` defers that eviction while an echo
3030
+ * is in flight, and both halves of the condition can change without a
3031
+ * subscriber going anywhere: the echo can verify, be dropped by a sync, be
3032
+ * discarded by a revert, or simply never arrive. Every reducer that can settle
3033
+ * an in-flight transaction sweeps, so the deferred decision is always re-made.
3034
+ *
3035
+ * Note this can evict the very document whose remote event is being processed,
3036
+ * which synchronously unsubscribes that document's listener from inside its own
3037
+ * emission (see `subscribeToSubscriptionsAndListenToDocuments`).
3038
+ */
3039
+ function evictOrphanedDocumentStates(documentStates) {
3040
+ let next = documentStates;
3041
+ for (let [documentId, documentState] of Object.entries(documentStates)) documentState && (documentState.subscriptions.length || isAwaitingOwnEcho(documentState) || (next = omitProperty(next, documentId)));
3042
+ return next;
3043
+ }
3044
+ function manageSubscriberIds({ state }, handles) {
3045
+ let documentIds = getDocumentIdsFromHandleLikes(handles), subscriptionId = randomId(16);
3046
+ return state.set("addSubscribers", (prev) => documentIds.reduce((acc, id) => addSubscriptionIdToDocument(acc, id, subscriptionId), prev)), () => {
3047
+ setCleanupTimeout(() => {
3048
+ state.set("removeSubscribers", (prev) => documentIds.reduce((acc, id) => removeSubscriptionIdFromDocument(acc, id, subscriptionId), prev));
3049
+ }, DOCUMENT_STATE_CLEAR_DELAY);
3050
+ };
3051
+ }
3052
+ function throwDocumentError(documentStates, documentIds) {
3053
+ for (let documentId of documentIds) {
3054
+ let documentError = documentStates[documentId]?.error;
3055
+ if (documentError) throw documentError;
3056
+ }
3057
+ }
3058
+ function getDocumentIdsFromHandleLikes(handles) {
3059
+ return handles.flatMap((handle) => {
3060
+ if ("type" in handle && isReleaseAction(handle)) return [getReleaseDocumentId(handle.releaseId)];
3061
+ let idsForDocument = [];
3062
+ return handle.documentId ? handle.liveEdit ? [handle.documentId] : (isReleasePerspective(handle.perspective) && idsForDocument.push(getVersionId(DocumentId(handle.documentId), handle.perspective.releaseName)), idsForDocument.push(getDraftId(DocumentId(handle.documentId))), idsForDocument.push(getPublishedId(DocumentId(handle.documentId))), idsForDocument) : [];
3063
+ });
3064
+ }
3065
+ const actionMap = {
1865
3066
  "document.create": "created",
1866
3067
  "document.delete": "deleted",
1867
3068
  "document.discard": "discarded",