@sanity/sdk 3.18.0-next.20261201154713 → 3.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  import { d as getEnv, f as isReleasePerspective, n as bindActionByResource, o as UPSTREAM_CLOSE_DELAY_MS, s as defineStore, t as createStateSourceAction, u as setCleanupTimeout } from "./createStateSourceAction-Bn0po7Z3.js";
2
- import { A as DOCUMENT_STATE_CLEAR_DELAY, B as getClientErrorApiType, C as retryRead, P as UNVERIFIED_REVISION_RETENTION_TIME, R as getClientErrorApiBody, T as isNetworkFailure, a as getClientAuthState, l as getTokenState, o as getCurrentUserState, w as retryWithCredential, z as getClientErrorApiProjectId } from "./authStore-C9ZFvN7U.js";
2
+ import { B as getClientErrorApiType, C as retryRead, R as getClientErrorApiBody, T as isNetworkFailure, a as getClientAuthState, l as getTokenState, o as getCurrentUserState, w as retryWithCredential, z as getClientErrorApiProjectId } from "./authStore-C9ZFvN7U.js";
3
3
  import { h as randomUuid, m as randomId } from "./topicStore-B3xCclrk.js";
4
- import { r as omitProperty, t as isDeepEqual } from "./object-CxXlSVg7.js";
4
+ import { r as omitProperty } from "./object-CxXlSVg7.js";
5
5
  import { r as getClientState } from "./clientStore-B_AT0A7B.js";
6
6
  import { n as defineFetcher, r as defineMutation } from "./commentFieldPath-DkiKA0H9.js";
7
7
  import { t as getNodeState } from "./getNodeState-Bp9sxNE1.js";
