@sanity/document-internationalization 3.1.0 → 3.2.1

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