@sanity/embeddings-index-ui 2.0.0 → 2.1.0

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