@@ -10,10 +10,8 @@ import { BehaviorSubject, EMPTY, NEVER, Observable, catchError, combineLatest, d
10
10
  import { isKeySegment, isKeyedObject } from "@sanity/types";
11
11
  import { createSelector } from "reselect";
12
12
  import { SDK_CHANNEL_NAME, SDK_NODE_NAME } from "@sanity/message-protocol";
13
- import { DocumentId, getDraftId, getPublishedId, getVersionId } from "@sanity/id-utils";
14
13
  import { getIndexForKey, jsonMatch, slicePath, stringifyPath } from "@sanity/json-match";
15
- import "groq";
16
- import { evaluateSync, parse } from "groq-js";
14
+ import { evaluateSync } from "groq-js";
17
15
  import { applyPatches, parsePatch } from "@sanity/diff-match-patch";
18
16
  import { diffValue } from "@sanity/diff-patch";
19
17
  function findClientError(error) {
@@ -122,27 +120,6 @@ function withProjectAccessMessage(instance, error) {
122
120
  let provider = getCurrentUserState(instance).getCurrent()?.provider;
123
121
  return new ProjectAccessClientError(error, getProjectAccessErrorMessage(details, provider));
124
122
  }
125
- /**
126
- * Returns the full release document ID for the given release name.
127
- * e.g. `getReleaseDocumentId('my-release') === '_.releases.my-release'`
128
- * @beta
129
- */
130
- function getReleaseDocumentId(releaseId) {
131
- return `_.releases.${releaseId}`;
132
- }
133
- const RELEASE_ACTION_TYPES = /* @__PURE__ */ new Set([
134
- "release.create",
135
- "release.edit",
136
- "release.publish",
137
- "release.schedule",
138
- "release.unschedule",
139
- "release.archive",
140
- "release.unarchive",
141
- "release.delete"
142
- ]);
143
- function isReleaseAction(action) {
144
- return RELEASE_ACTION_TYPES.has(action.type);
145
- }
146
123
  function generateArrayKey(length = 12) {
147
124
  let numBytes = Math.ceil(length / 2), bytes = crypto.getRandomValues(new Uint8Array(numBytes));
148
125
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("").slice(0, length);
@@ -489,63 +466,6 @@ function processMutations({ documents, mutations, transactionId, timestamp }) {
489
466
  }
490
467
  return dataset;
491
468
  }
492
- var MultiKeyWeakMap = class MultiKeyWeakMap {
493
- #rootMap = /* @__PURE__ */ new WeakMap();
494
- static #globalIdCounter = 0;
495
- #idCache = /* @__PURE__ */ new WeakMap();
496
- /**
497
- * Assigns a numeric ID to the key.
498
- */
499
- #assignId(key) {
500
- let cachedId = this.#idCache.get(key);
501
- if (cachedId !== void 0) return cachedId;
502
- let id = MultiKeyWeakMap.#globalIdCounter;
503
- return this.#idCache.set(key, id), MultiKeyWeakMap.#globalIdCounter++, id;
504
- }
505
- /**
506
- * Remove duplicate keys and arrange them in a consistent order
507
- * by sorting according to their assigned IDs.
508
- */
509
- #arrangeKeys(keys) {
510
- let keyed = Array.from(new Set(keys)).map((key) => [this.#assignId(key), key]);
511
- return keyed.sort((a, b) => a[0] - b[0]), keyed.map(([, key]) => key);
512
- }
513
- /**
514
- * Recursively search the nested WeakMap structure for the value.
515
- */
516
- #getDeep(keys, map) {
517
- if (keys.length === 0) return;
518
- let [firstKey, ...restKeys] = keys, node = map.get(firstKey);
519
- if (node) return restKeys.length === 0 ? node.value : this.#getDeep(restKeys, node.next);
520
- }
521
- /**
522
- * Recursively create nodes along the key chain until the final key
523
- * is reached, then assign the value.
524
- */
525
- #setDeep(keys, map, value) {
526
- if (keys.length === 0) return;
527
- let [firstKey, ...restKeys] = keys, node = map.get(firstKey);
528
- node || (node = {
529
- value: void 0,
530
- next: /* @__PURE__ */ new WeakMap()
531
- }, map.set(firstKey, node)), restKeys.length === 0 ? node.value = value : this.#setDeep(restKeys, node.next, value);
532
- }
533
- /**
534
- * Retrieves the value associated with the array of keys.
535
- * The keys are de-duplicated and sorted so that the order does not matter.
536
- */
537
- get(keys) {
538
- let arrangedKeys = this.#arrangeKeys(keys);
539
- return this.#getDeep(arrangedKeys, this.#rootMap);
540
- }
541
- /**
542
- * Associates the value with the given array of keys.
543
- */
544
- set(keys, value) {
545
- let arrangedKeys = this.#arrangeKeys(keys);
546
- this.#setDeep(arrangedKeys, this.#rootMap, value);
547
- }
548
- };
549
469
  function checkGrant(grantExpr, document, identity) {
550
470
  let value = evaluateSync(grantExpr, {
551
471
  params: { document },
@@ -708,1124 +628,6 @@ function applySingleDocPatch({ base: initialBase, working: initialWorking, docum
708
628
  workingMutations
709
629
  };
710
630
  }
711
- function createGrantsLookup(datasetAcl) {
712
- let filtersByGrant = {
713
- create: /* @__PURE__ */ new Set(),
714
- history: /* @__PURE__ */ new Set(),
715
- read: /* @__PURE__ */ new Set(),
716
- update: /* @__PURE__ */ new Set()
717
- };
718
- for (let entry of datasetAcl) for (let grant of entry.permissions) {
719
- let set = filtersByGrant[grant];
720
- set && (set.add(entry.filter), filtersByGrant[grant] = set);
721
- }
722
- return Object.fromEntries(Object.entries(filtersByGrant).map(([grant, filters]) => {
723
- let combinedFilter = Array.from(filters).map((i) => `(${i})`).join("||");
724
- return combinedFilter ? [grant, parse(`$document {"_": ${combinedFilter}}._`)] : [grant, parse("false")];
725
- }));
726
- }
727
- const documentsCache = new MultiKeyWeakMap(), actionsCache = /* @__PURE__ */ new WeakMap(), nullReplacer = {}, documentsSelector = createSelector([({ state: { documentStates } }) => documentStates, (_context, { actions }) => actions], (documentStates, actions) => {
728
- let documentIds = new Set(actions.map((action) => {
729
- if (typeof action.documentId != "string") return [];
730
- if (action.liveEdit) return [action.documentId];
731
- let ids = [getPublishedId(DocumentId(action.documentId)), getDraftId(DocumentId(action.documentId))];
732
- return isReleasePerspective(action.perspective) && ids.push(getVersionId(DocumentId(action.documentId), action.perspective.releaseName)), ids;
733
- }).flat());
734
- throwDocumentError(documentStates, documentIds);
735
- let documents = {};
736
- for (let documentId of documentIds) {
737
- let local = documentStates[documentId]?.local;
738
- if (local === void 0) return;
739
- documents[documentId] = local;
740
- }
741
- let keys = Object.values(documents).map((doc) => doc === null ? nullReplacer : doc);
742
- return documentsCache.get(keys) || (documentsCache.set(keys, documents), documents);
743
- }), memoizedActionsSelector = createSelector([documentsSelector, (_state, { actions }) => actions], (documents, actions) => {
744
- if (!documents) return;
745
- let nestedCache = actionsCache.get(documents);
746
- nestedCache || (nestedCache = /* @__PURE__ */ new Map(), actionsCache.set(documents, nestedCache));
747
- let normalizedActions = Array.isArray(actions) ? actions : [actions], actionsKey = JSON.stringify(normalizedActions);
748
- return nestedCache.get(actionsKey) || (nestedCache.set(actionsKey, normalizedActions), normalizedActions);
749
- }), enNarrowConjunction = new Intl.ListFormat("en", {
750
- style: "narrow",
751
- type: "conjunction"
752
- });
753
- function calculatePermissions(...args) {
754
- return _calculatePermissions(...args);
755
- }
756
- const _calculatePermissions = createSelector([
757
- ({ state: { grants } }) => grants,
758
- ({ state: { identity } }) => identity,
759
- documentsSelector,
760
- memoizedActionsSelector
761
- ], (grants, identity, documents, actions) => {
762
- if (!documents || !grants || !actions) return;
763
- let timestamp = (/* @__PURE__ */ new Date()).toISOString(), reasons = [];
764
- try {
765
- processActions({
766
- actions,
767
- transactionId: randomId(16),
768
- working: documents,
769
- base: documents,
770
- timestamp,
771
- grants,
772
- identity
773
- });
774
- } catch (error) {
775
- if (error instanceof PermissionActionError) reasons.push({
776
- message: error.message,
777
- documentId: error.documentId,
778
- type: "access"
779
- });
780
- else if (error instanceof ActionError) reasons.push({
781
- message: error.message,
782
- documentId: error.documentId,
783
- type: "precondition"
784
- });
785
- else throw error;
786
- }
787
- for (let action of actions) if (action.type === "document.edit" && !action.patches?.length) {
788
- let docId = action.documentId, doc;
789
- 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({
790
- type: "access",
791
- message: `You are not allowed to edit the document with ID "${docId}".`,
792
- documentId: docId
793
- }) : isReleasePerspective(action.perspective) ? reasons.push({
794
- type: "precondition",
795
- message: `The version document with ID "${docId}" could not be found. Please create it or add it to the release first.`,
796
- documentId: docId
797
- }) : reasons.push({
798
- type: "precondition",
799
- message: `The document with ID "${docId}" could not be found. Please check that it exists before editing.`,
800
- documentId: docId
801
- });
802
- }
803
- let allowed = reasons.length === 0;
804
- if (allowed) return { allowed };
805
- let sortedReasons = reasons.map((reason, index) => ({
806
- ...reason,
807
- index
808
- })).sort((a, b) => a.type === b.type ? a.message.localeCompare(b.message, "en-US") : a.type === "access" ? -1 : 1).map(({ index: _index, ...reason }) => reason);
809
- return {
810
- allowed,
811
- reasons: sortedReasons,
812
- message: enNarrowConjunction.format(sortedReasons.map((i) => i.message))
813
- };
814
- });
815
- function handleCreate(action, ctx) {
816
- let { transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations } = ctx, { base, working } = ctx, documentId = getId(action.documentId);
817
- if (action.liveEdit) {
818
- if (working[documentId]) throw new ActionError({
819
- documentId,
820
- transactionId,
821
- message: "This document already exists."
822
- });
823
- let newDocBase = {
824
- _type: action.documentType,
825
- _id: documentId,
826
- ...action.initialValue
827
- }, mutations = [{ create: {
828
- _type: action.documentType,
829
- _id: documentId,
830
- ...action.initialValue
831
- } }];
832
- if (base = processMutations({
833
- documents: base,
834
- transactionId,
835
- mutations: [{ create: newDocBase }],
836
- timestamp
837
- }), working = processMutations({
838
- documents: working,
839
- transactionId,
840
- mutations,
841
- timestamp
842
- }), !checkGrant(grants.create, working[documentId], identity)) throw new PermissionActionError({
843
- documentId,
844
- transactionId,
845
- message: `You do not have permission to create document "${documentId}".`
846
- });
847
- return outgoingMutations.push(...mutations), {
848
- base,
849
- working
850
- };
851
- }
852
- let versionId = isReleasePerspective(action.perspective) ? getVersionId(DocumentId(documentId), action.perspective.releaseName) : void 0, draftId = getDraftId(DocumentId(documentId)), publishedId = getPublishedId(DocumentId(documentId));
853
- if (versionId ? working[versionId] : working[draftId]) {
854
- let errorDocType = versionId ? "release version" : "draft";
855
- throw new ActionError({
856
- documentId,
857
- transactionId,
858
- message: `A ${errorDocType} of this document already exists. Please use or discard the existing ${errorDocType} before creating a new one.`
859
- });
860
- }
861
- let newDocBase = {
862
- ...base[draftId] ?? base[publishedId],
863
- _type: action.documentType,
864
- _id: versionId ?? draftId,
865
- ...action.initialValue
866
- }, newDocWorking = {
867
- ...working[draftId] ?? working[publishedId],
868
- _type: action.documentType,
869
- _id: versionId ?? draftId,
870
- ...action.initialValue
871
- }, mutations = [{ create: newDocWorking }];
872
- if (base = processMutations({
873
- documents: base,
874
- transactionId,
875
- mutations: [{ create: newDocBase }],
876
- timestamp
877
- }), working = processMutations({
878
- documents: working,
879
- transactionId,
880
- mutations,
881
- timestamp
882
- }), versionId && !checkGrant(grants.create, working[versionId], identity)) throw new PermissionActionError({
883
- documentId,
884
- transactionId,
885
- message: `You do not have permission to create a release version for document "${documentId}".`
886
- });
887
- if (!versionId && !checkGrant(grants.create, working[draftId], identity)) throw new PermissionActionError({
888
- documentId,
889
- transactionId,
890
- message: `You do not have permission to create a draft for document "${documentId}".`
891
- });
892
- return outgoingMutations.push(...mutations), outgoingActions.push({
893
- actionType: "sanity.action.document.version.create",
894
- publishedId,
895
- attributes: newDocWorking
896
- }), {
897
- base,
898
- working
899
- };
900
- }
901
- function handleDelete(action, ctx) {
902
- let { transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations } = ctx, { base, working } = ctx, documentId = action.documentId;
903
- if (isReleasePerspective(action.perspective)) throw new ActionError({
904
- documentId,
905
- transactionId,
906
- message: "Cannot delete a version document. You may want to use the \"unpublish\" or \"discard\" actions instead."
907
- });
908
- if (action.liveEdit) {
909
- if (!working[documentId]) throw new ActionError({
910
- documentId,
911
- transactionId,
912
- message: "The document you are trying to delete does not exist."
913
- });
914
- if (!checkGrant(grants.update, working[documentId], identity)) throw new PermissionActionError({
915
- documentId,
916
- transactionId,
917
- message: "You do not have permission to delete this document."
918
- });
919
- let mutations = [{ delete: { id: documentId } }];
920
- return base = processMutations({
921
- documents: base,
922
- transactionId,
923
- mutations,
924
- timestamp
925
- }), working = processMutations({
926
- documents: working,
927
- transactionId,
928
- mutations,
929
- timestamp
930
- }), outgoingMutations.push(...mutations), {
931
- base,
932
- working
933
- };
934
- }
935
- let draftId = getDraftId(DocumentId(documentId)), publishedId = getPublishedId(DocumentId(documentId));
936
- if (!working[publishedId]) throw new ActionError({
937
- documentId,
938
- transactionId,
939
- message: working[draftId] ? "Cannot delete a document without a published version." : "The document you are trying to delete does not exist."
940
- });
941
- let cantDeleteDraft = working[draftId] && !checkGrant(grants.update, working[draftId], identity), cantDeletePublished = working[publishedId] && !checkGrant(grants.update, working[publishedId], identity);
942
- if (cantDeleteDraft || cantDeletePublished) throw new PermissionActionError({
943
- documentId,
944
- transactionId,
945
- message: "You do not have permission to delete this document."
946
- });
947
- let mutations = [{ delete: { id: publishedId } }, { delete: { id: draftId } }], includeDrafts = working[draftId] ? [draftId] : void 0;
948
- return base = processMutations({
949
- documents: base,
950
- transactionId,
951
- mutations,
952
- timestamp
953
- }), working = processMutations({
954
- documents: working,
955
- transactionId,
956
- mutations,
957
- timestamp
958
- }), outgoingMutations.push(...mutations), outgoingActions.push({
959
- actionType: "sanity.action.document.delete",
960
- publishedId,
961
- ...includeDrafts ? { includeDrafts } : {}
962
- }), {
963
- base,
964
- working
965
- };
966
- }
967
- function handleDiscard(action, ctx) {
968
- let { transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations } = ctx, { base, working } = ctx, documentId = getId(action.documentId);
969
- if (action.liveEdit) throw new ActionError({
970
- documentId,
971
- transactionId,
972
- message: `Cannot discard changes for liveEdit document "${documentId}". LiveEdit documents do not support drafts.`
973
- });
974
- let versionId = isReleasePerspective(action.perspective) ? getVersionId(DocumentId(documentId), action.perspective.releaseName) : getDraftId(DocumentId(documentId)), mutations = [{ delete: { id: versionId } }];
975
- if (!working[versionId]) throw new ActionError({
976
- documentId,
977
- transactionId,
978
- message: `There is no draft or version available to discard for document "${documentId}".`
979
- });
980
- if (!checkGrant(grants.update, working[versionId], identity)) throw new PermissionActionError({
981
- documentId,
982
- transactionId,
983
- message: `You do not have permission to discard changes for document "${documentId}".`
984
- });
985
- return base = processMutations({
986
- documents: base,
987
- transactionId,
988
- mutations,
989
- timestamp
990
- }), working = processMutations({
991
- documents: working,
992
- transactionId,
993
- mutations,
994
- timestamp
995
- }), outgoingMutations.push(...mutations), outgoingActions.push({
996
- actionType: "sanity.action.document.version.discard",
997
- versionId
998
- }), {
999
- base,
1000
- working
1001
- };
1002
- }
1003
- function handleEdit(action, ctx) {
1004
- let { transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations } = ctx, { base, working } = ctx, documentId = getId(action.documentId);
1005
- if (action.liveEdit) {
1006
- let result = applySingleDocPatch({
1007
- base,
1008
- working,
1009
- documentId,
1010
- patches: action.patches,
1011
- transactionId,
1012
- timestamp,
1013
- grants,
1014
- identity,
1015
- preserveOperations: action.preserveOperations
1016
- });
1017
- return outgoingMutations.push(...result.workingMutations), {
1018
- base: result.base,
1019
- working: result.working
1020
- };
1021
- }
1022
- 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: {
1023
- id: patchDocumentId,
1024
- ...patch
1025
- } }));
1026
- if (!userPatches?.length) return {
1027
- base,
1028
- working
1029
- };
1030
- if (isReleasePerspective(action.perspective)) {
1031
- if (!working[versionId] && !base[versionId]) throw new ActionError({
1032
- documentId,
1033
- transactionId,
1034
- message: "This document does not exist in the release. Please create it or add it to the release first."
1035
- });
1036
- } else if (!working[draftId] && !working[publishedId] || !base[draftId] && !base[publishedId]) throw new ActionError({
1037
- documentId,
1038
- transactionId,
1039
- message: "Cannot edit document because it does not exist in draft or published form."
1040
- });
1041
- let applyMutations = createMutationApplier({
1042
- documentId,
1043
- transactionId,
1044
- timestamp,
1045
- preserveOperations: action.preserveOperations
1046
- }), baseMutations = [];
1047
- !isReleasePerspective(action.perspective) && !base[draftId] && base[publishedId] && baseMutations.push({ create: {
1048
- ...base[publishedId],
1049
- _id: draftId
1050
- } });
1051
- let baseBefore = base[patchDocumentId] ?? base[publishedId];
1052
- userPatches && baseMutations.push(...userPatches), base = applyMutations(base, baseMutations, "base");
1053
- let baseAfter = base[patchDocumentId], patches = action.preserveOperations ? action.patches ?? [] : preserveNumericOperations(baseBefore, action.patches, diffValue(baseBefore, baseAfter)), workingMutations = [];
1054
- if (!isReleasePerspective(action.perspective) && !working[draftId] && working[publishedId]) {
1055
- let newDraftFromPublished = {
1056
- ...working[publishedId],
1057
- _id: draftId
1058
- };
1059
- if (!checkGrant(grants.create, newDraftFromPublished, identity)) throw new PermissionActionError({
1060
- documentId,
1061
- transactionId,
1062
- message: "You do not have permission to create a draft for editing this document."
1063
- });
1064
- workingMutations.push({ create: newDraftFromPublished });
1065
- }
1066
- let workingBefore = working[patchDocumentId] ?? working[publishedId];
1067
- if (!checkGrant(grants.update, workingBefore, identity)) throw new PermissionActionError({
1068
- documentId,
1069
- transactionId,
1070
- message: `You do not have permission to edit document "${documentId}".`
1071
- });
1072
- return workingMutations.push(...patches.map((patch) => ({ patch: {
1073
- id: patchDocumentId,
1074
- ...patch
1075
- } }))), working = applyMutations(working, workingMutations, "working"), outgoingMutations.push(...workingMutations), outgoingActions.push(...patches.map((patch) => ({
1076
- actionType: "sanity.action.document.edit",
1077
- draftId: patchDocumentId,
1078
- publishedId,
1079
- patch
1080
- }))), {
1081
- base,
1082
- working
1083
- };
1084
- }
1085
- function handlePublish(action, ctx) {
1086
- let { transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations } = ctx, { base, working } = ctx, documentId = getId(action.documentId);
1087
- if (action.liveEdit || isReleasePerspective(action.perspective)) throw new ActionError({
1088
- documentId,
1089
- transactionId,
1090
- message: "Cannot publish this document. Publishing is not supported for liveEdit or version (release) documents."
1091
- });
1092
- let draftId = getDraftId(DocumentId(documentId)), publishedId = getPublishedId(DocumentId(documentId)), workingDraft = working[draftId], baseDraft = base[draftId];
1093
- if (!workingDraft || !baseDraft) throw new ActionError({
1094
- documentId,
1095
- transactionId,
1096
- message: `Cannot publish because no draft version was found for document "${documentId}".`
1097
- });
1098
- if (!isDeepEqual(workingDraft, baseDraft)) throw new ActionError({
1099
- documentId,
1100
- transactionId,
1101
- message: "Publish aborted: The document has changed elsewhere. Please try again."
1102
- });
1103
- let newPublishedFromDraft = {
1104
- ...strengthenOnPublish(workingDraft),
1105
- _id: publishedId
1106
- }, mutations = [{ delete: { id: draftId } }, { createOrReplace: newPublishedFromDraft }];
1107
- if (working[draftId] && !checkGrant(grants.update, working[draftId], identity)) throw new PermissionActionError({
1108
- documentId,
1109
- transactionId,
1110
- message: `Publish failed: You do not have permission to update the draft for "${documentId}".`
1111
- });
1112
- if (working[publishedId] && !checkGrant(grants.update, newPublishedFromDraft, identity)) throw new PermissionActionError({
1113
- documentId,
1114
- transactionId,
1115
- message: `Publish failed: You do not have permission to update the published version of "${documentId}".`
1116
- });
1117
- if (!working[publishedId] && !checkGrant(grants.create, newPublishedFromDraft, identity)) throw new PermissionActionError({
1118
- documentId,
1119
- transactionId,
1120
- message: `Publish failed: You do not have permission to publish a new version of "${documentId}".`
1121
- });
1122
- return base = processMutations({
1123
- documents: base,
1124
- transactionId,
1125
- mutations,
1126
- timestamp
1127
- }), working = processMutations({
1128
- documents: working,
1129
- transactionId,
1130
- mutations,
1131
- timestamp
1132
- }), outgoingMutations.push(...mutations), outgoingActions.push({
1133
- actionType: "sanity.action.document.publish",
1134
- draftId,
1135
- publishedId
1136
- }), {
1137
- base,
1138
- working
1139
- };
1140
- }
1141
- function strengthenOnPublish(draft) {
1142
- let isStrengthenReference = (value) => "_strengthenOnPublish" in value;
1143
- function strengthen(value) {
1144
- if (typeof value != "object" || !value) return value;
1145
- if (isStrengthenReference(value)) {
1146
- let { _strengthenOnPublish, _weak, ...rest } = value;
1147
- return {
1148
- ...rest,
1149
- ..._strengthenOnPublish.weak && { _weak: !0 }
1150
- };
1151
- }
1152
- return Array.isArray(value) ? value.map(strengthen) : Object.fromEntries(Object.entries(value).map(([k, v]) => [k, strengthen(v)]));
1153
- }
1154
- return strengthen(draft);
1155
- }
1156
- function handleReleaseArchive(action, ctx) {
1157
- let { base, working, grants, outgoingActions, transactionId, identity } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId), existing = working[releaseDocumentId] ?? base[releaseDocumentId];
1158
- if (!existing) throw new ActionError({
1159
- documentId: releaseDocumentId,
1160
- transactionId,
1161
- message: `Cannot archive release "${action.releaseId}" because it does not exist.`
1162
- });
1163
- if (!checkGrant(grants.update, existing, identity)) throw new PermissionActionError({
1164
- documentId: releaseDocumentId,
1165
- transactionId,
1166
- message: `You do not have permission to archive release "${action.releaseId}".`
1167
- });
1168
- return outgoingActions.push({
1169
- actionType: "sanity.action.release.archive",
1170
- releaseId: action.releaseId
1171
- }), {
1172
- base,
1173
- working
1174
- };
1175
- }
1176
- function handleReleaseUnarchive(action, ctx) {
1177
- let { base, working, grants, outgoingActions, transactionId, identity } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId), existing = working[releaseDocumentId] ?? base[releaseDocumentId];
1178
- if (!existing) throw new ActionError({
1179
- documentId: releaseDocumentId,
1180
- transactionId,
1181
- message: `Cannot unarchive release "${action.releaseId}" because it does not exist.`
1182
- });
1183
- if (!checkGrant(grants.update, existing, identity)) throw new PermissionActionError({
1184
- documentId: releaseDocumentId,
1185
- transactionId,
1186
- message: `You do not have permission to unarchive release "${action.releaseId}".`
1187
- });
1188
- return outgoingActions.push({
1189
- actionType: "sanity.action.release.unarchive",
1190
- releaseId: action.releaseId
1191
- }), {
1192
- base,
1193
- working
1194
- };
1195
- }
1196
- function handleReleaseCreate(action, ctx) {
1197
- let { transactionId, timestamp, grants, outgoingActions, outgoingMutations, identity } = ctx, { base, working } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId);
1198
- if (working[releaseDocumentId] || base[releaseDocumentId]) throw new ActionError({
1199
- documentId: releaseDocumentId,
1200
- transactionId,
1201
- message: `A release with id "${action.releaseId}" already exists.`
1202
- });
1203
- let mutations = [{ create: {
1204
- _id: releaseDocumentId,
1205
- _type: "system.release",
1206
- name: action.releaseId,
1207
- state: "active",
1208
- metadata: action.metadata
1209
- } }];
1210
- if (base = processMutations({
1211
- documents: base,
1212
- transactionId,
1213
- mutations,
1214
- timestamp
1215
- }), working = processMutations({
1216
- documents: working,
1217
- transactionId,
1218
- mutations,
1219
- timestamp
1220
- }), !checkGrant(grants.create, working[releaseDocumentId], identity)) throw new PermissionActionError({
1221
- documentId: releaseDocumentId,
1222
- transactionId,
1223
- message: `You do not have permission to create release "${action.releaseId}".`
1224
- });
1225
- return outgoingMutations.push(...mutations), outgoingActions.push({
1226
- actionType: "sanity.action.release.create",
1227
- releaseId: action.releaseId,
1228
- metadata: action.metadata
1229
- }), {
1230
- base,
1231
- working
1232
- };
1233
- }
1234
- const DELETABLE_STATES = /* @__PURE__ */ new Set(["archived", "published"]);
1235
- function handleReleaseDelete(action, ctx) {
1236
- let { transactionId, timestamp, grants, outgoingActions, outgoingMutations, identity } = ctx, { base, working } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId), existing = working[releaseDocumentId] ?? base[releaseDocumentId];
1237
- if (!existing) throw new ActionError({
1238
- documentId: releaseDocumentId,
1239
- transactionId,
1240
- message: `Cannot delete release "${action.releaseId}" because it does not exist.`
1241
- });
1242
- let state = existing.state;
1243
- if (state && typeof state == "string" && !DELETABLE_STATES.has(state)) throw new ActionError({
1244
- documentId: releaseDocumentId,
1245
- transactionId,
1246
- message: `Cannot delete release "${action.releaseId}" while it is "${state}". Archive it first.`
1247
- });
1248
- if (!checkGrant(grants.update, existing, identity)) throw new PermissionActionError({
1249
- documentId: releaseDocumentId,
1250
- transactionId,
1251
- message: `You do not have permission to delete release "${action.releaseId}".`
1252
- });
1253
- let mutations = [{ delete: { id: releaseDocumentId } }];
1254
- return base = processMutations({
1255
- documents: base,
1256
- transactionId,
1257
- mutations,
1258
- timestamp
1259
- }), working = processMutations({
1260
- documents: working,
1261
- transactionId,
1262
- mutations,
1263
- timestamp
1264
- }), outgoingMutations.push(...mutations), outgoingActions.push({
1265
- actionType: "sanity.action.release.delete",
1266
- releaseId: action.releaseId
1267
- }), {
1268
- base,
1269
- working
1270
- };
1271
- }
1272
- function handleReleaseEdit(action, ctx) {
1273
- let { transactionId, timestamp, grants, outgoingActions, outgoingMutations, identity } = ctx, { base, working } = ctx, result = applySingleDocPatch({
1274
- base,
1275
- working,
1276
- documentId: getReleaseDocumentId(action.releaseId),
1277
- patches: [action.patch],
1278
- transactionId,
1279
- timestamp,
1280
- grants,
1281
- identity,
1282
- notFoundMessage: `Cannot edit release "${action.releaseId}" because it does not exist.`,
1283
- permissionMessage: `You do not have permission to edit release "${action.releaseId}".`
1284
- });
1285
- return outgoingMutations.push(...result.workingMutations), outgoingActions.push(...result.diffedPatches.map((patch) => ({
1286
- actionType: "sanity.action.release.edit",
1287
- releaseId: action.releaseId,
1288
- patch
1289
- }))), {
1290
- base: result.base,
1291
- working: result.working
1292
- };
1293
- }
1294
- function handleReleasePublish(action, ctx) {
1295
- let { base, working, grants, outgoingActions, transactionId, identity } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId), existing = working[releaseDocumentId] ?? base[releaseDocumentId];
1296
- if (!existing) throw new ActionError({
1297
- documentId: releaseDocumentId,
1298
- transactionId,
1299
- message: `Cannot publish release "${action.releaseId}" because it does not exist.`
1300
- });
1301
- if (!checkGrant(grants.update, existing, identity)) throw new PermissionActionError({
1302
- documentId: releaseDocumentId,
1303
- transactionId,
1304
- message: `You do not have permission to publish release "${action.releaseId}".`
1305
- });
1306
- return outgoingActions.push({
1307
- actionType: "sanity.action.release.publish",
1308
- releaseId: action.releaseId
1309
- }), {
1310
- base,
1311
- working
1312
- };
1313
- }
1314
- function handleReleaseSchedule(action, ctx) {
1315
- let { base, working, grants, outgoingActions, transactionId, identity } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId);
1316
- if (Number.isNaN(Date.parse(action.publishAt))) throw new ActionError({
1317
- documentId: releaseDocumentId,
1318
- transactionId,
1319
- message: `Cannot schedule release "${action.releaseId}": "publishAt" must be a valid ISO 8601 timestamp (received "${action.publishAt}").`
1320
- });
1321
- let existing = working[releaseDocumentId] ?? base[releaseDocumentId];
1322
- if (!existing) throw new ActionError({
1323
- documentId: releaseDocumentId,
1324
- transactionId,
1325
- message: `Cannot schedule release "${action.releaseId}" because it does not exist.`
1326
- });
1327
- if (!checkGrant(grants.update, existing, identity)) throw new PermissionActionError({
1328
- documentId: releaseDocumentId,
1329
- transactionId,
1330
- message: `You do not have permission to schedule release "${action.releaseId}".`
1331
- });
1332
- return outgoingActions.push({
1333
- actionType: "sanity.action.release.schedule",
1334
- releaseId: action.releaseId,
1335
- publishAt: action.publishAt
1336
- }), {
1337
- base,
1338
- working
1339
- };
1340
- }
1341
- function handleReleaseUnschedule(action, ctx) {
1342
- let { base, working, grants, outgoingActions, transactionId, identity } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId), existing = working[releaseDocumentId] ?? base[releaseDocumentId];
1343
- if (!existing) throw new ActionError({
1344
- documentId: releaseDocumentId,
1345
- transactionId,
1346
- message: `Cannot unschedule release "${action.releaseId}" because it does not exist.`
1347
- });
1348
- if (!checkGrant(grants.update, existing, identity)) throw new PermissionActionError({
1349
- documentId: releaseDocumentId,
1350
- transactionId,
1351
- message: `You do not have permission to unschedule release "${action.releaseId}".`
1352
- });
1353
- return outgoingActions.push({
1354
- actionType: "sanity.action.release.unschedule",
1355
- releaseId: action.releaseId
1356
- }), {
1357
- base,
1358
- working
1359
- };
1360
- }
1361
- function handleUnpublish(action, ctx) {
1362
- let { transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations } = ctx, { base, working } = ctx, documentId = getId(action.documentId);
1363
- if (action.liveEdit || isReleasePerspective(action.perspective)) throw new ActionError({
1364
- documentId,
1365
- transactionId,
1366
- message: "Cannot unpublish this document. Unpublishing is not supported for liveEdit or version (release) documents."
1367
- });
1368
- let draftId = getDraftId(DocumentId(documentId)), publishedId = getPublishedId(DocumentId(documentId));
1369
- if (!working[publishedId] && !base[publishedId]) throw new ActionError({
1370
- documentId,
1371
- transactionId,
1372
- message: `Cannot unpublish because the document "${documentId}" is not currently published.`
1373
- });
1374
- let sourceDoc = working[publishedId] ?? base[publishedId], newDraftFromPublished = {
1375
- ...sourceDoc,
1376
- _id: draftId
1377
- }, mutations = [{ delete: { id: publishedId } }, { createIfNotExists: newDraftFromPublished }];
1378
- if (!checkGrant(grants.update, sourceDoc, identity)) throw new PermissionActionError({
1379
- documentId,
1380
- transactionId,
1381
- message: `You do not have permission to unpublish the document "${documentId}".`
1382
- });
1383
- if (!working[draftId] && !checkGrant(grants.create, newDraftFromPublished, identity)) throw new PermissionActionError({
1384
- documentId,
1385
- transactionId,
1386
- message: `You do not have permission to create a draft from the published version of "${documentId}".`
1387
- });
1388
- return base = processMutations({
1389
- documents: base,
1390
- transactionId,
1391
- mutations: [{ delete: { id: publishedId } }, { createIfNotExists: {
1392
- ...base[publishedId] ?? sourceDoc,
1393
- _id: draftId
1394
- } }],
1395
- timestamp
1396
- }), working = processMutations({
1397
- documents: working,
1398
- transactionId,
1399
- mutations,
1400
- timestamp
1401
- }), outgoingMutations.push(...mutations), outgoingActions.push({
1402
- actionType: "sanity.action.document.unpublish",
1403
- draftId,
1404
- publishedId
1405
- }), {
1406
- base,
1407
- working
1408
- };
1409
- }
1410
- /**
1411
- * Applies the given set of actions to the working set of documents and converts
1412
- * high-level actions into lower-level outgoing mutations/actions that respect
1413
- * the current state of the working documents.
1414
- *
1415
- * Supports a "base" and "working" set of documents to allow actions to be
1416
- * applied on top of a different working set of documents in a 3-way merge
1417
- *
1418
- * Actions are applied to the base set of documents first. The difference
1419
- * between the base before and after is used to create a patch. This patch is
1420
- * then applied to the working set of documents and is set as the outgoing patch
1421
- * sent to the server.
1422
- */
1423
- function processActions({ actions, transactionId, working: initialWorking, base: initialBase, timestamp, grants, identity }) {
1424
- let base = { ...initialBase }, working = { ...initialWorking }, outgoingActions = [], outgoingMutations = [], liveEditAction = actions.find((action) => !isReleaseAction(action) && action.liveEdit), otherAction = actions.find((action) => isReleaseAction(action) || !action.liveEdit);
1425
- if (liveEditAction && otherAction) throw new ActionError({
1426
- documentId: liveEditAction.documentId,
1427
- transactionId,
1428
- message: "Cannot combine liveEdit document actions with other actions in the same transaction. Submit them as separate transactions."
1429
- });
1430
- for (let action of actions) {
1431
- let result = dispatch(action, {
1432
- base,
1433
- working,
1434
- transactionId,
1435
- timestamp,
1436
- grants,
1437
- identity,
1438
- outgoingActions,
1439
- outgoingMutations
1440
- });
1441
- base = result.base, working = result.working;
1442
- }
1443
- let previousRevs = Object.fromEntries(Object.entries(initialWorking).map(([id, doc]) => [id, doc?._rev]));
1444
- return {
1445
- working,
1446
- outgoingActions,
1447
- outgoingMutations,
1448
- previous: initialWorking,
1449
- previousRevs
1450
- };
1451
- }
1452
- function dispatch(action, ctx) {
1453
- switch (action.type) {
1454
- case "document.create": return handleCreate(action, ctx);
1455
- case "document.delete": return handleDelete(action, ctx);
1456
- case "document.discard": return handleDiscard(action, ctx);
1457
- case "document.edit": return handleEdit(action, ctx);
1458
- case "document.publish": return handlePublish(action, ctx);
1459
- case "document.unpublish": return handleUnpublish(action, ctx);
1460
- case "release.create": return handleReleaseCreate(action, ctx);
1461
- case "release.edit": return handleReleaseEdit(action, ctx);
1462
- case "release.publish": return handleReleasePublish(action, ctx);
1463
- case "release.schedule": return handleReleaseSchedule(action, ctx);
1464
- case "release.unschedule": return handleReleaseUnschedule(action, ctx);
1465
- case "release.archive": return handleReleaseArchive(action, ctx);
1466
- case "release.unarchive": return handleReleaseUnarchive(action, ctx);
1467
- case "release.delete": return handleReleaseDelete(action, ctx);
1468
- default: throw Error(`Unknown action type: "${action.type}". Please contact support if this issue persists.`);
1469
- }
1470
- }
1471
- const EMPTY_REVISIONS = {};
1472
- function queueTransaction(prev, transaction) {
1473
- let { transactionId, actions } = transaction;
1474
- return {
1475
- ...getDocumentIdsFromHandleLikes(actions).reduce((acc, id) => addSubscriptionIdToDocument(acc, id, transactionId), prev),
1476
- queued: [...prev.queued, transaction]
1477
- };
1478
- }
1479
- function removeQueuedTransaction(prev, transactionId) {
1480
- let transaction = prev.queued.find((t) => t.transactionId === transactionId);
1481
- return transaction ? {
1482
- ...getDocumentIdsFromHandleLikes(transaction.actions).reduce((acc, id) => removeSubscriptionIdFromDocument(acc, id, transactionId), prev),
1483
- queued: prev.queued.filter((t) => transactionId !== t.transactionId)
1484
- } : prev;
1485
- }
1486
- function applyFirstQueuedTransaction(prev) {
1487
- let queued = prev.queued.at(0);
1488
- if (!queued || !prev.grants) return prev;
1489
- let ids = getDocumentIdsFromHandleLikes(queued.actions);
1490
- if (ids.some((id) => prev.documentStates[id]?.local === void 0)) return prev;
1491
- let working = ids.reduce((acc, id) => (acc[id] = prev.documentStates[id]?.local, acc), {}), timestamp = (/* @__PURE__ */ new Date()).toISOString(), result = processActions({
1492
- ...queued,
1493
- working,
1494
- base: working,
1495
- timestamp,
1496
- grants: prev.grants,
1497
- identity: prev.identity
1498
- }), applied = {
1499
- ...queued,
1500
- ...result,
1501
- base: result.previous,
1502
- timestamp
1503
- };
1504
- return {
1505
- ...prev,
1506
- applied: [...prev.applied, applied],
1507
- queued: prev.queued.filter((t) => t.transactionId !== queued.transactionId),
1508
- documentStates: Object.entries(result.working).reduce((acc, [id, next]) => {
1509
- let prevDoc = acc[id];
1510
- return prevDoc && (acc[id] = {
1511
- ...prevDoc,
1512
- local: next
1513
- }), acc;
1514
- }, { ...prev.documentStates })
1515
- };
1516
- }
1517
- /** Whether a transaction can be combined with adjacent edits in the submission queue. */
1518
- function isBatchableTransaction(transaction) {
1519
- return !transaction.disableBatching && transaction.actions.length === 1 && transaction.actions[0].type === "document.edit";
1520
- }
1521
- function batchAppliedTransactions([curr, ...rest]) {
1522
- if (!curr) return;
1523
- if (!curr.actions.length) return batchAppliedTransactions(rest);
1524
- if (!isBatchableTransaction(curr)) return {
1525
- ...curr,
1526
- disableBatching: !0,
1527
- batchedTransactionIds: [curr.transactionId]
1528
- };
1529
- let [action] = curr.actions, editAction = {
1530
- ...curr,
1531
- actions: [action],
1532
- disableBatching: !1,
1533
- batchedTransactionIds: [curr.transactionId]
1534
- };
1535
- if (!rest.length) return editAction;
1536
- let next = batchAppliedTransactions(rest);
1537
- if (!next || next.disableBatching) return editAction;
1538
- let nextFirst = next.actions[0], nextLiveEdit = nextFirst && "liveEdit" in nextFirst ? nextFirst.liveEdit : !1;
1539
- return !!action.liveEdit == !!nextLiveEdit ? {
1540
- disableBatching: !1,
1541
- transactionId: next.transactionId,
1542
- actions: [action, ...next.actions],
1543
- outgoingActions: [...curr.outgoingActions, ...next.outgoingActions],
1544
- batchedTransactionIds: [curr.transactionId, ...next.batchedTransactionIds],
1545
- outgoingMutations: [...curr.outgoingMutations, ...next.outgoingMutations],
1546
- working: {
1547
- ...curr.working,
1548
- ...next.working
1549
- },
1550
- previousRevs: {
1551
- ...next.previousRevs,
1552
- ...curr.previousRevs
1553
- },
1554
- previous: {
1555
- ...next.previous,
1556
- ...curr.previous
1557
- },
1558
- base: {
1559
- ...next.base,
1560
- ...curr.base
1561
- },
1562
- timestamp: curr.timestamp ?? next.timestamp
1563
- } : editAction;
1564
- }
1565
- function transitionAppliedTransactionsToOutgoing(prev) {
1566
- if (prev.outgoing) return prev;
1567
- let transaction = batchAppliedTransactions(prev.applied);
1568
- if (!transaction) return prev;
1569
- let { transactionId, previousRevs, working, batchedTransactionIds: consumedTransactions } = transaction, timestamp = (/* @__PURE__ */ new Date()).toISOString();
1570
- return {
1571
- ...prev,
1572
- outgoing: transaction,
1573
- applied: prev.applied.filter((i) => !consumedTransactions.includes(i.transactionId)),
1574
- documentStates: Object.entries(previousRevs).reduce((acc, [documentId, previousRev]) => {
1575
- if (working[documentId]?._rev === previousRev) return acc;
1576
- let documentState = prev.documentStates[documentId];
1577
- return documentState && (acc[documentId] = {
1578
- ...documentState,
1579
- unverifiedRevisions: {
1580
- ...documentState.unverifiedRevisions,
1581
- [transactionId]: {
1582
- documentId,
1583
- previousRev,
1584
- transactionId,
1585
- timestamp
1586
- }
1587
- },
1588
- recentOwnTransactionIds: [...(documentState.recentOwnTransactionIds ?? []).slice(-49), transactionId]
1589
- }), acc;
1590
- }, { ...prev.documentStates })
1591
- };
1592
- }
1593
- function cleanupOutgoingTransaction(prev) {
1594
- let { outgoing } = prev;
1595
- if (!outgoing) return prev;
1596
- let next = prev, ids = getDocumentIdsFromHandleLikes(outgoing.actions);
1597
- for (let transactionId of outgoing.batchedTransactionIds) for (let documentId of ids) next = removeSubscriptionIdFromDocument(next, documentId, transactionId);
1598
- return {
1599
- ...next,
1600
- outgoing: void 0,
1601
- documentStates: evictOrphanedDocumentStates(next.documentStates)
1602
- };
1603
- }
1604
- function revertOutgoingTransaction(prev) {
1605
- if (!prev.grants) return prev;
1606
- let base = prev;
1607
- if (prev.outgoing) {
1608
- let ids = getDocumentIdsFromHandleLikes(prev.outgoing.actions);
1609
- for (let transactionId of prev.outgoing.batchedTransactionIds) for (let documentId of ids) base = removeSubscriptionIdFromDocument(base, documentId, transactionId);
1610
- }
1611
- let working = Object.fromEntries(Object.entries(base.documentStates).map(([documentId, documentState]) => [documentId, documentState?.remote])), nextApplied = [];
1612
- for (let t of prev.applied) try {
1613
- let next = processActions({
1614
- ...t,
1615
- working,
1616
- grants: prev.grants,
1617
- identity: prev.identity
1618
- });
1619
- working = next.working, nextApplied.push({
1620
- ...t,
1621
- ...next
1622
- });
1623
- } catch (error) {
1624
- if (error instanceof ActionError) continue;
1625
- throw error;
1626
- }
1627
- return {
1628
- ...base,
1629
- applied: nextApplied,
1630
- outgoing: void 0,
1631
- documentStates: evictOrphanedDocumentStates(Object.fromEntries(Object.entries(base.documentStates).filter((e) => !!e[1]).map(([documentId, documentState]) => {
1632
- let { unverifiedRevisions = {} } = documentState, next = {
1633
- ...documentState,
1634
- unverifiedRevisions: prev.outgoing && prev.outgoing.transactionId in unverifiedRevisions ? omitProperty(unverifiedRevisions, prev.outgoing.transactionId) : unverifiedRevisions
1635
- };
1636
- return !next.subscriptions.length && isAwaitingOwnEcho(next) ? [documentId, next] : [documentId, {
1637
- ...next,
1638
- local: documentId in working ? working[documentId] : next.local
1639
- }];
1640
- })))
1641
- };
1642
- }
1643
- /**
1644
- * Extracts the patch operations addressed to the given document from a set of
1645
- * raw listener mutations, stripping the mutation-level `id` addressing so the
1646
- * patches are rooted at the document. A transaction can carry mutations for
1647
- * other documents, so anything not explicitly id-addressed to this document
1648
- * (including query-addressed patches) is dropped.
1649
- */
1650
- function extractPatchOperations(mutations, documentId) {
1651
- return mutations ? mutations.flatMap((mutation) => {
1652
- if (!("patch" in mutation) || !mutation.patch) return [];
1653
- let { id, ...operations } = mutation.patch;
1654
- return id === documentId ? [operations] : [];
1655
- }) : [];
1656
- }
1657
- function applyRemoteDocument(prev, { document, documentId, previousRev, revision, timestamp, type, mutations }, events) {
1658
- if (!prev.grants) return prev;
1659
- let prevDocState = prev.documentStates[documentId];
1660
- if (!prevDocState) return prev;
1661
- let prevUnverifiedRevisions = prevDocState.unverifiedRevisions, revisionToVerify = revision ? prevUnverifiedRevisions?.[revision] : void 0, unverifiedRevisions = prevUnverifiedRevisions ?? EMPTY_REVISIONS;
1662
- if (revision && revisionToVerify && (unverifiedRevisions = omitProperty(prevUnverifiedRevisions, revision)), type === "mutation" && revision) {
1663
- let patches = extractPatchOperations(mutations, documentId);
1664
- if (patches.length) {
1665
- let isOwnTransaction = !!revisionToVerify || (prevDocState.recentOwnTransactionIds?.includes(revision) ?? !1);
1666
- events.next({
1667
- type: "remote-patches",
1668
- documentId,
1669
- transactionId: revision,
1670
- previousRev,
1671
- timestamp,
1672
- patches,
1673
- origin: isOwnTransaction ? "local" : "remote"
1674
- });
1675
- }
1676
- }
1677
- 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) {
1678
- 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;
1679
- return {
1680
- ...prev,
1681
- documentStates: evictOrphanedDocumentStates({
1682
- ...prev.documentStates,
1683
- [documentId]: {
1684
- ...prevDocState,
1685
- remote: document,
1686
- remoteRev: revision,
1687
- local,
1688
- unverifiedRevisions
1689
- }
1690
- })
1691
- };
1692
- }
1693
- let working = {
1694
- ...prev.applied.at(0)?.previous,
1695
- [documentId]: document
1696
- }, nextApplied = [];
1697
- for (let curr of prev.applied) try {
1698
- let next = processActions({
1699
- ...curr,
1700
- working,
1701
- grants: prev.grants,
1702
- identity: prev.identity
1703
- });
1704
- working = next.working, nextApplied.push({
1705
- ...curr,
1706
- ...next
1707
- });
1708
- } catch (error) {
1709
- if (error instanceof ActionError) {
1710
- events.next({
1711
- type: "rebase-error",
1712
- transactionId: error.transactionId,
1713
- documentId: error.documentId,
1714
- message: error.message,
1715
- error
1716
- });
1717
- continue;
1718
- }
1719
- throw error;
1720
- }
1721
- let nextLocal = working[documentId], local = isDeepEqual(prevDocState.local, nextLocal) ? prevDocState.local : nextLocal;
1722
- return {
1723
- ...prev,
1724
- applied: nextApplied,
1725
- documentStates: evictOrphanedDocumentStates({
1726
- ...prev.documentStates,
1727
- [documentId]: {
1728
- ...prevDocState,
1729
- remote: document,
1730
- remoteRev: revision,
1731
- local,
1732
- unverifiedRevisions
1733
- }
1734
- })
1735
- };
1736
- }
1737
- function addSubscriptionIdToDocument(prev, documentId, subscriptionId) {
1738
- let prevDocState = prev.documentStates?.[documentId], prevSubscriptions = prevDocState?.subscriptions ?? [];
1739
- return {
1740
- ...prev,
1741
- documentStates: {
1742
- ...prev.documentStates,
1743
- [documentId]: {
1744
- ...prevDocState,
1745
- id: documentId,
1746
- subscriptions: [...prevSubscriptions, subscriptionId]
1747
- }
1748
- }
1749
- };
1750
- }
1751
- function removeSubscriptionIdFromDocument(prev, documentId, subscriptionId) {
1752
- let prevDocState = prev.documentStates?.[documentId];
1753
- if (!prevDocState) return prev;
1754
- let subscriptions = prevDocState.subscriptions.filter((id) => id !== subscriptionId);
1755
- return !subscriptions.length && !isAwaitingOwnEcho(prevDocState) ? {
1756
- ...prev,
1757
- documentStates: omitProperty(prev.documentStates, documentId)
1758
- } : {
1759
- ...prev,
1760
- documentStates: {
1761
- ...prev.documentStates,
1762
- [documentId]: {
1763
- ...prevDocState,
1764
- subscriptions
1765
- }
1766
- }
1767
- };
1768
- }
1769
- /**
1770
- * Whether this document still expects the listener echo of one of its own
1771
- * submitted transactions. That expectation is the only reason a document state
1772
- * with no subscribers is kept around.
1773
- *
1774
- * Revisions stop counting after `UNVERIFIED_REVISION_RETENTION_TIME` because an
1775
- * echo is not guaranteed to arrive at all: Content Lake records no transaction
1776
- * when every operation resolves to a no-op (e.g. a keyed path that no longer
1777
- * exists), while the client bumps `_rev` regardless and so tracks a revision
1778
- * for it. Without the expiry, such a document (and the listener keyed off its
1779
- * state) would be pinned for the lifetime of the store.
1780
- *
1781
- * `recentOwnTransactionIds` deliberately does not extend the wait: it is capped
1782
- * rather than drained, so honoring it would keep every edited document alive.
1783
- */
1784
- function isAwaitingOwnEcho(documentState) {
1785
- let expiresAfter = Date.now() - UNVERIFIED_REVISION_RETENTION_TIME;
1786
- return Object.values(documentState.unverifiedRevisions ?? {}).some((revision) => !!revision && new Date(revision.timestamp).getTime() > expiresAfter);
1787
- }
1788
- /**
1789
- * Removes every document state that has no subscribers left and no own
1790
- * transaction still awaiting its echo.
1791
- *
1792
- * This is a sweep rather than a decision made where the last subscriber leaves
1793
- * because `removeSubscriptionIdFromDocument` defers that eviction while an echo
1794
- * is in flight, and both halves of the condition can change without a
1795
- * subscriber going anywhere: the echo can verify, be dropped by a sync, be
1796
- * discarded by a revert, or simply never arrive. Every reducer that can settle
1797
- * an in-flight transaction sweeps, so the deferred decision is always re-made.
1798
- *
1799
- * Note this can evict the very document whose remote event is being processed,
1800
- * which synchronously unsubscribes that document's listener from inside its own
1801
- * emission (see `subscribeToSubscriptionsAndListenToDocuments`).
1802
- */
1803
- function evictOrphanedDocumentStates(documentStates) {
1804
- let next = documentStates;
1805
- for (let [documentId, documentState] of Object.entries(documentStates)) documentState && (documentState.subscriptions.length || isAwaitingOwnEcho(documentState) || (next = omitProperty(next, documentId)));
1806
- return next;
1807
- }
1808
- function manageSubscriberIds({ state }, handles) {
1809
- let documentIds = getDocumentIdsFromHandleLikes(handles), subscriptionId = randomId(16);
1810
- return state.set("addSubscribers", (prev) => documentIds.reduce((acc, id) => addSubscriptionIdToDocument(acc, id, subscriptionId), prev)), () => {
1811
- setCleanupTimeout(() => {
1812
- state.set("removeSubscribers", (prev) => documentIds.reduce((acc, id) => removeSubscriptionIdFromDocument(acc, id, subscriptionId), prev));
1813
- }, DOCUMENT_STATE_CLEAR_DELAY);
1814
- };
1815
- }
1816
- function throwDocumentError(documentStates, documentIds) {
1817
- for (let documentId of documentIds) {
1818
- let documentError = documentStates[documentId]?.error;
1819
- if (documentError) throw documentError;
1820
- }
1821
- }
1822
- function getDocumentIdsFromHandleLikes(handles) {
1823
- return handles.flatMap((handle) => {
1824
- if ("type" in handle && isReleaseAction(handle)) return [getReleaseDocumentId(handle.releaseId)];
1825
- let idsForDocument = [];
1826
- 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) : [];
1827
- });
1828
- }
1829
631
  /**
1830
632
  * The `document` a favorite write addresses over Comlink.
1831
633
  *
@@ -2326,12 +1128,12 @@ const _resolveQuery = bindActionByResource(queryStore, ({ state, instance }, { s
2326
1128
  };
2327
1129
  return promise.then(releaseSubscriber, releaseSubscriber), promise;
2328
1130
  });
2329
- var version = "3.18.0-next.20261201154713";
1131
+ var version = "3.18.0";
2330
1132
  /**
2331
1133
  * This version is provided by pkg-utils at build time
2332
1134
  * @internal
2333
1135
  */
