@sanity/embeddings-index-ui 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2792 @@
1
+ import { useClient, useSchema, DefaultPreview, useDocumentPreviewStore, SanityDefaultPreview, getPreviewValueWithFallback, getPreviewStateObservable, typed, unset, setIfMissing, set, definePlugin, isObjectInputProps } from 'sanity';
2
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
3
+ import { Card, Button, Box, Flex, Autocomplete, Text, Stack, Label, TextInput, TextArea, Dialog, Spinner, Heading, MenuButton, Menu, MenuItem } from '@sanity/ui';
4
+ import { ErrorOutlineIcon, EarthGlobeIcon, LinkIcon, AddIcon, SearchIcon, EllipsisVerticalIcon, TrashIcon, UndoIcon } from '@sanity/icons';
5
+ import require$$0, { useMemo, useRef, useEffect, useState, useCallback, useId } from 'react';
6
+ import { useIntentLink } from 'sanity/router';
7
+ import { useDocumentPane } from 'sanity/desk';
8
+
9
+ /******************************************************************************
10
+ Copyright (c) Microsoft Corporation.
11
+
12
+ Permission to use, copy, modify, and/or distribute this software for any
13
+ purpose with or without fee is hereby granted.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
16
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
17
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
18
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
19
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
20
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
21
+ PERFORMANCE OF THIS SOFTWARE.
22
+ ***************************************************************************** */
23
+ /* global Reflect, Promise, SuppressedError, Symbol */
24
+
25
+ var extendStatics = function (d, b) {
26
+ extendStatics = Object.setPrototypeOf || {
27
+ __proto__: []
28
+ } instanceof Array && function (d, b) {
29
+ d.__proto__ = b;
30
+ } || function (d, b) {
31
+ for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
32
+ };
33
+ return extendStatics(d, b);
34
+ };
35
+ function __extends(d, b) {
36
+ if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
37
+ extendStatics(d, b);
38
+ function __() {
39
+ this.constructor = d;
40
+ }
41
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
42
+ }
43
+ function __awaiter(thisArg, _arguments, P, generator) {
44
+ function adopt(value) {
45
+ return value instanceof P ? value : new P(function (resolve) {
46
+ resolve(value);
47
+ });
48
+ }
49
+ return new (P || (P = Promise))(function (resolve, reject) {
50
+ function fulfilled(value) {
51
+ try {
52
+ step(generator.next(value));
53
+ } catch (e) {
54
+ reject(e);
55
+ }
56
+ }
57
+ function rejected(value) {
58
+ try {
59
+ step(generator["throw"](value));
60
+ } catch (e) {
61
+ reject(e);
62
+ }
63
+ }
64
+ function step(result) {
65
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
66
+ }
67
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
68
+ });
69
+ }
70
+ function __generator(thisArg, body) {
71
+ var _ = {
72
+ label: 0,
73
+ sent: function () {
74
+ if (t[0] & 1) throw t[1];
75
+ return t[1];
76
+ },
77
+ trys: [],
78
+ ops: []
79
+ },
80
+ f,
81
+ y,
82
+ t,
83
+ g;
84
+ return g = {
85
+ next: verb(0),
86
+ "throw": verb(1),
87
+ "return": verb(2)
88
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
89
+ return this;
90
+ }), g;
91
+ function verb(n) {
92
+ return function (v) {
93
+ return step([n, v]);
94
+ };
95
+ }
96
+ function step(op) {
97
+ if (f) throw new TypeError("Generator is already executing.");
98
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
99
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
100
+ if (y = 0, t) op = [op[0] & 2, t.value];
101
+ switch (op[0]) {
102
+ case 0:
103
+ case 1:
104
+ t = op;
105
+ break;
106
+ case 4:
107
+ _.label++;
108
+ return {
109
+ value: op[1],
110
+ done: false
111
+ };
112
+ case 5:
113
+ _.label++;
114
+ y = op[1];
115
+ op = [0];
116
+ continue;
117
+ case 7:
118
+ op = _.ops.pop();
119
+ _.trys.pop();
120
+ continue;
121
+ default:
122
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
123
+ _ = 0;
124
+ continue;
125
+ }
126
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
127
+ _.label = op[1];
128
+ break;
129
+ }
130
+ if (op[0] === 6 && _.label < t[1]) {
131
+ _.label = t[1];
132
+ t = op;
133
+ break;
134
+ }
135
+ if (t && _.label < t[2]) {
136
+ _.label = t[2];
137
+ _.ops.push(op);
138
+ break;
139
+ }
140
+ if (t[2]) _.ops.pop();
141
+ _.trys.pop();
142
+ continue;
143
+ }
144
+ op = body.call(thisArg, _);
145
+ } catch (e) {
146
+ op = [6, e];
147
+ y = 0;
148
+ } finally {
149
+ f = t = 0;
150
+ }
151
+ if (op[0] & 5) throw op[1];
152
+ return {
153
+ value: op[0] ? op[1] : void 0,
154
+ done: true
155
+ };
156
+ }
157
+ }
158
+ function __values(o) {
159
+ var s = typeof Symbol === "function" && Symbol.iterator,
160
+ m = s && o[s],
161
+ i = 0;
162
+ if (m) return m.call(o);
163
+ if (o && typeof o.length === "number") return {
164
+ next: function () {
165
+ if (o && i >= o.length) o = void 0;
166
+ return {
167
+ value: o && o[i++],
168
+ done: !o
169
+ };
170
+ }
171
+ };
172
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
173
+ }
174
+ function __read(o, n) {
175
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
176
+ if (!m) return o;
177
+ var i = m.call(o),
178
+ r,
179
+ ar = [],
180
+ e;
181
+ try {
182
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
183
+ } catch (error) {
184
+ e = {
185
+ error: error
186
+ };
187
+ } finally {
188
+ try {
189
+ if (r && !r.done && (m = i["return"])) m.call(i);
190
+ } finally {
191
+ if (e) throw e.error;
192
+ }
193
+ }
194
+ return ar;
195
+ }
196
+ function __spreadArray(to, from, pack) {
197
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
198
+ if (ar || !(i in from)) {
199
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
200
+ ar[i] = from[i];
201
+ }
202
+ }
203
+ return to.concat(ar || Array.prototype.slice.call(from));
204
+ }
205
+ function __await(v) {
206
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
207
+ }
208
+ function __asyncGenerator(thisArg, _arguments, generator) {
209
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
210
+ var g = generator.apply(thisArg, _arguments || []),
211
+ i,
212
+ q = [];
213
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {
214
+ return this;
215
+ }, i;
216
+ function verb(n) {
217
+ if (g[n]) i[n] = function (v) {
218
+ return new Promise(function (a, b) {
219
+ q.push([n, v, a, b]) > 1 || resume(n, v);
220
+ });
221
+ };
222
+ }
223
+ function resume(n, v) {
224
+ try {
225
+ step(g[n](v));
226
+ } catch (e) {
227
+ settle(q[0][3], e);
228
+ }
229
+ }
230
+ function step(r) {
231
+ r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
232
+ }
233
+ function fulfill(value) {
234
+ resume("next", value);
235
+ }
236
+ function reject(value) {
237
+ resume("throw", value);
238
+ }
239
+ function settle(f, v) {
240
+ if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
241
+ }
242
+ }
243
+ function __asyncValues(o) {
244
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
245
+ var m = o[Symbol.asyncIterator],
246
+ i;
247
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {
248
+ return this;
249
+ }, i);
250
+ function verb(n) {
251
+ i[n] = o[n] && function (v) {
252
+ return new Promise(function (resolve, reject) {
253
+ v = o[n](v), settle(resolve, reject, v.done, v.value);
254
+ });
255
+ };
256
+ }
257
+ function settle(resolve, reject, d, v) {
258
+ Promise.resolve(v).then(function (v) {
259
+ resolve({
260
+ value: v,
261
+ done: d
262
+ });
263
+ }, reject);
264
+ }
265
+ }
266
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
267
+ var e = new Error(message);
268
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
269
+ };
270
+ function isFunction(value) {
271
+ return typeof value === 'function';
272
+ }
273
+ function createErrorClass(createImpl) {
274
+ var _super = function (instance) {
275
+ Error.call(instance);
276
+ instance.stack = new Error().stack;
277
+ };
278
+ var ctorFunc = createImpl(_super);
279
+ ctorFunc.prototype = Object.create(Error.prototype);
280
+ ctorFunc.prototype.constructor = ctorFunc;
281
+ return ctorFunc;
282
+ }
283
+ var UnsubscriptionError = createErrorClass(function (_super) {
284
+ return function UnsubscriptionErrorImpl(errors) {
285
+ _super(this);
286
+ this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) {
287
+ return i + 1 + ") " + err.toString();
288
+ }).join('\n ') : '';
289
+ this.name = 'UnsubscriptionError';
290
+ this.errors = errors;
291
+ };
292
+ });
293
+ function arrRemove(arr, item) {
294
+ if (arr) {
295
+ var index = arr.indexOf(item);
296
+ 0 <= index && arr.splice(index, 1);
297
+ }
298
+ }
299
+ var Subscription = function () {
300
+ function Subscription(initialTeardown) {
301
+ this.initialTeardown = initialTeardown;
302
+ this.closed = false;
303
+ this._parentage = null;
304
+ this._finalizers = null;
305
+ }
306
+ Subscription.prototype.unsubscribe = function () {
307
+ var e_1, _a, e_2, _b;
308
+ var errors;
309
+ if (!this.closed) {
310
+ this.closed = true;
311
+ var _parentage = this._parentage;
312
+ if (_parentage) {
313
+ this._parentage = null;
314
+ if (Array.isArray(_parentage)) {
315
+ try {
316
+ for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
317
+ var parent_1 = _parentage_1_1.value;
318
+ parent_1.remove(this);
319
+ }
320
+ } catch (e_1_1) {
321
+ e_1 = {
322
+ error: e_1_1
323
+ };
324
+ } finally {
325
+ try {
326
+ if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
327
+ } finally {
328
+ if (e_1) throw e_1.error;
329
+ }
330
+ }
331
+ } else {
332
+ _parentage.remove(this);
333
+ }
334
+ }
335
+ var initialFinalizer = this.initialTeardown;
336
+ if (isFunction(initialFinalizer)) {
337
+ try {
338
+ initialFinalizer();
339
+ } catch (e) {
340
+ errors = e instanceof UnsubscriptionError ? e.errors : [e];
341
+ }
342
+ }
343
+ var _finalizers = this._finalizers;
344
+ if (_finalizers) {
345
+ this._finalizers = null;
346
+ try {
347
+ for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
348
+ var finalizer = _finalizers_1_1.value;
349
+ try {
350
+ execFinalizer(finalizer);
351
+ } catch (err) {
352
+ errors = errors !== null && errors !== void 0 ? errors : [];
353
+ if (err instanceof UnsubscriptionError) {
354
+ errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
355
+ } else {
356
+ errors.push(err);
357
+ }
358
+ }
359
+ }
360
+ } catch (e_2_1) {
361
+ e_2 = {
362
+ error: e_2_1
363
+ };
364
+ } finally {
365
+ try {
366
+ if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
367
+ } finally {
368
+ if (e_2) throw e_2.error;
369
+ }
370
+ }
371
+ }
372
+ if (errors) {
373
+ throw new UnsubscriptionError(errors);
374
+ }
375
+ }
376
+ };
377
+ Subscription.prototype.add = function (teardown) {
378
+ var _a;
379
+ if (teardown && teardown !== this) {
380
+ if (this.closed) {
381
+ execFinalizer(teardown);
382
+ } else {
383
+ if (teardown instanceof Subscription) {
384
+ if (teardown.closed || teardown._hasParent(this)) {
385
+ return;
386
+ }
387
+ teardown._addParent(this);
388
+ }
389
+ (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
390
+ }
391
+ }
392
+ };
393
+ Subscription.prototype._hasParent = function (parent) {
394
+ var _parentage = this._parentage;
395
+ return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent);
396
+ };
397
+ Subscription.prototype._addParent = function (parent) {
398
+ var _parentage = this._parentage;
399
+ this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
400
+ };
401
+ Subscription.prototype._removeParent = function (parent) {
402
+ var _parentage = this._parentage;
403
+ if (_parentage === parent) {
404
+ this._parentage = null;
405
+ } else if (Array.isArray(_parentage)) {
406
+ arrRemove(_parentage, parent);
407
+ }
408
+ };
409
+ Subscription.prototype.remove = function (teardown) {
410
+ var _finalizers = this._finalizers;
411
+ _finalizers && arrRemove(_finalizers, teardown);
412
+ if (teardown instanceof Subscription) {
413
+ teardown._removeParent(this);
414
+ }
415
+ };
416
+ Subscription.EMPTY = function () {
417
+ var empty = new Subscription();
418
+ empty.closed = true;
419
+ return empty;
420
+ }();
421
+ return Subscription;
422
+ }();
423
+ var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
424
+ function isSubscription(value) {
425
+ return value instanceof Subscription || value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe);
426
+ }
427
+ function execFinalizer(finalizer) {
428
+ if (isFunction(finalizer)) {
429
+ finalizer();
430
+ } else {
431
+ finalizer.unsubscribe();
432
+ }
433
+ }
434
+ var config = {
435
+ onUnhandledError: null,
436
+ onStoppedNotification: null,
437
+ Promise: undefined,
438
+ useDeprecatedSynchronousErrorHandling: false,
439
+ useDeprecatedNextContext: false
440
+ };
441
+ var timeoutProvider = {
442
+ setTimeout: function (handler, timeout) {
443
+ var args = [];
444
+ for (var _i = 2; _i < arguments.length; _i++) {
445
+ args[_i - 2] = arguments[_i];
446
+ }
447
+ return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
448
+ },
449
+ clearTimeout: function (handle) {
450
+ return clearTimeout(handle);
451
+ },
452
+ delegate: undefined
453
+ };
454
+ function reportUnhandledError(err) {
455
+ timeoutProvider.setTimeout(function () {
456
+ {
457
+ throw err;
458
+ }
459
+ });
460
+ }
461
+ function noop() {}
462
+ function errorContext(cb) {
463
+ {
464
+ cb();
465
+ }
466
+ }
467
+ var Subscriber = function (_super) {
468
+ __extends(Subscriber, _super);
469
+ function Subscriber(destination) {
470
+ var _this = _super.call(this) || this;
471
+ _this.isStopped = false;
472
+ if (destination) {
473
+ _this.destination = destination;
474
+ if (isSubscription(destination)) {
475
+ destination.add(_this);
476
+ }
477
+ } else {
478
+ _this.destination = EMPTY_OBSERVER;
479
+ }
480
+ return _this;
481
+ }
482
+ Subscriber.create = function (next, error, complete) {
483
+ return new SafeSubscriber(next, error, complete);
484
+ };
485
+ Subscriber.prototype.next = function (value) {
486
+ if (this.isStopped) ;else {
487
+ this._next(value);
488
+ }
489
+ };
490
+ Subscriber.prototype.error = function (err) {
491
+ if (this.isStopped) ;else {
492
+ this.isStopped = true;
493
+ this._error(err);
494
+ }
495
+ };
496
+ Subscriber.prototype.complete = function () {
497
+ if (this.isStopped) ;else {
498
+ this.isStopped = true;
499
+ this._complete();
500
+ }
501
+ };
502
+ Subscriber.prototype.unsubscribe = function () {
503
+ if (!this.closed) {
504
+ this.isStopped = true;
505
+ _super.prototype.unsubscribe.call(this);
506
+ this.destination = null;
507
+ }
508
+ };
509
+ Subscriber.prototype._next = function (value) {
510
+ this.destination.next(value);
511
+ };
512
+ Subscriber.prototype._error = function (err) {
513
+ try {
514
+ this.destination.error(err);
515
+ } finally {
516
+ this.unsubscribe();
517
+ }
518
+ };
519
+ Subscriber.prototype._complete = function () {
520
+ try {
521
+ this.destination.complete();
522
+ } finally {
523
+ this.unsubscribe();
524
+ }
525
+ };
526
+ return Subscriber;
527
+ }(Subscription);
528
+ var _bind = Function.prototype.bind;
529
+ function bind(fn, thisArg) {
530
+ return _bind.call(fn, thisArg);
531
+ }
532
+ var ConsumerObserver = function () {
533
+ function ConsumerObserver(partialObserver) {
534
+ this.partialObserver = partialObserver;
535
+ }
536
+ ConsumerObserver.prototype.next = function (value) {
537
+ var partialObserver = this.partialObserver;
538
+ if (partialObserver.next) {
539
+ try {
540
+ partialObserver.next(value);
541
+ } catch (error) {
542
+ handleUnhandledError(error);
543
+ }
544
+ }
545
+ };
546
+ ConsumerObserver.prototype.error = function (err) {
547
+ var partialObserver = this.partialObserver;
548
+ if (partialObserver.error) {
549
+ try {
550
+ partialObserver.error(err);
551
+ } catch (error) {
552
+ handleUnhandledError(error);
553
+ }
554
+ } else {
555
+ handleUnhandledError(err);
556
+ }
557
+ };
558
+ ConsumerObserver.prototype.complete = function () {
559
+ var partialObserver = this.partialObserver;
560
+ if (partialObserver.complete) {
561
+ try {
562
+ partialObserver.complete();
563
+ } catch (error) {
564
+ handleUnhandledError(error);
565
+ }
566
+ }
567
+ };
568
+ return ConsumerObserver;
569
+ }();
570
+ var SafeSubscriber = function (_super) {
571
+ __extends(SafeSubscriber, _super);
572
+ function SafeSubscriber(observerOrNext, error, complete) {
573
+ var _this = _super.call(this) || this;
574
+ var partialObserver;
575
+ if (isFunction(observerOrNext) || !observerOrNext) {
576
+ partialObserver = {
577
+ next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined,
578
+ error: error !== null && error !== void 0 ? error : undefined,
579
+ complete: complete !== null && complete !== void 0 ? complete : undefined
580
+ };
581
+ } else {
582
+ var context_1;
583
+ if (_this && config.useDeprecatedNextContext) {
584
+ context_1 = Object.create(observerOrNext);
585
+ context_1.unsubscribe = function () {
586
+ return _this.unsubscribe();
587
+ };
588
+ partialObserver = {
589
+ next: observerOrNext.next && bind(observerOrNext.next, context_1),
590
+ error: observerOrNext.error && bind(observerOrNext.error, context_1),
591
+ complete: observerOrNext.complete && bind(observerOrNext.complete, context_1)
592
+ };
593
+ } else {
594
+ partialObserver = observerOrNext;
595
+ }
596
+ }
597
+ _this.destination = new ConsumerObserver(partialObserver);
598
+ return _this;
599
+ }
600
+ return SafeSubscriber;
601
+ }(Subscriber);
602
+ function handleUnhandledError(error) {
603
+ {
604
+ reportUnhandledError(error);
605
+ }
606
+ }
607
+ function defaultErrorHandler(err) {
608
+ throw err;
609
+ }
610
+ var EMPTY_OBSERVER = {
611
+ closed: true,
612
+ next: noop,
613
+ error: defaultErrorHandler,
614
+ complete: noop
615
+ };
616
+ var observable = function () {
617
+ return typeof Symbol === 'function' && Symbol.observable || '@@observable';
618
+ }();
619
+ function identity(x) {
620
+ return x;
621
+ }
622
+ function pipeFromArray(fns) {
623
+ if (fns.length === 0) {
624
+ return identity;
625
+ }
626
+ if (fns.length === 1) {
627
+ return fns[0];
628
+ }
629
+ return function piped(input) {
630
+ return fns.reduce(function (prev, fn) {
631
+ return fn(prev);
632
+ }, input);
633
+ };
634
+ }
635
+ var Observable = function () {
636
+ function Observable(subscribe) {
637
+ if (subscribe) {
638
+ this._subscribe = subscribe;
639
+ }
640
+ }
641
+ Observable.prototype.lift = function (operator) {
642
+ var observable = new Observable();
643
+ observable.source = this;
644
+ observable.operator = operator;
645
+ return observable;
646
+ };
647
+ Observable.prototype.subscribe = function (observerOrNext, error, complete) {
648
+ var _this = this;
649
+ var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
650
+ errorContext(function () {
651
+ var _a = _this,
652
+ operator = _a.operator,
653
+ source = _a.source;
654
+ subscriber.add(operator ? operator.call(subscriber, source) : source ? _this._subscribe(subscriber) : _this._trySubscribe(subscriber));
655
+ });
656
+ return subscriber;
657
+ };
658
+ Observable.prototype._trySubscribe = function (sink) {
659
+ try {
660
+ return this._subscribe(sink);
661
+ } catch (err) {
662
+ sink.error(err);
663
+ }
664
+ };
665
+ Observable.prototype.forEach = function (next, promiseCtor) {
666
+ var _this = this;
667
+ promiseCtor = getPromiseCtor(promiseCtor);
668
+ return new promiseCtor(function (resolve, reject) {
669
+ var subscriber = new SafeSubscriber({
670
+ next: function (value) {
671
+ try {
672
+ next(value);
673
+ } catch (err) {
674
+ reject(err);
675
+ subscriber.unsubscribe();
676
+ }
677
+ },
678
+ error: reject,
679
+ complete: resolve
680
+ });
681
+ _this.subscribe(subscriber);
682
+ });
683
+ };
684
+ Observable.prototype._subscribe = function (subscriber) {
685
+ var _a;
686
+ return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
687
+ };
688
+ Observable.prototype[observable] = function () {
689
+ return this;
690
+ };
691
+ Observable.prototype.pipe = function () {
692
+ var operations = [];
693
+ for (var _i = 0; _i < arguments.length; _i++) {
694
+ operations[_i] = arguments[_i];
695
+ }
696
+ return pipeFromArray(operations)(this);
697
+ };
698
+ Observable.prototype.toPromise = function (promiseCtor) {
699
+ var _this = this;
700
+ promiseCtor = getPromiseCtor(promiseCtor);
701
+ return new promiseCtor(function (resolve, reject) {
702
+ var value;
703
+ _this.subscribe(function (x) {
704
+ return value = x;
705
+ }, function (err) {
706
+ return reject(err);
707
+ }, function () {
708
+ return resolve(value);
709
+ });
710
+ });
711
+ };
712
+ Observable.create = function (subscribe) {
713
+ return new Observable(subscribe);
714
+ };
715
+ return Observable;
716
+ }();
717
+ function getPromiseCtor(promiseCtor) {
718
+ var _a;
719
+ return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;
720
+ }
721
+ function isObserver(value) {
722
+ return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
723
+ }
724
+ function isSubscriber(value) {
725
+ return value && value instanceof Subscriber || isObserver(value) && isSubscription(value);
726
+ }
727
+ function hasLift(source) {
728
+ return isFunction(source === null || source === void 0 ? void 0 : source.lift);
729
+ }
730
+ function operate(init) {
731
+ return function (source) {
732
+ if (hasLift(source)) {
733
+ return source.lift(function (liftedSource) {
734
+ try {
735
+ return init(liftedSource, this);
736
+ } catch (err) {
737
+ this.error(err);
738
+ }
739
+ });
740
+ }
741
+ throw new TypeError('Unable to lift unknown Observable type');
742
+ };
743
+ }
744
+ function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
745
+ return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
746
+ }
747
+ var OperatorSubscriber = function (_super) {
748
+ __extends(OperatorSubscriber, _super);
749
+ function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
750
+ var _this = _super.call(this, destination) || this;
751
+ _this.onFinalize = onFinalize;
752
+ _this.shouldUnsubscribe = shouldUnsubscribe;
753
+ _this._next = onNext ? function (value) {
754
+ try {
755
+ onNext(value);
756
+ } catch (err) {
757
+ destination.error(err);
758
+ }
759
+ } : _super.prototype._next;
760
+ _this._error = onError ? function (err) {
761
+ try {
762
+ onError(err);
763
+ } catch (err) {
764
+ destination.error(err);
765
+ } finally {
766
+ this.unsubscribe();
767
+ }
768
+ } : _super.prototype._error;
769
+ _this._complete = onComplete ? function () {
770
+ try {
771
+ onComplete();
772
+ } catch (err) {
773
+ destination.error(err);
774
+ } finally {
775
+ this.unsubscribe();
776
+ }
777
+ } : _super.prototype._complete;
778
+ return _this;
779
+ }
780
+ OperatorSubscriber.prototype.unsubscribe = function () {
781
+ var _a;
782
+ if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
783
+ var closed_1 = this.closed;
784
+ _super.prototype.unsubscribe.call(this);
785
+ !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
786
+ }
787
+ };
788
+ return OperatorSubscriber;
789
+ }(Subscriber);
790
+ var ObjectUnsubscribedError = createErrorClass(function (_super) {
791
+ return function ObjectUnsubscribedErrorImpl() {
792
+ _super(this);
793
+ this.name = 'ObjectUnsubscribedError';
794
+ this.message = 'object unsubscribed';
795
+ };
796
+ });
797
+ var Subject = function (_super) {
798
+ __extends(Subject, _super);
799
+ function Subject() {
800
+ var _this = _super.call(this) || this;
801
+ _this.closed = false;
802
+ _this.currentObservers = null;
803
+ _this.observers = [];
804
+ _this.isStopped = false;
805
+ _this.hasError = false;
806
+ _this.thrownError = null;
807
+ return _this;
808
+ }
809
+ Subject.prototype.lift = function (operator) {
810
+ var subject = new AnonymousSubject(this, this);
811
+ subject.operator = operator;
812
+ return subject;
813
+ };
814
+ Subject.prototype._throwIfClosed = function () {
815
+ if (this.closed) {
816
+ throw new ObjectUnsubscribedError();
817
+ }
818
+ };
819
+ Subject.prototype.next = function (value) {
820
+ var _this = this;
821
+ errorContext(function () {
822
+ var e_1, _a;
823
+ _this._throwIfClosed();
824
+ if (!_this.isStopped) {
825
+ if (!_this.currentObservers) {
826
+ _this.currentObservers = Array.from(_this.observers);
827
+ }
828
+ try {
829
+ for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
830
+ var observer = _c.value;
831
+ observer.next(value);
832
+ }
833
+ } catch (e_1_1) {
834
+ e_1 = {
835
+ error: e_1_1
836
+ };
837
+ } finally {
838
+ try {
839
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
840
+ } finally {
841
+ if (e_1) throw e_1.error;
842
+ }
843
+ }
844
+ }
845
+ });
846
+ };
847
+ Subject.prototype.error = function (err) {
848
+ var _this = this;
849
+ errorContext(function () {
850
+ _this._throwIfClosed();
851
+ if (!_this.isStopped) {
852
+ _this.hasError = _this.isStopped = true;
853
+ _this.thrownError = err;
854
+ var observers = _this.observers;
855
+ while (observers.length) {
856
+ observers.shift().error(err);
857
+ }
858
+ }
859
+ });
860
+ };
861
+ Subject.prototype.complete = function () {
862
+ var _this = this;
863
+ errorContext(function () {
864
+ _this._throwIfClosed();
865
+ if (!_this.isStopped) {
866
+ _this.isStopped = true;
867
+ var observers = _this.observers;
868
+ while (observers.length) {
869
+ observers.shift().complete();
870
+ }
871
+ }
872
+ });
873
+ };
874
+ Subject.prototype.unsubscribe = function () {
875
+ this.isStopped = this.closed = true;
876
+ this.observers = this.currentObservers = null;
877
+ };
878
+ Object.defineProperty(Subject.prototype, "observed", {
879
+ get: function () {
880
+ var _a;
881
+ return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
882
+ },
883
+ enumerable: false,
884
+ configurable: true
885
+ });
886
+ Subject.prototype._trySubscribe = function (subscriber) {
887
+ this._throwIfClosed();
888
+ return _super.prototype._trySubscribe.call(this, subscriber);
889
+ };
890
+ Subject.prototype._subscribe = function (subscriber) {
891
+ this._throwIfClosed();
892
+ this._checkFinalizedStatuses(subscriber);
893
+ return this._innerSubscribe(subscriber);
894
+ };
895
+ Subject.prototype._innerSubscribe = function (subscriber) {
896
+ var _this = this;
897
+ var _a = this,
898
+ hasError = _a.hasError,
899
+ isStopped = _a.isStopped,
900
+ observers = _a.observers;
901
+ if (hasError || isStopped) {
902
+ return EMPTY_SUBSCRIPTION;
903
+ }
904
+ this.currentObservers = null;
905
+ observers.push(subscriber);
906
+ return new Subscription(function () {
907
+ _this.currentObservers = null;
908
+ arrRemove(observers, subscriber);
909
+ });
910
+ };
911
+ Subject.prototype._checkFinalizedStatuses = function (subscriber) {
912
+ var _a = this,
913
+ hasError = _a.hasError,
914
+ thrownError = _a.thrownError,
915
+ isStopped = _a.isStopped;
916
+ if (hasError) {
917
+ subscriber.error(thrownError);
918
+ } else if (isStopped) {
919
+ subscriber.complete();
920
+ }
921
+ };
922
+ Subject.prototype.asObservable = function () {
923
+ var observable = new Observable();
924
+ observable.source = this;
925
+ return observable;
926
+ };
927
+ Subject.create = function (destination, source) {
928
+ return new AnonymousSubject(destination, source);
929
+ };
930
+ return Subject;
931
+ }(Observable);
932
+ var AnonymousSubject = function (_super) {
933
+ __extends(AnonymousSubject, _super);
934
+ function AnonymousSubject(destination, source) {
935
+ var _this = _super.call(this) || this;
936
+ _this.destination = destination;
937
+ _this.source = source;
938
+ return _this;
939
+ }
940
+ AnonymousSubject.prototype.next = function (value) {
941
+ var _a, _b;
942
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
943
+ };
944
+ AnonymousSubject.prototype.error = function (err) {
945
+ var _a, _b;
946
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
947
+ };
948
+ AnonymousSubject.prototype.complete = function () {
949
+ var _a, _b;
950
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
951
+ };
952
+ AnonymousSubject.prototype._subscribe = function (subscriber) {
953
+ var _a, _b;
954
+ return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;
955
+ };
956
+ return AnonymousSubject;
957
+ }(Subject);
958
+ var dateTimestampProvider = {
959
+ now: function () {
960
+ return (dateTimestampProvider.delegate || Date).now();
961
+ },
962
+ delegate: undefined
963
+ };
964
+ var ReplaySubject = function (_super) {
965
+ __extends(ReplaySubject, _super);
966
+ function ReplaySubject(_bufferSize, _windowTime, _timestampProvider) {
967
+ if (_bufferSize === void 0) {
968
+ _bufferSize = Infinity;
969
+ }
970
+ if (_windowTime === void 0) {
971
+ _windowTime = Infinity;
972
+ }
973
+ if (_timestampProvider === void 0) {
974
+ _timestampProvider = dateTimestampProvider;
975
+ }
976
+ var _this = _super.call(this) || this;
977
+ _this._bufferSize = _bufferSize;
978
+ _this._windowTime = _windowTime;
979
+ _this._timestampProvider = _timestampProvider;
980
+ _this._buffer = [];
981
+ _this._infiniteTimeWindow = true;
982
+ _this._infiniteTimeWindow = _windowTime === Infinity;
983
+ _this._bufferSize = Math.max(1, _bufferSize);
984
+ _this._windowTime = Math.max(1, _windowTime);
985
+ return _this;
986
+ }
987
+ ReplaySubject.prototype.next = function (value) {
988
+ var _a = this,
989
+ isStopped = _a.isStopped,
990
+ _buffer = _a._buffer,
991
+ _infiniteTimeWindow = _a._infiniteTimeWindow,
992
+ _timestampProvider = _a._timestampProvider,
993
+ _windowTime = _a._windowTime;
994
+ if (!isStopped) {
995
+ _buffer.push(value);
996
+ !_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime);
997
+ }
998
+ this._trimBuffer();
999
+ _super.prototype.next.call(this, value);
1000
+ };
1001
+ ReplaySubject.prototype._subscribe = function (subscriber) {
1002
+ this._throwIfClosed();
1003
+ this._trimBuffer();
1004
+ var subscription = this._innerSubscribe(subscriber);
1005
+ var _a = this,
1006
+ _infiniteTimeWindow = _a._infiniteTimeWindow,
1007
+ _buffer = _a._buffer;
1008
+ var copy = _buffer.slice();
1009
+ for (var i = 0; i < copy.length && !subscriber.closed; i += _infiniteTimeWindow ? 1 : 2) {
1010
+ subscriber.next(copy[i]);
1011
+ }
1012
+ this._checkFinalizedStatuses(subscriber);
1013
+ return subscription;
1014
+ };
1015
+ ReplaySubject.prototype._trimBuffer = function () {
1016
+ var _a = this,
1017
+ _bufferSize = _a._bufferSize,
1018
+ _timestampProvider = _a._timestampProvider,
1019
+ _buffer = _a._buffer,
1020
+ _infiniteTimeWindow = _a._infiniteTimeWindow;
1021
+ var adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize;
1022
+ _bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize);
1023
+ if (!_infiniteTimeWindow) {
1024
+ var now = _timestampProvider.now();
1025
+ var last = 0;
1026
+ for (var i = 1; i < _buffer.length && _buffer[i] <= now; i += 2) {
1027
+ last = i;
1028
+ }
1029
+ last && _buffer.splice(0, last + 1);
1030
+ }
1031
+ };
1032
+ return ReplaySubject;
1033
+ }(Subject);
1034
+ var isArrayLike = function (x) {
1035
+ return x && typeof x.length === 'number' && typeof x !== 'function';
1036
+ };
1037
+ function isPromise(value) {
1038
+ return isFunction(value === null || value === void 0 ? void 0 : value.then);
1039
+ }
1040
+ function isInteropObservable(input) {
1041
+ return isFunction(input[observable]);
1042
+ }
1043
+ function isAsyncIterable(obj) {
1044
+ return Symbol.asyncIterator && isFunction(obj === null || obj === void 0 ? void 0 : obj[Symbol.asyncIterator]);
1045
+ }
1046
+ function createInvalidObservableTypeError(input) {
1047
+ return new TypeError("You provided " + (input !== null && typeof input === 'object' ? 'an invalid object' : "'" + input + "'") + " where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.");
1048
+ }
1049
+ function getSymbolIterator() {
1050
+ if (typeof Symbol !== 'function' || !Symbol.iterator) {
1051
+ return '@@iterator';
1052
+ }
1053
+ return Symbol.iterator;
1054
+ }
1055
+ var iterator = getSymbolIterator();
1056
+ function isIterable(input) {
1057
+ return isFunction(input === null || input === void 0 ? void 0 : input[iterator]);
1058
+ }
1059
+ function readableStreamLikeToAsyncGenerator(readableStream) {
1060
+ return __asyncGenerator(this, arguments, function readableStreamLikeToAsyncGenerator_1() {
1061
+ var reader, _a, value, done;
1062
+ return __generator(this, function (_b) {
1063
+ switch (_b.label) {
1064
+ case 0:
1065
+ reader = readableStream.getReader();
1066
+ _b.label = 1;
1067
+ case 1:
1068
+ _b.trys.push([1,, 9, 10]);
1069
+ _b.label = 2;
1070
+ case 2:
1071
+ return [4, __await(reader.read())];
1072
+ case 3:
1073
+ _a = _b.sent(), value = _a.value, done = _a.done;
1074
+ if (!done) return [3, 5];
1075
+ return [4, __await(void 0)];
1076
+ case 4:
1077
+ return [2, _b.sent()];
1078
+ case 5:
1079
+ return [4, __await(value)];
1080
+ case 6:
1081
+ return [4, _b.sent()];
1082
+ case 7:
1083
+ _b.sent();
1084
+ return [3, 2];
1085
+ case 8:
1086
+ return [3, 10];
1087
+ case 9:
1088
+ reader.releaseLock();
1089
+ return [7];
1090
+ case 10:
1091
+ return [2];
1092
+ }
1093
+ });
1094
+ });
1095
+ }
1096
+ function isReadableStreamLike(obj) {
1097
+ return isFunction(obj === null || obj === void 0 ? void 0 : obj.getReader);
1098
+ }
1099
+ function innerFrom(input) {
1100
+ if (input instanceof Observable) {
1101
+ return input;
1102
+ }
1103
+ if (input != null) {
1104
+ if (isInteropObservable(input)) {
1105
+ return fromInteropObservable(input);
1106
+ }
1107
+ if (isArrayLike(input)) {
1108
+ return fromArrayLike(input);
1109
+ }
1110
+ if (isPromise(input)) {
1111
+ return fromPromise(input);
1112
+ }
1113
+ if (isAsyncIterable(input)) {
1114
+ return fromAsyncIterable(input);
1115
+ }
1116
+ if (isIterable(input)) {
1117
+ return fromIterable(input);
1118
+ }
1119
+ if (isReadableStreamLike(input)) {
1120
+ return fromReadableStreamLike(input);
1121
+ }
1122
+ }
1123
+ throw createInvalidObservableTypeError(input);
1124
+ }
1125
+ function fromInteropObservable(obj) {
1126
+ return new Observable(function (subscriber) {
1127
+ var obs = obj[observable]();
1128
+ if (isFunction(obs.subscribe)) {
1129
+ return obs.subscribe(subscriber);
1130
+ }
1131
+ throw new TypeError('Provided object does not correctly implement Symbol.observable');
1132
+ });
1133
+ }
1134
+ function fromArrayLike(array) {
1135
+ return new Observable(function (subscriber) {
1136
+ for (var i = 0; i < array.length && !subscriber.closed; i++) {
1137
+ subscriber.next(array[i]);
1138
+ }
1139
+ subscriber.complete();
1140
+ });
1141
+ }
1142
+ function fromPromise(promise) {
1143
+ return new Observable(function (subscriber) {
1144
+ promise.then(function (value) {
1145
+ if (!subscriber.closed) {
1146
+ subscriber.next(value);
1147
+ subscriber.complete();
1148
+ }
1149
+ }, function (err) {
1150
+ return subscriber.error(err);
1151
+ }).then(null, reportUnhandledError);
1152
+ });
1153
+ }
1154
+ function fromIterable(iterable) {
1155
+ return new Observable(function (subscriber) {
1156
+ var e_1, _a;
1157
+ try {
1158
+ for (var iterable_1 = __values(iterable), iterable_1_1 = iterable_1.next(); !iterable_1_1.done; iterable_1_1 = iterable_1.next()) {
1159
+ var value = iterable_1_1.value;
1160
+ subscriber.next(value);
1161
+ if (subscriber.closed) {
1162
+ return;
1163
+ }
1164
+ }
1165
+ } catch (e_1_1) {
1166
+ e_1 = {
1167
+ error: e_1_1
1168
+ };
1169
+ } finally {
1170
+ try {
1171
+ if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) _a.call(iterable_1);
1172
+ } finally {
1173
+ if (e_1) throw e_1.error;
1174
+ }
1175
+ }
1176
+ subscriber.complete();
1177
+ });
1178
+ }
1179
+ function fromAsyncIterable(asyncIterable) {
1180
+ return new Observable(function (subscriber) {
1181
+ process$1(asyncIterable, subscriber).catch(function (err) {
1182
+ return subscriber.error(err);
1183
+ });
1184
+ });
1185
+ }
1186
+ function fromReadableStreamLike(readableStream) {
1187
+ return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream));
1188
+ }
1189
+ function process$1(asyncIterable, subscriber) {
1190
+ var asyncIterable_1, asyncIterable_1_1;
1191
+ var e_2, _a;
1192
+ return __awaiter(this, void 0, void 0, function () {
1193
+ var value, e_2_1;
1194
+ return __generator(this, function (_b) {
1195
+ switch (_b.label) {
1196
+ case 0:
1197
+ _b.trys.push([0, 5, 6, 11]);
1198
+ asyncIterable_1 = __asyncValues(asyncIterable);
1199
+ _b.label = 1;
1200
+ case 1:
1201
+ return [4, asyncIterable_1.next()];
1202
+ case 2:
1203
+ if (!(asyncIterable_1_1 = _b.sent(), !asyncIterable_1_1.done)) return [3, 4];
1204
+ value = asyncIterable_1_1.value;
1205
+ subscriber.next(value);
1206
+ if (subscriber.closed) {
1207
+ return [2];
1208
+ }
1209
+ _b.label = 3;
1210
+ case 3:
1211
+ return [3, 1];
1212
+ case 4:
1213
+ return [3, 11];
1214
+ case 5:
1215
+ e_2_1 = _b.sent();
1216
+ e_2 = {
1217
+ error: e_2_1
1218
+ };
1219
+ return [3, 11];
1220
+ case 6:
1221
+ _b.trys.push([6,, 9, 10]);
1222
+ if (!(asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return))) return [3, 8];
1223
+ return [4, _a.call(asyncIterable_1)];
1224
+ case 7:
1225
+ _b.sent();
1226
+ _b.label = 8;
1227
+ case 8:
1228
+ return [3, 10];
1229
+ case 9:
1230
+ if (e_2) throw e_2.error;
1231
+ return [7];
1232
+ case 10:
1233
+ return [7];
1234
+ case 11:
1235
+ subscriber.complete();
1236
+ return [2];
1237
+ }
1238
+ });
1239
+ });
1240
+ }
1241
+ function share(options) {
1242
+ if (options === void 0) {
1243
+ options = {};
1244
+ }
1245
+ var _a = options.connector,
1246
+ connector = _a === void 0 ? function () {
1247
+ return new Subject();
1248
+ } : _a,
1249
+ _b = options.resetOnError,
1250
+ resetOnError = _b === void 0 ? true : _b,
1251
+ _c = options.resetOnComplete,
1252
+ resetOnComplete = _c === void 0 ? true : _c,
1253
+ _d = options.resetOnRefCountZero,
1254
+ resetOnRefCountZero = _d === void 0 ? true : _d;
1255
+ return function (wrapperSource) {
1256
+ var connection;
1257
+ var resetConnection;
1258
+ var subject;
1259
+ var refCount = 0;
1260
+ var hasCompleted = false;
1261
+ var hasErrored = false;
1262
+ var cancelReset = function () {
1263
+ resetConnection === null || resetConnection === void 0 ? void 0 : resetConnection.unsubscribe();
1264
+ resetConnection = undefined;
1265
+ };
1266
+ var reset = function () {
1267
+ cancelReset();
1268
+ connection = subject = undefined;
1269
+ hasCompleted = hasErrored = false;
1270
+ };
1271
+ var resetAndUnsubscribe = function () {
1272
+ var conn = connection;
1273
+ reset();
1274
+ conn === null || conn === void 0 ? void 0 : conn.unsubscribe();
1275
+ };
1276
+ return operate(function (source, subscriber) {
1277
+ refCount++;
1278
+ if (!hasErrored && !hasCompleted) {
1279
+ cancelReset();
1280
+ }
1281
+ var dest = subject = subject !== null && subject !== void 0 ? subject : connector();
1282
+ subscriber.add(function () {
1283
+ refCount--;
1284
+ if (refCount === 0 && !hasErrored && !hasCompleted) {
1285
+ resetConnection = handleReset(resetAndUnsubscribe, resetOnRefCountZero);
1286
+ }
1287
+ });
1288
+ dest.subscribe(subscriber);
1289
+ if (!connection && refCount > 0) {
1290
+ connection = new SafeSubscriber({
1291
+ next: function (value) {
1292
+ return dest.next(value);
1293
+ },
1294
+ error: function (err) {
1295
+ hasErrored = true;
1296
+ cancelReset();
1297
+ resetConnection = handleReset(reset, resetOnError, err);
1298
+ dest.error(err);
1299
+ },
1300
+ complete: function () {
1301
+ hasCompleted = true;
1302
+ cancelReset();
1303
+ resetConnection = handleReset(reset, resetOnComplete);
1304
+ dest.complete();
1305
+ }
1306
+ });
1307
+ innerFrom(source).subscribe(connection);
1308
+ }
1309
+ })(wrapperSource);
1310
+ };
1311
+ }
1312
+ function handleReset(reset, on) {
1313
+ var args = [];
1314
+ for (var _i = 2; _i < arguments.length; _i++) {
1315
+ args[_i - 2] = arguments[_i];
1316
+ }
1317
+ if (on === true) {
1318
+ reset();
1319
+ return;
1320
+ }
1321
+ if (on === false) {
1322
+ return;
1323
+ }
1324
+ var onSubscriber = new SafeSubscriber({
1325
+ next: function () {
1326
+ onSubscriber.unsubscribe();
1327
+ reset();
1328
+ }
1329
+ });
1330
+ return innerFrom(on.apply(void 0, __spreadArray([], __read(args)))).subscribe(onSubscriber);
1331
+ }
1332
+ function shareReplay(configOrBufferSize, windowTime, scheduler) {
1333
+ var _a, _b, _c;
1334
+ var bufferSize;
1335
+ var refCount = false;
1336
+ if (configOrBufferSize && typeof configOrBufferSize === 'object') {
1337
+ _a = configOrBufferSize.bufferSize, bufferSize = _a === void 0 ? Infinity : _a, _b = configOrBufferSize.windowTime, windowTime = _b === void 0 ? Infinity : _b, _c = configOrBufferSize.refCount, refCount = _c === void 0 ? false : _c, scheduler = configOrBufferSize.scheduler;
1338
+ } else {
1339
+ bufferSize = configOrBufferSize !== null && configOrBufferSize !== void 0 ? configOrBufferSize : Infinity;
1340
+ }
1341
+ return share({
1342
+ connector: function () {
1343
+ return new ReplaySubject(bufferSize, windowTime, scheduler);
1344
+ },
1345
+ resetOnError: true,
1346
+ resetOnComplete: false,
1347
+ resetOnRefCountZero: refCount
1348
+ });
1349
+ }
1350
+ function tap(observerOrNext, error, complete) {
1351
+ var tapObserver = isFunction(observerOrNext) || error || complete ? {
1352
+ next: observerOrNext,
1353
+ error: error,
1354
+ complete: complete
1355
+ } : observerOrNext;
1356
+ return tapObserver ? operate(function (source, subscriber) {
1357
+ var _a;
1358
+ (_a = tapObserver.subscribe) === null || _a === void 0 ? void 0 : _a.call(tapObserver);
1359
+ var isUnsub = true;
1360
+ source.subscribe(createOperatorSubscriber(subscriber, function (value) {
1361
+ var _a;
1362
+ (_a = tapObserver.next) === null || _a === void 0 ? void 0 : _a.call(tapObserver, value);
1363
+ subscriber.next(value);
1364
+ }, function () {
1365
+ var _a;
1366
+ isUnsub = false;
1367
+ (_a = tapObserver.complete) === null || _a === void 0 ? void 0 : _a.call(tapObserver);
1368
+ subscriber.complete();
1369
+ }, function (err) {
1370
+ var _a;
1371
+ isUnsub = false;
1372
+ (_a = tapObserver.error) === null || _a === void 0 ? void 0 : _a.call(tapObserver, err);
1373
+ subscriber.error(err);
1374
+ }, function () {
1375
+ var _a, _b;
1376
+ if (isUnsub) {
1377
+ (_a = tapObserver.unsubscribe) === null || _a === void 0 ? void 0 : _a.call(tapObserver);
1378
+ }
1379
+ (_b = tapObserver.finalize) === null || _b === void 0 ? void 0 : _b.call(tapObserver);
1380
+ }));
1381
+ }) : identity;
1382
+ }
1383
+ var shim = {
1384
+ exports: {}
1385
+ };
1386
+ var useSyncExternalStoreShim_production_min = {};
1387
+
1388
+ /**
1389
+ * @license React
1390
+ * use-sync-external-store-shim.production.min.js
1391
+ *
1392
+ * Copyright (c) Facebook, Inc. and its affiliates.
1393
+ *
1394
+ * This source code is licensed under the MIT license found in the
1395
+ * LICENSE file in the root directory of this source tree.
1396
+ */
1397
+
1398
+ var hasRequiredUseSyncExternalStoreShim_production_min;
1399
+ function requireUseSyncExternalStoreShim_production_min() {
1400
+ if (hasRequiredUseSyncExternalStoreShim_production_min) return useSyncExternalStoreShim_production_min;
1401
+ hasRequiredUseSyncExternalStoreShim_production_min = 1;
1402
+ var e = require$$0;
1403
+ function h(a, b) {
1404
+ return a === b && (0 !== a || 1 / a === 1 / b) || a !== a && b !== b;
1405
+ }
1406
+ var k = "function" === typeof Object.is ? Object.is : h,
1407
+ l = e.useState,
1408
+ m = e.useEffect,
1409
+ n = e.useLayoutEffect,
1410
+ p = e.useDebugValue;
1411
+ function q(a, b) {
1412
+ var d = b(),
1413
+ f = l({
1414
+ inst: {
1415
+ value: d,
1416
+ getSnapshot: b
1417
+ }
1418
+ }),
1419
+ c = f[0].inst,
1420
+ g = f[1];
1421
+ n(function () {
1422
+ c.value = d;
1423
+ c.getSnapshot = b;
1424
+ r(c) && g({
1425
+ inst: c
1426
+ });
1427
+ }, [a, d, b]);
1428
+ m(function () {
1429
+ r(c) && g({
1430
+ inst: c
1431
+ });
1432
+ return a(function () {
1433
+ r(c) && g({
1434
+ inst: c
1435
+ });
1436
+ });
1437
+ }, [a]);
1438
+ p(d);
1439
+ return d;
1440
+ }
1441
+ function r(a) {
1442
+ var b = a.getSnapshot;
1443
+ a = a.value;
1444
+ try {
1445
+ var d = b();
1446
+ return !k(a, d);
1447
+ } catch (f) {
1448
+ return !0;
1449
+ }
1450
+ }
1451
+ function t(a, b) {
1452
+ return b();
1453
+ }
1454
+ var u = "undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement ? t : q;
1455
+ useSyncExternalStoreShim_production_min.useSyncExternalStore = void 0 !== e.useSyncExternalStore ? e.useSyncExternalStore : u;
1456
+ return useSyncExternalStoreShim_production_min;
1457
+ }
1458
+ var useSyncExternalStoreShim_development = {};
1459
+
1460
+ /**
1461
+ * @license React
1462
+ * use-sync-external-store-shim.development.js
1463
+ *
1464
+ * Copyright (c) Facebook, Inc. and its affiliates.
1465
+ *
1466
+ * This source code is licensed under the MIT license found in the
1467
+ * LICENSE file in the root directory of this source tree.
1468
+ */
1469
+
1470
+ var hasRequiredUseSyncExternalStoreShim_development;
1471
+ function requireUseSyncExternalStoreShim_development() {
1472
+ if (hasRequiredUseSyncExternalStoreShim_development) return useSyncExternalStoreShim_development;
1473
+ hasRequiredUseSyncExternalStoreShim_development = 1;
1474
+ if (process.env.NODE_ENV !== "production") {
1475
+ (function () {
1476
+ /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
1477
+ if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === 'function') {
1478
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
1479
+ }
1480
+ var React = require$$0;
1481
+ var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
1482
+ function error(format) {
1483
+ {
1484
+ {
1485
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
1486
+ args[_key2 - 1] = arguments[_key2];
1487
+ }
1488
+ printWarning('error', format, args);
1489
+ }
1490
+ }
1491
+ }
1492
+ function printWarning(level, format, args) {
1493
+ // When changing this logic, you might want to also
1494
+ // update consoleWithStackDev.www.js as well.
1495
+ {
1496
+ var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
1497
+ var stack = ReactDebugCurrentFrame.getStackAddendum();
1498
+ if (stack !== '') {
1499
+ format += '%s';
1500
+ args = args.concat([stack]);
1501
+ } // eslint-disable-next-line react-internal/safe-string-coercion
1502
+
1503
+ var argsWithFormat = args.map(function (item) {
1504
+ return String(item);
1505
+ }); // Careful: RN currently depends on this prefix
1506
+
1507
+ argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
1508
+ // breaks IE9: https://github.com/facebook/react/issues/13610
1509
+ // eslint-disable-next-line react-internal/no-production-logging
1510
+
1511
+ Function.prototype.apply.call(console[level], console, argsWithFormat);
1512
+ }
1513
+ }
1514
+
1515
+ /**
1516
+ * inlined Object.is polyfill to avoid requiring consumers ship their own
1517
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
1518
+ */
1519
+ function is(x, y) {
1520
+ return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
1521
+ ;
1522
+ }
1523
+
1524
+ var objectIs = typeof Object.is === 'function' ? Object.is : is;
1525
+
1526
+ // dispatch for CommonJS interop named imports.
1527
+
1528
+ var useState = React.useState,
1529
+ useEffect = React.useEffect,
1530
+ useLayoutEffect = React.useLayoutEffect,
1531
+ useDebugValue = React.useDebugValue;
1532
+ var didWarnOld18Alpha = false;
1533
+ var didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works
1534
+ // because of a very particular set of implementation details and assumptions
1535
+ // -- change any one of them and it will break. The most important assumption
1536
+ // is that updates are always synchronous, because concurrent rendering is
1537
+ // only available in versions of React that also have a built-in
1538
+ // useSyncExternalStore API. And we only use this shim when the built-in API
1539
+ // does not exist.
1540
+ //
1541
+ // Do not assume that the clever hacks used by this hook also work in general.
1542
+ // The point of this shim is to replace the need for hacks by other libraries.
1543
+
1544
+ function useSyncExternalStore(subscribe, getSnapshot,
1545
+ // Note: The shim does not use getServerSnapshot, because pre-18 versions of
1546
+ // React do not expose a way to check if we're hydrating. So users of the shim
1547
+ // will need to track that themselves and return the correct value
1548
+ // from `getSnapshot`.
1549
+ getServerSnapshot) {
1550
+ {
1551
+ if (!didWarnOld18Alpha) {
1552
+ if (React.startTransition !== undefined) {
1553
+ didWarnOld18Alpha = true;
1554
+ error('You are using an outdated, pre-release alpha of React 18 that ' + 'does not support useSyncExternalStore. The ' + 'use-sync-external-store shim will not work correctly. Upgrade ' + 'to a newer pre-release.');
1555
+ }
1556
+ }
1557
+ } // Read the current snapshot from the store on every render. Again, this
1558
+ // breaks the rules of React, and only works here because of specific
1559
+ // implementation details, most importantly that updates are
1560
+ // always synchronous.
1561
+
1562
+ var value = getSnapshot();
1563
+ {
1564
+ if (!didWarnUncachedGetSnapshot) {
1565
+ var cachedValue = getSnapshot();
1566
+ if (!objectIs(value, cachedValue)) {
1567
+ error('The result of getSnapshot should be cached to avoid an infinite loop');
1568
+ didWarnUncachedGetSnapshot = true;
1569
+ }
1570
+ }
1571
+ } // Because updates are synchronous, we don't queue them. Instead we force a
1572
+ // re-render whenever the subscribed state changes by updating an some
1573
+ // arbitrary useState hook. Then, during render, we call getSnapshot to read
1574
+ // the current value.
1575
+ //
1576
+ // Because we don't actually use the state returned by the useState hook, we
1577
+ // can save a bit of memory by storing other stuff in that slot.
1578
+ //
1579
+ // To implement the early bailout, we need to track some things on a mutable
1580
+ // object. Usually, we would put that in a useRef hook, but we can stash it in
1581
+ // our useState hook instead.
1582
+ //
1583
+ // To force a re-render, we call forceUpdate({inst}). That works because the
1584
+ // new object always fails an equality check.
1585
+
1586
+ var _useState = useState({
1587
+ inst: {
1588
+ value: value,
1589
+ getSnapshot: getSnapshot
1590
+ }
1591
+ }),
1592
+ inst = _useState[0].inst,
1593
+ forceUpdate = _useState[1]; // Track the latest getSnapshot function with a ref. This needs to be updated
1594
+ // in the layout phase so we can access it during the tearing check that
1595
+ // happens on subscribe.
1596
+
1597
+ useLayoutEffect(function () {
1598
+ inst.value = value;
1599
+ inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the
1600
+ // commit phase if there was an interleaved mutation. In concurrent mode
1601
+ // this can happen all the time, but even in synchronous mode, an earlier
1602
+ // effect may have mutated the store.
1603
+
1604
+ if (checkIfSnapshotChanged(inst)) {
1605
+ // Force a re-render.
1606
+ forceUpdate({
1607
+ inst: inst
1608
+ });
1609
+ }
1610
+ }, [subscribe, value, getSnapshot]);
1611
+ useEffect(function () {
1612
+ // Check for changes right before subscribing. Subsequent changes will be
1613
+ // detected in the subscription handler.
1614
+ if (checkIfSnapshotChanged(inst)) {
1615
+ // Force a re-render.
1616
+ forceUpdate({
1617
+ inst: inst
1618
+ });
1619
+ }
1620
+ var handleStoreChange = function () {
1621
+ // TODO: Because there is no cross-renderer API for batching updates, it's
1622
+ // up to the consumer of this library to wrap their subscription event
1623
+ // with unstable_batchedUpdates. Should we try to detect when this isn't
1624
+ // the case and print a warning in development?
1625
+ // The store changed. Check if the snapshot changed since the last time we
1626
+ // read from the store.
1627
+ if (checkIfSnapshotChanged(inst)) {
1628
+ // Force a re-render.
1629
+ forceUpdate({
1630
+ inst: inst
1631
+ });
1632
+ }
1633
+ }; // Subscribe to the store and return a clean-up function.
1634
+
1635
+ return subscribe(handleStoreChange);
1636
+ }, [subscribe]);
1637
+ useDebugValue(value);
1638
+ return value;
1639
+ }
1640
+ function checkIfSnapshotChanged(inst) {
1641
+ var latestGetSnapshot = inst.getSnapshot;
1642
+ var prevValue = inst.value;
1643
+ try {
1644
+ var nextValue = latestGetSnapshot();
1645
+ return !objectIs(prevValue, nextValue);
1646
+ } catch (error) {
1647
+ return true;
1648
+ }
1649
+ }
1650
+ function useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {
1651
+ // Note: The shim does not use getServerSnapshot, because pre-18 versions of
1652
+ // React do not expose a way to check if we're hydrating. So users of the shim
1653
+ // will need to track that themselves and return the correct value
1654
+ // from `getSnapshot`.
1655
+ return getSnapshot();
1656
+ }
1657
+ var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');
1658
+ var isServerEnvironment = !canUseDOM;
1659
+ var shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore;
1660
+ var useSyncExternalStore$2 = React.useSyncExternalStore !== undefined ? React.useSyncExternalStore : shim;
1661
+ useSyncExternalStoreShim_development.useSyncExternalStore = useSyncExternalStore$2;
1662
+ /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
1663
+ if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === 'function') {
1664
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
1665
+ }
1666
+ })();
1667
+ }
1668
+ return useSyncExternalStoreShim_development;
1669
+ }
1670
+ if (process.env.NODE_ENV === 'production') {
1671
+ shim.exports = requireUseSyncExternalStoreShim_production_min();
1672
+ } else {
1673
+ shim.exports = requireUseSyncExternalStoreShim_development();
1674
+ }
1675
+ var shimExports = shim.exports;
1676
+ function getValue(value) {
1677
+ return typeof value === 'function' ? value() : value;
1678
+ }
1679
+ var cache = new WeakMap();
1680
+ function getOrCreateStore(inputObservable, initialValue) {
1681
+ if (!cache.has(inputObservable)) {
1682
+ var entry_1 = {
1683
+ currentValue: initialValue
1684
+ };
1685
+ entry_1.observable = inputObservable.pipe(shareReplay({
1686
+ refCount: true,
1687
+ bufferSize: 1
1688
+ }), tap(function (value) {
1689
+ return entry_1.currentValue = value;
1690
+ }));
1691
+ // Eagerly subscribe to sync set `entry.currentValue` to what the observable returns
1692
+ entry_1.subscription = entry_1.observable.subscribe();
1693
+ cache.set(inputObservable, entry_1);
1694
+ }
1695
+ return cache.get(inputObservable);
1696
+ }
1697
+ function useObservable(observable, initialValue) {
1698
+ var _a = useMemo(function () {
1699
+ var store = getOrCreateStore(observable, getValue(initialValue));
1700
+ if (store.subscription.closed) {
1701
+ store.subscription = store.observable.subscribe();
1702
+ }
1703
+ return [function getSnapshot() {
1704
+ // @TODO: perf opt opportunity: we could do `store.subscription.unsubscribe()` here to clear up some memory, as this subscription is only needed to provide a sync initialValue.
1705
+ return store.currentValue;
1706
+ }, function subscribe(callback) {
1707
+ // @TODO: perf opt opportunity: we could do `store.subscription.unsubscribe()` here as we only need 1 subscription active to keep the observer alive
1708
+ var sub = store.observable.subscribe(callback);
1709
+ return function () {
1710
+ sub.unsubscribe();
1711
+ };
1712
+ }];
1713
+ }, [observable]),
1714
+ getSnapshot = _a[0],
1715
+ subscribe = _a[1];
1716
+ var shouldRestoreSubscriptionRef = useRef(false);
1717
+ useEffect(function () {
1718
+ var store = getOrCreateStore(observable, getValue(initialValue));
1719
+ if (shouldRestoreSubscriptionRef.current) {
1720
+ if (store.subscription.closed) {
1721
+ store.subscription = store.observable.subscribe();
1722
+ }
1723
+ shouldRestoreSubscriptionRef.current = false;
1724
+ }
1725
+ return function () {
1726
+ // React StrictMode will call effects as `setup + teardown + setup` thus we can't trust this callback as "react is about to unmount"
1727
+ // Tracking this ref lets us set the subscription back up on the next `setup` call if needed, and if it really did unmounted then all is well
1728
+ shouldRestoreSubscriptionRef.current = !store.subscription.closed;
1729
+ store.subscription.unsubscribe();
1730
+ };
1731
+ }, [observable]);
1732
+ return shimExports.useSyncExternalStore(subscribe, getSnapshot);
1733
+ }
1734
+ function useMemoObservable(observableOrFactory, deps, initialValue) {
1735
+ return useObservable(useMemo(function () {
1736
+ return getValue(observableOrFactory);
1737
+ }, deps), initialValue);
1738
+ }
1739
+ function DocumentPreview(_ref) {
1740
+ let {
1741
+ documentId,
1742
+ style,
1743
+ ...buttonProps
1744
+ } = _ref;
1745
+ const client = useClient({
1746
+ apiVersion: "2023-06-06"
1747
+ });
1748
+ const [type, setType] = useState(void 0);
1749
+ const schema = useSchema();
1750
+ const schemaType = type ? schema.get(type) : void 0;
1751
+ useEffect(() => {
1752
+ client.fetch("* [_id==$id]._type", {
1753
+ id: documentId
1754
+ }).then(setType);
1755
+ }, [documentId, client]);
1756
+ if (!type) {
1757
+ return /* @__PURE__ */jsx(Card, {
1758
+ style: {
1759
+ minHeight: "36px"
1760
+ },
1761
+ children: /* @__PURE__ */jsx(DefaultPreview, {
1762
+ withShadow: false,
1763
+ withBorder: false,
1764
+ title: "Loading...",
1765
+ schemaType,
1766
+ isPlaceholder: true
1767
+ })
1768
+ });
1769
+ }
1770
+ if (!schemaType) {
1771
+ return /* @__PURE__ */jsx(Card, {
1772
+ children: /* @__PURE__ */jsx(DefaultPreview, {
1773
+ withShadow: false,
1774
+ withBorder: false,
1775
+ media: () => /* @__PURE__ */jsx(ErrorOutlineIcon, {}),
1776
+ title: /* @__PURE__ */jsxs(Fragment, {
1777
+ children: ["Unknown type ", /* @__PURE__ */jsx("code", {
1778
+ children: type != null ? type : "N/A"
1779
+ }), " for ", documentId]
1780
+ })
1781
+ })
1782
+ });
1783
+ }
1784
+ return /* @__PURE__ */jsx(DocumentPreviewInner, {
1785
+ documentId,
1786
+ schemaType,
1787
+ style,
1788
+ ...buttonProps
1789
+ });
1790
+ }
1791
+ function DocumentPreviewInner(_ref2) {
1792
+ let {
1793
+ documentId,
1794
+ schemaType,
1795
+ style,
1796
+ button
1797
+ } = _ref2;
1798
+ const documentPreviewStore = useDocumentPreviewStore();
1799
+ const {
1800
+ draft,
1801
+ published,
1802
+ isLoading
1803
+ } = useMemoObservable(() => getPreviewStateObservable(documentPreviewStore, schemaType, documentId, ""), [documentId, documentPreviewStore, schemaType]);
1804
+ const sanityDocument = useMemo(() => {
1805
+ return {
1806
+ _id: documentId,
1807
+ _type: schemaType == null ? void 0 : schemaType.name
1808
+ };
1809
+ }, [documentId, schemaType == null ? void 0 : schemaType.name]);
1810
+ const {
1811
+ onClick: onIntentClick,
1812
+ href
1813
+ } = useIntentLink({
1814
+ intent: "edit",
1815
+ params: {
1816
+ id: documentId,
1817
+ type: schemaType == null ? void 0 : schemaType.name
1818
+ }
1819
+ });
1820
+ const preview = /* @__PURE__ */jsx(SanityDefaultPreview, {
1821
+ ...getPreviewValueWithFallback({
1822
+ draft,
1823
+ published,
1824
+ value: sanityDocument
1825
+ }),
1826
+ isPlaceholder: isLoading != null ? isLoading : true,
1827
+ layout: "default",
1828
+ icon: schemaType == null ? void 0 : schemaType.icon
1829
+ });
1830
+ if (button) {
1831
+ return /* @__PURE__ */jsx(Button, {
1832
+ as: "a",
1833
+ href,
1834
+ onClick: onIntentClick,
1835
+ mode: "ghost",
1836
+ style: {
1837
+ width: "100%",
1838
+ ...style
1839
+ },
1840
+ children: preview
1841
+ });
1842
+ }
1843
+ return /* @__PURE__ */jsx(Box, {
1844
+ style: {
1845
+ width: "100%"
1846
+ },
1847
+ children: preview
1848
+ });
1849
+ }
1850
+ function queryIndex(queryConfig, client) {
1851
+ const {
1852
+ query,
1853
+ indexName,
1854
+ maxResults,
1855
+ filter
1856
+ } = queryConfig;
1857
+ const projectId = client.config().projectId;
1858
+ const dataset = client.config().dataset;
1859
+ const queryString = query == null ? void 0 : query.trim();
1860
+ return client.request({
1861
+ method: "POST",
1862
+ url: "/embeddings-index/query/".concat(dataset, "/").concat(indexName, "?projectId=").concat(projectId),
1863
+ body: {
1864
+ query: queryString,
1865
+ maxResults,
1866
+ filter
1867
+ }
1868
+ });
1869
+ }
1870
+ function getIndexes(client) {
1871
+ const projectId = client.config().projectId;
1872
+ const dataset = client.config().dataset;
1873
+ return client.request({
1874
+ method: "GET",
1875
+ url: "/embeddings-index/".concat(dataset, "?projectId=").concat(projectId)
1876
+ });
1877
+ }
1878
+ function deleteIndex(indexName, client) {
1879
+ const projectId = client.config().projectId;
1880
+ const dataset = client.config().dataset;
1881
+ return client.request({
1882
+ method: "DELETE",
1883
+ url: "/embeddings-index/".concat(dataset, "/").concat(indexName, "?projectId=").concat(projectId)
1884
+ });
1885
+ }
1886
+ function publicId(id) {
1887
+ return id.replace("drafts.", "");
1888
+ }
1889
+ const NO_OPTIONS = [];
1890
+ const NO_FILTER = () => true;
1891
+ function SemanticSearchReferenceInput(props) {
1892
+ var _a, _b, _c;
1893
+ const defaultEnabled = ((_c = (_b = (_a = props.schemaType) == null ? void 0 : _a.options) == null ? void 0 : _b.embeddingsIndex) == null ? void 0 : _c.searchMode) === "embeddings";
1894
+ const [semantic, setSemantic] = useState(defaultEnabled);
1895
+ const toggleSemantic = useCallback(() => setSemantic(current => !current), []);
1896
+ return /* @__PURE__ */jsxs(Flex, {
1897
+ gap: 2,
1898
+ flex: 1,
1899
+ style: {
1900
+ width: "100%"
1901
+ },
1902
+ children: [/* @__PURE__ */jsx(Box, {
1903
+ flex: 1,
1904
+ style: {
1905
+ maxHeight: 36,
1906
+ overflow: "hidden"
1907
+ },
1908
+ children: semantic ? /* @__PURE__ */jsx(SemanticSearchInput, {
1909
+ ...props
1910
+ }) : props.renderDefault(props)
1911
+ }), /* @__PURE__ */jsx(Button, {
1912
+ icon: semantic ? EarthGlobeIcon : LinkIcon,
1913
+ onClick: toggleSemantic,
1914
+ mode: "bleed",
1915
+ title: semantic ? "Switch to standard reference search" : "Switch to semantic reference search"
1916
+ })]
1917
+ });
1918
+ }
1919
+ function useDebouncedValue(value, ms) {
1920
+ const [debouncedValue, setDebouncedValue] = useState(value);
1921
+ useEffect(() => {
1922
+ const timeoutId = setTimeout(() => {
1923
+ setDebouncedValue(value);
1924
+ }, ms);
1925
+ return () => clearTimeout(timeoutId);
1926
+ }, [value, ms]);
1927
+ return debouncedValue;
1928
+ }
1929
+ function useApiClient$2() {
1930
+ const client = useClient({
1931
+ apiVersion: "vX"
1932
+ });
1933
+ return useMemo(() => client, [client]);
1934
+ }
1935
+ function SemanticSearchInput(props) {
1936
+ const {
1937
+ onPathFocus,
1938
+ onChange,
1939
+ readOnly,
1940
+ schemaType,
1941
+ value
1942
+ } = props;
1943
+ const {
1944
+ value: currentDocument
1945
+ } = useDocumentPane();
1946
+ const docRef = useRef(currentDocument);
1947
+ const autocompleteRef = useRef(null);
1948
+ const id = useId();
1949
+ const [query, setQuery] = useState("");
1950
+ const queryRef = useRef(query);
1951
+ const debouncedQuery = useDebouncedValue(query, 300);
1952
+ const prevDebouncedQuery = useRef(debouncedQuery);
1953
+ const [searching, setSearching] = useState(false);
1954
+ const [options, setOptions] = useState(NO_OPTIONS);
1955
+ const client = useApiClient$2();
1956
+ useEffect(() => {
1957
+ docRef.current = currentDocument;
1958
+ }, [currentDocument]);
1959
+ useEffect(() => {
1960
+ var _a;
1961
+ if (value == null ? void 0 : value._ref) {
1962
+ (_a = autocompleteRef.current) == null ? void 0 : _a.focus();
1963
+ }
1964
+ }, []);
1965
+ const handleFocus = useCallback(() => onPathFocus(["_ref"]), [onPathFocus]);
1966
+ const handleBlur = useCallback(() => onPathFocus([]), [onPathFocus]);
1967
+ const runIndexQuery = useCallback(queryString => {
1968
+ var _a, _b, _c, _d;
1969
+ setSearching(true);
1970
+ const refSchema = schemaType;
1971
+ const indexName = (_b = (_a = refSchema.options) == null ? void 0 : _a.embeddingsIndex) == null ? void 0 : _b.indexName;
1972
+ const maxResults = (_d = (_c = refSchema.options) == null ? void 0 : _c.embeddingsIndex) == null ? void 0 : _d.maxResults;
1973
+ const typeFilter = refSchema.to.map(ref => ref.name);
1974
+ if (!indexName) {
1975
+ throw new Error("Reference option embeddingsIndex.indexName is required, but was missing in type ".concat(refSchema.name));
1976
+ }
1977
+ queryIndex({
1978
+ query: queryString,
1979
+ indexName,
1980
+ maxResults,
1981
+ filter: {
1982
+ type: typeFilter
1983
+ }
1984
+ }, client).then(result => {
1985
+ if (queryRef.current === queryString) {
1986
+ setSearching(false);
1987
+ setOptions(result.filter(r => r.value.documentId !== publicId(docRef.current._id)).map(r => typed({
1988
+ result: r,
1989
+ value: r.value.documentId
1990
+ })));
1991
+ }
1992
+ }).catch(e => {
1993
+ if (queryRef.current === queryString) {
1994
+ setSearching(false);
1995
+ }
1996
+ throw e;
1997
+ });
1998
+ }, [client, schemaType]);
1999
+ useEffect(() => {
2000
+ if (prevDebouncedQuery.current !== debouncedQuery) {
2001
+ runIndexQuery(debouncedQuery);
2002
+ }
2003
+ prevDebouncedQuery.current = debouncedQuery;
2004
+ }, [debouncedQuery, runIndexQuery]);
2005
+ const handleChange = useCallback(nextId => {
2006
+ if (!nextId) {
2007
+ onChange(unset());
2008
+ onPathFocus([]);
2009
+ return;
2010
+ }
2011
+ const patches = [setIfMissing({}), set(schemaType.name, ["_type"]), set(publicId(nextId), ["_ref"]), unset(["_weak"]), unset(["_strengthenOnPublish"])];
2012
+ onChange(patches);
2013
+ onPathFocus([]);
2014
+ }, [onChange, onPathFocus, schemaType.name]);
2015
+ const openButtonConfig = useMemo(() => ({
2016
+ onClick: () => runIndexQuery(queryRef.current)
2017
+ }), [runIndexQuery, queryRef]);
2018
+ const handleQueryChange = useCallback(newValue => {
2019
+ const newQuery = newValue != null ? newValue : "";
2020
+ queryRef.current = newQuery;
2021
+ setQuery(newQuery);
2022
+ }, [setQuery]);
2023
+ return /* @__PURE__ */jsx(Autocomplete, {
2024
+ id,
2025
+ ref: autocompleteRef,
2026
+ "data-testid": "semantic-autocomplete",
2027
+ placeholder: "Type to search",
2028
+ openButton: openButtonConfig,
2029
+ onFocus: handleFocus,
2030
+ onChange: handleChange,
2031
+ loading: searching,
2032
+ onBlur: handleBlur,
2033
+ readOnly,
2034
+ filterOption: NO_FILTER,
2035
+ onQueryChange: handleQueryChange,
2036
+ options,
2037
+ renderOption: AutocompleteOption
2038
+ });
2039
+ }
2040
+ function AutocompleteOption(props) {
2041
+ return /* @__PURE__ */jsx(Button, {
2042
+ mode: "bleed",
2043
+ padding: 1,
2044
+ style: {
2045
+ width: "100%"
2046
+ },
2047
+ children: /* @__PURE__ */jsxs(Flex, {
2048
+ gap: 2,
2049
+ align: "center",
2050
+ children: [/* @__PURE__ */jsx(Box, {
2051
+ flex: 1,
2052
+ children: /* @__PURE__ */jsx(DocumentPreview, {
2053
+ documentId: props.result.value.documentId
2054
+ })
2055
+ }), /* @__PURE__ */jsx(Box, {
2056
+ padding: 2,
2057
+ children: /* @__PURE__ */jsxs(Text, {
2058
+ size: 1,
2059
+ muted: true,
2060
+ title: "Relevance",
2061
+ children: [Math.floor(props.result.score * 100), "%"]
2062
+ })
2063
+ })]
2064
+ })
2065
+ });
2066
+ }
2067
+ function isType(schemaType, typeName) {
2068
+ if (schemaType.name === typeName) {
2069
+ return true;
2070
+ }
2071
+ if (!schemaType.type) {
2072
+ return false;
2073
+ }
2074
+ return isType(schemaType.type, typeName);
2075
+ }
2076
+ const embeddingsIndexReferenceInput = definePlugin({
2077
+ name: "@sanity/embeddings-index-reference-input",
2078
+ form: {
2079
+ components: {
2080
+ input: props => {
2081
+ var _a, _b;
2082
+ if (isObjectInputProps(props) && isType(props.schemaType, "reference") && ((_b = (_a = props.schemaType.options) == null ? void 0 : _a.embeddingsIndex) == null ? void 0 : _b.indexName)) {
2083
+ return /* @__PURE__ */jsx(SemanticSearchReferenceInput, {
2084
+ ...props
2085
+ });
2086
+ }
2087
+ return props.renderDefault(props);
2088
+ }
2089
+ }
2090
+ }
2091
+ });
2092
+ function useApiClient$1(customApiClient) {
2093
+ const client = useClient({
2094
+ apiVersion: "vX"
2095
+ });
2096
+ return useMemo(() => customApiClient ? customApiClient(client) : client, [client, customApiClient]);
2097
+ }
2098
+ const defaultProjection = "{...}";
2099
+ function useDefaultIndex(schema, dataset) {
2100
+ const defaultFilter = useMemo(() => "_type in [".concat(schema.getTypeNames().map(n => schema.get(n)).filter(schemaType => Boolean(schemaType && isType(schemaType, "document"))).filter(documentType => !documentType.name.startsWith("sanity.") && !documentType.name.startsWith("assist.") && documentType.name !== "document").map(documentType => '"'.concat(documentType.name, '"')).join(",\n"), "]"), [schema]);
2101
+ return useMemo(() => ({
2102
+ dataset,
2103
+ projection: defaultProjection,
2104
+ filter: defaultFilter
2105
+ }), [defaultFilter, dataset]);
2106
+ }
2107
+ function IndexFormInput(props) {
2108
+ var _a;
2109
+ const {
2110
+ label,
2111
+ index,
2112
+ prop,
2113
+ onChange,
2114
+ readOnly,
2115
+ placeholder,
2116
+ type
2117
+ } = props;
2118
+ const handleChange = useCallback(propValue => onChange(current => ({
2119
+ ...current,
2120
+ [prop]: propValue
2121
+ })), [onChange, prop]);
2122
+ return /* @__PURE__ */jsx(FormInput, {
2123
+ label,
2124
+ onChange: handleChange,
2125
+ value: (_a = index[prop]) != null ? _a : "",
2126
+ readOnly,
2127
+ placeholder,
2128
+ type
2129
+ });
2130
+ }
2131
+ function FormInput(props) {
2132
+ const {
2133
+ label,
2134
+ onChange,
2135
+ value,
2136
+ readOnly,
2137
+ placeholder,
2138
+ type = "text"
2139
+ } = props;
2140
+ const id = useId();
2141
+ const handleChange = useCallback(e => onChange(e.currentTarget.value), [onChange]);
2142
+ return /* @__PURE__ */jsxs(Stack, {
2143
+ space: 3,
2144
+ children: [/* @__PURE__ */jsx(Label, {
2145
+ muted: true,
2146
+ htmlFor: id,
2147
+ children: /* @__PURE__ */jsx("label", {
2148
+ htmlFor: id,
2149
+ children: label
2150
+ })
2151
+ }), type === "text" ? /* @__PURE__ */jsx(TextInput, {
2152
+ id,
2153
+ value,
2154
+ onChange: handleChange,
2155
+ readOnly,
2156
+ placeholder
2157
+ }) : /* @__PURE__ */jsx(TextArea, {
2158
+ id,
2159
+ value,
2160
+ rows: 3,
2161
+ onChange: handleChange,
2162
+ readOnly,
2163
+ placeholder,
2164
+ style: {
2165
+ resize: "vertical"
2166
+ }
2167
+ })]
2168
+ });
2169
+ }
2170
+ function EditIndexDialog(props) {
2171
+ const {
2172
+ open,
2173
+ onClose,
2174
+ onSubmit
2175
+ } = props;
2176
+ const id = useId();
2177
+ const ref = useRef(null);
2178
+ useEffect(() => {
2179
+ if (!open) {
2180
+ return;
2181
+ }
2182
+ setTimeout(() => {
2183
+ var _a, _b;
2184
+ return (_b = (_a = ref.current) == null ? void 0 : _a.querySelector("input")) == null ? void 0 : _b.focus();
2185
+ });
2186
+ }, [ref, open]);
2187
+ const handleSubmit = useCallback(index => {
2188
+ onSubmit(index);
2189
+ onClose();
2190
+ }, [onSubmit, onClose]);
2191
+ return open ? /* @__PURE__ */jsx(Dialog, {
2192
+ id,
2193
+ width: 1,
2194
+ ref,
2195
+ onClose,
2196
+ header: "Create embeddings index",
2197
+ children: /* @__PURE__ */jsx(Stack, {
2198
+ padding: 4,
2199
+ space: 5,
2200
+ children: /* @__PURE__ */jsx(IndexEditor, {
2201
+ readOnly: false,
2202
+ onSubmit: handleSubmit
2203
+ })
2204
+ })
2205
+ }) : null;
2206
+ }
2207
+ function IndexEditor(props) {
2208
+ var _a;
2209
+ const {
2210
+ readOnly,
2211
+ index: selectedIndex,
2212
+ onSubmit
2213
+ } = props;
2214
+ const client = useApiClient$1();
2215
+ const schema = useSchema();
2216
+ const defaultIndex = useDefaultIndex(schema, (_a = client.config().dataset) != null ? _a : "");
2217
+ const [errors, setErrors] = useState();
2218
+ const [loading, setLoading] = useState();
2219
+ const [index, setIndex] = useState(() => ({
2220
+ ...defaultIndex,
2221
+ ...selectedIndex
2222
+ }));
2223
+ useEffect(() => setIndex(selectedIndex != null ? selectedIndex : {
2224
+ ...defaultIndex
2225
+ }), [selectedIndex, defaultIndex]);
2226
+ const handleSubmit = useCallback(e => {
2227
+ e.preventDefault();
2228
+ if (readOnly) {
2229
+ return;
2230
+ }
2231
+ const validationErrors = [];
2232
+ if (!index.indexName) {
2233
+ validationErrors.push("Index name is required");
2234
+ } else if (!index.indexName.match(/^[a-zA-Z0-9-_]+$/g)) {
2235
+ validationErrors.push("Index name can only contain the letters a-z, numbers - and _");
2236
+ }
2237
+ if (!index.dataset) {
2238
+ validationErrors.push("Dataset is required");
2239
+ }
2240
+ if (!index.filter) {
2241
+ validationErrors.push("Filter is required");
2242
+ }
2243
+ if (!index.projection) {
2244
+ validationErrors.push("Projection is required");
2245
+ }
2246
+ if (validationErrors.length) {
2247
+ setErrors(validationErrors);
2248
+ return;
2249
+ }
2250
+ const {
2251
+ projectId
2252
+ } = client.config();
2253
+ setLoading(true);
2254
+ client.request({
2255
+ method: "POST",
2256
+ url: "/embeddings-index/".concat(index.dataset, "?projectId=").concat(projectId),
2257
+ body: {
2258
+ indexName: index.indexName,
2259
+ projection: index.projection,
2260
+ filter: index.filter
2261
+ }
2262
+ }).then(response => {
2263
+ if (onSubmit) {
2264
+ onSubmit(response.index);
2265
+ }
2266
+ }).catch(err => {
2267
+ console.error(err);
2268
+ setErrors([err.message]);
2269
+ }).finally(() => {
2270
+ setLoading(false);
2271
+ });
2272
+ }, [index, readOnly, onSubmit, client]);
2273
+ return /* @__PURE__ */jsx("form", {
2274
+ onSubmit: handleSubmit,
2275
+ children: /* @__PURE__ */jsxs(Stack, {
2276
+ space: 4,
2277
+ children: [(errors == null ? void 0 : errors.length) ? /* @__PURE__ */jsx(Card, {
2278
+ tone: "critical",
2279
+ border: true,
2280
+ padding: 2,
2281
+ children: /* @__PURE__ */jsx(Text, {
2282
+ children: /* @__PURE__ */jsx("ul", {
2283
+ style: {
2284
+ marginLeft: -10
2285
+ },
2286
+ children: errors == null ? void 0 : errors.map((error, i) => /* @__PURE__ */jsx("li", {
2287
+ children: error
2288
+ }, "".concat(error, "-").concat(i)))
2289
+ })
2290
+ })
2291
+ }) : null, /* @__PURE__ */jsx(IndexFormInput, {
2292
+ label: "Index name",
2293
+ placeholder: "Name of index without spaces...",
2294
+ index,
2295
+ prop: "indexName",
2296
+ onChange: setIndex,
2297
+ readOnly
2298
+ }), /* @__PURE__ */jsx(IndexFormInput, {
2299
+ label: "Dataset",
2300
+ index,
2301
+ prop: "dataset",
2302
+ onChange: setIndex,
2303
+ readOnly: true
2304
+ }), /* @__PURE__ */jsx(IndexFormInput, {
2305
+ label: "Projection",
2306
+ placeholder: defaultIndex.projection,
2307
+ index,
2308
+ prop: "projection",
2309
+ onChange: setIndex,
2310
+ readOnly,
2311
+ type: "textarea"
2312
+ }), /* @__PURE__ */jsx(IndexFormInput, {
2313
+ label: "Filter",
2314
+ placeholder: defaultIndex.filter,
2315
+ index,
2316
+ prop: "filter",
2317
+ onChange: setIndex,
2318
+ readOnly,
2319
+ type: "textarea"
2320
+ }), onSubmit && /* @__PURE__ */jsx(Button, {
2321
+ type: "submit",
2322
+ text: "Create index",
2323
+ icon: loading ? /* @__PURE__ */jsx(Box, {
2324
+ style: {
2325
+ marginTop: 5
2326
+ },
2327
+ children: /* @__PURE__ */jsx(Spinner, {})
2328
+ }) : AddIcon,
2329
+ disabled: readOnly || loading,
2330
+ tone: "primary"
2331
+ })]
2332
+ })
2333
+ });
2334
+ }
2335
+ function IndexList(props) {
2336
+ const {
2337
+ loading,
2338
+ selectedIndex,
2339
+ indexes,
2340
+ onIndexSelected
2341
+ } = props;
2342
+ return /* @__PURE__ */jsx(Card, {
2343
+ tone: "default",
2344
+ style: {
2345
+ opacity: loading ? 0.5 : 1
2346
+ },
2347
+ children: /* @__PURE__ */jsxs(Stack, {
2348
+ space: 2,
2349
+ children: [/* @__PURE__ */jsx(Card, {
2350
+ borderBottom: true,
2351
+ flex: 1,
2352
+ paddingBottom: 2,
2353
+ children: /* @__PURE__ */jsxs(Flex, {
2354
+ children: [/* @__PURE__ */jsx(Box, {
2355
+ flex: 1,
2356
+ children: /* @__PURE__ */jsx(Label, {
2357
+ muted: true,
2358
+ children: "Index name"
2359
+ })
2360
+ }), /* @__PURE__ */jsx(Box, {
2361
+ flex: 1,
2362
+ children: /* @__PURE__ */jsx(Label, {
2363
+ muted: true,
2364
+ children: "Dataset"
2365
+ })
2366
+ }), /* @__PURE__ */jsx(Box, {
2367
+ flex: 1,
2368
+ children: /* @__PURE__ */jsx(Label, {
2369
+ muted: true,
2370
+ children: "Status"
2371
+ })
2372
+ }), /* @__PURE__ */jsx(Box, {
2373
+ flex: 1,
2374
+ children: /* @__PURE__ */jsx(Label, {
2375
+ muted: true,
2376
+ children: "Progress"
2377
+ })
2378
+ })]
2379
+ })
2380
+ }), indexes.length ? /* @__PURE__ */jsx(Stack, {
2381
+ space: 2,
2382
+ style: {
2383
+ maxHeight: 200,
2384
+ overflow: "auto"
2385
+ },
2386
+ children: indexes.map(index => /* @__PURE__ */jsx(IndexRow, {
2387
+ selectedIndex,
2388
+ index,
2389
+ onIndexSelected
2390
+ }, index.indexName))
2391
+ }) : /* @__PURE__ */jsx(Text, {
2392
+ muted: true,
2393
+ children: "No indexes found."
2394
+ })]
2395
+ })
2396
+ });
2397
+ }
2398
+ function IndexRow(props) {
2399
+ const {
2400
+ selectedIndex,
2401
+ index,
2402
+ onIndexSelected
2403
+ } = props;
2404
+ const onSelect = useCallback(() => onIndexSelected(index), [onIndexSelected, index]);
2405
+ return /* @__PURE__ */jsx(Button, {
2406
+ tone: (selectedIndex == null ? void 0 : selectedIndex.indexName) === index.indexName ? "primary" : "default",
2407
+ mode: (selectedIndex == null ? void 0 : selectedIndex.indexName) === index.indexName ? "default" : "bleed",
2408
+ onClick: onSelect,
2409
+ children: /* @__PURE__ */jsxs(Flex, {
2410
+ children: [/* @__PURE__ */jsx(Box, {
2411
+ flex: 1,
2412
+ children: index.indexName
2413
+ }), /* @__PURE__ */jsx(Box, {
2414
+ flex: 1,
2415
+ children: index.dataset
2416
+ }), /* @__PURE__ */jsx(Box, {
2417
+ flex: 1,
2418
+ children: index.status
2419
+ }), /* @__PURE__ */jsxs(Box, {
2420
+ flex: 1,
2421
+ children: [index.startDocumentCount ? Math.floor((index.startDocumentCount - index.remainingDocumentCount) / index.startDocumentCount * 100) : "?", "%"]
2422
+ })]
2423
+ })
2424
+ }, index.indexName);
2425
+ }
2426
+ const NO_RESULTS = [];
2427
+ function QueryIndex(props) {
2428
+ const {
2429
+ indexName
2430
+ } = props;
2431
+ const [query, setQuery] = useState("");
2432
+ const [searching, setSearching] = useState(false);
2433
+ const [results, setResults] = useState(NO_RESULTS);
2434
+ const client = useApiClient$1();
2435
+ const search = useCallback(queryString => {
2436
+ setSearching(true);
2437
+ return queryIndex({
2438
+ query: queryString,
2439
+ indexName,
2440
+ maxResults: 5
2441
+ }, client).then(setResults).finally(() => setSearching(false));
2442
+ }, [client, indexName]);
2443
+ const onInputChange = useCallback(e => {
2444
+ setQuery(e.currentTarget.value);
2445
+ }, []);
2446
+ const onKeyDown = useCallback(e => {
2447
+ if (e.key === "Enter") {
2448
+ search(query).catch(console.error);
2449
+ }
2450
+ }, [search, query]);
2451
+ return /* @__PURE__ */jsxs(Stack, {
2452
+ space: 3,
2453
+ flex: 1,
2454
+ children: [/* @__PURE__ */jsx(Flex, {
2455
+ flex: 1,
2456
+ children: /* @__PURE__ */jsx(Card, {
2457
+ flex: 1,
2458
+ children: /* @__PURE__ */jsx(TextInput, {
2459
+ iconRight: searching ? /* @__PURE__ */jsx(Box, {
2460
+ style: {
2461
+ marginTop: 5
2462
+ },
2463
+ children: /* @__PURE__ */jsx(Spinner, {})
2464
+ }) : SearchIcon,
2465
+ placeholder: "Find documents",
2466
+ value: query,
2467
+ disabled: searching,
2468
+ onChange: onInputChange,
2469
+ onKeyDown
2470
+ })
2471
+ })
2472
+ }), /* @__PURE__ */jsx(Flex, {
2473
+ gap: 4,
2474
+ style: {
2475
+ opacity: searching ? 0.5 : 1
2476
+ },
2477
+ children: /* @__PURE__ */jsx(Box, {
2478
+ flex: 1,
2479
+ children: /* @__PURE__ */jsx(ResultList, {
2480
+ results,
2481
+ query
2482
+ })
2483
+ })
2484
+ })]
2485
+ });
2486
+ }
2487
+ function ResultList(props) {
2488
+ const {
2489
+ results,
2490
+ query
2491
+ } = props;
2492
+ return /* @__PURE__ */jsx(Stack, {
2493
+ space: 4,
2494
+ height: "fill",
2495
+ children: /* @__PURE__ */jsxs(Stack, {
2496
+ space: 2,
2497
+ children: [results.map(r => /* @__PURE__ */jsx(ResultEntry, {
2498
+ result: r
2499
+ }, r.value.documentId)), !results.length && query ? "No results." : null]
2500
+ })
2501
+ });
2502
+ }
2503
+ function ResultEntry(props) {
2504
+ return /* @__PURE__ */jsxs(Flex, {
2505
+ gap: 4,
2506
+ align: "center",
2507
+ children: [/* @__PURE__ */jsx(Box, {
2508
+ flex: 1,
2509
+ children: /* @__PURE__ */jsx(DocumentPreview, {
2510
+ documentId: props.result.value.documentId,
2511
+ button: true
2512
+ })
2513
+ }), /* @__PURE__ */jsx(Box, {
2514
+ children: /* @__PURE__ */jsxs(Text, {
2515
+ muted: true,
2516
+ size: 1,
2517
+ children: [Math.floor(props.result.score * 100), " %"]
2518
+ })
2519
+ })]
2520
+ });
2521
+ }
2522
+ function IndexInfo(_ref3) {
2523
+ let {
2524
+ selectedIndex,
2525
+ onDeleteIndex
2526
+ } = _ref3;
2527
+ var _a;
2528
+ const handleDelete = useCallback(() => onDeleteIndex(selectedIndex), [selectedIndex, onDeleteIndex]);
2529
+ return /* @__PURE__ */jsxs(Stack, {
2530
+ space: 4,
2531
+ flex: 1,
2532
+ children: [/* @__PURE__ */jsxs(Flex, {
2533
+ align: "center",
2534
+ flex: 1,
2535
+ gap: 2,
2536
+ children: [/* @__PURE__ */jsx(Box, {
2537
+ flex: 1,
2538
+ children: /* @__PURE__ */jsxs(Heading, {
2539
+ children: ["Index: ", (_a = selectedIndex == null ? void 0 : selectedIndex.indexName) != null ? _a : "Untitled"]
2540
+ })
2541
+ }), /* @__PURE__ */jsx(Box, {
2542
+ children: /* @__PURE__ */jsx(MenuButton, {
2543
+ button: /* @__PURE__ */jsx(Button, {
2544
+ title: "Open index actions",
2545
+ icon: EllipsisVerticalIcon,
2546
+ padding: 2,
2547
+ mode: "ghost"
2548
+ }),
2549
+ id: "button-".concat(selectedIndex.indexName),
2550
+ menu: /* @__PURE__ */jsx(Menu, {
2551
+ children: /* @__PURE__ */jsx(MenuItem, {
2552
+ text: "Delete index",
2553
+ icon: TrashIcon,
2554
+ tone: "critical",
2555
+ onClick: handleDelete
2556
+ })
2557
+ }),
2558
+ popover: {
2559
+ placement: "right"
2560
+ }
2561
+ })
2562
+ })]
2563
+ }), /* @__PURE__ */jsxs(Flex, {
2564
+ gap: 6,
2565
+ children: [/* @__PURE__ */jsxs(Stack, {
2566
+ space: 4,
2567
+ flex: 1,
2568
+ style: {
2569
+ maxWidth: 600
2570
+ },
2571
+ children: [/* @__PURE__ */jsx(Box, {
2572
+ children: /* @__PURE__ */jsx(IndexEditor, {
2573
+ index: selectedIndex,
2574
+ readOnly: true
2575
+ })
2576
+ }), /* @__PURE__ */jsx(IndexStatus, {
2577
+ selectedIndex
2578
+ })]
2579
+ }), /* @__PURE__ */jsxs(Stack, {
2580
+ space: 3,
2581
+ flex: 1,
2582
+ children: [/* @__PURE__ */jsx(Label, {
2583
+ muted: true,
2584
+ children: "Query index"
2585
+ }), /* @__PURE__ */jsx(QueryIndex, {
2586
+ indexName: selectedIndex.indexName
2587
+ }, selectedIndex.indexName)]
2588
+ })]
2589
+ })]
2590
+ });
2591
+ }
2592
+ function IndexStatus(_ref4) {
2593
+ let {
2594
+ selectedIndex
2595
+ } = _ref4;
2596
+ return /* @__PURE__ */jsxs(Stack, {
2597
+ space: 4,
2598
+ flex: 1,
2599
+ children: [/* @__PURE__ */jsxs(Flex, {
2600
+ gap: 2,
2601
+ align: "center",
2602
+ children: [/* @__PURE__ */jsx(Box, {
2603
+ flex: 1,
2604
+ children: /* @__PURE__ */jsx(Label, {
2605
+ size: 1,
2606
+ muted: true,
2607
+ children: "Status"
2608
+ })
2609
+ }), /* @__PURE__ */jsx(Stack, {
2610
+ space: 2,
2611
+ children: /* @__PURE__ */jsx(Text, {
2612
+ children: selectedIndex.status
2613
+ })
2614
+ })]
2615
+ }), /* @__PURE__ */jsxs(Flex, {
2616
+ gap: 5,
2617
+ align: "center",
2618
+ children: [/* @__PURE__ */jsx(Box, {
2619
+ flex: 1,
2620
+ children: /* @__PURE__ */jsx(Label, {
2621
+ size: 1,
2622
+ muted: true,
2623
+ children: "Indexing progress"
2624
+ })
2625
+ }), /* @__PURE__ */jsx(Stack, {
2626
+ space: 2,
2627
+ children: /* @__PURE__ */jsxs(Text, {
2628
+ children: [selectedIndex.startDocumentCount - selectedIndex.remainingDocumentCount, " /", " ", selectedIndex.startDocumentCount]
2629
+ })
2630
+ })]
2631
+ }), /* @__PURE__ */jsxs(Flex, {
2632
+ gap: 5,
2633
+ align: "center",
2634
+ children: [/* @__PURE__ */jsx(Box, {
2635
+ flex: 1,
2636
+ children: /* @__PURE__ */jsx(Label, {
2637
+ size: 1,
2638
+ muted: true,
2639
+ children: "Failed documents"
2640
+ })
2641
+ }), /* @__PURE__ */jsx(Stack, {
2642
+ space: 2,
2643
+ children: /* @__PURE__ */jsx(Text, {
2644
+ children: selectedIndex.failedDocumentCount
2645
+ })
2646
+ })]
2647
+ })]
2648
+ });
2649
+ }
2650
+ function useApiClient() {
2651
+ const client = useClient({
2652
+ apiVersion: "vX"
2653
+ });
2654
+ return useMemo(() => client, [client]);
2655
+ }
2656
+ function EmbeddingsIndexTool() {
2657
+ return /* @__PURE__ */jsx(Card, {
2658
+ children: /* @__PURE__ */jsx(Flex, {
2659
+ justify: "center",
2660
+ flex: 1,
2661
+ children: /* @__PURE__ */jsx(Card, {
2662
+ flex: 1,
2663
+ style: {
2664
+ maxWidth: 1200
2665
+ },
2666
+ padding: 5,
2667
+ children: /* @__PURE__ */jsx(Indexes, {})
2668
+ })
2669
+ })
2670
+ });
2671
+ }
2672
+ const NO_INDEXES = [];
2673
+ function Indexes() {
2674
+ const client = useApiClient();
2675
+ const [indexes, setIndexes] = useState(NO_INDEXES);
2676
+ const [loading, setLoading] = useState(false);
2677
+ const [error, setError] = useState(false);
2678
+ const [createIndexOpen, setCreateIndexOpen] = useState(false);
2679
+ const [selectedIndex, setSelectedIndex] = useState(void 0);
2680
+ const onCreateIndexClose = useCallback(() => setCreateIndexOpen(false), []);
2681
+ useEffect(() => {
2682
+ setSelectedIndex(indexes.find(i => i.indexName === (selectedIndex == null ? void 0 : selectedIndex.indexName)));
2683
+ }, [indexes, selectedIndex]);
2684
+ const updateIndexes = useCallback(() => {
2685
+ setLoading(true);
2686
+ setError(false);
2687
+ getIndexes(client).then(response => {
2688
+ setLoading(false);
2689
+ setIndexes(response);
2690
+ }).catch(e => {
2691
+ console.error(e);
2692
+ setError(true);
2693
+ }).finally(() => {
2694
+ setLoading(false);
2695
+ });
2696
+ }, [client]);
2697
+ const deleteNamedIndex = useCallback(index => {
2698
+ if (
2699
+ // eslint-disable-next-line no-alert
2700
+ !confirm("Are you sure you want to delete ".concat(index.indexName, " for dataset ").concat(index.dataset, "?"))) {
2701
+ return;
2702
+ }
2703
+ setLoading(true);
2704
+ setError(false);
2705
+ deleteIndex(index.indexName, client).then(() => {
2706
+ setTimeout(() => updateIndexes());
2707
+ }).catch(e => {
2708
+ console.error(e);
2709
+ setError(true);
2710
+ }).finally(() => {
2711
+ setLoading(false);
2712
+ });
2713
+ }, [client, updateIndexes]);
2714
+ const onSelectIndex = useCallback(index => {
2715
+ setSelectedIndex(index);
2716
+ updateIndexes();
2717
+ }, [setSelectedIndex, updateIndexes]);
2718
+ useEffect(() => {
2719
+ updateIndexes();
2720
+ }, [updateIndexes]);
2721
+ const openCreate = useCallback(() => setCreateIndexOpen(true), []);
2722
+ const onSubmit = useCallback(index => {
2723
+ setIndexes(current => [...current, index]);
2724
+ setSelectedIndex(index);
2725
+ updateIndexes();
2726
+ }, [updateIndexes]);
2727
+ return /* @__PURE__ */jsxs(Stack, {
2728
+ space: 4,
2729
+ children: [/* @__PURE__ */jsxs(Flex, {
2730
+ gap: 2,
2731
+ align: "center",
2732
+ style: {
2733
+ height: 30
2734
+ },
2735
+ children: [/* @__PURE__ */jsx(Box, {
2736
+ flex: 1,
2737
+ children: /* @__PURE__ */jsx(Heading, {
2738
+ size: 1,
2739
+ children: "Embeddings indexes"
2740
+ })
2741
+ }), /* @__PURE__ */jsx(Box, {
2742
+ style: {
2743
+ justifySelf: "flex-end"
2744
+ },
2745
+ children: /* @__PURE__ */jsx(Button, {
2746
+ icon: AddIcon,
2747
+ text: "New index",
2748
+ tone: "default",
2749
+ mode: "ghost",
2750
+ onClick: openCreate
2751
+ })
2752
+ }), /* @__PURE__ */jsx(Button, {
2753
+ size: 1,
2754
+ icon: loading ? /* @__PURE__ */jsx(Spinner, {}) : UndoIcon,
2755
+ title: "Refresh index list",
2756
+ tone: "default",
2757
+ mode: "bleed",
2758
+ onClick: updateIndexes,
2759
+ disabled: loading
2760
+ })]
2761
+ }), error ? /* @__PURE__ */jsx(Card, {
2762
+ tone: "critical",
2763
+ padding: 2,
2764
+ border: true,
2765
+ children: "An error occurred. See console for details."
2766
+ }) : null, /* @__PURE__ */jsx(IndexList, {
2767
+ loading,
2768
+ indexes,
2769
+ selectedIndex,
2770
+ onIndexSelected: onSelectIndex
2771
+ }), selectedIndex && /* @__PURE__ */jsx(IndexInfo, {
2772
+ selectedIndex,
2773
+ onDeleteIndex: deleteNamedIndex
2774
+ }), /* @__PURE__ */jsx(EditIndexDialog, {
2775
+ open: createIndexOpen,
2776
+ onClose: onCreateIndexClose,
2777
+ onSubmit
2778
+ })]
2779
+ });
2780
+ }
2781
+ const embeddingsIndexTool = {
2782
+ name: "embeddings-index",
2783
+ title: "Embeddings",
2784
+ icon: EarthGlobeIcon,
2785
+ component: EmbeddingsIndexTool
2786
+ };
2787
+ const embeddingsIndexDashboard = definePlugin({
2788
+ name: "@sanity/embeddings-index-dashboard",
2789
+ tools: [embeddingsIndexTool]
2790
+ });
2791
+ export { deleteIndex, embeddingsIndexDashboard, embeddingsIndexReferenceInput, getIndexes, queryIndex };
2792
+ //# sourceMappingURL=index.esm.js.map