@sanity/document-internationalization 3.2.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,21 @@
1
1
  "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty, __propIsEnum = Object.prototype.propertyIsEnumerable;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues = (a, b) => {
6
+ for (var prop in b || (b = {}))
7
+ __hasOwnProp.call(b, prop) && __defNormalProp(a, prop, b[prop]);
8
+ if (__getOwnPropSymbols)
9
+ for (var prop of __getOwnPropSymbols(b))
10
+ __propIsEnum.call(b, prop) && __defNormalProp(a, prop, b[prop]);
11
+ return a;
12
+ };
2
13
  Object.defineProperty(exports, "__esModule", { value: !0 });
3
- var jsxRuntime = require("react/jsx-runtime"), icons = require("@sanity/icons"), ui = require("@sanity/ui"), react = require("react"), sanity = require("sanity"), sanityPluginUtils = require("sanity-plugin-utils"), uuid = require("@sanity/uuid"), router = require("sanity/router"), structure = require("sanity/structure"), mutator = require("@sanity/mutator"), styledComponents = require("styled-components"), sanityPluginInternationalizedArray = require("sanity-plugin-internationalized-array");
14
+ var jsxRuntime = require("react/jsx-runtime"), icons = require("@sanity/icons"), ui = require("@sanity/ui"), react = require("react"), sanity = require("sanity"), sanityPluginUtils = require("sanity-plugin-utils"), uuid = require("@sanity/uuid"), router = require("sanity/router"), structure = require("sanity/structure"), require$$0 = require("tty"), require$$1 = require("util"), styledComponents = require("styled-components"), sanityPluginInternationalizedArray = require("sanity-plugin-internationalized-array");
15
+ function _interopDefaultCompat(e) {
16
+ return e && typeof e == "object" && "default" in e ? e : { default: e };
17
+ }
18
+ var require$$0__default = /* @__PURE__ */ _interopDefaultCompat(require$$0), require$$1__default = /* @__PURE__ */ _interopDefaultCompat(require$$1);
4
19
  function DocumentPreview(props) {
5
20
  const schemaType = sanity.useSchema().get(props.type);
6
21
  return schemaType ? /* @__PURE__ */ jsxRuntime.jsx(sanity.Preview, { value: props.value, schemaType }) : /* @__PURE__ */ jsxRuntime.jsx(sanityPluginUtils.Feedback, { tone: "critical", title: "Schema type not found" });
@@ -13,7 +28,8 @@ const METADATA_SCHEMA_NAME = "translation.metadata", TRANSLATIONS_ARRAY_NAME = "
13
28
  bulkPublish: !1,
14
29
  metadataFields: [],
15
30
  apiVersion: API_VERSION,
16
- allowCreateMetaDoc: !1
31
+ allowCreateMetaDoc: !1,
32
+ callback: null
17
33
  };