2334
1136
  const CORE_SDK_VERSION = getEnv("PKG_VERSION") || `${version}-development`;
2335
- export { getDocumentIdsFromHandleLikes as A, ActionError as B, favoriteScope as C, applyFirstQueuedTransaction as D, toFavoriteDocument as E, revertOutgoingTransaction as F, getProjectAccessErrorDetails as G, processMutations as H, throwDocumentError as I, getProjectAccessErrorProjectId as K, transitionAppliedTransactionsToOutgoing as L, manageSubscriberIds as M, queueTransaction as N, applyRemoteDocument as O, removeQueuedTransaction as P, calculatePermissions as R, toPreferenceError as S, setFavorite as T, getReleaseDocumentId as U, patchOperations as V, isReleaseAction as W, setUsersError as _, parseQueryKey as a, USERS_STATE_CLEAR_DELAY as b, getActiveReleasesState as c, cancelRequest as d, getUsersKey as f, setUsersData as g, removeSubscription as h, getQueryState as i, isBatchableTransaction as j, cleanupOutgoingTransaction as k, getAllReleasesState as l, parseUsersKey as m, version as n, resolveQuery as o, initializeRequest as p, getSignInMethodLabel as q, getQueryKey as r, getPerspectiveState as s, CORE_SDK_VERSION as t, addSubscription as u, updateLastLoadMoreRequest as v, favorites as w, PreferenceError as x, PROJECT_API_VERSION as y, createGrantsLookup as z };
1137
+ export { checkGrant as A, favoriteScope as C, ActionError as D, toFavoriteDocument as E, processMutations as F, getProjectAccessErrorDetails as I, getProjectAccessErrorProjectId as L, preserveNumericOperations as M, getId as N, PermissionActionError as O, patchOperations as P, getSignInMethodLabel as R, toPreferenceError as S, setFavorite as T, setUsersError as _, parseQueryKey as a, USERS_STATE_CLEAR_DELAY as b, getActiveReleasesState as c, cancelRequest as d, getUsersKey as f, setUsersData as g, removeSubscription as h, getQueryState as i, createMutationApplier as j, applySingleDocPatch as k, getAllReleasesState as l, parseUsersKey as m, version as n, resolveQuery as o, initializeRequest as p, getQueryKey as r, getPerspectiveState as s, CORE_SDK_VERSION as t, addSubscription as u, updateLastLoadMoreRequest as v, favorites as w, PreferenceError as x, PROJECT_API_VERSION as y };
2336
1138
 
2337
- //# sourceMappingURL=version-ClZD8IhJ.js.map
1139
+ //# sourceMappingURL=version-CnBDPBaC.js.map