@sanity/document-internationalization 3.3.0 → 3.3.2

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