18
34
  function separateReferences(data = []) {
19
35
  const translations = [], otherReferences = [];
@@ -132,7 +148,16 @@ function query$1(fn, keys = null, preload = !1, config2 = {}) {
132
148
  if (globalCache.push(entry), !preload)
133
149
  throw entry.promise;
134
150
  }
135
- const suspend = (fn, keys, config2) => query$1(fn, keys, !1, config2), DocumentInternationalizationContext = react.createContext(DEFAULT_CONFIG);
151
+ const suspend = (fn, keys, config2) => query$1(fn, keys, !1, config2);
152
+ var __defProp$i = Object.defineProperty, __defProps$2 = Object.defineProperties, __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors, __getOwnPropSymbols$3 = Object.getOwnPropertySymbols, __hasOwnProp$3 = Object.prototype.hasOwnProperty, __propIsEnum$3 = Object.prototype.propertyIsEnumerable, __defNormalProp$i = (obj, key, value) => key in obj ? __defProp$i(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$3 = (a, b) => {
153
+ for (var prop in b || (b = {}))
154
+ __hasOwnProp$3.call(b, prop) && __defNormalProp$i(a, prop, b[prop]);
155
+ if (__getOwnPropSymbols$3)
156
+ for (var prop of __getOwnPropSymbols$3(b))
157
+ __propIsEnum$3.call(b, prop) && __defNormalProp$i(a, prop, b[prop]);
158
+ return a;
159
+ }, __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
160
+ const DocumentInternationalizationContext = react.createContext(DEFAULT_CONFIG);
136
161
  function useDocumentInternationalizationContext() {
137
162
  return react.useContext(DocumentInternationalizationContext);
138
163
  }
@@ -144,7 +169,7 @@ function DocumentInternationalizationProvider(props) {
144
169
  return /* @__PURE__ */ jsxRuntime.jsx(
145
170
  DocumentInternationalizationContext.Provider,
146
171
  {
147
- value: { ...pluginConfig, supportedLanguages },
172
+ value: __spreadProps$2(__spreadValues$3({}, pluginConfig), { supportedLanguages }),
148
173
  children: props.renderDefault(props)
149
174
  }
150
175
  );
@@ -260,7 +285,7 @@ function __spreadArray(to, from, pack) {
260
285
  (ar || !(i in from)) && (ar || (ar = Array.prototype.slice.call(from, 0, i)), ar[i] = from[i]);
261
286
  return to.concat(ar || Array.prototype.slice.call(from));
262
287
  }
263
- function isFunction(value) {
288
+ function isFunction$2(value) {
264
289
  return typeof value == "function";
265
290
  }
266
291
  function createErrorClass(createImpl) {
@@ -313,7 +338,7 @@ var Subscription = function() {
313
338
  else
314
339
  _parentage.remove(this);
315
340
  var initialFinalizer = this.initialTeardown;
316
- if (isFunction(initialFinalizer))
341
+ if (isFunction$2(initialFinalizer))
317
342
  try {
318
343
  initialFinalizer();
319
344
  } catch (e) {
@@ -376,10 +401,10 @@ var Subscription = function() {
376
401
  }(), Subscription2;
377
402
  }();
378
403
  function isSubscription(value) {
379
- return value instanceof Subscription || value && "closed" in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe);
404
+ return value instanceof Subscription || value && "closed" in value && isFunction$2(value.remove) && isFunction$2(value.add) && isFunction$2(value.unsubscribe);
380
405
  }
381
406
  function execFinalizer(finalizer) {
382
- isFunction(finalizer) ? finalizer() : finalizer.unsubscribe();
407
+ isFunction$2(finalizer) ? finalizer() : finalizer.unsubscribe();
383
408
  }
384
409
  var config = {
385
410
  onUnhandledError: null,
@@ -475,7 +500,7 @@ var ConsumerObserver = function() {
475
500
  __extends(SafeSubscriber2, _super);
476
501
  function SafeSubscriber2(observerOrNext, error, complete) {
477
502
  var _this = _super.call(this) || this, partialObserver;
478
- if (isFunction(observerOrNext) || !observerOrNext)
503
+ if (isFunction$2(observerOrNext) || !observerOrNext)
479
504
  partialObserver = {
480
505
  next: observerOrNext != null ? observerOrNext : void 0,
481
506
  error: error != null ? error : void 0,
@@ -508,7 +533,7 @@ var EMPTY_OBSERVER = {
508
533
  complete: noop
509
534
  };
510
535
  function hasLift(source) {
511
- return isFunction(source == null ? void 0 : source.lift);
536
+ return isFunction$2(source == null ? void 0 : source.lift);
512
537
  }
513
538
  function operate(init) {
514
539
  return function(source) {
@@ -567,7 +592,6 @@ var OperatorSubscriber = function(_super) {
567
592
  };
568
593
  });
569
594
  function firstValueFrom(source, config2) {
570
- var hasConfig = typeof config2 == "object";
571
595
  return new Promise(function(resolve, reject) {
572
596
  var subscriber = new SafeSubscriber({
573
597
  next: function(value) {
@@ -575,7 +599,7 @@ function firstValueFrom(source, config2) {
575
599
  },
576
600
  error: reject,
577
601
  complete: function() {
578
- hasConfig ? resolve(config2.defaultValue) : reject(new EmptyError());
602
+ reject(new EmptyError());
579
603
  }
580
604
  });
581
605
  source.subscribe(subscriber);
@@ -745,17 +769,23 @@ function useOpenInNewPane(id, type) {
745
769
  routerContext.navigateUrl({ path: href });
746
770
  }, [id, type, routerContext, routerPanesState, groupIndex]);
747
771
  }
772
+ var __defProp$2 = Object.defineProperty, __getOwnPropSymbols$2 = Object.getOwnPropertySymbols, __hasOwnProp$2 = Object.prototype.hasOwnProperty, __propIsEnum$2 = Object.prototype.propertyIsEnumerable, __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$2 = (a, b) => {
773
+ for (var prop in b || (b = {}))
774
+ __hasOwnProp$2.call(b, prop) && __defNormalProp$2(a, prop, b[prop]);
775
+ if (__getOwnPropSymbols$2)
776
+ for (var prop of __getOwnPropSymbols$2(b))
777
+ __propIsEnum$2.call(b, prop) && __defNormalProp$2(a, prop, b[prop]);
778
+ return a;
779
+ };
748
780
  function createReference(key, ref, type, strengthenOnPublish = !0) {
749
781
  return {
750
782
  _key: key,
751
783
  _type: "internationalizedArrayReferenceValue",
752
- value: {
784
+ value: __spreadValues$2({
753
785
  _type: "reference",
754
786
  _ref: ref,
755
- _weak: !0,
756
- // If the user has configured weakReferences, we won't want to strengthen them
757
- ...strengthenOnPublish ? { _strengthenOnPublish: { type } } : {}
758
- }
787
+ _weak: !0
788
+ }, strengthenOnPublish ? { _strengthenOnPublish: { type } } : {})
759
789
  };
760
790
  }
761
791
  function LanguageManage(props) {
@@ -814,155 +844,2963 @@ function LanguageManage(props) {
814
844
  }
815
845
  );
816
846
  }
817
- function removeExcludedPaths(doc, schemaType) {
818
- if (!sanity.isDocumentSchemaType(schemaType) || !doc)
819
- return doc;
820
- const pathsToExclude = extractPaths(doc, schemaType, []).filter(
821
- (field) => {
822
- var _a, _b, _c;
823
- return ((_c = (_b = (_a = field.schemaType) == null ? void 0 : _a.options) == null ? void 0 : _b.documentInternationalization) == null ? void 0 : _c.exclude) === !0;
847
+ var commonjsGlobal = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {};
848
+ function getDefaultExportFromCjs(x) {
849
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x.default : x;
850
+ }
851
+ function listCacheClear$1() {
852
+ this.__data__ = [], this.size = 0;
853
+ }
854
+ var _listCacheClear = listCacheClear$1;
855
+ function eq$1(value, other) {
856
+ return value === other || value !== value && other !== other;
857
+ }
858
+ var eq_1 = eq$1, eq = eq_1;
859
+ function assocIndexOf$4(array, key) {
860
+ for (var length = array.length; length--; )
861
+ if (eq(array[length][0], key))
862
+ return length;
863
+ return -1;
864
+ }
865
+ var _assocIndexOf = assocIndexOf$4, assocIndexOf$3 = _assocIndexOf, arrayProto = Array.prototype, splice = arrayProto.splice;
866
+ function listCacheDelete$1(key) {
867
+ var data = this.__data__, index = assocIndexOf$3(data, key);
868
+ if (index < 0)
869
+ return !1;
870
+ var lastIndex = data.length - 1;
871
+ return index == lastIndex ? data.pop() : splice.call(data, index, 1), --this.size, !0;
872
+ }
873
+ var _listCacheDelete = listCacheDelete$1, assocIndexOf$2 = _assocIndexOf;
874
+ function listCacheGet$1(key) {
875
+ var data = this.__data__, index = assocIndexOf$2(data, key);
876
+ return index < 0 ? void 0 : data[index][1];
877
+ }
878
+ var _listCacheGet = listCacheGet$1, assocIndexOf$1 = _assocIndexOf;
879
+ function listCacheHas$1(key) {
880
+ return assocIndexOf$1(this.__data__, key) > -1;
881
+ }
882
+ var _listCacheHas = listCacheHas$1, assocIndexOf = _assocIndexOf;
883
+ function listCacheSet$1(key, value) {
884
+ var data = this.__data__, index = assocIndexOf(data, key);
885
+ return index < 0 ? (++this.size, data.push([key, value])) : data[index][1] = value, this;
886
+ }
887
+ var _listCacheSet = listCacheSet$1, listCacheClear = _listCacheClear, listCacheDelete = _listCacheDelete, listCacheGet = _listCacheGet, listCacheHas = _listCacheHas, listCacheSet = _listCacheSet;
888
+ function ListCache$4(entries) {
889
+ var index = -1, length = entries == null ? 0 : entries.length;
890
+ for (this.clear(); ++index < length; ) {
891
+ var entry = entries[index];
892
+ this.set(entry[0], entry[1]);
893
+ }
894
+ }
895
+ ListCache$4.prototype.clear = listCacheClear;
896
+ ListCache$4.prototype.delete = listCacheDelete;
897
+ ListCache$4.prototype.get = listCacheGet;
898
+ ListCache$4.prototype.has = listCacheHas;
899
+ ListCache$4.prototype.set = listCacheSet;
900
+ var _ListCache = ListCache$4, ListCache$3 = _ListCache;
901
+ function stackClear$1() {
902
+ this.__data__ = new ListCache$3(), this.size = 0;
903
+ }
904
+ var _stackClear = stackClear$1;
905
+ function stackDelete$1(key) {
906
+ var data = this.__data__, result = data.delete(key);
907
+ return this.size = data.size, result;
908
+ }
909
+ var _stackDelete = stackDelete$1;
910
+ function stackGet$1(key) {
911
+ return this.__data__.get(key);
912
+ }
913
+ var _stackGet = stackGet$1;
914
+ function stackHas$1(key) {
915
+ return this.__data__.has(key);
916
+ }
917
+ var _stackHas = stackHas$1, freeGlobal$1 = typeof commonjsGlobal == "object" && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal, _freeGlobal = freeGlobal$1, freeGlobal = _freeGlobal, freeSelf = typeof self == "object" && self && self.Object === Object && self, root$7 = freeGlobal || freeSelf || Function("return this")(), _root = root$7, root$6 = _root, Symbol$4 = root$6.Symbol, _Symbol = Symbol$4, Symbol$3 = _Symbol, objectProto$5 = Object.prototype, hasOwnProperty$4 = objectProto$5.hasOwnProperty, nativeObjectToString$1 = objectProto$5.toString, symToStringTag$1 = Symbol$3 ? Symbol$3.toStringTag : void 0;
918
+ function getRawTag$1(value) {
919
+ var isOwn = hasOwnProperty$4.call(value, symToStringTag$1), tag = value[symToStringTag$1];
920
+ try {
921
+ value[symToStringTag$1] = void 0;
922
+ var unmasked = !0;
923
+ } catch (e) {
924
+ }
925
+ var result = nativeObjectToString$1.call(value);
926
+ return unmasked && (isOwn ? value[symToStringTag$1] = tag : delete value[symToStringTag$1]), result;
927
+ }
928
+ var _getRawTag = getRawTag$1, objectProto$4 = Object.prototype, nativeObjectToString = objectProto$4.toString;
929
+ function objectToString$1(value) {
930
+ return nativeObjectToString.call(value);
931
+ }
932
+ var _objectToString = objectToString$1, Symbol$2 = _Symbol, getRawTag = _getRawTag, objectToString = _objectToString, nullTag = "[object Null]", undefinedTag = "[object Undefined]", symToStringTag = Symbol$2 ? Symbol$2.toStringTag : void 0;
933
+ function baseGetTag$4(value) {
934
+ return value == null ? value === void 0 ? undefinedTag : nullTag : symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
935
+ }
936
+ var _baseGetTag = baseGetTag$4;
937
+ function isObject$2(value) {
938
+ var type = typeof value;
939
+ return value != null && (type == "object" || type == "function");
940
+ }
941
+ var isObject_1 = isObject$2, baseGetTag$3 = _baseGetTag, isObject$1 = isObject_1, asyncTag = "[object AsyncFunction]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", proxyTag = "[object Proxy]";
942
+ function isFunction$1(value) {
943
+ if (!isObject$1(value))
944
+ return !1;
945
+ var tag = baseGetTag$3(value);
946
+ return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
947
+ }
948
+ var isFunction_1 = isFunction$1, root$5 = _root, coreJsData$1 = root$5["__core-js_shared__"], _coreJsData = coreJsData$1, coreJsData = _coreJsData, maskSrcKey = function() {
949
+ var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || "");
950
+ return uid ? "Symbol(src)_1." + uid : "";
951
+ }();
952
+ function isMasked$1(func) {
953
+ return !!maskSrcKey && maskSrcKey in func;
954
+ }
955
+ var _isMasked = isMasked$1, funcProto$1 = Function.prototype, funcToString$1 = funcProto$1.toString;
956
+ function toSource$2(func) {
957
+ if (func != null) {
958
+ try {
959
+ return funcToString$1.call(func);
960
+ } catch (e) {
824
961
  }
825
- ).map((field) => sanity.pathToString(field.path));
826
- return new mutator.Mutation({
827
- mutations: [
828
- {
829
- patch: {
830
- id: doc._id,
831
- unset: pathsToExclude
962
+ try {
963
+ return func + "";
964
+ } catch (e) {
965
+ }
966
+ }
967
+ return "";
968
+ }
969
+ var _toSource = toSource$2, isFunction = isFunction_1, isMasked = _isMasked, isObject = isObject_1, toSource$1 = _toSource, reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reIsHostCtor = /^\[object .+?Constructor\]$/, funcProto = Function.prototype, objectProto$3 = Object.prototype, funcToString = funcProto.toString, hasOwnProperty$3 = objectProto$3.hasOwnProperty, reIsNative = RegExp(
970
+ "^" + funcToString.call(hasOwnProperty$3).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"
971
+ );
972
+ function baseIsNative$1(value) {
973
+ if (!isObject(value) || isMasked(value))
974
+ return !1;
975
+ var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
976
+ return pattern.test(toSource$1(value));
977
+ }
978
+ var _baseIsNative = baseIsNative$1;
979
+ function getValue$1(object, key) {
980
+ return object == null ? void 0 : object[key];
981
+ }
982
+ var _getValue = getValue$1, baseIsNative = _baseIsNative, getValue = _getValue;
983
+ function getNative$6(object, key) {
984
+ var value = getValue(object, key);
985
+ return baseIsNative(value) ? value : void 0;
986
+ }
987
+ var _getNative = getNative$6, getNative$5 = _getNative, root$4 = _root, Map$4 = getNative$5(root$4, "Map"), _Map = Map$4, getNative$4 = _getNative, nativeCreate$4 = getNative$4(Object, "create"), _nativeCreate = nativeCreate$4, nativeCreate$3 = _nativeCreate;
988
+ function hashClear$1() {
989
+ this.__data__ = nativeCreate$3 ? nativeCreate$3(null) : {}, this.size = 0;
990
+ }
991
+ var _hashClear = hashClear$1;
992
+ function hashDelete$1(key) {
993
+ var result = this.has(key) && delete this.__data__[key];
994
+ return this.size -= result ? 1 : 0, result;
995
+ }
996
+ var _hashDelete = hashDelete$1, nativeCreate$2 = _nativeCreate, HASH_UNDEFINED$2 = "__lodash_hash_undefined__", objectProto$2 = Object.prototype, hasOwnProperty$2 = objectProto$2.hasOwnProperty;
997
+ function hashGet$1(key) {
998
+ var data = this.__data__;
999
+ if (nativeCreate$2) {
1000
+ var result = data[key];
1001
+ return result === HASH_UNDEFINED$2 ? void 0 : result;
1002
+ }
1003
+ return hasOwnProperty$2.call(data, key) ? data[key] : void 0;
1004
+ }
1005
+ var _hashGet = hashGet$1, nativeCreate$1 = _nativeCreate, objectProto$1 = Object.prototype, hasOwnProperty$1 = objectProto$1.hasOwnProperty;
1006
+ function hashHas$1(key) {
1007
+ var data = this.__data__;
1008
+ return nativeCreate$1 ? data[key] !== void 0 : hasOwnProperty$1.call(data, key);
1009
+ }
1010
+ var _hashHas = hashHas$1, nativeCreate = _nativeCreate, HASH_UNDEFINED$1 = "__lodash_hash_undefined__";
1011
+ function hashSet$1(key, value) {
1012
+ var data = this.__data__;
1013
+ return this.size += this.has(key) ? 0 : 1, data[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED$1 : value, this;
1014
+ }
1015
+ var _hashSet = hashSet$1, hashClear = _hashClear, hashDelete = _hashDelete, hashGet = _hashGet, hashHas = _hashHas, hashSet = _hashSet;
1016
+ function Hash$1(entries) {
1017
+ var index = -1, length = entries == null ? 0 : entries.length;
1018
+ for (this.clear(); ++index < length; ) {
1019
+ var entry = entries[index];
1020
+ this.set(entry[0], entry[1]);
1021
+ }
1022
+ }
1023
+ Hash$1.prototype.clear = hashClear;
1024
+ Hash$1.prototype.delete = hashDelete;
1025
+ Hash$1.prototype.get = hashGet;
1026
+ Hash$1.prototype.has = hashHas;
1027
+ Hash$1.prototype.set = hashSet;
1028
+ var _Hash = Hash$1, Hash = _Hash, ListCache$2 = _ListCache, Map$3 = _Map;
1029
+ function mapCacheClear$1() {
1030
+ this.size = 0, this.__data__ = {
1031
+ hash: new Hash(),
1032
+ map: new (Map$3 || ListCache$2)(),
1033
+ string: new Hash()
1034
+ };
1035
+ }
1036
+ var _mapCacheClear = mapCacheClear$1;
1037
+ function isKeyable$1(value) {
1038
+ var type = typeof value;
1039
+ return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
1040
+ }
1041
+ var _isKeyable = isKeyable$1, isKeyable = _isKeyable;
1042
+ function getMapData$4(map, key) {
1043
+ var data = map.__data__;
1044
+ return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
1045
+ }
1046
+ var _getMapData = getMapData$4, getMapData$3 = _getMapData;
1047
+ function mapCacheDelete$1(key) {
1048
+ var result = getMapData$3(this, key).delete(key);
1049
+ return this.size -= result ? 1 : 0, result;
1050
+ }
1051
+ var _mapCacheDelete = mapCacheDelete$1, getMapData$2 = _getMapData;
1052
+ function mapCacheGet$1(key) {
1053
+ return getMapData$2(this, key).get(key);
1054
+ }
1055
+ var _mapCacheGet = mapCacheGet$1, getMapData$1 = _getMapData;
1056
+ function mapCacheHas$1(key) {
1057
+ return getMapData$1(this, key).has(key);
1058
+ }
1059
+ var _mapCacheHas = mapCacheHas$1, getMapData = _getMapData;
1060
+ function mapCacheSet$1(key, value) {
1061
+ var data = getMapData(this, key), size = data.size;
1062
+ return data.set(key, value), this.size += data.size == size ? 0 : 1, this;
1063
+ }
1064
+ var _mapCacheSet = mapCacheSet$1, mapCacheClear = _mapCacheClear, mapCacheDelete = _mapCacheDelete, mapCacheGet = _mapCacheGet, mapCacheHas = _mapCacheHas, mapCacheSet = _mapCacheSet;
1065
+ function MapCache$2(entries) {
1066
+ var index = -1, length = entries == null ? 0 : entries.length;
1067
+ for (this.clear(); ++index < length; ) {
1068
+ var entry = entries[index];
1069
+ this.set(entry[0], entry[1]);
1070
+ }
1071
+ }
1072
+ MapCache$2.prototype.clear = mapCacheClear;
1073
+ MapCache$2.prototype.delete = mapCacheDelete;
1074
+ MapCache$2.prototype.get = mapCacheGet;
1075
+ MapCache$2.prototype.has = mapCacheHas;
1076
+ MapCache$2.prototype.set = mapCacheSet;
1077
+ var _MapCache = MapCache$2, ListCache$1 = _ListCache, Map$2 = _Map, MapCache$1 = _MapCache, LARGE_ARRAY_SIZE = 200;
1078
+ function stackSet$1(key, value) {
1079
+ var data = this.__data__;
1080
+ if (data instanceof ListCache$1) {
1081
+ var pairs = data.__data__;
1082
+ if (!Map$2 || pairs.length < LARGE_ARRAY_SIZE - 1)
1083
+ return pairs.push([key, value]), this.size = ++data.size, this;
1084
+ data = this.__data__ = new MapCache$1(pairs);
1085
+ }
1086
+ return data.set(key, value), this.size = data.size, this;
1087
+ }
1088
+ var _stackSet = stackSet$1, ListCache = _ListCache, stackClear = _stackClear, stackDelete = _stackDelete, stackGet = _stackGet, stackHas = _stackHas, stackSet = _stackSet;
1089
+ function Stack(entries) {
1090
+ var data = this.__data__ = new ListCache(entries);
1091
+ this.size = data.size;
1092
+ }
1093
+ Stack.prototype.clear = stackClear;
1094
+ Stack.prototype.delete = stackDelete;
1095
+ Stack.prototype.get = stackGet;
1096
+ Stack.prototype.has = stackHas;
1097
+ Stack.prototype.set = stackSet;
1098
+ var HASH_UNDEFINED = "__lodash_hash_undefined__";
1099
+ function setCacheAdd$1(value) {
1100
+ return this.__data__.set(value, HASH_UNDEFINED), this;
1101
+ }
1102
+ var _setCacheAdd = setCacheAdd$1;
1103
+ function setCacheHas$1(value) {
1104
+ return this.__data__.has(value);
1105
+ }
1106
+ var _setCacheHas = setCacheHas$1, MapCache = _MapCache, setCacheAdd = _setCacheAdd, setCacheHas = _setCacheHas;
1107
+ function SetCache(values) {
1108
+ var index = -1, length = values == null ? 0 : values.length;
1109
+ for (this.__data__ = new MapCache(); ++index < length; )
1110
+ this.add(values[index]);
1111
+ }
1112
+ SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
1113
+ SetCache.prototype.has = setCacheHas;
1114
+ function arrayPush$1(array, values) {
1115
+ for (var index = -1, length = values.length, offset = array.length; ++index < length; )
1116
+ array[offset + index] = values[index];
1117
+ return array;
1118
+ }
1119
+ var _arrayPush = arrayPush$1, isArray$1 = Array.isArray, isArray_1 = isArray$1;
1120
+ function isObjectLike$3(value) {
1121
+ return value != null && typeof value == "object";
1122
+ }
1123
+ var isObjectLike_1 = isObjectLike$3, baseGetTag$2 = _baseGetTag, isObjectLike$2 = isObjectLike_1, argsTag = "[object Arguments]";
1124
+ function baseIsArguments$1(value) {
1125
+ return isObjectLike$2(value) && baseGetTag$2(value) == argsTag;
1126
+ }
1127
+ var _baseIsArguments = baseIsArguments$1, baseIsArguments = _baseIsArguments, isObjectLike$1 = isObjectLike_1, objectProto = Object.prototype, hasOwnProperty = objectProto.hasOwnProperty, propertyIsEnumerable = objectProto.propertyIsEnumerable, isArguments$1 = baseIsArguments(/* @__PURE__ */ function() {
1128
+ return arguments;
1129
+ }()) ? baseIsArguments : function(value) {
1130
+ return isObjectLike$1(value) && hasOwnProperty.call(value, "callee") && !propertyIsEnumerable.call(value, "callee");
1131
+ }, isArguments_1 = isArguments$1, isBuffer = { exports: {} };
1132
+ function stubFalse() {
1133
+ return !1;
1134
+ }
1135
+ var stubFalse_1 = stubFalse;
1136
+ (function(module2, exports2) {
1137
+ var root2 = _root, stubFalse2 = stubFalse_1, freeExports = exports2 && !exports2.nodeType && exports2, freeModule = freeExports && !0 && module2 && !module2.nodeType && module2, moduleExports = freeModule && freeModule.exports === freeExports, Buffer2 = moduleExports ? root2.Buffer : void 0, nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : void 0, isBuffer2 = nativeIsBuffer || stubFalse2;
1138
+ module2.exports = isBuffer2;
1139
+ })(isBuffer, isBuffer.exports);
1140
+ var _nodeUtil = { exports: {} };
1141
+ (function(module2, exports2) {
1142
+ var freeGlobal2 = _freeGlobal, freeExports = exports2 && !exports2.nodeType && exports2, freeModule = freeExports && !0 && module2 && !module2.nodeType && module2, moduleExports = freeModule && freeModule.exports === freeExports, freeProcess = moduleExports && freeGlobal2.process, nodeUtil = function() {
1143
+ try {
1144
+ var types = freeModule && freeModule.require && freeModule.require("util").types;
1145
+ return types || freeProcess && freeProcess.binding && freeProcess.binding("util");
1146
+ } catch (e) {
1147
+ }
1148
+ }();
1149
+ module2.exports = nodeUtil;
1150
+ })(_nodeUtil, _nodeUtil.exports);
1151
+ var getNative$3 = _getNative, root$3 = _root, DataView$1 = getNative$3(root$3, "DataView"), _DataView = DataView$1, getNative$2 = _getNative, root$2 = _root, Promise$2 = getNative$2(root$2, "Promise"), _Promise = Promise$2, getNative$1 = _getNative, root$1 = _root, Set$2 = getNative$1(root$1, "Set"), _Set = Set$2, getNative = _getNative, root = _root, WeakMap$1 = getNative(root, "WeakMap"), _WeakMap = WeakMap$1, DataView = _DataView, Map$1 = _Map, Promise$1 = _Promise, Set$1 = _Set, WeakMap = _WeakMap, baseGetTag$1 = _baseGetTag, toSource = _toSource, mapTag = "[object Map]", objectTag = "[object Object]", promiseTag = "[object Promise]", setTag = "[object Set]", weakMapTag = "[object WeakMap]", dataViewTag = "[object DataView]", dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map$1), promiseCtorString = toSource(Promise$1), setCtorString = toSource(Set$1), weakMapCtorString = toSource(WeakMap), getTag = baseGetTag$1;
1152
+ (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map$1 && getTag(new Map$1()) != mapTag || Promise$1 && getTag(Promise$1.resolve()) != promiseTag || Set$1 && getTag(new Set$1()) != setTag || WeakMap && getTag(new WeakMap()) != weakMapTag) && (getTag = function(value) {
1153
+ var result = baseGetTag$1(value), Ctor = result == objectTag ? value.constructor : void 0, ctorString = Ctor ? toSource(Ctor) : "";
1154
+ if (ctorString)
1155
+ switch (ctorString) {
1156
+ case dataViewCtorString:
1157
+ return dataViewTag;
1158
+ case mapCtorString:
1159
+ return mapTag;
1160
+ case promiseCtorString:
1161
+ return promiseTag;
1162
+ case setCtorString:
1163
+ return setTag;
1164
+ case weakMapCtorString:
1165
+ return weakMapTag;
1166
+ }
1167
+ return result;
1168
+ });
1169
+ var src = { exports: {} }, browser$1 = { exports: {} }, ms, hasRequiredMs;
1170
+ function requireMs() {
1171
+ if (hasRequiredMs)
1172
+ return ms;
1173
+ hasRequiredMs = 1;
1174
+ var s = 1e3, m = s * 60, h = m * 60, d = h * 24, w = d * 7, y = d * 365.25;
1175
+ ms = function(val, options) {
1176
+ options = options || {};
1177
+ var type = typeof val;
1178
+ if (type === "string" && val.length > 0)
1179
+ return parse2(val);
1180
+ if (type === "number" && isFinite(val))
1181
+ return options.long ? fmtLong(val) : fmtShort(val);
1182
+ throw new Error(
1183
+ "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
1184
+ );
1185
+ };
1186
+ function parse2(str) {
1187
+ if (str = String(str), !(str.length > 100)) {
1188
+ var match2 = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
1189
+ str
1190
+ );
1191
+ if (match2) {
1192
+ var n = parseFloat(match2[1]), type = (match2[2] || "ms").toLowerCase();
1193
+ switch (type) {
1194
+ case "years":
1195
+ case "year":
1196
+ case "yrs":
1197
+ case "yr":
1198
+ case "y":
1199
+ return n * y;
1200
+ case "weeks":
1201
+ case "week":
1202
+ case "w":
1203
+ return n * w;
1204
+ case "days":
1205
+ case "day":
1206
+ case "d":
1207
+ return n * d;
1208
+ case "hours":
1209
+ case "hour":
1210
+ case "hrs":
1211
+ case "hr":
1212
+ case "h":
1213
+ return n * h;
1214
+ case "minutes":
1215
+ case "minute":
1216
+ case "mins":
1217
+ case "min":
1218
+ case "m":
1219
+ return n * m;
1220
+ case "seconds":
1221
+ case "second":
1222
+ case "secs":
1223
+ case "sec":
1224
+ case "s":
1225
+ return n * s;
1226
+ case "milliseconds":
1227
+ case "millisecond":
1228
+ case "msecs":
1229
+ case "msec":
1230
+ case "ms":
1231
+ return n;
1232
+ default:
1233
+ return;
832
1234
  }
833
1235
  }
834
- ]
835
- }).apply(doc);
1236
+ }
1237
+ }
1238
+ function fmtShort(ms2) {
1239
+ var msAbs = Math.abs(ms2);
1240
+ return msAbs >= d ? Math.round(ms2 / d) + "d" : msAbs >= h ? Math.round(ms2 / h) + "h" : msAbs >= m ? Math.round(ms2 / m) + "m" : msAbs >= s ? Math.round(ms2 / s) + "s" : ms2 + "ms";
1241
+ }
1242
+ function fmtLong(ms2) {
1243
+ var msAbs = Math.abs(ms2);
1244
+ return msAbs >= d ? plural(ms2, msAbs, d, "day") : msAbs >= h ? plural(ms2, msAbs, h, "hour") : msAbs >= m ? plural(ms2, msAbs, m, "minute") : msAbs >= s ? plural(ms2, msAbs, s, "second") : ms2 + " ms";
1245
+ }
1246
+ function plural(ms2, msAbs, n, name) {
1247
+ var isPlural = msAbs >= n * 1.5;
1248
+ return Math.round(ms2 / n) + " " + name + (isPlural ? "s" : "");
1249
+ }
1250
+ return ms;
836
1251
  }
837
- function extractPaths(doc, schemaType, path) {
838
- return schemaType.fields.reduce((acc, field) => {
839
- var _a, _b;
840
- const fieldPath = [...path, field.name], fieldSchema = field.type, { value } = (_a = mutator.extractWithPath(sanity.pathToString(fieldPath), doc)[0]) != null ? _a : {};
841
- if (!value)
842
- return acc;
843
- const thisFieldWithPath = {
844
- path: fieldPath,
845
- name: field.name,
846
- schemaType: fieldSchema,
847
- value
848
- };
849
- if (fieldSchema.jsonType === "object") {
850
- const innerFields = extractPaths(doc, fieldSchema, fieldPath);
851
- return [...acc, thisFieldWithPath, ...innerFields];
852
- } else if (fieldSchema.jsonType === "array" && fieldSchema.of.length && fieldSchema.of.some((item) => "fields" in item)) {
853
- const { value: arrayValue } = (_b = mutator.extractWithPath(sanity.pathToString(fieldPath), doc)[0]) != null ? _b : {};
854
- let arrayPaths = [];
855
- if (arrayValue != null && arrayValue.length)
856
- for (const item of arrayValue) {
857
- const itemPath = [...fieldPath, { _key: item._key }];
858
- let itemSchema = fieldSchema.of.find((t) => t.name === item._type);
859
- if (item._type || (itemSchema = fieldSchema.of[0]), item._key && itemSchema) {
860
- const innerFields = extractPaths(
861
- doc,
862
- itemSchema,
863
- itemPath
864
- ), arrayMember = {
865
- path: itemPath,
866
- name: item._key,
867
- schemaType: itemSchema,
868
- value: item
869
- };
870
- arrayPaths = [...arrayPaths, arrayMember, ...innerFields];
1252
+ var common, hasRequiredCommon;
1253
+ function requireCommon() {
1254
+ if (hasRequiredCommon)
1255
+ return common;
1256
+ hasRequiredCommon = 1;
1257
+ function setup(env) {
1258
+ createDebug.debug = createDebug, createDebug.default = createDebug, createDebug.coerce = coerce, createDebug.disable = disable, createDebug.enable = enable, createDebug.enabled = enabled, createDebug.humanize = requireMs(), createDebug.destroy = destroy, Object.keys(env).forEach((key) => {
1259
+ createDebug[key] = env[key];
1260
+ }), createDebug.names = [], createDebug.skips = [], createDebug.formatters = {};
1261
+ function selectColor(namespace) {
1262
+ let hash = 0;
1263
+ for (let i = 0; i < namespace.length; i++)
1264
+ hash = (hash << 5) - hash + namespace.charCodeAt(i), hash |= 0;
1265
+ return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
1266
+ }
1267
+ createDebug.selectColor = selectColor;
1268
+ function createDebug(namespace) {
1269
+ let prevTime, enableOverride = null, namespacesCache, enabledCache;
1270
+ function debug2(...args) {
1271
+ if (!debug2.enabled)
1272
+ return;
1273
+ const self2 = debug2, curr = Number(/* @__PURE__ */ new Date()), ms2 = curr - (prevTime || curr);
1274
+ self2.diff = ms2, self2.prev = prevTime, self2.curr = curr, prevTime = curr, args[0] = createDebug.coerce(args[0]), typeof args[0] != "string" && args.unshift("%O");
1275
+ let index = 0;
1276
+ args[0] = args[0].replace(/%([a-zA-Z%])/g, (match2, format) => {
1277
+ if (match2 === "%%")
1278
+ return "%";
1279
+ index++;
1280
+ const formatter = createDebug.formatters[format];
1281
+ if (typeof formatter == "function") {
1282
+ const val = args[index];
1283
+ match2 = formatter.call(self2, val), args.splice(index, 1), index--;
871
1284
  }
1285
+ return match2;
1286
+ }), createDebug.formatArgs.call(self2, args), (self2.log || createDebug.log).apply(self2, args);
1287
+ }
1288
+ return debug2.namespace = namespace, debug2.useColors = createDebug.useColors(), debug2.color = createDebug.selectColor(namespace), debug2.extend = extend, debug2.destroy = createDebug.destroy, Object.defineProperty(debug2, "enabled", {
1289
+ enumerable: !0,
1290
+ configurable: !1,
1291
+ get: () => enableOverride !== null ? enableOverride : (namespacesCache !== createDebug.namespaces && (namespacesCache = createDebug.namespaces, enabledCache = createDebug.enabled(namespace)), enabledCache),
1292
+ set: (v) => {
1293
+ enableOverride = v;
872
1294
  }
873
- return [...acc, thisFieldWithPath, ...arrayPaths];
1295
+ }), typeof createDebug.init == "function" && createDebug.init(debug2), debug2;
874
1296
  }
875
- return [...acc, thisFieldWithPath];
876
- }, []);
1297
+ function extend(namespace, delimiter) {
1298
+ const newDebug = createDebug(this.namespace + (typeof delimiter > "u" ? ":" : delimiter) + namespace);
1299
+ return newDebug.log = this.log, newDebug;
1300
+ }
1301
+ function enable(namespaces) {
1302
+ createDebug.save(namespaces), createDebug.namespaces = namespaces, createDebug.names = [], createDebug.skips = [];
1303
+ const split = (typeof namespaces == "string" ? namespaces : "").trim().replace(" ", ",").split(",").filter(Boolean);
1304
+ for (const ns of split)
1305
+ ns[0] === "-" ? createDebug.skips.push(ns.slice(1)) : createDebug.names.push(ns);
1306
+ }
1307
+ function matchesTemplate(search, template) {
1308
+ let searchIndex = 0, templateIndex = 0, starIndex = -1, matchIndex = 0;
1309
+ for (; searchIndex < search.length; )
1310
+ if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*"))
1311
+ template[templateIndex] === "*" ? (starIndex = templateIndex, matchIndex = searchIndex, templateIndex++) : (searchIndex++, templateIndex++);
1312
+ else if (starIndex !== -1)
1313
+ templateIndex = starIndex + 1, matchIndex++, searchIndex = matchIndex;
1314
+ else
1315
+ return !1;
1316
+ for (; templateIndex < template.length && template[templateIndex] === "*"; )
1317
+ templateIndex++;
1318
+ return templateIndex === template.length;
1319
+ }
1320
+ function disable() {
1321
+ const namespaces = [
1322
+ ...createDebug.names,
1323
+ ...createDebug.skips.map((namespace) => "-" + namespace)
1324
+ ].join(",");
1325
+ return createDebug.enable(""), namespaces;
1326
+ }
1327
+ function enabled(name) {
1328
+ for (const skip of createDebug.skips)
1329
+ if (matchesTemplate(name, skip))
1330
+ return !1;
1331
+ for (const ns of createDebug.names)
1332
+ if (matchesTemplate(name, ns))
1333
+ return !0;
1334
+ return !1;
1335
+ }
1336
+ function coerce(val) {
1337
+ return val instanceof Error ? val.stack || val.message : val;
1338
+ }
1339
+ function destroy() {
1340
+ console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
1341
+ }
1342
+ return createDebug.enable(createDebug.load()), createDebug;
1343
+ }
1344
+ return common = setup, common;
877
1345
  }
878
- function LanguageOption(props) {
879
- var _a;
880
- const {
881
- language,
882
- schemaType,
883
- documentId,
884
- current,
885
- source,
886
- sourceLanguageId,
887
- metadata: metadata2,
888
- metadataId
889
- } = props, [userHasClicked, setUserHasClicked] = react.useState(!1), disabled = props.disabled || userHasClicked || current || !source || !sourceLanguageId || !metadataId, translation = metadata2 != null && metadata2.translations.length ? metadata2.translations.find((t) => t._key === language.id) : void 0, { apiVersion, languageField, weakReferences } = useDocumentInternationalizationContext(), client = sanity.useClient({ apiVersion }), toast = ui.useToast(), open = useOpenInNewPane((_a = translation == null ? void 0 : translation.value) == null ? void 0 : _a._ref, schemaType.name), handleOpen = react.useCallback(() => open(), [open]);
890
- react.useEffect(() => {
891
- setUserHasClicked(!1);
892
- }, [!!translation]);
893
- const handleCreate = react.useCallback(async () => {
894
- if (!source)
895
- throw new Error("Cannot create translation without source document");
896
- if (!sourceLanguageId)
897
- throw new Error("Cannot create translation without source language ID");
898
- if (!metadataId)
899
- throw new Error("Cannot create translation without a metadata ID");
900
- setUserHasClicked(!0);
901
- const transaction = client.transaction(), newTranslationDocumentId = uuid.uuid();
902
- let newTranslationDocument = {
903
- ...source,
904
- _id: `drafts.${newTranslationDocumentId}`,
905
- // 2. Update language of the translation
906
- [languageField]: language.id
1346
+ var hasRequiredBrowser$1;
1347
+ function requireBrowser$1() {
1348
+ return hasRequiredBrowser$1 || (hasRequiredBrowser$1 = 1, function(module2, exports2) {
1349
+ exports2.formatArgs = formatArgs, exports2.save = save, exports2.load = load, exports2.useColors = useColors, exports2.storage = localstorage(), exports2.destroy = /* @__PURE__ */ (() => {
1350
+ let warned = !1;
1351
+ return () => {
1352
+ warned || (warned = !0, console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."));
1353
+ };
1354
+ })(), exports2.colors = [
1355
+ "#0000CC",
1356
+ "#0000FF",
1357
+ "#0033CC",
1358
+ "#0033FF",
1359
+ "#0066CC",
1360
+ "#0066FF",
1361
+ "#0099CC",
1362
+ "#0099FF",
1363
+ "#00CC00",
1364
+ "#00CC33",
1365
+ "#00CC66",
1366
+ "#00CC99",
1367
+ "#00CCCC",
1368
+ "#00CCFF",
1369
+ "#3300CC",
1370
+ "#3300FF",
1371
+ "#3333CC",
1372
+ "#3333FF",
1373
+ "#3366CC",
1374
+ "#3366FF",
1375
+ "#3399CC",
1376
+ "#3399FF",
1377
+ "#33CC00",
1378
+ "#33CC33",
1379
+ "#33CC66",
1380
+ "#33CC99",
1381
+ "#33CCCC",
1382
+ "#33CCFF",
1383
+ "#6600CC",
1384
+ "#6600FF",
1385
+ "#6633CC",
1386
+ "#6633FF",
1387
+ "#66CC00",
1388
+ "#66CC33",
1389
+ "#9900CC",
1390
+ "#9900FF",
1391
+ "#9933CC",
1392
+ "#9933FF",
1393
+ "#99CC00",
1394
+ "#99CC33",
1395
+ "#CC0000",
1396
+ "#CC0033",
1397
+ "#CC0066",
1398
+ "#CC0099",
1399
+ "#CC00CC",
1400
+ "#CC00FF",
1401
+ "#CC3300",
1402
+ "#CC3333",
1403
+ "#CC3366",
1404
+ "#CC3399",
1405
+ "#CC33CC",
1406
+ "#CC33FF",
1407
+ "#CC6600",
1408
+ "#CC6633",
1409
+ "#CC9900",
1410
+ "#CC9933",
1411
+ "#CCCC00",
1412
+ "#CCCC33",
1413
+ "#FF0000",
1414
+ "#FF0033",
1415
+ "#FF0066",
1416
+ "#FF0099",
1417
+ "#FF00CC",
1418
+ "#FF00FF",
1419
+ "#FF3300",
1420
+ "#FF3333",
1421
+ "#FF3366",
1422
+ "#FF3399",
1423
+ "#FF33CC",
1424
+ "#FF33FF",
1425
+ "#FF6600",
1426
+ "#FF6633",
1427
+ "#FF9900",
1428
+ "#FF9933",
1429
+ "#FFCC00",
1430
+ "#FFCC33"
1431
+ ];
1432
+ function useColors() {
1433
+ if (typeof window < "u" && window.process && (window.process.type === "renderer" || window.process.__nwjs))
1434
+ return !0;
1435
+ if (typeof navigator < "u" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))
1436
+ return !1;
1437
+ let m;
1438
+ return typeof document < "u" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
1439
+ typeof window < "u" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
1440
+ // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
1441
+ typeof navigator < "u" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
1442
+ typeof navigator < "u" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
1443
+ }
1444
+ function formatArgs(args) {
1445
+ if (args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff), !this.useColors)
1446
+ return;
1447
+ const c = "color: " + this.color;
1448
+ args.splice(1, 0, c, "color: inherit");
1449
+ let index = 0, lastC = 0;
1450
+ args[0].replace(/%[a-zA-Z%]/g, (match2) => {
1451
+ match2 !== "%%" && (index++, match2 === "%c" && (lastC = index));
1452
+ }), args.splice(lastC, 0, c);
1453
+ }
1454
+ exports2.log = console.debug || console.log || (() => {
1455
+ });
1456
+ function save(namespaces) {
1457
+ try {
1458
+ namespaces ? exports2.storage.setItem("debug", namespaces) : exports2.storage.removeItem("debug");
1459
+ } catch (error) {
1460
+ }
1461
+ }
1462
+ function load() {
1463
+ let r;
1464
+ try {
1465
+ r = exports2.storage.getItem("debug");
1466
+ } catch (error) {
1467
+ }
1468
+ return !r && typeof process < "u" && "env" in process && (r = process.env.DEBUG), r;
1469
+ }
1470
+ function localstorage() {
1471
+ try {
1472
+ return localStorage;
1473
+ } catch (error) {
1474
+ }
1475
+ }
1476
+ module2.exports = requireCommon()(exports2);
1477
+ const { formatters } = module2.exports;
1478
+ formatters.j = function(v) {
1479
+ try {
1480
+ return JSON.stringify(v);
1481
+ } catch (error) {
1482
+ return "[UnexpectedJSONParseError]: " + error.message;
1483
+ }
907
1484
  };
908
- newTranslationDocument = removeExcludedPaths(
909
- newTranslationDocument,
910
- schemaType
911
- ), transaction.create(newTranslationDocument);
912
- const sourceReference = createReference(
913
- sourceLanguageId,
914
- documentId,
915
- schemaType.name,
916
- !weakReferences
917
- ), newTranslationReference = createReference(
918
- language.id,
919
- newTranslationDocumentId,
920
- schemaType.name,
921
- !weakReferences
922
- ), newMetadataDocument = {
923
- _id: metadataId,
924
- _type: METADATA_SCHEMA_NAME,
925
- schemaTypes: [schemaType.name],
926
- translations: [sourceReference]
1485
+ }(browser$1, browser$1.exports)), browser$1.exports;
1486
+ }
1487
+ var node = { exports: {} }, browser, hasRequiredBrowser;
1488
+ function requireBrowser() {
1489
+ if (hasRequiredBrowser)
1490
+ return browser;
1491
+ hasRequiredBrowser = 1;
1492
+ function getChromeVersion() {
1493
+ const matches = new RegExp("(Chrome|Chromium)\\/(?<chromeVersion>\\d+)\\.").exec(navigator.userAgent);
1494
+ if (matches)
1495
+ return Number.parseInt(matches.groups.chromeVersion, 10);
1496
+ }
1497
+ const colorSupport = getChromeVersion() >= 69 ? {
1498
+ level: 1,
1499
+ hasBasic: !0,
1500
+ has256: !1,
1501
+ has16m: !1
1502
+ } : !1;
1503
+ return browser = {
1504
+ stdout: colorSupport,
1505
+ stderr: colorSupport
1506
+ }, browser;
1507
+ }
1508
+ var hasRequiredNode;
1509
+ function requireNode() {
1510
+ return hasRequiredNode || (hasRequiredNode = 1, function(module2, exports2) {
1511
+ const tty = require$$0__default.default, util = require$$1__default.default;
1512
+ exports2.init = init, exports2.log = log, exports2.formatArgs = formatArgs, exports2.save = save, exports2.load = load, exports2.useColors = useColors, exports2.destroy = util.deprecate(
1513
+ () => {
1514
+ },
1515
+ "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."
1516
+ ), exports2.colors = [6, 2, 3, 4, 5, 1];
1517
+ try {
1518
+ const supportsColor = requireBrowser();
1519
+ supportsColor && (supportsColor.stderr || supportsColor).level >= 2 && (exports2.colors = [
1520
+ 20,
1521
+ 21,
1522
+ 26,
1523
+ 27,
1524
+ 32,
1525
+ 33,
1526
+ 38,
1527
+ 39,
1528
+ 40,
1529
+ 41,
1530
+ 42,
1531
+ 43,
1532
+ 44,
1533
+ 45,
1534
+ 56,
1535
+ 57,
1536
+ 62,
1537
+ 63,
1538
+ 68,
1539
+ 69,
1540
+ 74,
1541
+ 75,
1542
+ 76,
1543
+ 77,
1544
+ 78,
1545
+ 79,
1546
+ 80,
1547
+ 81,
1548
+ 92,
1549
+ 93,
1550
+ 98,
1551
+ 99,
1552
+ 112,
1553
+ 113,
1554
+ 128,
1555
+ 129,
1556
+ 134,
1557
+ 135,
1558
+ 148,
1559
+ 149,
1560
+ 160,
1561
+ 161,
1562
+ 162,
1563
+ 163,
1564
+ 164,
1565
+ 165,
1566
+ 166,
1567
+ 167,
1568
+ 168,
1569
+ 169,
1570
+ 170,
1571
+ 171,
1572
+ 172,
1573
+ 173,
1574
+ 178,
1575
+ 179,
1576
+ 184,
1577
+ 185,
1578
+ 196,
1579
+ 197,
1580
+ 198,
1581
+ 199,
1582
+ 200,
1583
+ 201,
1584
+ 202,
1585
+ 203,
1586
+ 204,
1587
+ 205,
1588
+ 206,
1589
+ 207,
1590
+ 208,
1591
+ 209,
1592
+ 214,
1593
+ 215,
1594
+ 220,
1595
+ 221
1596
+ ]);
1597
+ } catch (error) {
1598
+ }
1599
+ exports2.inspectOpts = Object.keys(process.env).filter((key) => /^debug_/i.test(key)).reduce((obj, key) => {
1600
+ const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => k.toUpperCase());
1601
+ let val = process.env[key];
1602
+ return /^(yes|on|true|enabled)$/i.test(val) ? val = !0 : /^(no|off|false|disabled)$/i.test(val) ? val = !1 : val === "null" ? val = null : val = Number(val), obj[prop] = val, obj;
1603
+ }, {});
1604
+ function useColors() {
1605
+ return "colors" in exports2.inspectOpts ? !!exports2.inspectOpts.colors : tty.isatty(process.stderr.fd);
1606
+ }
1607
+ function formatArgs(args) {
1608
+ const { namespace: name, useColors: useColors2 } = this;
1609
+ if (useColors2) {
1610
+ const c = this.color, colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c), prefix = ` ${colorCode};1m${name} \x1B[0m`;
1611
+ args[0] = prefix + args[0].split(`
1612
+ `).join(`
1613
+ ` + prefix), args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m");
1614
+ } else
1615
+ args[0] = getDate() + name + " " + args[0];
1616
+ }
1617
+ function getDate() {
1618
+ return exports2.inspectOpts.hideDate ? "" : (/* @__PURE__ */ new Date()).toISOString() + " ";
1619
+ }
1620
+ function log(...args) {
1621
+ return process.stderr.write(util.formatWithOptions(exports2.inspectOpts, ...args) + `
1622
+ `);
1623
+ }
1624
+ function save(namespaces) {
1625
+ namespaces ? process.env.DEBUG = namespaces : delete process.env.DEBUG;
1626
+ }
1627
+ function load() {
1628
+ return process.env.DEBUG;
1629
+ }
1630
+ function init(debug2) {
1631
+ debug2.inspectOpts = {};
1632
+ const keys = Object.keys(exports2.inspectOpts);
1633
+ for (let i = 0; i < keys.length; i++)
1634
+ debug2.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]];
1635
+ }
1636
+ module2.exports = requireCommon()(exports2);
1637
+ const { formatters } = module2.exports;
1638
+ formatters.o = function(v) {
1639
+ return this.inspectOpts.colors = this.useColors, util.inspect(v, this.inspectOpts).split(`
1640
+ `).map((str) => str.trim()).join(" ");
1641
+ }, formatters.O = function(v) {
1642
+ return this.inspectOpts.colors = this.useColors, util.inspect(v, this.inspectOpts);
927
1643
  };
928
- transaction.createIfNotExists(newMetadataDocument);
929
- const metadataPatch = client.patch(metadataId).setIfMissing({ translations: [sourceReference] }).insert("after", "translations[-1]", [newTranslationReference]);
930
- transaction.patch(metadataPatch), transaction.commit().then(() => {
931
- const metadataExisted = !!(metadata2 != null && metadata2._createdAt);
932
- return toast.push({
933
- status: "success",
934
- title: `Created "${language.title}" translation`,
935
- description: metadataExisted ? "Updated Translations Metadata" : "Created Translations Metadata"
936
- });
937
- }).catch((err) => (console.error(err), setUserHasClicked(!1), toast.push({
938
- status: "error",
939
- title: "Error creating translation",
940
- description: err.message
941
- })));
942
- }, [
943
- client,
944
- documentId,
945
- language.id,
946
- language.title,
947
- languageField,
948
- metadata2 == null ? void 0 : metadata2._createdAt,
949
- metadataId,
950
- schemaType,
951
- source,
952
- sourceLanguageId,
953
- toast,
954
- weakReferences
955
- ]);
956
- let message;
957
- return current ? message = "Current document" : translation ? message = `Open ${language.title} translation` : translation || (message = `Create new ${language.title} translation`), /* @__PURE__ */ jsxRuntime.jsx(
958
- ui.Tooltip,
959
- {
960
- animate: !0,
961
- content: /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { padding: 2, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { muted: !0, size: 1, children: message }) }),
962
- fallbackPlacements: ["right", "left"],
963
- placement: "top",
964
- portal: !0,
965
- children: /* @__PURE__ */ jsxRuntime.jsx(
1644
+ }(node, node.exports)), node.exports;
1645
+ }
1646
+ typeof process > "u" || process.type === "renderer" || process.browser === !0 || process.__nwjs ? src.exports = requireBrowser$1() : src.exports = requireNode();
1647
+ var srcExports = src.exports, debugIt = /* @__PURE__ */ getDefaultExportFromCjs(srcExports), Symbol$1 = _Symbol, isArguments = isArguments_1, isArray = isArray_1, spreadableSymbol = Symbol$1 ? Symbol$1.isConcatSpreadable : void 0;
1648
+ function isFlattenable$1(value) {
1649
+ return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
1650
+ }
1651
+ var _isFlattenable = isFlattenable$1, arrayPush = _arrayPush, isFlattenable = _isFlattenable;
1652
+ function baseFlatten$1(array, depth, predicate, isStrict, result) {
1653
+ var index = -1, length = array.length;
1654
+ for (predicate || (predicate = isFlattenable), result || (result = []); ++index < length; ) {
1655
+ var value = array[index];
1656
+ depth > 0 && predicate(value) ? depth > 1 ? baseFlatten$1(value, depth - 1, predicate, isStrict, result) : arrayPush(result, value) : isStrict || (result[result.length] = value);
1657
+ }
1658
+ return result;
1659
+ }
1660
+ var _baseFlatten = baseFlatten$1, baseFlatten = _baseFlatten;
1661
+ function flatten(array) {
1662
+ var length = array == null ? 0 : array.length;
1663
+ return length ? baseFlatten(array, 1) : [];
1664
+ }
1665
+ var flatten_1 = flatten, flatten$1 = /* @__PURE__ */ getDefaultExportFromCjs(flatten_1);
1666
+ function isHighSurrogate(char) {
1667
+ const charCode = char.charCodeAt(0);
1668
+ return charCode >= 55296 && charCode <= 56319;
1669
+ }
1670
+ function isLowSurrogate(char) {
1671
+ const charCode = char.charCodeAt(0);
1672
+ return charCode >= 56320 && charCode <= 57343;
1673
+ }
1674
+ function cloneDiff(diff2) {
1675
+ const [type, patch] = diff2;
1676
+ return [type, patch];
1677
+ }
1678
+ function getCommonOverlap(textA, textB) {
1679
+ let text1 = textA, text2 = textB;
1680
+ const text1Length = text1.length, text2Length = text2.length;
1681
+ if (text1Length === 0 || text2Length === 0)
1682
+ return 0;
1683
+ text1Length > text2Length ? text1 = text1.substring(text1Length - text2Length) : text1Length < text2Length && (text2 = text2.substring(0, text1Length));
1684
+ const textLength = Math.min(text1Length, text2Length);
1685
+ if (text1 === text2)
1686
+ return textLength;
1687
+ let best = 0, length = 1;
1688
+ for (let found = 0; found !== -1; ) {
1689
+ const pattern = text1.substring(textLength - length);
1690
+ if (found = text2.indexOf(pattern), found === -1)
1691
+ return best;
1692
+ length += found, (found === 0 || text1.substring(textLength - length) === text2.substring(0, length)) && (best = length, length++);
1693
+ }
1694
+ return best;
1695
+ }
1696
+ function getCommonPrefix(text1, text2) {
1697
+ if (!text1 || !text2 || text1[0] !== text2[0])
1698
+ return 0;
1699
+ let pointerMin = 0, pointerMax = Math.min(text1.length, text2.length), pointerMid = pointerMax, pointerStart = 0;
1700
+ for (; pointerMin < pointerMid; )
1701
+ text1.substring(pointerStart, pointerMid) === text2.substring(pointerStart, pointerMid) ? (pointerMin = pointerMid, pointerStart = pointerMin) : pointerMax = pointerMid, pointerMid = Math.floor((pointerMax - pointerMin) / 2 + pointerMin);
1702
+ return pointerMid;
1703
+ }
1704
+ function getCommonSuffix(text1, text2) {
1705
+ if (!text1 || !text2 || text1[text1.length - 1] !== text2[text2.length - 1])
1706
+ return 0;
1707
+ let pointerMin = 0, pointerMax = Math.min(text1.length, text2.length), pointerMid = pointerMax, pointerEnd = 0;
1708
+ for (; pointerMin < pointerMid; )
1709
+ text1.substring(text1.length - pointerMid, text1.length - pointerEnd) === text2.substring(text2.length - pointerMid, text2.length - pointerEnd) ? (pointerMin = pointerMid, pointerEnd = pointerMin) : pointerMax = pointerMid, pointerMid = Math.floor((pointerMax - pointerMin) / 2 + pointerMin);
1710
+ return pointerMid;
1711
+ }
1712
+ function cleanupSemantic(rawDiffs) {
1713
+ let diffs = rawDiffs.map((diff2) => cloneDiff(diff2)), hasChanges = !1;
1714
+ const equalities = [];
1715
+ let equalitiesLength = 0, lastEquality = null, pointer = 0, lengthInsertions1 = 0, lengthDeletions1 = 0, lengthInsertions2 = 0, lengthDeletions2 = 0;
1716
+ for (; pointer < diffs.length; )
1717
+ diffs[pointer][0] === DIFF_EQUAL ? (equalities[equalitiesLength++] = pointer, lengthInsertions1 = lengthInsertions2, lengthDeletions1 = lengthDeletions2, lengthInsertions2 = 0, lengthDeletions2 = 0, lastEquality = diffs[pointer][1]) : (diffs[pointer][0] === DIFF_INSERT ? lengthInsertions2 += diffs[pointer][1].length : lengthDeletions2 += diffs[pointer][1].length, lastEquality && lastEquality.length <= Math.max(lengthInsertions1, lengthDeletions1) && lastEquality.length <= Math.max(lengthInsertions2, lengthDeletions2) && (diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastEquality]), diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT, equalitiesLength--, equalitiesLength--, pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1, lengthInsertions1 = 0, lengthDeletions1 = 0, lengthInsertions2 = 0, lengthDeletions2 = 0, lastEquality = null, hasChanges = !0)), pointer++;
1718
+ for (hasChanges && (diffs = cleanupMerge(diffs)), diffs = cleanupSemanticLossless(diffs), pointer = 1; pointer < diffs.length; ) {
1719
+ if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) {
1720
+ const deletion = diffs[pointer - 1][1], insertion = diffs[pointer][1], overlapLength1 = getCommonOverlap(deletion, insertion), overlapLength2 = getCommonOverlap(insertion, deletion);
1721
+ overlapLength1 >= overlapLength2 ? (overlapLength1 >= deletion.length / 2 || overlapLength1 >= insertion.length / 2) && (diffs.splice(pointer, 0, [DIFF_EQUAL, insertion.substring(0, overlapLength1)]), diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlapLength1), diffs[pointer + 1][1] = insertion.substring(overlapLength1), pointer++) : (overlapLength2 >= deletion.length / 2 || overlapLength2 >= insertion.length / 2) && (diffs.splice(pointer, 0, [DIFF_EQUAL, deletion.substring(0, overlapLength2)]), diffs[pointer - 1][0] = DIFF_INSERT, diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlapLength2), diffs[pointer + 1][0] = DIFF_DELETE, diffs[pointer + 1][1] = deletion.substring(overlapLength2), pointer++), pointer++;
1722
+ }
1723
+ pointer++;
1724
+ }
1725
+ return diffs;
1726
+ }
1727
+ const nonAlphaNumericRegex = /[^a-zA-Z0-9]/, whitespaceRegex = /\s/, linebreakRegex = /[\r\n]/, blanklineEndRegex = /\n\r?\n$/, blanklineStartRegex = /^\r?\n\r?\n/;
1728
+ function cleanupSemanticLossless(rawDiffs) {
1729
+ const diffs = rawDiffs.map((diff2) => cloneDiff(diff2));
1730
+ function diffCleanupSemanticScore(one, two) {
1731
+ if (!one || !two)
1732
+ return 6;
1733
+ const char1 = one.charAt(one.length - 1), char2 = two.charAt(0), nonAlphaNumeric1 = char1.match(nonAlphaNumericRegex), nonAlphaNumeric2 = char2.match(nonAlphaNumericRegex), whitespace1 = nonAlphaNumeric1 && char1.match(whitespaceRegex), whitespace2 = nonAlphaNumeric2 && char2.match(whitespaceRegex), lineBreak1 = whitespace1 && char1.match(linebreakRegex), lineBreak2 = whitespace2 && char2.match(linebreakRegex), blankLine1 = lineBreak1 && one.match(blanklineEndRegex), blankLine2 = lineBreak2 && two.match(blanklineStartRegex);
1734
+ return blankLine1 || blankLine2 ? 5 : lineBreak1 || lineBreak2 ? 4 : nonAlphaNumeric1 && !whitespace1 && whitespace2 ? 3 : whitespace1 || whitespace2 ? 2 : nonAlphaNumeric1 || nonAlphaNumeric2 ? 1 : 0;
1735
+ }
1736
+ let pointer = 1;
1737
+ for (; pointer < diffs.length - 1; ) {
1738
+ if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) {
1739
+ let equality1 = diffs[pointer - 1][1], edit = diffs[pointer][1], equality2 = diffs[pointer + 1][1];
1740
+ const commonOffset = getCommonSuffix(equality1, edit);
1741
+ if (commonOffset) {
1742
+ const commonString = edit.substring(edit.length - commonOffset);
1743
+ equality1 = equality1.substring(0, equality1.length - commonOffset), edit = commonString + edit.substring(0, edit.length - commonOffset), equality2 = commonString + equality2;
1744
+ }
1745
+ let bestEquality1 = equality1, bestEdit = edit, bestEquality2 = equality2, bestScore = diffCleanupSemanticScore(equality1, edit) + diffCleanupSemanticScore(edit, equality2);
1746
+ for (; edit.charAt(0) === equality2.charAt(0); ) {
1747
+ equality1 += edit.charAt(0), edit = edit.substring(1) + equality2.charAt(0), equality2 = equality2.substring(1);
1748
+ const score = diffCleanupSemanticScore(equality1, edit) + diffCleanupSemanticScore(edit, equality2);
1749
+ score >= bestScore && (bestScore = score, bestEquality1 = equality1, bestEdit = edit, bestEquality2 = equality2);
1750
+ }
1751
+ diffs[pointer - 1][1] !== bestEquality1 && (bestEquality1 ? diffs[pointer - 1][1] = bestEquality1 : (diffs.splice(pointer - 1, 1), pointer--), diffs[pointer][1] = bestEdit, bestEquality2 ? diffs[pointer + 1][1] = bestEquality2 : (diffs.splice(pointer + 1, 1), pointer--));
1752
+ }
1753
+ pointer++;
1754
+ }
1755
+ return diffs;
1756
+ }
1757
+ function cleanupMerge(rawDiffs) {
1758
+ let diffs = rawDiffs.map((diff2) => cloneDiff(diff2));
1759
+ diffs.push([DIFF_EQUAL, ""]);
1760
+ let pointer = 0, countDelete = 0, countInsert = 0, textDelete = "", textInsert = "", commonlength;
1761
+ for (; pointer < diffs.length; )
1762
+ switch (diffs[pointer][0]) {
1763
+ case DIFF_INSERT:
1764
+ countInsert++, textInsert += diffs[pointer][1], pointer++;
1765
+ break;
1766
+ case DIFF_DELETE:
1767
+ countDelete++, textDelete += diffs[pointer][1], pointer++;
1768
+ break;
1769
+ case DIFF_EQUAL:
1770
+ countDelete + countInsert > 1 ? (countDelete !== 0 && countInsert !== 0 && (commonlength = getCommonPrefix(textInsert, textDelete), commonlength !== 0 && (pointer - countDelete - countInsert > 0 && diffs[pointer - countDelete - countInsert - 1][0] === DIFF_EQUAL ? diffs[pointer - countDelete - countInsert - 1][1] += textInsert.substring(0, commonlength) : (diffs.splice(0, 0, [DIFF_EQUAL, textInsert.substring(0, commonlength)]), pointer++), textInsert = textInsert.substring(commonlength), textDelete = textDelete.substring(commonlength)), commonlength = getCommonSuffix(textInsert, textDelete), commonlength !== 0 && (diffs[pointer][1] = textInsert.substring(textInsert.length - commonlength) + diffs[pointer][1], textInsert = textInsert.substring(0, textInsert.length - commonlength), textDelete = textDelete.substring(0, textDelete.length - commonlength))), pointer -= countDelete + countInsert, diffs.splice(pointer, countDelete + countInsert), textDelete.length && (diffs.splice(pointer, 0, [DIFF_DELETE, textDelete]), pointer++), textInsert.length && (diffs.splice(pointer, 0, [DIFF_INSERT, textInsert]), pointer++), pointer++) : pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL ? (diffs[pointer - 1][1] += diffs[pointer][1], diffs.splice(pointer, 1)) : pointer++, countInsert = 0, countDelete = 0, textDelete = "", textInsert = "";
1771
+ break;
1772
+ default:
1773
+ throw new Error("Unknown diff operation");
1774
+ }
1775
+ diffs[diffs.length - 1][1] === "" && diffs.pop();
1776
+ let hasChanges = !1;
1777
+ for (pointer = 1; pointer < diffs.length - 1; )
1778
+ diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL && (diffs[pointer][1].substring(diffs[pointer][1].length - diffs[pointer - 1][1].length) === diffs[pointer - 1][1] ? (diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length), diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1], diffs.splice(pointer - 1, 1), hasChanges = !0) : diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1] && (diffs[pointer - 1][1] += diffs[pointer + 1][1], diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1], diffs.splice(pointer + 1, 1), hasChanges = !0)), pointer++;
1779
+ return hasChanges && (diffs = cleanupMerge(diffs)), diffs;
1780
+ }
1781
+ function bisect(text1, text2, deadline) {
1782
+ const text1Length = text1.length, text2Length = text2.length, maxD = Math.ceil((text1Length + text2Length) / 2), vOffset = maxD, vLength = 2 * maxD, v1 = new Array(vLength), v2 = new Array(vLength);
1783
+ for (let x = 0; x < vLength; x++)
1784
+ v1[x] = -1, v2[x] = -1;
1785
+ v1[vOffset + 1] = 0, v2[vOffset + 1] = 0;
1786
+ const delta = text1Length - text2Length, front = delta % 2 !== 0;
1787
+ let k1start = 0, k1end = 0, k2start = 0, k2end = 0;
1788
+ for (let d = 0; d < maxD && !(Date.now() > deadline); d++) {
1789
+ for (let k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
1790
+ const k1Offset = vOffset + k1;
1791
+ let x1;
1792
+ k1 === -d || k1 !== d && v1[k1Offset - 1] < v1[k1Offset + 1] ? x1 = v1[k1Offset + 1] : x1 = v1[k1Offset - 1] + 1;
1793
+ let y1 = x1 - k1;
1794
+ for (; x1 < text1Length && y1 < text2Length && text1.charAt(x1) === text2.charAt(y1); )
1795
+ x1++, y1++;
1796
+ if (v1[k1Offset] = x1, x1 > text1Length)
1797
+ k1end += 2;
1798
+ else if (y1 > text2Length)
1799
+ k1start += 2;
1800
+ else if (front) {
1801
+ const k2Offset = vOffset + delta - k1;
1802
+ if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) {
1803
+ const x2 = text1Length - v2[k2Offset];
1804
+ if (x1 >= x2)
1805
+ return bisectSplit(text1, text2, x1, y1, deadline);
1806
+ }
1807
+ }
1808
+ }
1809
+ for (let k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
1810
+ const k2Offset = vOffset + k2;
1811
+ let x2;
1812
+ k2 === -d || k2 !== d && v2[k2Offset - 1] < v2[k2Offset + 1] ? x2 = v2[k2Offset + 1] : x2 = v2[k2Offset - 1] + 1;
1813
+ let y2 = x2 - k2;
1814
+ for (; x2 < text1Length && y2 < text2Length && text1.charAt(text1Length - x2 - 1) === text2.charAt(text2Length - y2 - 1); )
1815
+ x2++, y2++;
1816
+ if (v2[k2Offset] = x2, x2 > text1Length)
1817
+ k2end += 2;
1818
+ else if (y2 > text2Length)
1819
+ k2start += 2;
1820
+ else if (!front) {
1821
+ const k1Offset = vOffset + delta - k2;
1822
+ if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) {
1823
+ const x1 = v1[k1Offset], y1 = vOffset + x1 - k1Offset;
1824
+ if (x2 = text1Length - x2, x1 >= x2)
1825
+ return bisectSplit(text1, text2, x1, y1, deadline);
1826
+ }
1827
+ }
1828
+ }
1829
+ }
1830
+ return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
1831
+ }
1832
+ function bisectSplit(text1, text2, x, y, deadline) {
1833
+ const text1a = text1.substring(0, x), text2a = text2.substring(0, y), text1b = text1.substring(x), text2b = text2.substring(y), diffs = doDiff(text1a, text2a, {
1834
+ checkLines: !1,
1835
+ deadline
1836
+ }), diffsb = doDiff(text1b, text2b, {
1837
+ checkLines: !1,
1838
+ deadline
1839
+ });
1840
+ return diffs.concat(diffsb);
1841
+ }
1842
+ function findHalfMatch(text1, text2) {
1843
+ if ((arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 1) <= 0)
1844
+ return null;
1845
+ const longText = text1.length > text2.length ? text1 : text2, shortText = text1.length > text2.length ? text2 : text1;
1846
+ if (longText.length < 4 || shortText.length * 2 < longText.length)
1847
+ return null;
1848
+ const halfMatch1 = halfMatchI(longText, shortText, Math.ceil(longText.length / 4)), halfMatch2 = halfMatchI(longText, shortText, Math.ceil(longText.length / 2));
1849
+ let halfMatch;
1850
+ if (halfMatch1 && halfMatch2)
1851
+ halfMatch = halfMatch1[4].length > halfMatch2[4].length ? halfMatch1 : halfMatch2;
1852
+ else {
1853
+ if (!halfMatch1 && !halfMatch2)
1854
+ return null;
1855
+ halfMatch2 ? halfMatch1 || (halfMatch = halfMatch2) : halfMatch = halfMatch1;
1856
+ }
1857
+ if (!halfMatch)
1858
+ throw new Error("Unable to find a half match.");
1859
+ let text1A, text1B, text2A, text2B;
1860
+ text1.length > text2.length ? (text1A = halfMatch[0], text1B = halfMatch[1], text2A = halfMatch[2], text2B = halfMatch[3]) : (text2A = halfMatch[0], text2B = halfMatch[1], text1A = halfMatch[2], text1B = halfMatch[3]);
1861
+ const midCommon = halfMatch[4];
1862
+ return [text1A, text1B, text2A, text2B, midCommon];
1863
+ }
1864
+ function halfMatchI(longText, shortText, i) {
1865
+ const seed = longText.slice(i, i + Math.floor(longText.length / 4));
1866
+ let j = -1, bestCommon = "", bestLongTextA, bestLongTextB, bestShortTextA, bestShortTextB;
1867
+ for (; (j = shortText.indexOf(seed, j + 1)) !== -1; ) {
1868
+ const prefixLength = getCommonPrefix(longText.slice(i), shortText.slice(j)), suffixLength = getCommonSuffix(longText.slice(0, i), shortText.slice(0, j));
1869
+ bestCommon.length < suffixLength + prefixLength && (bestCommon = shortText.slice(j - suffixLength, j) + shortText.slice(j, j + prefixLength), bestLongTextA = longText.slice(0, i - suffixLength), bestLongTextB = longText.slice(i + prefixLength), bestShortTextA = shortText.slice(0, j - suffixLength), bestShortTextB = shortText.slice(j + prefixLength));
1870
+ }
1871
+ return bestCommon.length * 2 >= longText.length ? [bestLongTextA || "", bestLongTextB || "", bestShortTextA || "", bestShortTextB || "", bestCommon || ""] : null;
1872
+ }
1873
+ function charsToLines(diffs, lineArray) {
1874
+ for (let x = 0; x < diffs.length; x++) {
1875
+ const chars = diffs[x][1], text = [];
1876
+ for (let y = 0; y < chars.length; y++)
1877
+ text[y] = lineArray[chars.charCodeAt(y)];
1878
+ diffs[x][1] = text.join("");
1879
+ }
1880
+ }
1881
+ function linesToChars(textA, textB) {
1882
+ const lineArray = [], lineHash = {};
1883
+ lineArray[0] = "";
1884
+ function diffLinesToMunge(text) {
1885
+ let chars = "", lineStart = 0, lineEnd = -1, lineArrayLength = lineArray.length;
1886
+ for (; lineEnd < text.length - 1; ) {
1887
+ lineEnd = text.indexOf(`
1888
+ `, lineStart), lineEnd === -1 && (lineEnd = text.length - 1);
1889
+ let line = text.slice(lineStart, lineEnd + 1);
1890
+ (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : lineHash[line] !== void 0) ? chars += String.fromCharCode(lineHash[line]) : (lineArrayLength === maxLines && (line = text.slice(lineStart), lineEnd = text.length), chars += String.fromCharCode(lineArrayLength), lineHash[line] = lineArrayLength, lineArray[lineArrayLength++] = line), lineStart = lineEnd + 1;
1891
+ }
1892
+ return chars;
1893
+ }
1894
+ let maxLines = 4e4;
1895
+ const chars1 = diffLinesToMunge(textA);
1896
+ maxLines = 65535;
1897
+ const chars2 = diffLinesToMunge(textB);
1898
+ return {
1899
+ chars1,
1900
+ chars2,
1901
+ lineArray
1902
+ };
1903
+ }
1904
+ function doLineModeDiff(textA, textB, opts) {
1905
+ let text1 = textA, text2 = textB;
1906
+ const a = linesToChars(text1, text2);
1907
+ text1 = a.chars1, text2 = a.chars2;
1908
+ const linearray = a.lineArray;
1909
+ let diffs = doDiff(text1, text2, {
1910
+ checkLines: !1,
1911
+ deadline: opts.deadline
1912
+ });
1913
+ charsToLines(diffs, linearray), diffs = cleanupSemantic(diffs), diffs.push([DIFF_EQUAL, ""]);
1914
+ let pointer = 0, countDelete = 0, countInsert = 0, textDelete = "", textInsert = "";
1915
+ for (; pointer < diffs.length; ) {
1916
+ switch (diffs[pointer][0]) {
1917
+ case DIFF_INSERT:
1918
+ countInsert++, textInsert += diffs[pointer][1];
1919
+ break;
1920
+ case DIFF_DELETE:
1921
+ countDelete++, textDelete += diffs[pointer][1];
1922
+ break;
1923
+ case DIFF_EQUAL:
1924
+ if (countDelete >= 1 && countInsert >= 1) {
1925
+ diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert), pointer = pointer - countDelete - countInsert;
1926
+ const aa = doDiff(textDelete, textInsert, {
1927
+ checkLines: !1,
1928
+ deadline: opts.deadline
1929
+ });
1930
+ for (let j = aa.length - 1; j >= 0; j--)
1931
+ diffs.splice(pointer, 0, aa[j]);
1932
+ pointer += aa.length;
1933
+ }
1934
+ countInsert = 0, countDelete = 0, textDelete = "", textInsert = "";
1935
+ break;
1936
+ default:
1937
+ throw new Error("Unknown diff operation.");
1938
+ }
1939
+ pointer++;
1940
+ }
1941
+ return diffs.pop(), diffs;
1942
+ }
1943
+ function computeDiff(text1, text2, opts) {
1944
+ let diffs;
1945
+ if (!text1)
1946
+ return [[DIFF_INSERT, text2]];
1947
+ if (!text2)
1948
+ return [[DIFF_DELETE, text1]];
1949
+ const longtext = text1.length > text2.length ? text1 : text2, shorttext = text1.length > text2.length ? text2 : text1, i = longtext.indexOf(shorttext);
1950
+ if (i !== -1)
1951
+ return diffs = [[DIFF_INSERT, longtext.substring(0, i)], [DIFF_EQUAL, shorttext], [DIFF_INSERT, longtext.substring(i + shorttext.length)]], text1.length > text2.length && (diffs[0][0] = DIFF_DELETE, diffs[2][0] = DIFF_DELETE), diffs;
1952
+ if (shorttext.length === 1)
1953
+ return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
1954
+ const halfMatch = findHalfMatch(text1, text2);
1955
+ if (halfMatch) {
1956
+ const text1A = halfMatch[0], text1B = halfMatch[1], text2A = halfMatch[2], text2B = halfMatch[3], midCommon = halfMatch[4], diffsA = doDiff(text1A, text2A, opts), diffsB = doDiff(text1B, text2B, opts);
1957
+ return diffsA.concat([[DIFF_EQUAL, midCommon]], diffsB);
1958
+ }
1959
+ return opts.checkLines && text1.length > 100 && text2.length > 100 ? doLineModeDiff(text1, text2, opts) : bisect(text1, text2, opts.deadline);
1960
+ }
1961
+ const DIFF_DELETE = -1, DIFF_INSERT = 1, DIFF_EQUAL = 0;
1962
+ function diff(textA, textB, opts) {
1963
+ if (textA === null || textB === null)
1964
+ throw new Error("Null input. (diff)");
1965
+ const diffs = doDiff(textA, textB, createInternalOpts(opts || {}));
1966
+ return adjustDiffForSurrogatePairs(diffs), diffs;
1967
+ }
1968
+ function doDiff(textA, textB, options) {
1969
+ let text1 = textA, text2 = textB;
1970
+ if (text1 === text2)
1971
+ return text1 ? [[DIFF_EQUAL, text1]] : [];
1972
+ let commonlength = getCommonPrefix(text1, text2);
1973
+ const commonprefix = text1.substring(0, commonlength);
1974
+ text1 = text1.substring(commonlength), text2 = text2.substring(commonlength), commonlength = getCommonSuffix(text1, text2);
1975
+ const commonsuffix = text1.substring(text1.length - commonlength);
1976
+ text1 = text1.substring(0, text1.length - commonlength), text2 = text2.substring(0, text2.length - commonlength);
1977
+ let diffs = computeDiff(text1, text2, options);
1978
+ return commonprefix && diffs.unshift([DIFF_EQUAL, commonprefix]), commonsuffix && diffs.push([DIFF_EQUAL, commonsuffix]), diffs = cleanupMerge(diffs), diffs;
1979
+ }
1980
+ function createDeadLine(timeout) {
1981
+ let t = 1;
1982
+ return typeof timeout < "u" && (t = timeout <= 0 ? Number.MAX_VALUE : timeout), Date.now() + t * 1e3;
1983
+ }
1984
+ function createInternalOpts(opts) {
1985
+ return __spreadValues({
1986
+ checkLines: !0,
1987
+ deadline: createDeadLine(opts.timeout || 1)
1988
+ }, opts);
1989
+ }
1990
+ function combineChar(data, char, dir) {
1991
+ return dir === 1 ? data + char : char + data;
1992
+ }
1993
+ function splitChar(data, dir) {
1994
+ return dir === 1 ? [data.substring(0, data.length - 1), data[data.length - 1]] : [data.substring(1), data[0]];
1995
+ }
1996
+ function hasSharedChar(diffs, i, j, dir) {
1997
+ return dir === 1 ? diffs[i][1][diffs[i][1].length - 1] === diffs[j][1][diffs[j][1].length - 1] : diffs[i][1][0] === diffs[j][1][0];
1998
+ }
1999
+ function deisolateChar(diffs, i, dir) {
2000
+ const inv = dir === 1 ? -1 : 1;
2001
+ let insertIdx = null, deleteIdx = null, j = i + dir;
2002
+ for (; j >= 0 && j < diffs.length && (insertIdx === null || deleteIdx === null); j += dir) {
2003
+ const [op, text2] = diffs[j];
2004
+ if (text2.length !== 0) {
2005
+ if (op === DIFF_INSERT) {
2006
+ insertIdx === null && (insertIdx = j);
2007
+ continue;
2008
+ } else if (op === DIFF_DELETE) {
2009
+ deleteIdx === null && (deleteIdx = j);
2010
+ continue;
2011
+ } else if (op === DIFF_EQUAL) {
2012
+ if (insertIdx === null && deleteIdx === null) {
2013
+ const [rest, char2] = splitChar(diffs[i][1], dir);
2014
+ diffs[i][1] = rest, diffs[j][1] = combineChar(diffs[j][1], char2, inv);
2015
+ return;
2016
+ }
2017
+ break;
2018
+ }
2019
+ }
2020
+ }
2021
+ if (insertIdx !== null && deleteIdx !== null && hasSharedChar(diffs, insertIdx, deleteIdx, dir)) {
2022
+ const [insertText, insertChar] = splitChar(diffs[insertIdx][1], inv), [deleteText] = splitChar(diffs[deleteIdx][1], inv);
2023
+ diffs[insertIdx][1] = insertText, diffs[deleteIdx][1] = deleteText, diffs[i][1] = combineChar(diffs[i][1], insertChar, dir);
2024
+ return;
2025
+ }
2026
+ const [text, char] = splitChar(diffs[i][1], dir);
2027
+ diffs[i][1] = text, insertIdx === null ? (diffs.splice(j, 0, [DIFF_INSERT, char]), deleteIdx !== null && deleteIdx >= j && deleteIdx++) : diffs[insertIdx][1] = combineChar(diffs[insertIdx][1], char, inv), deleteIdx === null ? diffs.splice(j, 0, [DIFF_DELETE, char]) : diffs[deleteIdx][1] = combineChar(diffs[deleteIdx][1], char, inv);
2028
+ }
2029
+ function adjustDiffForSurrogatePairs(diffs) {
2030
+ for (let i = 0; i < diffs.length; i++) {
2031
+ const [diffType, diffText] = diffs[i];
2032
+ if (diffText.length === 0)
2033
+ continue;
2034
+ const firstChar = diffText[0], lastChar = diffText[diffText.length - 1];
2035
+ isHighSurrogate(lastChar) && diffType === DIFF_EQUAL && deisolateChar(diffs, i, 1), isLowSurrogate(firstChar) && diffType === DIFF_EQUAL && deisolateChar(diffs, i, -1);
2036
+ }
2037
+ for (let i = 0; i < diffs.length; i++)
2038
+ diffs[i][1].length === 0 && diffs.splice(i, 1);
2039
+ }
2040
+ const DEFAULT_OPTIONS = {
2041
+ /**
2042
+ * At what point is no match declared (0.0 = perfection, 1.0 = very loose).
2043
+ */
2044
+ threshold: 0.5,
2045
+ /**
2046
+ * How far to search for a match (0 = exact location, 1000+ = broad match).
2047
+ * A match this many characters away from the expected location will add
2048
+ * 1.0 to the score (0.0 is a perfect match).
2049
+ */
2050
+ distance: 1e3
2051
+ };
2052
+ function applyDefaults(options) {
2053
+ return __spreadValues(__spreadValues({}, DEFAULT_OPTIONS), options);
2054
+ }
2055
+ const MAX_BITS$1 = 32;
2056
+ function bitap(text, pattern, loc) {
2057
+ let opts = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
2058
+ if (pattern.length > MAX_BITS$1)
2059
+ throw new Error("Pattern too long for this browser.");
2060
+ const options = applyDefaults(opts), s = getAlphabetFromPattern(pattern);
2061
+ function getBitapScore(e, x) {
2062
+ const accuracy = e / pattern.length, proximity = Math.abs(loc - x);
2063
+ return options.distance ? accuracy + proximity / options.distance : proximity ? 1 : accuracy;
2064
+ }
2065
+ let scoreThreshold = options.threshold, bestLoc = text.indexOf(pattern, loc);
2066
+ bestLoc !== -1 && (scoreThreshold = Math.min(getBitapScore(0, bestLoc), scoreThreshold), bestLoc = text.lastIndexOf(pattern, loc + pattern.length), bestLoc !== -1 && (scoreThreshold = Math.min(getBitapScore(0, bestLoc), scoreThreshold)));
2067
+ const matchmask = 1 << pattern.length - 1;
2068
+ bestLoc = -1;
2069
+ let binMin, binMid, binMax = pattern.length + text.length, lastRd = [];
2070
+ for (let d = 0; d < pattern.length; d++) {
2071
+ for (binMin = 0, binMid = binMax; binMin < binMid; )
2072
+ getBitapScore(d, loc + binMid) <= scoreThreshold ? binMin = binMid : binMax = binMid, binMid = Math.floor((binMax - binMin) / 2 + binMin);
2073
+ binMax = binMid;
2074
+ let start = Math.max(1, loc - binMid + 1);
2075
+ const finish = Math.min(loc + binMid, text.length) + pattern.length, rd = new Array(finish + 2);
2076
+ rd[finish + 1] = (1 << d) - 1;
2077
+ for (let j = finish; j >= start; j--) {
2078
+ const charMatch = s[text.charAt(j - 1)];
2079
+ if (d === 0 ? rd[j] = (rd[j + 1] << 1 | 1) & charMatch : rd[j] = (rd[j + 1] << 1 | 1) & charMatch | ((lastRd[j + 1] | lastRd[j]) << 1 | 1) | lastRd[j + 1], rd[j] & matchmask) {
2080
+ const score = getBitapScore(d, j - 1);
2081
+ if (score <= scoreThreshold)
2082
+ if (scoreThreshold = score, bestLoc = j - 1, bestLoc > loc)
2083
+ start = Math.max(1, 2 * loc - bestLoc);
2084
+ else
2085
+ break;
2086
+ }
2087
+ }
2088
+ if (getBitapScore(d + 1, loc) > scoreThreshold)
2089
+ break;
2090
+ lastRd = rd;
2091
+ }
2092
+ return bestLoc;
2093
+ }
2094
+ function getAlphabetFromPattern(pattern) {
2095
+ const s = {};
2096
+ for (let i = 0; i < pattern.length; i++)
2097
+ s[pattern.charAt(i)] = 0;
2098
+ for (let i = 0; i < pattern.length; i++)
2099
+ s[pattern.charAt(i)] |= 1 << pattern.length - i - 1;
2100
+ return s;
2101
+ }
2102
+ function match(text, pattern, searchLocation) {
2103
+ if (text === null || pattern === null || searchLocation === null)
2104
+ throw new Error("Null input. (match())");
2105
+ const loc = Math.max(0, Math.min(searchLocation, text.length));
2106
+ if (text === pattern)
2107
+ return 0;
2108
+ if (text.length) {
2109
+ if (text.substring(loc, loc + pattern.length) === pattern)
2110
+ return loc;
2111
+ } else
2112
+ return -1;
2113
+ return bitap(text, pattern, loc);
2114
+ }
2115
+ function createPatchObject(start1, start2) {
2116
+ return {
2117
+ diffs: [],
2118
+ start1,
2119
+ start2,
2120
+ utf8Start1: start1,
2121
+ utf8Start2: start2,
2122
+ length1: 0,
2123
+ length2: 0,
2124
+ utf8Length1: 0,
2125
+ utf8Length2: 0
2126
+ };
2127
+ }
2128
+ function diffText1(diffs) {
2129
+ const text = [];
2130
+ for (let x = 0; x < diffs.length; x++)
2131
+ diffs[x][0] !== DIFF_INSERT && (text[x] = diffs[x][1]);
2132
+ return text.join("");
2133
+ }
2134
+ function diffText2(diffs) {
2135
+ const text = [];
2136
+ for (let x = 0; x < diffs.length; x++)
2137
+ diffs[x][0] !== DIFF_DELETE && (text[x] = diffs[x][1]);
2138
+ return text.join("");
2139
+ }
2140
+ function countUtf8Bytes(str) {
2141
+ let bytes = 0;
2142
+ for (let i = 0; i < str.length; i++) {
2143
+ const codePoint = str.codePointAt(i);
2144
+ if (typeof codePoint > "u")
2145
+ throw new Error("Failed to get codepoint");
2146
+ bytes += utf8len(codePoint);
2147
+ }
2148
+ return bytes;
2149
+ }
2150
+ function adjustIndiciesToUcs2(patches, base) {
2151
+ let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}, byteOffset = 0, idx = 0;
2152
+ function advanceTo(target) {
2153
+ for (; byteOffset < target; ) {
2154
+ const codePoint = base.codePointAt(idx);
2155
+ if (typeof codePoint > "u")
2156
+ return idx;
2157
+ byteOffset += utf8len(codePoint), codePoint > 65535 ? idx += 2 : idx += 1;
2158
+ }
2159
+ if (!options.allowExceedingIndices && byteOffset !== target)
2160
+ throw new Error("Failed to determine byte offset");
2161
+ return idx;
2162
+ }
2163
+ const adjusted = [];
2164
+ for (const patch of patches)
2165
+ adjusted.push({
2166
+ diffs: patch.diffs.map((diff2) => cloneDiff(diff2)),
2167
+ start1: advanceTo(patch.start1),
2168
+ start2: advanceTo(patch.start2),
2169
+ utf8Start1: patch.utf8Start1,
2170
+ utf8Start2: patch.utf8Start2,
2171
+ length1: patch.length1,
2172
+ length2: patch.length2,
2173
+ utf8Length1: patch.utf8Length1,
2174
+ utf8Length2: patch.utf8Length2
2175
+ });
2176
+ return adjusted;
2177
+ }
2178
+ function utf8len(codePoint) {
2179
+ return codePoint <= 127 ? 1 : codePoint <= 2047 ? 2 : codePoint <= 65535 ? 3 : 4;
2180
+ }
2181
+ const MAX_BITS = 32, DEFAULT_MARGIN = 4;
2182
+ function levenshtein(diffs) {
2183
+ let leven = 0, insertions = 0, deletions = 0;
2184
+ for (let x = 0; x < diffs.length; x++) {
2185
+ const op = diffs[x][0], data = diffs[x][1];
2186
+ switch (op) {
2187
+ case DIFF_INSERT:
2188
+ insertions += data.length;
2189
+ break;
2190
+ case DIFF_DELETE:
2191
+ deletions += data.length;
2192
+ break;
2193
+ case DIFF_EQUAL:
2194
+ leven += Math.max(insertions, deletions), insertions = 0, deletions = 0;
2195
+ break;
2196
+ default:
2197
+ throw new Error("Unknown diff operation.");
2198
+ }
2199
+ }
2200
+ return leven += Math.max(insertions, deletions), leven;
2201
+ }
2202
+ function xIndex(diffs, loc) {
2203
+ let chars1 = 0, chars2 = 0, lastChars1 = 0, lastChars2 = 0, x;
2204
+ for (x = 0; x < diffs.length && (diffs[x][0] !== DIFF_INSERT && (chars1 += diffs[x][1].length), diffs[x][0] !== DIFF_DELETE && (chars2 += diffs[x][1].length), !(chars1 > loc)); x++)
2205
+ lastChars1 = chars1, lastChars2 = chars2;
2206
+ return diffs.length !== x && diffs[x][0] === DIFF_DELETE ? lastChars2 : lastChars2 + (loc - lastChars1);
2207
+ }
2208
+ function addPadding(patches) {
2209
+ const paddingLength = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : DEFAULT_MARGIN;
2210
+ let nullPadding = "";
2211
+ for (let x = 1; x <= paddingLength; x++)
2212
+ nullPadding += String.fromCharCode(x);
2213
+ for (const p of patches)
2214
+ p.start1 += paddingLength, p.start2 += paddingLength, p.utf8Start1 += paddingLength, p.utf8Start2 += paddingLength;
2215
+ let patch = patches[0], diffs = patch.diffs;
2216
+ if (diffs.length === 0 || diffs[0][0] !== DIFF_EQUAL)
2217
+ diffs.unshift([DIFF_EQUAL, nullPadding]), patch.start1 -= paddingLength, patch.start2 -= paddingLength, patch.utf8Start1 -= paddingLength, patch.utf8Start2 -= paddingLength, patch.length1 += paddingLength, patch.length2 += paddingLength, patch.utf8Length1 += paddingLength, patch.utf8Length2 += paddingLength;
2218
+ else if (paddingLength > diffs[0][1].length) {
2219
+ const firstDiffLength = diffs[0][1].length, extraLength = paddingLength - firstDiffLength;
2220
+ diffs[0][1] = nullPadding.substring(firstDiffLength) + diffs[0][1], patch.start1 -= extraLength, patch.start2 -= extraLength, patch.utf8Start1 -= extraLength, patch.utf8Start2 -= extraLength, patch.length1 += extraLength, patch.length2 += extraLength, patch.utf8Length1 += extraLength, patch.utf8Length2 += extraLength;
2221
+ }
2222
+ if (patch = patches[patches.length - 1], diffs = patch.diffs, diffs.length === 0 || diffs[diffs.length - 1][0] !== DIFF_EQUAL)
2223
+ diffs.push([DIFF_EQUAL, nullPadding]), patch.length1 += paddingLength, patch.length2 += paddingLength, patch.utf8Length1 += paddingLength, patch.utf8Length2 += paddingLength;
2224
+ else if (paddingLength > diffs[diffs.length - 1][1].length) {
2225
+ const extraLength = paddingLength - diffs[diffs.length - 1][1].length;
2226
+ diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength), patch.length1 += extraLength, patch.length2 += extraLength, patch.utf8Length1 += extraLength, patch.utf8Length2 += extraLength;
2227
+ }
2228
+ return nullPadding;
2229
+ }
2230
+ function splitMax(patches) {
2231
+ let margin = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : DEFAULT_MARGIN;
2232
+ const patchSize = MAX_BITS;
2233
+ for (let x = 0; x < patches.length; x++) {
2234
+ if (patches[x].length1 <= patchSize)
2235
+ continue;
2236
+ const bigpatch = patches[x];
2237
+ patches.splice(x--, 1);
2238
+ let start1 = bigpatch.start1, start2 = bigpatch.start2, preContext = "";
2239
+ for (; bigpatch.diffs.length !== 0; ) {
2240
+ const patch = createPatchObject(start1 - preContext.length, start2 - preContext.length);
2241
+ let empty = !0;
2242
+ if (preContext !== "") {
2243
+ const precontextByteCount = countUtf8Bytes(preContext);
2244
+ patch.length1 = preContext.length, patch.utf8Length1 = precontextByteCount, patch.length2 = preContext.length, patch.utf8Length2 = precontextByteCount, patch.diffs.push([DIFF_EQUAL, preContext]);
2245
+ }
2246
+ for (; bigpatch.diffs.length !== 0 && patch.length1 < patchSize - margin; ) {
2247
+ const diffType = bigpatch.diffs[0][0];
2248
+ let diffText = bigpatch.diffs[0][1], diffTextByteCount = countUtf8Bytes(diffText);
2249
+ if (diffType === DIFF_INSERT) {
2250
+ patch.length2 += diffText.length, patch.utf8Length2 += diffTextByteCount, start2 += diffText.length;
2251
+ const diff2 = bigpatch.diffs.shift();
2252
+ diff2 && patch.diffs.push(diff2), empty = !1;
2253
+ } else
2254
+ diffType === DIFF_DELETE && patch.diffs.length === 1 && patch.diffs[0][0] === DIFF_EQUAL && diffText.length > 2 * patchSize ? (patch.length1 += diffText.length, patch.utf8Length1 += diffTextByteCount, start1 += diffText.length, empty = !1, patch.diffs.push([diffType, diffText]), bigpatch.diffs.shift()) : (diffText = diffText.substring(0, patchSize - patch.length1 - margin), diffTextByteCount = countUtf8Bytes(diffText), patch.length1 += diffText.length, patch.utf8Length1 += diffTextByteCount, start1 += diffText.length, diffType === DIFF_EQUAL ? (patch.length2 += diffText.length, patch.utf8Length2 += diffTextByteCount, start2 += diffText.length) : empty = !1, patch.diffs.push([diffType, diffText]), diffText === bigpatch.diffs[0][1] ? bigpatch.diffs.shift() : bigpatch.diffs[0][1] = bigpatch.diffs[0][1].substring(diffText.length));
2255
+ }
2256
+ preContext = diffText2(patch.diffs), preContext = preContext.substring(preContext.length - margin);
2257
+ const postContext = diffText1(bigpatch.diffs).substring(0, margin), postContextByteCount = countUtf8Bytes(postContext);
2258
+ postContext !== "" && (patch.length1 += postContext.length, patch.length2 += postContext.length, patch.utf8Length1 += postContextByteCount, patch.utf8Length2 += postContextByteCount, patch.diffs.length !== 0 && patch.diffs[patch.diffs.length - 1][0] === DIFF_EQUAL ? patch.diffs[patch.diffs.length - 1][1] += postContext : patch.diffs.push([DIFF_EQUAL, postContext])), empty || patches.splice(++x, 0, patch);
2259
+ }
2260
+ }
2261
+ }
2262
+ function apply(patches, originalText) {
2263
+ let opts = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
2264
+ if (typeof patches == "string")
2265
+ throw new Error("Patches must be an array - pass the patch to `parsePatch()` first");
2266
+ let text = originalText;
2267
+ if (patches.length === 0)
2268
+ return [text, []];
2269
+ const parsed = adjustIndiciesToUcs2(patches, text, {
2270
+ allowExceedingIndices: opts.allowExceedingIndices
2271
+ }), margin = opts.margin || DEFAULT_MARGIN, deleteThreshold = opts.deleteThreshold || 0.4, nullPadding = addPadding(parsed, margin);
2272
+ text = nullPadding + text + nullPadding, splitMax(parsed, margin);
2273
+ let delta = 0;
2274
+ const results = [];
2275
+ for (let x = 0; x < parsed.length; x++) {
2276
+ const expectedLoc = parsed[x].start2 + delta, text1 = diffText1(parsed[x].diffs);
2277
+ let startLoc, endLoc = -1;
2278
+ if (text1.length > MAX_BITS ? (startLoc = match(text, text1.substring(0, MAX_BITS), expectedLoc), startLoc !== -1 && (endLoc = match(text, text1.substring(text1.length - MAX_BITS), expectedLoc + text1.length - MAX_BITS), (endLoc === -1 || startLoc >= endLoc) && (startLoc = -1))) : startLoc = match(text, text1, expectedLoc), startLoc === -1)
2279
+ results[x] = !1, delta -= parsed[x].length2 - parsed[x].length1;
2280
+ else {
2281
+ results[x] = !0, delta = startLoc - expectedLoc;
2282
+ let text2;
2283
+ if (endLoc === -1 ? text2 = text.substring(startLoc, startLoc + text1.length) : text2 = text.substring(startLoc, endLoc + MAX_BITS), text1 === text2)
2284
+ text = text.substring(0, startLoc) + diffText2(parsed[x].diffs) + text.substring(startLoc + text1.length);
2285
+ else {
2286
+ let diffs = diff(text1, text2, {
2287
+ checkLines: !1
2288
+ });
2289
+ if (text1.length > MAX_BITS && levenshtein(diffs) / text1.length > deleteThreshold)
2290
+ results[x] = !1;
2291
+ else {
2292
+ diffs = cleanupSemanticLossless(diffs);
2293
+ let index1 = 0, index2 = 0;
2294
+ for (let y = 0; y < parsed[x].diffs.length; y++) {
2295
+ const mod = parsed[x].diffs[y];
2296
+ mod[0] !== DIFF_EQUAL && (index2 = xIndex(diffs, index1)), mod[0] === DIFF_INSERT ? text = text.substring(0, startLoc + index2) + mod[1] + text.substring(startLoc + index2) : mod[0] === DIFF_DELETE && (text = text.substring(0, startLoc + index2) + text.substring(startLoc + xIndex(diffs, index1 + mod[1].length))), mod[0] !== DIFF_DELETE && (index1 += mod[1].length);
2297
+ }
2298
+ }
2299
+ }
2300
+ }
2301
+ }
2302
+ return text = text.substring(nullPadding.length, text.length - nullPadding.length), [text, results];
2303
+ }
2304
+ const patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;
2305
+ function parse(textline) {
2306
+ if (!textline)
2307
+ return [];
2308
+ const patches = [], lines = textline.split(`
2309
+ `);
2310
+ let textPointer = 0;
2311
+ for (; textPointer < lines.length; ) {
2312
+ const m = lines[textPointer].match(patchHeader);
2313
+ if (!m)
2314
+ throw new Error("Invalid patch string: ".concat(lines[textPointer]));
2315
+ const patch = createPatchObject(toInt(m[1]), toInt(m[3]));
2316
+ for (patches.push(patch), m[2] === "" ? (patch.start1--, patch.utf8Start1--, patch.length1 = 1, patch.utf8Length1 = 1) : m[2] === "0" ? (patch.length1 = 0, patch.utf8Length1 = 0) : (patch.start1--, patch.utf8Start1--, patch.utf8Length1 = toInt(m[2]), patch.length1 = patch.utf8Length1), m[4] === "" ? (patch.start2--, patch.utf8Start2--, patch.length2 = 1, patch.utf8Length2 = 1) : m[4] === "0" ? (patch.length2 = 0, patch.utf8Length2 = 0) : (patch.start2--, patch.utf8Start2--, patch.utf8Length2 = toInt(m[4]), patch.length2 = patch.utf8Length2), textPointer++; textPointer < lines.length; ) {
2317
+ const currentLine = lines[textPointer], sign = currentLine.charAt(0);
2318
+ if (sign === "@")
2319
+ break;
2320
+ if (sign === "") {
2321
+ textPointer++;
2322
+ continue;
2323
+ }
2324
+ let line;
2325
+ try {
2326
+ line = decodeURI(currentLine.slice(1));
2327
+ } catch (ex) {
2328
+ throw new Error("Illegal escape in parse: ".concat(currentLine));
2329
+ }
2330
+ const utf8Diff = countUtf8Bytes(line) - line.length;
2331
+ if (sign === "-")
2332
+ patch.diffs.push([DIFF_DELETE, line]), patch.length1 -= utf8Diff;
2333
+ else if (sign === "+")
2334
+ patch.diffs.push([DIFF_INSERT, line]), patch.length2 -= utf8Diff;
2335
+ else if (sign === " ")
2336
+ patch.diffs.push([DIFF_EQUAL, line]), patch.length1 -= utf8Diff, patch.length2 -= utf8Diff;
2337
+ else
2338
+ throw new Error('Invalid patch mode "'.concat(sign, '" in: ').concat(line));
2339
+ textPointer++;
2340
+ }
2341
+ }
2342
+ return patches;
2343
+ }
2344
+ function toInt(num) {
2345
+ return parseInt(num, 10);
2346
+ }
2347
+ var baseGetTag = _baseGetTag, isObjectLike = isObjectLike_1, symbolTag = "[object Symbol]";
2348
+ function isSymbol$1(value) {
2349
+ return typeof value == "symbol" || isObjectLike(value) && baseGetTag(value) == symbolTag;
2350
+ }
2351
+ var isSymbol_1 = isSymbol$1, isSymbol = isSymbol_1;
2352
+ function baseExtremum$2(array, iteratee, comparator) {
2353
+ for (var index = -1, length = array.length; ++index < length; ) {
2354
+ var value = array[index], current = iteratee(value);
2355
+ if (current != null && (computed === void 0 ? current === current && !isSymbol(current) : comparator(current, computed)))
2356
+ var computed = current, result = value;
2357
+ }
2358
+ return result;
2359
+ }
2360
+ var _baseExtremum = baseExtremum$2;
2361
+ function baseGt$1(value, other) {
2362
+ return value > other;
2363
+ }
2364
+ var _baseGt = baseGt$1;
2365
+ function identity$2(value) {
2366
+ return value;
2367
+ }
2368
+ var identity_1 = identity$2, baseExtremum$1 = _baseExtremum, baseGt = _baseGt, identity$1 = identity_1;
2369
+ function max(array) {
2370
+ return array && array.length ? baseExtremum$1(array, identity$1, baseGt) : void 0;
2371
+ }
2372
+ var max_1 = max, max$1 = /* @__PURE__ */ getDefaultExportFromCjs(max_1);
2373
+ function baseLt$1(value, other) {
2374
+ return value < other;
2375
+ }
2376
+ var _baseLt = baseLt$1, baseExtremum = _baseExtremum, baseLt = _baseLt, identity = identity_1;
2377
+ function min(array) {
2378
+ return array && array.length ? baseExtremum(array, identity, baseLt) : void 0;
2379
+ }
2380
+ var min_1 = min, min$1 = /* @__PURE__ */ getDefaultExportFromCjs(min_1);
2381
+ function compact(array) {
2382
+ for (var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; ++index < length; ) {
2383
+ var value = array[index];
2384
+ value && (result[resIndex++] = value);
2385
+ }
2386
+ return result;
2387
+ }
2388
+ var compact_1 = compact, compact$1 = /* @__PURE__ */ getDefaultExportFromCjs(compact_1);
2389
+ const debug = debugIt("mutator-document");
2390
+ var __defProp$h = Object.defineProperty, __defNormalProp$h = (obj, key, value) => key in obj ? __defProp$h(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __publicField$h = (obj, key, value) => __defNormalProp$h(obj, typeof key != "symbol" ? key + "" : key, value);
2391
+ class ImmutableAccessor {
2392
+ constructor(value, path) {
2393
+ __publicField$h(this, "_value"), __publicField$h(this, "path"), this._value = value, this.path = path || [];
2394
+ }
2395
+ containerType() {
2396
+ return Array.isArray(this._value) ? "array" : this._value !== null && typeof this._value == "object" ? "object" : "primitive";
2397
+ }
2398
+ // Common reader, supported by all containers
2399
+ get() {
2400
+ return this._value;
2401
+ }
2402
+ // Array reader
2403
+ length() {
2404
+ if (!Array.isArray(this._value))
2405
+ throw new Error("Won't return length of non-indexable _value");
2406
+ return this._value.length;
2407
+ }
2408
+ getIndex(i) {
2409
+ return Array.isArray(this._value) ? i >= this.length() ? null : new ImmutableAccessor(this._value[i], this.path.concat(i)) : !1;
2410
+ }
2411
+ // Object reader
2412
+ hasAttribute(key) {
2413
+ return isRecord$1(this._value) ? this._value.hasOwnProperty(key) : !1;
2414
+ }
2415
+ attributeKeys() {
2416
+ return isRecord$1(this._value) ? Object.keys(this._value) : [];
2417
+ }
2418
+ getAttribute(key) {
2419
+ if (!isRecord$1(this._value))
2420
+ throw new Error("getAttribute only applies to plain objects");
2421
+ return this.hasAttribute(key) ? new ImmutableAccessor(this._value[key], this.path.concat(key)) : null;
2422
+ }
2423
+ // Common writer, supported by all containers
2424
+ set(value) {
2425
+ return value === this._value ? this : new ImmutableAccessor(value, this.path);
2426
+ }
2427
+ // array writer interface
2428
+ setIndex(i, value) {
2429
+ if (!Array.isArray(this._value))
2430
+ throw new Error("setIndex only applies to arrays");
2431
+ if (Object.is(value, this._value[i]))
2432
+ return this;
2433
+ const nextValue = this._value.slice();
2434
+ return nextValue[i] = value, new ImmutableAccessor(nextValue, this.path);
2435
+ }
2436
+ setIndexAccessor(i, accessor) {
2437
+ return this.setIndex(i, accessor.get());
2438
+ }
2439
+ unsetIndices(indices) {
2440
+ if (!Array.isArray(this._value))
2441
+ throw new Error("unsetIndices only applies to arrays");
2442
+ const length = this._value.length, nextValue = [];
2443
+ for (let i = 0; i < length; i++)
2444
+ indices.indexOf(i) === -1 && nextValue.push(this._value[i]);
2445
+ return new ImmutableAccessor(nextValue, this.path);
2446
+ }
2447
+ insertItemsAt(pos, items) {
2448
+ if (!Array.isArray(this._value))
2449
+ throw new Error("insertItemsAt only applies to arrays");
2450
+ let nextValue;
2451
+ return this._value.length === 0 && pos === 0 ? nextValue = items : nextValue = this._value.slice(0, pos).concat(items).concat(this._value.slice(pos)), new ImmutableAccessor(nextValue, this.path);
2452
+ }
2453
+ // Object writer interface
2454
+ setAttribute(key, value) {
2455
+ if (!isRecord$1(this._value))
2456
+ throw new Error("Unable to set attribute of non-object container");
2457
+ if (Object.is(value, this._value[key]))
2458
+ return this;
2459
+ const nextValue = Object.assign({}, this._value, { [key]: value });
2460
+ return new ImmutableAccessor(nextValue, this.path);
2461
+ }
2462
+ setAttributeAccessor(key, accessor) {
2463
+ return this.setAttribute(key, accessor.get());
2464
+ }
2465
+ unsetAttribute(key) {
2466
+ if (!isRecord$1(this._value))
2467
+ throw new Error("Unable to unset attribute of non-object container");
2468
+ const nextValue = Object.assign({}, this._value);
2469
+ return delete nextValue[key], new ImmutableAccessor(nextValue, this.path);
2470
+ }
2471
+ }
2472
+ function isRecord$1(value) {
2473
+ return value !== null && typeof value == "object";
2474
+ }
2475
+ function isRecord(value) {
2476
+ return value !== null && typeof value == "object";
2477
+ }
2478
+ function descend$1(tail) {
2479
+ const [head, newTail] = splitIfPath(tail);
2480
+ if (!head)
2481
+ throw new Error("Head cannot be null");
2482
+ return spreadIfUnionHead(head, newTail);
2483
+ }
2484
+ function splitIfPath(tail) {
2485
+ if (tail.type !== "path")
2486
+ return [tail, null];
2487
+ const nodes = tail.nodes;
2488
+ return nodes.length === 0 ? [null, null] : nodes.length === 1 ? [nodes[0], null] : [nodes[0], { type: "path", nodes: nodes.slice(1) }];
2489
+ }
2490
+ function concatPaths(path1, path2) {
2491
+ if (!path1 && !path2)
2492
+ return null;
2493
+ const nodes1 = path1 ? path1.nodes : [], nodes2 = path2 ? path2.nodes : [];
2494
+ return {
2495
+ type: "path",
2496
+ nodes: nodes1.concat(nodes2)
2497
+ };
2498
+ }
2499
+ function spreadIfUnionHead(head, tail) {
2500
+ return head.type !== "union" ? [[head, tail]] : head.nodes.map((node2) => {
2501
+ if (node2.type === "path") {
2502
+ const [subHead, subTail] = splitIfPath(node2);
2503
+ return [subHead, concatPaths(subTail, tail)];
2504
+ }
2505
+ return [node2, tail];
2506
+ });
2507
+ }
2508
+ var __defProp$g = Object.defineProperty, __defNormalProp$g = (obj, key, value) => key in obj ? __defProp$g(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __publicField$g = (obj, key, value) => __defNormalProp$g(obj, typeof key != "symbol" ? key + "" : key, value);
2509
+ const digitChar = /[0-9]/, attributeCharMatcher = /^[a-zA-Z0-9_]$/, attributeFirstCharMatcher = /^[a-zA-Z_]$/, symbols = {
2510
+ // NOTE: These are compared against in order of definition,
2511
+ // thus '==' must come before '=', '>=' before '>', etc.
2512
+ operator: ["..", ".", ",", ":", "?"],
2513
+ comparator: [">=", "<=", "<", ">", "==", "!="],
2514
+ keyword: ["$", "@"],
2515
+ boolean: ["true", "false"],
2516
+ paren: ["[", "]"]
2517
+ }, symbolClasses = Object.keys(symbols);
2518
+ class Tokenizer {
2519
+ constructor(path) {
2520
+ __publicField$g(this, "source"), __publicField$g(this, "i"), __publicField$g(this, "length"), __publicField$g(this, "tokenizers"), this.source = path, this.length = path.length, this.i = 0, this.tokenizers = [
2521
+ this.tokenizeSymbol,
2522
+ this.tokenizeIdentifier,
2523
+ this.tokenizeNumber,
2524
+ this.tokenizeQuoted
2525
+ ].map((fn) => fn.bind(this));
2526
+ }
2527
+ tokenize() {
2528
+ const result = [];
2529
+ for (; !this.EOF(); ) {
2530
+ this.chompWhitespace();
2531
+ let token = null;
2532
+ if (!this.tokenizers.some((tokenizer) => (token = tokenizer(), !!token)) || !token)
2533
+ throw new Error(`Invalid tokens in jsonpath '${this.source}' @ ${this.i}`);
2534
+ result.push(token);
2535
+ }
2536
+ return result;
2537
+ }
2538
+ takeWhile(fn) {
2539
+ const start = this.i;
2540
+ let result = "";
2541
+ for (; !this.EOF(); ) {
2542
+ const nextChar = fn(this.source[this.i]);
2543
+ if (nextChar === null)
2544
+ break;
2545
+ result += nextChar, this.i++;
2546
+ }
2547
+ return this.i === start ? null : result;
2548
+ }
2549
+ EOF() {
2550
+ return this.i >= this.length;
2551
+ }
2552
+ peek() {
2553
+ return this.EOF() ? null : this.source[this.i];
2554
+ }
2555
+ consume(str) {
2556
+ if (this.i + str.length > this.length)
2557
+ throw new Error(`Expected ${str} at end of jsonpath`);
2558
+ if (str === this.source.slice(this.i, this.i + str.length))
2559
+ this.i += str.length;
2560
+ else
2561
+ throw new Error(`Expected "${str}", but source contained "${this.source.slice()}`);
2562
+ }
2563
+ // Tries to match the upcoming bit of string with the provided string. If it matches, returns
2564
+ // the string, then advances the read pointer to the next bit. If not, returns null and nothing
2565
+ // happens.
2566
+ tryConsume(str) {
2567
+ if (this.i + str.length > this.length)
2568
+ return null;
2569
+ if (str === this.source.slice(this.i, this.i + str.length)) {
2570
+ if (str[0].match(attributeCharMatcher) && this.length > this.i + str.length) {
2571
+ const nextChar = this.source[this.i + str.length];
2572
+ if (nextChar && nextChar.match(attributeCharMatcher))
2573
+ return null;
2574
+ }
2575
+ return this.i += str.length, str;
2576
+ }
2577
+ return null;
2578
+ }
2579
+ chompWhitespace() {
2580
+ this.takeWhile((char) => char === " " ? "" : null);
2581
+ }
2582
+ tokenizeQuoted() {
2583
+ const quote = this.peek();
2584
+ if (quote === "'" || quote === '"') {
2585
+ this.consume(quote);
2586
+ let escape = !1;
2587
+ const inner = this.takeWhile((char) => escape ? (escape = !1, char) : char === "\\" ? (escape = !0, "") : char != quote ? char : null);
2588
+ return this.consume(quote), {
2589
+ type: "quoted",
2590
+ value: inner,
2591
+ quote: quote === '"' ? "double" : "single"
2592
+ };
2593
+ }
2594
+ return null;
2595
+ }
2596
+ tokenizeIdentifier() {
2597
+ let first = !0;
2598
+ const identifier = this.takeWhile((char) => first ? (first = !1, char.match(attributeFirstCharMatcher) ? char : null) : char.match(attributeCharMatcher) ? char : null);
2599
+ return identifier !== null ? {
2600
+ type: "identifier",
2601
+ name: identifier
2602
+ } : null;
2603
+ }
2604
+ tokenizeNumber() {
2605
+ const start = this.i;
2606
+ let dotSeen = !1, digitSeen = !1, negative = !1;
2607
+ this.peek() === "-" && (negative = !0, this.consume("-"));
2608
+ const number = this.takeWhile((char) => char === "." && !dotSeen && digitSeen ? (dotSeen = !0, char) : (digitSeen = !0, char.match(digitChar) ? char : null));
2609
+ return number !== null ? {
2610
+ type: "number",
2611
+ value: negative ? -number : +number,
2612
+ raw: negative ? `-${number}` : number
2613
+ } : (this.i = start, null);
2614
+ }
2615
+ tokenizeSymbol() {
2616
+ for (const symbolClass of symbolClasses) {
2617
+ const symbol = symbols[symbolClass].find((pattern) => this.tryConsume(pattern));
2618
+ if (symbol)
2619
+ return {
2620
+ type: symbolClass,
2621
+ symbol
2622
+ };
2623
+ }
2624
+ return null;
2625
+ }
2626
+ }
2627
+ function tokenize(jsonpath) {
2628
+ return new Tokenizer(jsonpath).tokenize();
2629
+ }
2630
+ var __defProp$f = Object.defineProperty, __defNormalProp$f = (obj, key, value) => key in obj ? __defProp$f(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __publicField$f = (obj, key, value) => __defNormalProp$f(obj, typeof key != "symbol" ? key + "" : key, value);
2631
+ class Parser {
2632
+ constructor(path) {
2633
+ __publicField$f(this, "tokens"), __publicField$f(this, "length"), __publicField$f(this, "i"), this.tokens = tokenize(path), this.length = this.tokens.length, this.i = 0;
2634
+ }
2635
+ parse() {
2636
+ return this.parsePath();
2637
+ }
2638
+ EOF() {
2639
+ return this.i >= this.length;
2640
+ }
2641
+ // Look at upcoming token
2642
+ peek() {
2643
+ return this.EOF() ? null : this.tokens[this.i];
2644
+ }
2645
+ consume() {
2646
+ const result = this.peek();
2647
+ return this.i += 1, result;
2648
+ }
2649
+ // Return next token if it matches the pattern
2650
+ probe(pattern) {
2651
+ const token = this.peek();
2652
+ if (!token)
2653
+ return null;
2654
+ const record = token;
2655
+ return Object.keys(pattern).every((key) => key in token && pattern[key] === record[key]) ? token : null;
2656
+ }
2657
+ // Return and consume next token if it matches the pattern
2658
+ match(pattern) {
2659
+ return this.probe(pattern) ? this.consume() : null;
2660
+ }
2661
+ parseAttribute() {
2662
+ const token = this.match({ type: "identifier" });
2663
+ if (token && token.type === "identifier")
2664
+ return {
2665
+ type: "attribute",
2666
+ name: token.name
2667
+ };
2668
+ const quoted = this.match({ type: "quoted", quote: "single" });
2669
+ return quoted && quoted.type === "quoted" ? {
2670
+ type: "attribute",
2671
+ name: quoted.value || ""
2672
+ } : null;
2673
+ }
2674
+ parseAlias() {
2675
+ return this.match({ type: "keyword", symbol: "@" }) || this.match({ type: "keyword", symbol: "$" }) ? {
2676
+ type: "alias",
2677
+ target: "self"
2678
+ } : null;
2679
+ }
2680
+ parseNumber() {
2681
+ const token = this.match({ type: "number" });
2682
+ return token && token.type === "number" ? {
2683
+ type: "number",
2684
+ value: token.value
2685
+ } : null;
2686
+ }
2687
+ parseNumberValue() {
2688
+ const expr = this.parseNumber();
2689
+ return expr ? expr.value : null;
2690
+ }
2691
+ parseSliceSelector() {
2692
+ const start = this.i, rangeStart = this.parseNumberValue();
2693
+ if (!this.match({ type: "operator", symbol: ":" }))
2694
+ return rangeStart === null ? (this.i = start, null) : { type: "index", value: rangeStart };
2695
+ const result = {
2696
+ type: "range",
2697
+ start: rangeStart,
2698
+ end: this.parseNumberValue()
2699
+ };
2700
+ return this.match({ type: "operator", symbol: ":" }) && (result.step = this.parseNumberValue()), result.start === null && result.end === null ? (this.i = start, null) : result;
2701
+ }
2702
+ parseValueReference() {
2703
+ return this.parseAttribute() || this.parseSliceSelector();
2704
+ }
2705
+ parseLiteralValue() {
2706
+ const literalString = this.match({ type: "quoted", quote: "double" });
2707
+ if (literalString && literalString.type === "quoted")
2708
+ return {
2709
+ type: "string",
2710
+ value: literalString.value || ""
2711
+ };
2712
+ const literalBoolean = this.match({ type: "boolean" });
2713
+ return literalBoolean && literalBoolean.type === "boolean" ? {
2714
+ type: "boolean",
2715
+ value: literalBoolean.symbol === "true"
2716
+ } : this.parseNumber();
2717
+ }
2718
+ // TODO: Reorder constraints so that literal value is always on rhs, and variable is always
2719
+ // on lhs.
2720
+ parseFilterExpression() {
2721
+ const start = this.i, expr = this.parseAttribute() || this.parseAlias();
2722
+ if (!expr)
2723
+ return null;
2724
+ if (this.match({ type: "operator", symbol: "?" }))
2725
+ return {
2726
+ type: "constraint",
2727
+ operator: "?",
2728
+ lhs: expr
2729
+ };
2730
+ const binOp = this.match({ type: "comparator" });
2731
+ if (!binOp || binOp.type !== "comparator")
2732
+ return this.i = start, null;
2733
+ const lhs = expr, rhs = this.parseLiteralValue();
2734
+ if (!rhs)
2735
+ throw new Error(`Operator ${binOp.symbol} needs a literal value at the right hand side`);
2736
+ return {
2737
+ type: "constraint",
2738
+ operator: binOp.symbol,
2739
+ lhs,
2740
+ rhs
2741
+ };
2742
+ }
2743
+ parseExpression() {
2744
+ return this.parseFilterExpression() || this.parseValueReference();
2745
+ }
2746
+ parseUnion() {
2747
+ if (!this.match({ type: "paren", symbol: "[" }))
2748
+ return null;
2749
+ const terms = [];
2750
+ let expr = this.parseFilterExpression() || this.parsePath() || this.parseValueReference();
2751
+ for (; expr && (terms.push(expr), !this.match({ type: "paren", symbol: "]" })); ) {
2752
+ if (!this.match({ type: "operator", symbol: "," }))
2753
+ throw new Error("Expected ]");
2754
+ if (expr = this.parseFilterExpression() || this.parsePath() || this.parseValueReference(), !expr)
2755
+ throw new Error("Expected expression following ','");
2756
+ }
2757
+ return {
2758
+ type: "union",
2759
+ nodes: terms
2760
+ };
2761
+ }
2762
+ parseRecursive() {
2763
+ if (!this.match({ type: "operator", symbol: ".." }))
2764
+ return null;
2765
+ const subpath = this.parsePath();
2766
+ if (!subpath)
2767
+ throw new Error("Expected path following '..' operator");
2768
+ return {
2769
+ type: "recursive",
2770
+ term: subpath
2771
+ };
2772
+ }
2773
+ parsePath() {
2774
+ const nodes = [], expr = this.parseAttribute() || this.parseUnion() || this.parseRecursive();
2775
+ if (!expr)
2776
+ return null;
2777
+ for (nodes.push(expr); !this.EOF(); )
2778
+ if (this.match({ type: "operator", symbol: "." })) {
2779
+ const attr = this.parseAttribute();
2780
+ if (!attr)
2781
+ throw new Error("Expected attribute name following '.");
2782
+ nodes.push(attr);
2783
+ continue;
2784
+ } else if (this.probe({ type: "paren", symbol: "[" })) {
2785
+ const union = this.parseUnion();
2786
+ if (!union)
2787
+ throw new Error("Expected union following '['");
2788
+ nodes.push(union);
2789
+ } else {
2790
+ const recursive = this.parseRecursive();
2791
+ recursive && nodes.push(recursive);
2792
+ break;
2793
+ }
2794
+ return nodes.length === 1 ? nodes[0] : {
2795
+ type: "path",
2796
+ nodes
2797
+ };
2798
+ }
2799
+ }
2800
+ function parseJsonPath(path) {
2801
+ const parsed = new Parser(path).parse();
2802
+ if (!parsed)
2803
+ throw new Error(`Failed to parse JSON path "${path}"`);
2804
+ return parsed;
2805
+ }
2806
+ function toPath(expr) {
2807
+ return toPathInner(expr, !1);
2808
+ }
2809
+ function toPathInner(expr, inUnion) {
2810
+ switch (expr.type) {
2811
+ case "attribute":
2812
+ return expr.name;
2813
+ case "alias":
2814
+ return expr.target === "self" ? "@" : "$";
2815
+ case "number":
2816
+ return `${expr.value}`;
2817
+ case "range": {
2818
+ const result = [];
2819
+ return inUnion || result.push("["), expr.start && result.push(`${expr.start}`), result.push(":"), expr.end && result.push(`${expr.end}`), expr.step && result.push(`:${expr.step}`), inUnion || result.push("]"), result.join("");
2820
+ }
2821
+ case "index":
2822
+ return inUnion ? `${expr.value}` : `[${expr.value}]`;
2823
+ case "constraint": {
2824
+ const rhs = expr.rhs ? ` ${toPathInner(expr.rhs, !1)}` : "", inner = `${toPathInner(expr.lhs, !1)} ${expr.operator}${rhs}`;
2825
+ return inUnion ? inner : `[${inner}]`;
2826
+ }
2827
+ case "string":
2828
+ return JSON.stringify(expr.value);
2829
+ case "path": {
2830
+ const result = [], nodes = expr.nodes.slice();
2831
+ for (; nodes.length > 0; ) {
2832
+ const node2 = nodes.shift();
2833
+ node2 && result.push(toPath(node2));
2834
+ const upcoming = nodes[0];
2835
+ upcoming && toPathInner(upcoming, !1)[0] !== "[" && result.push(".");
2836
+ }
2837
+ return result.join("");
2838
+ }
2839
+ case "union":
2840
+ return `[${expr.nodes.map((e) => toPathInner(e, !0)).join(",")}]`;
2841
+ default:
2842
+ throw new Error(`Unknown node type ${expr.type}`);
2843
+ case "recursive":
2844
+ return `..${toPathInner(expr.term, !1)}`;
2845
+ }
2846
+ }
2847
+ var __defProp$e = Object.defineProperty, __defNormalProp$e = (obj, key, value) => key in obj ? __defProp$e(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __publicField$e = (obj, key, value) => __defNormalProp$e(obj, key + "", value);
2848
+ class Expression {
2849
+ constructor(expr) {
2850
+ if (__publicField$e(this, "expr"), !expr)
2851
+ throw new Error("Attempted to create Expression from null-value");
2852
+ if ("expr" in expr ? this.expr = expr.expr : this.expr = expr, !("type" in this.expr))
2853
+ throw new Error("Attempt to create Expression for expression with no type");
2854
+ }
2855
+ isPath() {
2856
+ return this.expr.type === "path";
2857
+ }
2858
+ isUnion() {
2859
+ return this.expr.type === "union";
2860
+ }
2861
+ isCollection() {
2862
+ return this.isPath() || this.isUnion();
2863
+ }
2864
+ isConstraint() {
2865
+ return this.expr.type === "constraint";
2866
+ }
2867
+ isRecursive() {
2868
+ return this.expr.type === "recursive";
2869
+ }
2870
+ isExistenceConstraint() {
2871
+ return this.expr.type === "constraint" && this.expr.operator === "?";
2872
+ }
2873
+ isIndex() {
2874
+ return this.expr.type === "index";
2875
+ }
2876
+ isRange() {
2877
+ return this.expr.type === "range";
2878
+ }
2879
+ expandRange(probe) {
2880
+ const probeLength = () => {
2881
+ if (!probe)
2882
+ throw new Error("expandRange() required a probe that was not passed");
2883
+ return probe.length();
2884
+ };
2885
+ let start = "start" in this.expr && this.expr.start || 0;
2886
+ start = interpretNegativeIndex(start, probe);
2887
+ let end = "end" in this.expr && this.expr.end || probeLength();
2888
+ end = interpretNegativeIndex(end, probe);
2889
+ const step = "step" in this.expr && this.expr.step || 1;
2890
+ return { start, end, step };
2891
+ }
2892
+ isAttributeReference() {
2893
+ return this.expr.type === "attribute";
2894
+ }
2895
+ // Is a range or index -> something referencing indexes
2896
+ isIndexReference() {
2897
+ return this.isIndex() || this.isRange();
2898
+ }
2899
+ name() {
2900
+ return "name" in this.expr ? this.expr.name : "";
2901
+ }
2902
+ isSelfReference() {
2903
+ return this.expr.type === "alias" && this.expr.target === "self";
2904
+ }
2905
+ constraintTargetIsSelf() {
2906
+ return this.expr.type === "constraint" && this.expr.lhs.type === "alias" && this.expr.lhs.target === "self";
2907
+ }
2908
+ constraintTargetIsAttribute() {
2909
+ return this.expr.type === "constraint" && this.expr.lhs.type === "attribute";
2910
+ }
2911
+ testConstraint(probe) {
2912
+ const expr = this.expr;
2913
+ if (expr.type === "constraint" && expr.lhs.type === "alias" && expr.lhs.target === "self") {
2914
+ if (probe.containerType() !== "primitive")
2915
+ return !1;
2916
+ if (expr.type === "constraint" && expr.operator === "?")
2917
+ return !0;
2918
+ const lhs2 = probe.get(), rhs2 = expr.rhs && "value" in expr.rhs ? expr.rhs.value : void 0;
2919
+ return testBinaryOperator(lhs2, expr.operator, rhs2);
2920
+ }
2921
+ if (expr.type !== "constraint")
2922
+ return !1;
2923
+ const lhs = expr.lhs;
2924
+ if (!lhs)
2925
+ throw new Error("No LHS of expression");
2926
+ if (lhs.type !== "attribute")
2927
+ throw new Error(`Constraint target ${lhs.type} not supported`);
2928
+ if (probe.containerType() !== "object")
2929
+ return !1;
2930
+ const lhsValue = probe.getAttribute(lhs.name);
2931
+ if (lhsValue == null || lhsValue.containerType() !== "primitive")
2932
+ return !1;
2933
+ if (this.isExistenceConstraint())
2934
+ return !0;
2935
+ const rhs = expr.rhs && "value" in expr.rhs ? expr.rhs.value : void 0;
2936
+ return testBinaryOperator(lhsValue.get(), expr.operator, rhs);
2937
+ }
2938
+ pathNodes() {
2939
+ return this.expr.type === "path" ? this.expr.nodes : [this.expr];
2940
+ }
2941
+ prepend(node2) {
2942
+ return node2 ? new Expression({
2943
+ type: "path",
2944
+ nodes: node2.pathNodes().concat(this.pathNodes())
2945
+ }) : this;
2946
+ }
2947
+ concat(other) {
2948
+ return other ? other.prepend(this) : this;
2949
+ }
2950
+ descend() {
2951
+ return descend$1(this.expr).map((headTail) => {
2952
+ const [head, tail] = headTail;
2953
+ return {
2954
+ head: head ? new Expression(head) : null,
2955
+ tail: tail ? new Expression(tail) : null
2956
+ };
2957
+ });
2958
+ }
2959
+ unwrapRecursive() {
2960
+ if (this.expr.type !== "recursive")
2961
+ throw new Error(`Attempt to unwrap recursive on type ${this.expr.type}`);
2962
+ return new Expression(this.expr.term);
2963
+ }
2964
+ toIndicies(probe) {
2965
+ if (this.expr.type !== "index" && this.expr.type !== "range")
2966
+ throw new Error("Node cannot be converted to indexes");
2967
+ if (this.expr.type === "index")
2968
+ return [interpretNegativeIndex(this.expr.value, probe)];
2969
+ const result = [], range = this.expandRange(probe);
2970
+ let { start, end } = range;
2971
+ range.step < 0 && ([start, end] = [end, start]);
2972
+ for (let i = start; i < end; i++)
2973
+ result.push(i);
2974
+ return result;
2975
+ }
2976
+ toFieldReferences() {
2977
+ if (this.isIndexReference())
2978
+ return this.toIndicies();
2979
+ if (this.expr.type === "attribute")
2980
+ return [this.expr.name];
2981
+ throw new Error(`Can't convert ${this.expr.type} to field references`);
2982
+ }
2983
+ toString() {
2984
+ return toPath(this.expr);
2985
+ }
2986
+ static fromPath(path) {
2987
+ const parsed = parseJsonPath(path);
2988
+ if (!parsed)
2989
+ throw new Error(`Failed to parse path "${path}"`);
2990
+ return new Expression(parsed);
2991
+ }
2992
+ static attributeReference(name) {
2993
+ return new Expression({
2994
+ type: "attribute",
2995
+ name
2996
+ });
2997
+ }
2998
+ static indexReference(i) {
2999
+ return new Expression({
3000
+ type: "index",
3001
+ value: i
3002
+ });
3003
+ }
3004
+ }
3005
+ function testBinaryOperator(lhsValue, operator, rhsValue) {
3006
+ switch (operator) {
3007
+ case ">":
3008
+ return lhsValue > rhsValue;
3009
+ case ">=":
3010
+ return lhsValue >= rhsValue;
3011
+ case "<":
3012
+ return lhsValue < rhsValue;
3013
+ case "<=":
3014
+ return lhsValue <= rhsValue;
3015
+ case "==":
3016
+ return lhsValue === rhsValue;
3017
+ case "!=":
3018
+ return lhsValue !== rhsValue;
3019
+ default:
3020
+ throw new Error(`Unsupported binary operator ${operator}`);
3021
+ }
3022
+ }
3023
+ function interpretNegativeIndex(index, probe) {
3024
+ if (index >= 0)
3025
+ return index;
3026
+ if (!probe)
3027
+ throw new Error("interpretNegativeIndex() must have a probe when < 0");
3028
+ return index + probe.length();
3029
+ }
3030
+ var __defProp$d = Object.defineProperty, __defNormalProp$d = (obj, key, value) => key in obj ? __defProp$d(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __publicField$d = (obj, key, value) => __defNormalProp$d(obj, typeof key != "symbol" ? key + "" : key, value);
3031
+ class Descender {
3032
+ constructor(head, tail) {
3033
+ __publicField$d(this, "head"), __publicField$d(this, "tail"), this.head = head, this.tail = tail;
3034
+ }
3035
+ // Iterate this descender once processing any constraints that are
3036
+ // resolvable on the current value. Returns an array of new descenders
3037
+ // that are guaranteed to be without constraints in the head
3038
+ iterate(probe) {
3039
+ let result = [this];
3040
+ if (this.head && this.head.isConstraint()) {
3041
+ let anyConstraints = !0;
3042
+ for (; anyConstraints; )
3043
+ result = flatten$1(
3044
+ result.map((descender) => descender.iterateConstraints(probe))
3045
+ ), anyConstraints = result.some((descender) => descender.head && descender.head.isConstraint());
3046
+ }
3047
+ return result;
3048
+ }
3049
+ isRecursive() {
3050
+ return !!(this.head && this.head.isRecursive());
3051
+ }
3052
+ hasArrived() {
3053
+ return this.head === null && this.tail === null;
3054
+ }
3055
+ extractRecursives() {
3056
+ if (this.head && this.head.isRecursive()) {
3057
+ const term = this.head.unwrapRecursive();
3058
+ return new Descender(null, term.concat(this.tail)).descend();
3059
+ }
3060
+ return [];
3061
+ }
3062
+ iterateConstraints(probe) {
3063
+ const head = this.head;
3064
+ if (head === null || !head.isConstraint())
3065
+ return [this];
3066
+ const result = [];
3067
+ if (probe.containerType() === "primitive" && head.constraintTargetIsSelf())
3068
+ return head.testConstraint(probe) && result.push(...this.descend()), result;
3069
+ if (probe.containerType() === "array") {
3070
+ const length = probe.length();
3071
+ for (let i = 0; i < length; i++) {
3072
+ const constraint = probe.getIndex(i);
3073
+ constraint && head.testConstraint(constraint) && result.push(new Descender(new Expression({ type: "index", value: i }), this.tail));
3074
+ }
3075
+ return result;
3076
+ }
3077
+ return probe.containerType() === "object" ? head.constraintTargetIsSelf() ? [] : head.testConstraint(probe) ? this.descend() : result : result;
3078
+ }
3079
+ descend() {
3080
+ return this.tail ? this.tail.descend().map((ht) => new Descender(ht.head, ht.tail)) : [new Descender(null, null)];
3081
+ }
3082
+ toString() {
3083
+ const result = ["<"];
3084
+ return this.head && result.push(this.head.toString()), result.push("|"), this.tail && result.push(this.tail.toString()), result.push(">"), result.join("");
3085
+ }
3086
+ }
3087
+ var __defProp$c = Object.defineProperty, __defNormalProp$c = (obj, key, value) => key in obj ? __defProp$c(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __publicField$c = (obj, key, value) => __defNormalProp$c(obj, typeof key != "symbol" ? key + "" : key, value);
3088
+ class Matcher {
3089
+ constructor(active, parent) {
3090
+ __publicField$c(this, "active"), __publicField$c(this, "recursives"), __publicField$c(this, "payload"), this.active = active || [], parent ? (this.recursives = parent.recursives, this.payload = parent.payload) : this.recursives = [], this.extractRecursives();
3091
+ }
3092
+ setPayload(payload) {
3093
+ return this.payload = payload, this;
3094
+ }
3095
+ // Moves any recursive descenders onto the recursive track, removing them from
3096
+ // the active set
3097
+ extractRecursives() {
3098
+ this.active = this.active.filter((descender) => descender.isRecursive() ? (this.recursives.push(...descender.extractRecursives()), !1) : !0);
3099
+ }
3100
+ // Find recursives that are relevant now and should be considered part of the active set
3101
+ activeRecursives(probe) {
3102
+ return this.recursives.filter((descender) => {
3103
+ const head = descender.head;
3104
+ return head ? head.isConstraint() || probe.containerType() === "array" && head.isIndexReference() ? !0 : probe.containerType() === "object" ? head.isAttributeReference() && probe.hasAttribute(head.name()) : !1 : !1;
3105
+ });
3106
+ }
3107
+ match(probe) {
3108
+ return this.iterate(probe).extractMatches(probe);
3109
+ }
3110
+ iterate(probe) {
3111
+ const newActiveSet = [];
3112
+ return this.active.concat(this.activeRecursives(probe)).forEach((descender) => {
3113
+ newActiveSet.push(...descender.iterate(probe));
3114
+ }), new Matcher(newActiveSet, this);
3115
+ }
3116
+ // Returns true if any of the descenders in the active or recursive set
3117
+ // consider the current state a final destination
3118
+ isDestination() {
3119
+ return this.active.some((descender) => descender.hasArrived());
3120
+ }
3121
+ hasRecursives() {
3122
+ return this.recursives.length > 0;
3123
+ }
3124
+ // Returns any payload delivieries and leads that needs to be followed to complete
3125
+ // the process.
3126
+ extractMatches(probe) {
3127
+ const leads = [], targets = [];
3128
+ if (this.active.forEach((descender) => {
3129
+ if (descender.hasArrived()) {
3130
+ targets.push(
3131
+ new Expression({
3132
+ type: "alias",
3133
+ target: "self"
3134
+ })
3135
+ );
3136
+ return;
3137
+ }
3138
+ const descenderHead = descender.head;
3139
+ if (descenderHead && !(probe.containerType() === "array" && !descenderHead.isIndexReference()) && !(probe.containerType() === "object" && !descenderHead.isAttributeReference()))
3140
+ if (descender.tail) {
3141
+ const matcher = new Matcher(descender.descend(), this);
3142
+ descenderHead.toFieldReferences().forEach(() => {
3143
+ leads.push({
3144
+ target: descenderHead,
3145
+ matcher
3146
+ });
3147
+ });
3148
+ } else
3149
+ targets.push(descenderHead);
3150
+ }), this.hasRecursives()) {
3151
+ const recursivesMatcher = new Matcher([], this);
3152
+ if (probe.containerType() === "array") {
3153
+ const length = probe.length();
3154
+ for (let i = 0; i < length; i++)
3155
+ leads.push({
3156
+ target: Expression.indexReference(i),
3157
+ matcher: recursivesMatcher
3158
+ });
3159
+ } else
3160
+ probe.containerType() === "object" && probe.attributeKeys().forEach((name) => {
3161
+ leads.push({
3162
+ target: Expression.attributeReference(name),
3163
+ matcher: recursivesMatcher
3164
+ });
3165
+ });
3166
+ }
3167
+ return targets.length > 0 ? { leads, delivery: { targets, payload: this.payload } } : { leads };
3168
+ }
3169
+ static fromPath(jsonpath) {
3170
+ const path = parseJsonPath(jsonpath);
3171
+ if (!path)
3172
+ throw new Error(`Failed to parse path from "${jsonpath}"`);
3173
+ const descender = new Descender(null, new Expression(path));
3174
+ return new Matcher(descender.descend());
3175
+ }
3176
+ }
3177
+ var __defProp$b = Object.defineProperty, __defNormalProp$b = (obj, key, value) => key in obj ? __defProp$b(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __publicField$b = (obj, key, value) => __defNormalProp$b(obj, typeof key != "symbol" ? key + "" : key, value);
3178
+ class PlainProbe {
3179
+ constructor(value, path) {
3180
+ __publicField$b(this, "_value"), __publicField$b(this, "path"), this._value = value, this.path = path || [];
3181
+ }
3182
+ containerType() {
3183
+ return Array.isArray(this._value) ? "array" : this._value !== null && typeof this._value == "object" ? "object" : "primitive";
3184
+ }
3185
+ length() {
3186
+ if (!Array.isArray(this._value))
3187
+ throw new Error("Won't return length of non-indexable _value");
3188
+ return this._value.length;
3189
+ }
3190
+ getIndex(i) {
3191
+ return Array.isArray(this._value) ? i >= this.length() ? null : new PlainProbe(this._value[i], this.path.concat(i)) : !1;
3192
+ }
3193
+ hasAttribute(key) {
3194
+ return isRecord(this._value) ? this._value.hasOwnProperty(key) : !1;
3195
+ }
3196
+ attributeKeys() {
3197
+ return isRecord(this._value) ? Object.keys(this._value) : [];
3198
+ }
3199
+ getAttribute(key) {
3200
+ if (!isRecord(this._value))
3201
+ throw new Error("getAttribute only applies to plain objects");
3202
+ return this.hasAttribute(key) ? new PlainProbe(this._value[key], this.path.concat(key)) : null;
3203
+ }
3204
+ get() {
3205
+ return this._value;
3206
+ }
3207
+ }
3208
+ function extractAccessors(path, value) {
3209
+ const result = [], matcher = Matcher.fromPath(path).setPayload(function(values) {
3210
+ result.push(...values);
3211
+ }), accessor = new PlainProbe(value);
3212
+ return descend(matcher, accessor), result;
3213
+ }
3214
+ function descend(matcher, accessor) {
3215
+ const { leads, delivery } = matcher.match(accessor);
3216
+ leads.forEach((lead) => {
3217
+ accessorsFromTarget(lead.target, accessor).forEach((childAccessor) => {
3218
+ descend(lead.matcher, childAccessor);
3219
+ });
3220
+ }), delivery && delivery.targets.forEach((target) => {
3221
+ typeof delivery.payload == "function" && delivery.payload(accessorsFromTarget(target, accessor));
3222
+ });
3223
+ }
3224
+ function accessorsFromTarget(target, accessor) {
3225
+ const result = [];
3226
+ if (target.isIndexReference())
3227
+ target.toIndicies(accessor).forEach((i) => {
3228
+ result.push(accessor.getIndex(i));
3229
+ });
3230
+ else if (target.isAttributeReference())
3231
+ result.push(accessor.getAttribute(target.name()));
3232
+ else if (target.isSelfReference())
3233
+ result.push(accessor);
3234
+ else
3235
+ throw new Error(`Unable to derive accessor for target ${target.toString()}`);
3236
+ return compact$1(result);
3237
+ }
3238
+ function extractWithPath(path, value) {
3239
+ return extractAccessors(path, value).map((acc) => ({ path: acc.path, value: acc.get() }));
3240
+ }
3241
+ var __defProp$a = Object.defineProperty, __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __publicField$a = (obj, key, value) => __defNormalProp$a(obj, typeof key != "symbol" ? key + "" : key, value);
3242
+ function applyPatch(patch, oldValue) {
3243
+ if (typeof oldValue != "string")
3244
+ return oldValue;
3245
+ const [result] = apply(patch, oldValue, { allowExceedingIndices: !0 });
3246
+ return result;
3247
+ }
3248
+ class DiffMatchPatch {
3249
+ constructor(id, path, dmpPatchSrc) {
3250
+ __publicField$a(this, "path"), __publicField$a(this, "dmpPatch"), __publicField$a(this, "id"), this.id = id, this.path = path, this.dmpPatch = parse(dmpPatchSrc);
3251
+ }
3252
+ apply(targets, accessor) {
3253
+ let result = accessor;
3254
+ if (result.containerType() === "primitive")
3255
+ return result;
3256
+ for (const target of targets) {
3257
+ if (target.isIndexReference()) {
3258
+ for (const index of target.toIndicies(accessor)) {
3259
+ const item = result.getIndex(index);
3260
+ if (!item)
3261
+ continue;
3262
+ const oldValue = item.get(), nextValue = applyPatch(this.dmpPatch, oldValue);
3263
+ result = result.setIndex(index, nextValue);
3264
+ }
3265
+ continue;
3266
+ }
3267
+ if (target.isAttributeReference() && result.hasAttribute(target.name())) {
3268
+ const attribute = result.getAttribute(target.name());
3269
+ if (!attribute)
3270
+ continue;
3271
+ const oldValue = attribute.get(), nextValue = applyPatch(this.dmpPatch, oldValue);
3272
+ result = result.setAttribute(target.name(), nextValue);
3273
+ continue;
3274
+ }
3275
+ throw new Error(`Unable to apply diffMatchPatch to target ${target.toString()}`);
3276
+ }
3277
+ return result;
3278
+ }
3279
+ }
3280
+ var __defProp$9 = Object.defineProperty, __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __publicField$9 = (obj, key, value) => __defNormalProp$9(obj, typeof key != "symbol" ? key + "" : key, value);
3281
+ function performIncrement(previousValue, delta) {
3282
+ return typeof previousValue != "number" || !Number.isFinite(previousValue) ? previousValue : previousValue + delta;
3283
+ }
3284
+ class IncPatch {
3285
+ constructor(id, path, value) {
3286
+ __publicField$9(this, "path"), __publicField$9(this, "value"), __publicField$9(this, "id"), this.path = path, this.value = value, this.id = id;
3287
+ }
3288
+ apply(targets, accessor) {
3289
+ let result = accessor;
3290
+ if (result.containerType() === "primitive")
3291
+ return result;
3292
+ for (const target of targets) {
3293
+ if (target.isIndexReference()) {
3294
+ for (const index of target.toIndicies(accessor)) {
3295
+ const item = result.getIndex(index);
3296
+ if (!item)
3297
+ continue;
3298
+ const previousValue = item.get();
3299
+ result = result.setIndex(index, performIncrement(previousValue, this.value));
3300
+ }
3301
+ continue;
3302
+ }
3303
+ if (target.isAttributeReference()) {
3304
+ const attribute = result.getAttribute(target.name());
3305
+ if (!attribute)
3306
+ continue;
3307
+ const previousValue = attribute.get();
3308
+ result = result.setAttribute(target.name(), performIncrement(previousValue, this.value));
3309
+ continue;
3310
+ }
3311
+ throw new Error(`Unable to apply to target ${target.toString()}`);
3312
+ }
3313
+ return result;
3314
+ }
3315
+ }
3316
+ function targetsToIndicies(targets, accessor) {
3317
+ const result = [];
3318
+ return targets.forEach((target) => {
3319
+ target.isIndexReference() && result.push(...target.toIndicies(accessor));
3320
+ }), result.sort();
3321
+ }
3322
+ var __defProp$8 = Object.defineProperty, __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __publicField$8 = (obj, key, value) => __defNormalProp$8(obj, typeof key != "symbol" ? key + "" : key, value);
3323
+ class InsertPatch {
3324
+ constructor(id, location, path, items) {
3325
+ __publicField$8(this, "location"), __publicField$8(this, "path"), __publicField$8(this, "items"), __publicField$8(this, "id"), this.id = id, this.location = location, this.path = path, this.items = items;
3326
+ }
3327
+ apply(targets, accessor) {
3328
+ let result = accessor;
3329
+ if (accessor.containerType() !== "array")
3330
+ throw new Error("Attempt to apply insert patch to non-array value");
3331
+ switch (this.location) {
3332
+ case "before": {
3333
+ const pos = minIndex(targets, accessor);
3334
+ result = result.insertItemsAt(pos, this.items);
3335
+ break;
3336
+ }
3337
+ case "after": {
3338
+ const pos = maxIndex(targets, accessor);
3339
+ result = result.insertItemsAt(pos + 1, this.items);
3340
+ break;
3341
+ }
3342
+ case "replace": {
3343
+ const indicies = targetsToIndicies(targets, accessor);
3344
+ result = result.unsetIndices(indicies), result = result.insertItemsAt(indicies[0], this.items);
3345
+ break;
3346
+ }
3347
+ default:
3348
+ throw new Error(`Unsupported location atm: ${this.location}`);
3349
+ }
3350
+ return result;
3351
+ }
3352
+ }
3353
+ function minIndex(targets, accessor) {
3354
+ let result = min$1(targetsToIndicies(targets, accessor)) || 0;
3355
+ return targets.forEach((target) => {
3356
+ if (target.isRange()) {
3357
+ const { start } = target.expandRange();
3358
+ start < result && (result = start);
3359
+ }
3360
+ }), result;
3361
+ }
3362
+ function maxIndex(targets, accessor) {
3363
+ let result = max$1(targetsToIndicies(targets, accessor)) || 0;
3364
+ return targets.forEach((target) => {
3365
+ if (target.isRange()) {
3366
+ const { end } = target.expandRange();
3367
+ end > result && (result = end);
3368
+ }
3369
+ }), result;
3370
+ }
3371
+ var __defProp$7 = Object.defineProperty, __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __publicField$7 = (obj, key, value) => __defNormalProp$7(obj, typeof key != "symbol" ? key + "" : key, value);
3372
+ class SetIfMissingPatch {
3373
+ constructor(id, path, value) {
3374
+ __publicField$7(this, "id"), __publicField$7(this, "path"), __publicField$7(this, "value"), this.id = id, this.path = path, this.value = value;
3375
+ }
3376
+ apply(targets, accessor) {
3377
+ let result = accessor;
3378
+ return targets.forEach((target) => {
3379
+ if (!target.isIndexReference())
3380
+ if (target.isAttributeReference())
3381
+ result.containerType() === "primitive" ? result = result.set({ [target.name()]: this.value }) : result.hasAttribute(target.name()) || (result = accessor.setAttribute(target.name(), this.value));
3382
+ else
3383
+ throw new Error(`Unable to apply to target ${target.toString()}`);
3384
+ }), result;
3385
+ }
3386
+ }
3387
+ var __defProp$6 = Object.defineProperty, __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __publicField$6 = (obj, key, value) => __defNormalProp$6(obj, typeof key != "symbol" ? key + "" : key, value);
3388
+ class SetPatch {
3389
+ constructor(id, path, value) {
3390
+ __publicField$6(this, "id"), __publicField$6(this, "path"), __publicField$6(this, "value"), this.id = id, this.path = path, this.value = value;
3391
+ }
3392
+ apply(targets, accessor) {
3393
+ let result = accessor;
3394
+ return targets.forEach((target) => {
3395
+ if (target.isSelfReference())
3396
+ result = result.set(this.value);
3397
+ else if (target.isIndexReference())
3398
+ target.toIndicies(accessor).forEach((i) => {
3399
+ result = result.setIndex(i, this.value);
3400
+ });
3401
+ else if (target.isAttributeReference())
3402
+ result.containerType() === "primitive" ? result = result.set({ [target.name()]: this.value }) : result = result.setAttribute(target.name(), this.value);
3403
+ else
3404
+ throw new Error(`Unable to apply to target ${target.toString()}`);
3405
+ }), result;
3406
+ }
3407
+ }
3408
+ var __defProp$5 = Object.defineProperty, __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __publicField$5 = (obj, key, value) => __defNormalProp$5(obj, typeof key != "symbol" ? key + "" : key, value);
3409
+ class UnsetPatch {
3410
+ constructor(id, path) {
3411
+ __publicField$5(this, "id"), __publicField$5(this, "path"), __publicField$5(this, "value"), this.id = id, this.path = path;
3412
+ }
3413
+ // eslint-disable-next-line class-methods-use-this
3414
+ apply(targets, accessor) {
3415
+ let result = accessor;
3416
+ switch (accessor.containerType()) {
3417
+ case "array":
3418
+ result = result.unsetIndices(targetsToIndicies(targets, accessor));
3419
+ break;
3420
+ case "object":
3421
+ targets.forEach((target) => {
3422
+ result = result.unsetAttribute(target.name());
3423
+ });
3424
+ break;
3425
+ default:
3426
+ throw new Error(
3427
+ "Target value is neither indexable or an object. This error should potentially just be silently ignored?"
3428
+ );
3429
+ }
3430
+ return result;
3431
+ }
3432
+ }
3433
+ function parsePatch(patch) {
3434
+ const result = [];
3435
+ if (Array.isArray(patch))
3436
+ return patch.reduce((r, p) => r.concat(parsePatch(p)), result);
3437
+ const { set, setIfMissing, unset, diffMatchPatch, inc, dec, insert } = patch;
3438
+ if (setIfMissing && Object.keys(setIfMissing).forEach((path) => {
3439
+ result.push(new SetIfMissingPatch(patch.id, path, setIfMissing[path]));
3440
+ }), set && Object.keys(set).forEach((path) => {
3441
+ result.push(new SetPatch(patch.id, path, set[path]));
3442
+ }), unset && unset.forEach((path) => {
3443
+ result.push(new UnsetPatch(patch.id, path));
3444
+ }), diffMatchPatch && Object.keys(diffMatchPatch).forEach((path) => {
3445
+ result.push(new DiffMatchPatch(patch.id, path, diffMatchPatch[path]));
3446
+ }), inc && Object.keys(inc).forEach((path) => {
3447
+ result.push(new IncPatch(patch.id, path, inc[path]));
3448
+ }), dec && Object.keys(dec).forEach((path) => {
3449
+ result.push(new IncPatch(patch.id, path, -dec[path]));
3450
+ }), insert) {
3451
+ let location, path;
3452
+ const spec = insert;
3453
+ if ("before" in spec)
3454
+ location = "before", path = spec.before;
3455
+ else if ("after" in spec)
3456
+ location = "after", path = spec.after;
3457
+ else if ("replace" in spec)
3458
+ location = "replace", path = spec.replace;
3459
+ else
3460
+ throw new Error("Invalid insert patch");
3461
+ result.push(new InsertPatch(patch.id, location, path, spec.items));
3462
+ }
3463
+ return result;
3464
+ }
3465
+ var __defProp$4 = Object.defineProperty, __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __publicField$4 = (obj, key, value) => __defNormalProp$4(obj, key + "", value);
3466
+ class Patcher {
3467
+ constructor(patch) {
3468
+ __publicField$4(this, "patches"), this.patches = parsePatch(patch);
3469
+ }
3470
+ apply(value) {
3471
+ const accessor = new ImmutableAccessor(value);
3472
+ return this.applyViaAccessor(accessor).get();
3473
+ }
3474
+ // If you want to use your own accessor implementation, you can use this method
3475
+ // to invoke the patcher. Since all subsequent accessors for children of this accessor
3476
+ // are obtained through the methods in the accessors, you retain full control of the
3477
+ // implementation throguhgout the application. Have a look in ImmutableAccessor
3478
+ // to see an example of how accessors are implemented.
3479
+ applyViaAccessor(accessor) {
3480
+ let result = accessor;
3481
+ const idAccessor = accessor.getAttribute("_id");
3482
+ if (!idAccessor)
3483
+ throw new Error("Cannot apply patch to document with no _id");
3484
+ const id = idAccessor.get();
3485
+ for (const patch of this.patches) {
3486
+ if (patch.id !== id)
3487
+ continue;
3488
+ const matcher = Matcher.fromPath(patch.path).setPayload(patch);
3489
+ result = process$1(matcher, result);
3490
+ }
3491
+ return result;
3492
+ }
3493
+ }
3494
+ function process$1(matcher, accessor) {
3495
+ const isSetPatch = matcher.payload instanceof SetPatch || matcher.payload instanceof SetIfMissingPatch;
3496
+ let result = accessor;
3497
+ const { leads, delivery } = matcher.match(accessor);
3498
+ return leads.forEach((lead) => {
3499
+ if (lead.target.isIndexReference())
3500
+ lead.target.toIndicies().forEach((i) => {
3501
+ const item = result.getIndex(i);
3502
+ if (!item)
3503
+ throw new Error("Index out of bounds");
3504
+ result = result.setIndexAccessor(i, process$1(lead.matcher, item));
3505
+ });
3506
+ else if (lead.target.isAttributeReference()) {
3507
+ isSetPatch && result.containerType() === "primitive" && (result = result.set({}));
3508
+ let oldValueAccessor = result.getAttribute(lead.target.name());
3509
+ if (!oldValueAccessor && isSetPatch && (result = result.setAttribute(lead.target.name(), {}), oldValueAccessor = result.getAttribute(lead.target.name())), !oldValueAccessor)
3510
+ return;
3511
+ const newValueAccessor = process$1(lead.matcher, oldValueAccessor);
3512
+ oldValueAccessor !== newValueAccessor && (result = result.setAttributeAccessor(lead.target.name(), newValueAccessor));
3513
+ } else
3514
+ throw new Error(`Unable to handle target ${lead.target.toString()}`);
3515
+ }), delivery && isPatcher(delivery.payload) && (result = delivery.payload.apply(delivery.targets, result)), result;
3516
+ }
3517
+ function isPatcher(payload) {
3518
+ return !!(payload && typeof payload == "object" && payload !== null && "apply" in payload && typeof payload.apply == "function");
3519
+ }
3520
+ const luid = uuid.uuid;
3521
+ var __defProp$3 = Object.defineProperty, __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __publicField$3 = (obj, key, value) => __defNormalProp$3(obj, typeof key != "symbol" ? key + "" : key, value);
3522
+ class Mutation {
3523
+ constructor(options) {
3524
+ __publicField$3(this, "params"), __publicField$3(this, "compiled"), __publicField$3(this, "_appliesToMissingDocument"), this.params = options;
3525
+ }
3526
+ get transactionId() {
3527
+ return this.params.transactionId;
3528
+ }
3529
+ get transition() {
3530
+ return this.params.transition;
3531
+ }
3532
+ get identity() {
3533
+ return this.params.identity;
3534
+ }
3535
+ get previousRev() {
3536
+ return this.params.previousRev;
3537
+ }
3538
+ get resultRev() {
3539
+ return this.params.resultRev;
3540
+ }
3541
+ get mutations() {
3542
+ return this.params.mutations;
3543
+ }
3544
+ get timestamp() {
3545
+ if (typeof this.params.timestamp == "string")
3546
+ return new Date(this.params.timestamp);
3547
+ }
3548
+ get effects() {
3549
+ return this.params.effects;
3550
+ }
3551
+ assignRandomTransactionId() {
3552
+ this.params.transactionId = luid(), this.params.resultRev = this.params.transactionId;
3553
+ }
3554
+ appliesToMissingDocument() {
3555
+ if (typeof this._appliesToMissingDocument < "u")
3556
+ return this._appliesToMissingDocument;
3557
+ const firstMut = this.mutations[0];
3558
+ return firstMut ? this._appliesToMissingDocument = !!(firstMut.create || firstMut.createIfNotExists || firstMut.createOrReplace) : this._appliesToMissingDocument = !0, this._appliesToMissingDocument;
3559
+ }
3560
+ // Compiles all mutations into a handy function
3561
+ compile() {
3562
+ const operations = [], getGuaranteedCreatedAt = (doc) => (doc == null ? void 0 : doc._createdAt) || this.params.timestamp || (/* @__PURE__ */ new Date()).toISOString();
3563
+ this.mutations.forEach((mutation) => {
3564
+ if (mutation.create) {
3565
+ const create = mutation.create || {};
3566
+ operations.push((doc) => doc || Object.assign(create, {
3567
+ _createdAt: getGuaranteedCreatedAt(create)
3568
+ }));
3569
+ return;
3570
+ }
3571
+ if (mutation.createIfNotExists) {
3572
+ const createIfNotExists = mutation.createIfNotExists || {};
3573
+ operations.push(
3574
+ (doc) => doc === null ? Object.assign(createIfNotExists, {
3575
+ _createdAt: getGuaranteedCreatedAt(createIfNotExists)
3576
+ }) : doc
3577
+ );
3578
+ return;
3579
+ }
3580
+ if (mutation.createOrReplace) {
3581
+ const createOrReplace = mutation.createOrReplace || {};
3582
+ operations.push(
3583
+ () => Object.assign(createOrReplace, {
3584
+ _createdAt: getGuaranteedCreatedAt(createOrReplace)
3585
+ })
3586
+ );
3587
+ return;
3588
+ }
3589
+ if (mutation.delete) {
3590
+ operations.push(() => null);
3591
+ return;
3592
+ }
3593
+ if (mutation.patch) {
3594
+ if ("query" in mutation.patch)
3595
+ return;
3596
+ const patch = new Patcher(mutation.patch);
3597
+ operations.push((doc) => patch.apply(doc));
3598
+ return;
3599
+ }
3600
+ throw new Error(`Unsupported mutation ${JSON.stringify(mutation, null, 2)}`);
3601
+ }), typeof this.params.timestamp == "string" && operations.push((doc) => doc ? Object.assign(doc, { _updatedAt: this.params.timestamp }) : null);
3602
+ const prevRev = this.previousRev, rev = this.resultRev || this.transactionId;
3603
+ this.compiled = (doc) => {
3604
+ if (prevRev && doc && prevRev !== doc._rev)
3605
+ throw new Error(
3606
+ `Previous revision for this mutation was ${prevRev}, but the document revision is ${doc._rev}`
3607
+ );
3608
+ let result = doc;
3609
+ for (const operation of operations)
3610
+ result = operation(result);
3611
+ return result && rev && (result === doc && (result = Object.assign({}, doc)), result._rev = rev), result;
3612
+ };
3613
+ }
3614
+ apply(document2) {
3615
+ debug("Applying mutation %O to document %O", this.mutations, document2), this.compiled || this.compile();
3616
+ const result = this.compiled(document2);
3617
+ return debug(" => %O", result), result;
3618
+ }
3619
+ static applyAll(document2, mutations) {
3620
+ return mutations.reduce((doc, mutation) => mutation.apply(doc), document2);
3621
+ }
3622
+ // Given a number of yet-to-be-committed mutation objects, collects them into one big mutation
3623
+ // any metadata like transactionId is ignored and must be submitted by the client. It is assumed
3624
+ // that all mutations are on the same document.
3625
+ // TOOO: Optimize mutations, eliminating mutations that overwrite themselves!
3626
+ static squash(document2, mutations) {
3627
+ const squashed = mutations.reduce(
3628
+ (result, mutation) => result.concat(...mutation.mutations),
3629
+ []
3630
+ );
3631
+ return new Mutation({ mutations: squashed });
3632
+ }
3633
+ }
3634
+ function removeExcludedPaths(doc, schemaType) {
3635
+ if (!sanity.isDocumentSchemaType(schemaType) || !doc)
3636
+ return doc;
3637
+ const pathsToExclude = extractPaths(doc, schemaType, []).filter(
3638
+ (field) => {
3639
+ var _a, _b, _c;
3640
+ return ((_c = (_b = (_a = field.schemaType) == null ? void 0 : _a.options) == null ? void 0 : _b.documentInternationalization) == null ? void 0 : _c.exclude) === !0;
3641
+ }
3642
+ ).map((field) => sanity.pathToString(field.path));
3643
+ return new Mutation({
3644
+ mutations: [
3645
+ {
3646
+ patch: {
3647
+ id: doc._id,
3648
+ unset: pathsToExclude
3649
+ }
3650
+ }
3651
+ ]
3652
+ }).apply(doc);
3653
+ }
3654
+ function extractPaths(doc, schemaType, path) {
3655
+ return schemaType.fields.reduce((acc, field) => {
3656
+ var _a, _b;
3657
+ const fieldPath = [...path, field.name], fieldSchema = field.type, { value } = (_a = extractWithPath(sanity.pathToString(fieldPath), doc)[0]) != null ? _a : {};
3658
+ if (!value)
3659
+ return acc;
3660
+ const thisFieldWithPath = {
3661
+ path: fieldPath,
3662
+ name: field.name,
3663
+ schemaType: fieldSchema,
3664
+ value
3665
+ };
3666
+ if (fieldSchema.jsonType === "object") {
3667
+ const innerFields = extractPaths(doc, fieldSchema, fieldPath);
3668
+ return [...acc, thisFieldWithPath, ...innerFields];
3669
+ } else if (fieldSchema.jsonType === "array" && fieldSchema.of.length && fieldSchema.of.some((item) => "fields" in item)) {
3670
+ const { value: arrayValue } = (_b = extractWithPath(sanity.pathToString(fieldPath), doc)[0]) != null ? _b : {};
3671
+ let arrayPaths = [];
3672
+ if (arrayValue != null && arrayValue.length)
3673
+ for (const item of arrayValue) {
3674
+ const itemPath = [...fieldPath, { _key: item._key }];
3675
+ let itemSchema = fieldSchema.of.find((t) => t.name === item._type);
3676
+ if (item._type || (itemSchema = fieldSchema.of[0]), item._key && itemSchema) {
3677
+ const innerFields = extractPaths(
3678
+ doc,
3679
+ itemSchema,
3680
+ itemPath
3681
+ ), arrayMember = {
3682
+ path: itemPath,
3683
+ name: item._key,
3684
+ schemaType: itemSchema,
3685
+ value: item
3686
+ };
3687
+ arrayPaths = [...arrayPaths, arrayMember, ...innerFields];
3688
+ }
3689
+ }
3690
+ return [...acc, thisFieldWithPath, ...arrayPaths];
3691
+ }
3692
+ return [...acc, thisFieldWithPath];
3693
+ }, []);
3694
+ }
3695
+ var __defProp$1 = Object.defineProperty, __defProps$1 = Object.defineProperties, __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors, __getOwnPropSymbols$1 = Object.getOwnPropertySymbols, __hasOwnProp$1 = Object.prototype.hasOwnProperty, __propIsEnum$1 = Object.prototype.propertyIsEnumerable, __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$1 = (a, b) => {
3696
+ for (var prop in b || (b = {}))
3697
+ __hasOwnProp$1.call(b, prop) && __defNormalProp$1(a, prop, b[prop]);
3698
+ if (__getOwnPropSymbols$1)
3699
+ for (var prop of __getOwnPropSymbols$1(b))
3700
+ __propIsEnum$1.call(b, prop) && __defNormalProp$1(a, prop, b[prop]);
3701
+ return a;
3702
+ }, __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
3703
+ function LanguageOption(props) {
3704
+ var _a;
3705
+ const {
3706
+ language,
3707
+ schemaType,
3708
+ documentId,
3709
+ current,
3710
+ source,
3711
+ sourceLanguageId,
3712
+ metadata: metadata2,
3713
+ metadataId
3714
+ } = props, [userHasClicked, setUserHasClicked] = react.useState(!1), disabled = props.disabled || userHasClicked || current || !source || !sourceLanguageId || !metadataId, translation = metadata2 != null && metadata2.translations.length ? metadata2.translations.find((t) => t._key === language.id) : void 0, { apiVersion, languageField, weakReferences, callback } = useDocumentInternationalizationContext(), client = sanity.useClient({ apiVersion }), toast = ui.useToast(), open = useOpenInNewPane((_a = translation == null ? void 0 : translation.value) == null ? void 0 : _a._ref, schemaType.name), handleOpen = react.useCallback(() => open(), [open]);
3715
+ react.useEffect(() => {
3716
+ setUserHasClicked(!1);
3717
+ }, [!!translation]);
3718
+ const handleCreate = react.useCallback(async () => {
3719
+ if (!source)
3720
+ throw new Error("Cannot create translation without source document");
3721
+ if (!sourceLanguageId)
3722
+ throw new Error("Cannot create translation without source language ID");
3723
+ if (!metadataId)
3724
+ throw new Error("Cannot create translation without a metadata ID");
3725
+ setUserHasClicked(!0);
3726
+ const transaction = client.transaction(), newTranslationDocumentId = uuid.uuid();
3727
+ let newTranslationDocument = __spreadProps$1(__spreadValues$1({}, source), {
3728
+ _id: `drafts.${newTranslationDocumentId}`,
3729
+ // 2. Update language of the translation
3730
+ [languageField]: language.id
3731
+ });
3732
+ newTranslationDocument = removeExcludedPaths(
3733
+ newTranslationDocument,
3734
+ schemaType
3735
+ ), transaction.create(newTranslationDocument);
3736
+ const sourceReference = createReference(
3737
+ sourceLanguageId,
3738
+ documentId,
3739
+ schemaType.name,
3740
+ !weakReferences
3741
+ ), newTranslationReference = createReference(
3742
+ language.id,
3743
+ newTranslationDocumentId,
3744
+ schemaType.name,
3745
+ !weakReferences
3746
+ ), newMetadataDocument = {
3747
+ _id: metadataId,
3748
+ _type: METADATA_SCHEMA_NAME,
3749
+ schemaTypes: [schemaType.name],
3750
+ translations: [sourceReference]
3751
+ };
3752
+ transaction.createIfNotExists(newMetadataDocument);
3753
+ const metadataPatch = client.patch(metadataId).setIfMissing({ translations: [sourceReference] }).insert("after", "translations[-1]", [newTranslationReference]);
3754
+ transaction.patch(metadataPatch), transaction.commit().then(() => {
3755
+ const metadataExisted = !!(metadata2 != null && metadata2._createdAt);
3756
+ return callback == null || callback({
3757
+ client,
3758
+ sourceLanguageId,
3759
+ sourceDocument: source,
3760
+ newDocument: newTranslationDocument,
3761
+ destinationLanguageId: language.id,
3762
+ metaDocumentId: metadataId
3763
+ }).catch((err) => {
3764
+ toast.push({
3765
+ status: "error",
3766
+ title: "Callback",
3767
+ description: `Error while running callback - ${err}.`
3768
+ });
3769
+ }), toast.push({
3770
+ status: "success",
3771
+ title: `Created "${language.title}" translation`,
3772
+ description: metadataExisted ? "Updated Translations Metadata" : "Created Translations Metadata"
3773
+ });
3774
+ }).catch((err) => (console.error(err), setUserHasClicked(!1), toast.push({
3775
+ status: "error",
3776
+ title: "Error creating translation",
3777
+ description: err.message
3778
+ })));
3779
+ }, [
3780
+ client,
3781
+ documentId,
3782
+ language.id,
3783
+ language.title,
3784
+ languageField,
3785
+ metadata2 == null ? void 0 : metadata2._createdAt,
3786
+ metadataId,
3787
+ schemaType,
3788
+ source,
3789
+ sourceLanguageId,
3790
+ toast,
3791
+ weakReferences,
3792
+ callback
3793
+ ]);
3794
+ let message;
3795
+ return current ? message = "Current document" : translation ? message = `Open ${language.title} translation` : translation || (message = `Create new ${language.title} translation`), /* @__PURE__ */ jsxRuntime.jsx(
3796
+ ui.Tooltip,
3797
+ {
3798
+ animate: !0,
3799
+ content: /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { padding: 2, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { muted: !0, size: 1, children: message }) }),
3800
+ fallbackPlacements: ["right", "left"],
3801
+ placement: "top",
3802
+ portal: !0,
3803
+ children: /* @__PURE__ */ jsxRuntime.jsx(
966
3804
  ui.Button,
967
3805
  {
968
3806
  onClick: translation ? handleOpen : handleCreate,
@@ -1425,10 +4263,17 @@ var metadata = (schemaTypes, metadataFields) => sanity.defineType({
1425
4263
  };
1426
4264
  }
1427
4265
  }
1428
- });
4266
+ }), __defProp2 = Object.defineProperty, __defProps = Object.defineProperties, __getOwnPropDescs = Object.getOwnPropertyDescriptors, __getOwnPropSymbols2 = Object.getOwnPropertySymbols, __hasOwnProp2 = Object.prototype.hasOwnProperty, __propIsEnum2 = Object.prototype.propertyIsEnumerable, __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues2 = (a, b) => {
4267
+ for (var prop in b || (b = {}))
4268
+ __hasOwnProp2.call(b, prop) && __defNormalProp2(a, prop, b[prop]);
4269
+ if (__getOwnPropSymbols2)
4270
+ for (var prop of __getOwnPropSymbols2(b))
4271
+ __propIsEnum2.call(b, prop) && __defNormalProp2(a, prop, b[prop]);
4272
+ return a;
4273
+ }, __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1429
4274
  const documentInternationalization = sanity.definePlugin(
1430
4275
  (config2) => {
1431
- const pluginConfig = { ...DEFAULT_CONFIG, ...config2 }, {
4276
+ const pluginConfig = __spreadValues2(__spreadValues2({}, DEFAULT_CONFIG), config2), {
1432
4277
  supportedLanguages,
1433
4278
  schemaTypes,
1434
4279
  languageField,
@@ -1443,7 +4288,7 @@ const documentInternationalization = sanity.definePlugin(
1443
4288
  name: "@sanity/document-internationalization",
1444
4289
  studio: {
1445
4290
  components: {
1446
- layout: (props) => DocumentInternationalizationProvider({ ...props, pluginConfig })
4291
+ layout: (props) => DocumentInternationalizationProvider(__spreadProps(__spreadValues2({}, props), { pluginConfig }))
1447
4292
  }
1448
4293
  },
1449
4294
  i18n: {
@@ -1485,7 +4330,7 @@ const documentInternationalization = sanity.definePlugin(
1485
4330
  const { schemaType, documentId } = ctx;
1486
4331
  return schemaTypes.includes(schemaType) && documentId ? [
1487
4332
  ...prev,
1488
- (props) => DocumentInternationalizationMenu({ ...props, documentId })
4333
+ (props) => DocumentInternationalizationMenu(__spreadProps(__spreadValues2({}, props), { documentId }))
1489
4334
  ] : prev;
1490
4335
  },
1491
4336
  badges: (prev, { schemaType }) => schemaTypes.includes(schemaType) ? [(props) => LanguageBadge(props), ...prev] : prev,
@@ -1561,14 +4406,14 @@ const documentInternationalization = sanity.definePlugin(
1561
4406
  ),
1562
4407
  options: {
1563
4408
  // @ts-expect-error - Update type once it knows the values of this filter
1564
- filter: ({ parent, document }) => {
4409
+ filter: ({ parent, document: document2 }) => {
1565
4410
  if (!parent)
1566
4411
  return null;
1567
4412
  const language = (Array.isArray(parent) ? parent : [parent]).find((p) => p._key);
1568
- return language != null && language._key ? document.schemaTypes ? {
4413
+ return language != null && language._key ? document2.schemaTypes ? {
1569
4414
  filter: `_type in $schemaTypes && ${languageField} == $language`,
1570
4415
  params: {
1571
- schemaTypes: document.schemaTypes,
4416
+ schemaTypes: document2.schemaTypes,
1572
4417
  language: language._key
1573
4418
  }
1574
4419
  } : {