@legendapp/state 0.21.10 → 0.21.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1604 @@
1
+ import { observable, observe } from '@legendapp/state';
2
+ import { useUnmount } from '@legendapp/state/react';
3
+ import * as React from 'react';
4
+ import React__default from 'react';
5
+
6
+ class Subscribable {
7
+ constructor() {
8
+ this.listeners = [];
9
+ this.subscribe = this.subscribe.bind(this);
10
+ }
11
+
12
+ subscribe(listener) {
13
+ this.listeners.push(listener);
14
+ this.onSubscribe();
15
+ return () => {
16
+ this.listeners = this.listeners.filter(x => x !== listener);
17
+ this.onUnsubscribe();
18
+ };
19
+ }
20
+
21
+ hasListeners() {
22
+ return this.listeners.length > 0;
23
+ }
24
+
25
+ onSubscribe() {// Do nothing
26
+ }
27
+
28
+ onUnsubscribe() {// Do nothing
29
+ }
30
+
31
+ }
32
+
33
+ // TYPES
34
+ // UTILS
35
+ const isServer = typeof window === 'undefined';
36
+ function noop$1() {
37
+ return undefined;
38
+ }
39
+ function isValidTimeout(value) {
40
+ return typeof value === 'number' && value >= 0 && value !== Infinity;
41
+ }
42
+ function timeUntilStale(updatedAt, staleTime) {
43
+ return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);
44
+ }
45
+ function parseMutationArgs(arg1, arg2, arg3) {
46
+ if (isQueryKey(arg1)) {
47
+ if (typeof arg2 === 'function') {
48
+ return { ...arg3,
49
+ mutationKey: arg1,
50
+ mutationFn: arg2
51
+ };
52
+ }
53
+
54
+ return { ...arg2,
55
+ mutationKey: arg1
56
+ };
57
+ }
58
+
59
+ if (typeof arg1 === 'function') {
60
+ return { ...arg2,
61
+ mutationFn: arg1
62
+ };
63
+ }
64
+
65
+ return { ...arg1
66
+ };
67
+ }
68
+ /**
69
+ * This function returns `a` if `b` is deeply equal.
70
+ * If not, it will replace any deeply equal children of `b` with those of `a`.
71
+ * This can be used for structural sharing between JSON values for example.
72
+ */
73
+
74
+ function replaceEqualDeep(a, b) {
75
+ if (a === b) {
76
+ return a;
77
+ }
78
+
79
+ const array = isPlainArray(a) && isPlainArray(b);
80
+
81
+ if (array || isPlainObject(a) && isPlainObject(b)) {
82
+ const aSize = array ? a.length : Object.keys(a).length;
83
+ const bItems = array ? b : Object.keys(b);
84
+ const bSize = bItems.length;
85
+ const copy = array ? [] : {};
86
+ let equalItems = 0;
87
+
88
+ for (let i = 0; i < bSize; i++) {
89
+ const key = array ? i : bItems[i];
90
+ copy[key] = replaceEqualDeep(a[key], b[key]);
91
+
92
+ if (copy[key] === a[key]) {
93
+ equalItems++;
94
+ }
95
+ }
96
+
97
+ return aSize === bSize && equalItems === aSize ? a : copy;
98
+ }
99
+
100
+ return b;
101
+ }
102
+ /**
103
+ * Shallow compare objects. Only works with objects that always have the same properties.
104
+ */
105
+
106
+ function shallowEqualObjects(a, b) {
107
+ if (a && !b || b && !a) {
108
+ return false;
109
+ }
110
+
111
+ for (const key in a) {
112
+ if (a[key] !== b[key]) {
113
+ return false;
114
+ }
115
+ }
116
+
117
+ return true;
118
+ }
119
+ function isPlainArray(value) {
120
+ return Array.isArray(value) && value.length === Object.keys(value).length;
121
+ } // Copied from: https://github.com/jonschlinkert/is-plain-object
122
+
123
+ function isPlainObject(o) {
124
+ if (!hasObjectPrototype(o)) {
125
+ return false;
126
+ } // If has modified constructor
127
+
128
+
129
+ const ctor = o.constructor;
130
+
131
+ if (typeof ctor === 'undefined') {
132
+ return true;
133
+ } // If has modified prototype
134
+
135
+
136
+ const prot = ctor.prototype;
137
+
138
+ if (!hasObjectPrototype(prot)) {
139
+ return false;
140
+ } // If constructor does not have an Object-specific method
141
+
142
+
143
+ if (!prot.hasOwnProperty('isPrototypeOf')) {
144
+ return false;
145
+ } // Most likely a plain Object
146
+
147
+
148
+ return true;
149
+ }
150
+
151
+ function hasObjectPrototype(o) {
152
+ return Object.prototype.toString.call(o) === '[object Object]';
153
+ }
154
+
155
+ function isQueryKey(value) {
156
+ return Array.isArray(value);
157
+ }
158
+ function sleep(timeout) {
159
+ return new Promise(resolve => {
160
+ setTimeout(resolve, timeout);
161
+ });
162
+ }
163
+ /**
164
+ * Schedules a microtask.
165
+ * This can be useful to schedule state updates after rendering.
166
+ */
167
+
168
+ function scheduleMicrotask(callback) {
169
+ sleep(0).then(callback);
170
+ }
171
+ function replaceData(prevData, data, options) {
172
+ // Use prev data if an isDataEqual function is defined and returns `true`
173
+ if (options.isDataEqual != null && options.isDataEqual(prevData, data)) {
174
+ return prevData;
175
+ } else if (typeof options.structuralSharing === 'function') {
176
+ return options.structuralSharing(prevData, data);
177
+ } else if (options.structuralSharing !== false) {
178
+ // Structurally share data between prev and new data if needed
179
+ return replaceEqualDeep(prevData, data);
180
+ }
181
+
182
+ return data;
183
+ }
184
+
185
+ class FocusManager extends Subscribable {
186
+ constructor() {
187
+ super();
188
+
189
+ this.setup = onFocus => {
190
+ // addEventListener does not exist in React Native, but window does
191
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
192
+ if (!isServer && window.addEventListener) {
193
+ const listener = () => onFocus(); // Listen to visibillitychange and focus
194
+
195
+
196
+ window.addEventListener('visibilitychange', listener, false);
197
+ window.addEventListener('focus', listener, false);
198
+ return () => {
199
+ // Be sure to unsubscribe if a new handler is set
200
+ window.removeEventListener('visibilitychange', listener);
201
+ window.removeEventListener('focus', listener);
202
+ };
203
+ }
204
+ };
205
+ }
206
+
207
+ onSubscribe() {
208
+ if (!this.cleanup) {
209
+ this.setEventListener(this.setup);
210
+ }
211
+ }
212
+
213
+ onUnsubscribe() {
214
+ if (!this.hasListeners()) {
215
+ var _this$cleanup;
216
+
217
+ (_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
218
+ this.cleanup = undefined;
219
+ }
220
+ }
221
+
222
+ setEventListener(setup) {
223
+ var _this$cleanup2;
224
+
225
+ this.setup = setup;
226
+ (_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
227
+ this.cleanup = setup(focused => {
228
+ if (typeof focused === 'boolean') {
229
+ this.setFocused(focused);
230
+ } else {
231
+ this.onFocus();
232
+ }
233
+ });
234
+ }
235
+
236
+ setFocused(focused) {
237
+ this.focused = focused;
238
+
239
+ if (focused) {
240
+ this.onFocus();
241
+ }
242
+ }
243
+
244
+ onFocus() {
245
+ this.listeners.forEach(listener => {
246
+ listener();
247
+ });
248
+ }
249
+
250
+ isFocused() {
251
+ if (typeof this.focused === 'boolean') {
252
+ return this.focused;
253
+ } // document global can be unavailable in react native
254
+
255
+
256
+ if (typeof document === 'undefined') {
257
+ return true;
258
+ }
259
+
260
+ return [undefined, 'visible', 'prerender'].includes(document.visibilityState);
261
+ }
262
+
263
+ }
264
+ const focusManager = new FocusManager();
265
+
266
+ class OnlineManager extends Subscribable {
267
+ constructor() {
268
+ super();
269
+
270
+ this.setup = onOnline => {
271
+ // addEventListener does not exist in React Native, but window does
272
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
273
+ if (!isServer && window.addEventListener) {
274
+ const listener = () => onOnline(); // Listen to online
275
+
276
+
277
+ window.addEventListener('online', listener, false);
278
+ window.addEventListener('offline', listener, false);
279
+ return () => {
280
+ // Be sure to unsubscribe if a new handler is set
281
+ window.removeEventListener('online', listener);
282
+ window.removeEventListener('offline', listener);
283
+ };
284
+ }
285
+ };
286
+ }
287
+
288
+ onSubscribe() {
289
+ if (!this.cleanup) {
290
+ this.setEventListener(this.setup);
291
+ }
292
+ }
293
+
294
+ onUnsubscribe() {
295
+ if (!this.hasListeners()) {
296
+ var _this$cleanup;
297
+
298
+ (_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
299
+ this.cleanup = undefined;
300
+ }
301
+ }
302
+
303
+ setEventListener(setup) {
304
+ var _this$cleanup2;
305
+
306
+ this.setup = setup;
307
+ (_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
308
+ this.cleanup = setup(online => {
309
+ if (typeof online === 'boolean') {
310
+ this.setOnline(online);
311
+ } else {
312
+ this.onOnline();
313
+ }
314
+ });
315
+ }
316
+
317
+ setOnline(online) {
318
+ this.online = online;
319
+
320
+ if (online) {
321
+ this.onOnline();
322
+ }
323
+ }
324
+
325
+ onOnline() {
326
+ this.listeners.forEach(listener => {
327
+ listener();
328
+ });
329
+ }
330
+
331
+ isOnline() {
332
+ if (typeof this.online === 'boolean') {
333
+ return this.online;
334
+ }
335
+
336
+ if (typeof navigator === 'undefined' || typeof navigator.onLine === 'undefined') {
337
+ return true;
338
+ }
339
+
340
+ return navigator.onLine;
341
+ }
342
+
343
+ }
344
+ const onlineManager = new OnlineManager();
345
+
346
+ function canFetch(networkMode) {
347
+ return (networkMode != null ? networkMode : 'online') === 'online' ? onlineManager.isOnline() : true;
348
+ }
349
+ class CancelledError {
350
+ constructor(options) {
351
+ this.revert = options == null ? void 0 : options.revert;
352
+ this.silent = options == null ? void 0 : options.silent;
353
+ }
354
+
355
+ }
356
+ function isCancelledError(value) {
357
+ return value instanceof CancelledError;
358
+ }
359
+
360
+ function createNotifyManager() {
361
+ let queue = [];
362
+ let transactions = 0;
363
+
364
+ let notifyFn = callback => {
365
+ callback();
366
+ };
367
+
368
+ let batchNotifyFn = callback => {
369
+ callback();
370
+ };
371
+
372
+ const batch = callback => {
373
+ let result;
374
+ transactions++;
375
+
376
+ try {
377
+ result = callback();
378
+ } finally {
379
+ transactions--;
380
+
381
+ if (!transactions) {
382
+ flush();
383
+ }
384
+ }
385
+
386
+ return result;
387
+ };
388
+
389
+ const schedule = callback => {
390
+ if (transactions) {
391
+ queue.push(callback);
392
+ } else {
393
+ scheduleMicrotask(() => {
394
+ notifyFn(callback);
395
+ });
396
+ }
397
+ };
398
+ /**
399
+ * All calls to the wrapped function will be batched.
400
+ */
401
+
402
+
403
+ const batchCalls = callback => {
404
+ return (...args) => {
405
+ schedule(() => {
406
+ callback(...args);
407
+ });
408
+ };
409
+ };
410
+
411
+ const flush = () => {
412
+ const originalQueue = queue;
413
+ queue = [];
414
+
415
+ if (originalQueue.length) {
416
+ scheduleMicrotask(() => {
417
+ batchNotifyFn(() => {
418
+ originalQueue.forEach(callback => {
419
+ notifyFn(callback);
420
+ });
421
+ });
422
+ });
423
+ }
424
+ };
425
+ /**
426
+ * Use this method to set a custom notify function.
427
+ * This can be used to for example wrap notifications with `React.act` while running tests.
428
+ */
429
+
430
+
431
+ const setNotifyFunction = fn => {
432
+ notifyFn = fn;
433
+ };
434
+ /**
435
+ * Use this method to set a custom function to batch notifications together into a single tick.
436
+ * By default React Query will use the batch function provided by ReactDOM or React Native.
437
+ */
438
+
439
+
440
+ const setBatchNotifyFunction = fn => {
441
+ batchNotifyFn = fn;
442
+ };
443
+
444
+ return {
445
+ batch,
446
+ batchCalls,
447
+ schedule,
448
+ setNotifyFunction,
449
+ setBatchNotifyFunction
450
+ };
451
+ } // SINGLETON
452
+
453
+ const notifyManager = createNotifyManager();
454
+
455
+ function getDefaultState() {
456
+ return {
457
+ context: undefined,
458
+ data: undefined,
459
+ error: null,
460
+ failureCount: 0,
461
+ failureReason: null,
462
+ isPaused: false,
463
+ status: 'idle',
464
+ variables: undefined
465
+ };
466
+ }
467
+
468
+ class QueryObserver extends Subscribable {
469
+ constructor(client, options) {
470
+ super();
471
+ this.client = client;
472
+ this.options = options;
473
+ this.trackedProps = new Set();
474
+ this.selectError = null;
475
+ this.bindMethods();
476
+ this.setOptions(options);
477
+ }
478
+
479
+ bindMethods() {
480
+ this.remove = this.remove.bind(this);
481
+ this.refetch = this.refetch.bind(this);
482
+ }
483
+
484
+ onSubscribe() {
485
+ if (this.listeners.length === 1) {
486
+ this.currentQuery.addObserver(this);
487
+
488
+ if (shouldFetchOnMount(this.currentQuery, this.options)) {
489
+ this.executeFetch();
490
+ }
491
+
492
+ this.updateTimers();
493
+ }
494
+ }
495
+
496
+ onUnsubscribe() {
497
+ if (!this.listeners.length) {
498
+ this.destroy();
499
+ }
500
+ }
501
+
502
+ shouldFetchOnReconnect() {
503
+ return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnReconnect);
504
+ }
505
+
506
+ shouldFetchOnWindowFocus() {
507
+ return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnWindowFocus);
508
+ }
509
+
510
+ destroy() {
511
+ this.listeners = [];
512
+ this.clearStaleTimeout();
513
+ this.clearRefetchInterval();
514
+ this.currentQuery.removeObserver(this);
515
+ }
516
+
517
+ setOptions(options, notifyOptions) {
518
+ const prevOptions = this.options;
519
+ const prevQuery = this.currentQuery;
520
+ this.options = this.client.defaultQueryOptions(options);
521
+
522
+ if (process.env.NODE_ENV !== 'production' && typeof (options == null ? void 0 : options.isDataEqual) !== 'undefined') {
523
+ this.client.getLogger().error("The isDataEqual option has been deprecated and will be removed in the next major version. You can achieve the same functionality by passing a function as the structuralSharing option");
524
+ }
525
+
526
+ if (!shallowEqualObjects(prevOptions, this.options)) {
527
+ this.client.getQueryCache().notify({
528
+ type: 'observerOptionsUpdated',
529
+ query: this.currentQuery,
530
+ observer: this
531
+ });
532
+ }
533
+
534
+ if (typeof this.options.enabled !== 'undefined' && typeof this.options.enabled !== 'boolean') {
535
+ throw new Error('Expected enabled to be a boolean');
536
+ } // Keep previous query key if the user does not supply one
537
+
538
+
539
+ if (!this.options.queryKey) {
540
+ this.options.queryKey = prevOptions.queryKey;
541
+ }
542
+
543
+ this.updateQuery();
544
+ const mounted = this.hasListeners(); // Fetch if there are subscribers
545
+
546
+ if (mounted && shouldFetchOptionally(this.currentQuery, prevQuery, this.options, prevOptions)) {
547
+ this.executeFetch();
548
+ } // Update result
549
+
550
+
551
+ this.updateResult(notifyOptions); // Update stale interval if needed
552
+
553
+ if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || this.options.staleTime !== prevOptions.staleTime)) {
554
+ this.updateStaleTimeout();
555
+ }
556
+
557
+ const nextRefetchInterval = this.computeRefetchInterval(); // Update refetch interval if needed
558
+
559
+ if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || nextRefetchInterval !== this.currentRefetchInterval)) {
560
+ this.updateRefetchInterval(nextRefetchInterval);
561
+ }
562
+ }
563
+
564
+ getOptimisticResult(options) {
565
+ const query = this.client.getQueryCache().build(this.client, options);
566
+ return this.createResult(query, options);
567
+ }
568
+
569
+ getCurrentResult() {
570
+ return this.currentResult;
571
+ }
572
+
573
+ trackResult(result) {
574
+ const trackedResult = {};
575
+ Object.keys(result).forEach(key => {
576
+ Object.defineProperty(trackedResult, key, {
577
+ configurable: false,
578
+ enumerable: true,
579
+ get: () => {
580
+ this.trackedProps.add(key);
581
+ return result[key];
582
+ }
583
+ });
584
+ });
585
+ return trackedResult;
586
+ }
587
+
588
+ getCurrentQuery() {
589
+ return this.currentQuery;
590
+ }
591
+
592
+ remove() {
593
+ this.client.getQueryCache().remove(this.currentQuery);
594
+ }
595
+
596
+ refetch({
597
+ refetchPage,
598
+ ...options
599
+ } = {}) {
600
+ return this.fetch({ ...options,
601
+ meta: {
602
+ refetchPage
603
+ }
604
+ });
605
+ }
606
+
607
+ fetchOptimistic(options) {
608
+ const defaultedOptions = this.client.defaultQueryOptions(options);
609
+ const query = this.client.getQueryCache().build(this.client, defaultedOptions);
610
+ query.isFetchingOptimistic = true;
611
+ return query.fetch().then(() => this.createResult(query, defaultedOptions));
612
+ }
613
+
614
+ fetch(fetchOptions) {
615
+ var _fetchOptions$cancelR;
616
+
617
+ return this.executeFetch({ ...fetchOptions,
618
+ cancelRefetch: (_fetchOptions$cancelR = fetchOptions.cancelRefetch) != null ? _fetchOptions$cancelR : true
619
+ }).then(() => {
620
+ this.updateResult();
621
+ return this.currentResult;
622
+ });
623
+ }
624
+
625
+ executeFetch(fetchOptions) {
626
+ // Make sure we reference the latest query as the current one might have been removed
627
+ this.updateQuery(); // Fetch
628
+
629
+ let promise = this.currentQuery.fetch(this.options, fetchOptions);
630
+
631
+ if (!(fetchOptions != null && fetchOptions.throwOnError)) {
632
+ promise = promise.catch(noop$1);
633
+ }
634
+
635
+ return promise;
636
+ }
637
+
638
+ updateStaleTimeout() {
639
+ this.clearStaleTimeout();
640
+
641
+ if (isServer || this.currentResult.isStale || !isValidTimeout(this.options.staleTime)) {
642
+ return;
643
+ }
644
+
645
+ const time = timeUntilStale(this.currentResult.dataUpdatedAt, this.options.staleTime); // The timeout is sometimes triggered 1 ms before the stale time expiration.
646
+ // To mitigate this issue we always add 1 ms to the timeout.
647
+
648
+ const timeout = time + 1;
649
+ this.staleTimeoutId = setTimeout(() => {
650
+ if (!this.currentResult.isStale) {
651
+ this.updateResult();
652
+ }
653
+ }, timeout);
654
+ }
655
+
656
+ computeRefetchInterval() {
657
+ var _this$options$refetch;
658
+
659
+ return typeof this.options.refetchInterval === 'function' ? this.options.refetchInterval(this.currentResult.data, this.currentQuery) : (_this$options$refetch = this.options.refetchInterval) != null ? _this$options$refetch : false;
660
+ }
661
+
662
+ updateRefetchInterval(nextInterval) {
663
+ this.clearRefetchInterval();
664
+ this.currentRefetchInterval = nextInterval;
665
+
666
+ if (isServer || this.options.enabled === false || !isValidTimeout(this.currentRefetchInterval) || this.currentRefetchInterval === 0) {
667
+ return;
668
+ }
669
+
670
+ this.refetchIntervalId = setInterval(() => {
671
+ if (this.options.refetchIntervalInBackground || focusManager.isFocused()) {
672
+ this.executeFetch();
673
+ }
674
+ }, this.currentRefetchInterval);
675
+ }
676
+
677
+ updateTimers() {
678
+ this.updateStaleTimeout();
679
+ this.updateRefetchInterval(this.computeRefetchInterval());
680
+ }
681
+
682
+ clearStaleTimeout() {
683
+ if (this.staleTimeoutId) {
684
+ clearTimeout(this.staleTimeoutId);
685
+ this.staleTimeoutId = undefined;
686
+ }
687
+ }
688
+
689
+ clearRefetchInterval() {
690
+ if (this.refetchIntervalId) {
691
+ clearInterval(this.refetchIntervalId);
692
+ this.refetchIntervalId = undefined;
693
+ }
694
+ }
695
+
696
+ createResult(query, options) {
697
+ const prevQuery = this.currentQuery;
698
+ const prevOptions = this.options;
699
+ const prevResult = this.currentResult;
700
+ const prevResultState = this.currentResultState;
701
+ const prevResultOptions = this.currentResultOptions;
702
+ const queryChange = query !== prevQuery;
703
+ const queryInitialState = queryChange ? query.state : this.currentQueryInitialState;
704
+ const prevQueryResult = queryChange ? this.currentResult : this.previousQueryResult;
705
+ const {
706
+ state
707
+ } = query;
708
+ let {
709
+ dataUpdatedAt,
710
+ error,
711
+ errorUpdatedAt,
712
+ fetchStatus,
713
+ status
714
+ } = state;
715
+ let isPreviousData = false;
716
+ let isPlaceholderData = false;
717
+ let data; // Optimistically set result in fetching state if needed
718
+
719
+ if (options._optimisticResults) {
720
+ const mounted = this.hasListeners();
721
+ const fetchOnMount = !mounted && shouldFetchOnMount(query, options);
722
+ const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
723
+
724
+ if (fetchOnMount || fetchOptionally) {
725
+ fetchStatus = canFetch(query.options.networkMode) ? 'fetching' : 'paused';
726
+
727
+ if (!dataUpdatedAt) {
728
+ status = 'loading';
729
+ }
730
+ }
731
+
732
+ if (options._optimisticResults === 'isRestoring') {
733
+ fetchStatus = 'idle';
734
+ }
735
+ } // Keep previous data if needed
736
+
737
+
738
+ if (options.keepPreviousData && !state.dataUpdatedAt && prevQueryResult != null && prevQueryResult.isSuccess && status !== 'error') {
739
+ data = prevQueryResult.data;
740
+ dataUpdatedAt = prevQueryResult.dataUpdatedAt;
741
+ status = prevQueryResult.status;
742
+ isPreviousData = true;
743
+ } // Select data if needed
744
+ else if (options.select && typeof state.data !== 'undefined') {
745
+ // Memoize select result
746
+ if (prevResult && state.data === (prevResultState == null ? void 0 : prevResultState.data) && options.select === this.selectFn) {
747
+ data = this.selectResult;
748
+ } else {
749
+ try {
750
+ this.selectFn = options.select;
751
+ data = options.select(state.data);
752
+ data = replaceData(prevResult == null ? void 0 : prevResult.data, data, options);
753
+ this.selectResult = data;
754
+ this.selectError = null;
755
+ } catch (selectError) {
756
+ if (process.env.NODE_ENV !== 'production') {
757
+ this.client.getLogger().error(selectError);
758
+ }
759
+
760
+ this.selectError = selectError;
761
+ }
762
+ }
763
+ } // Use query data
764
+ else {
765
+ data = state.data;
766
+ } // Show placeholder data if needed
767
+
768
+
769
+ if (typeof options.placeholderData !== 'undefined' && typeof data === 'undefined' && status === 'loading') {
770
+ let placeholderData; // Memoize placeholder data
771
+
772
+ if (prevResult != null && prevResult.isPlaceholderData && options.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) {
773
+ placeholderData = prevResult.data;
774
+ } else {
775
+ placeholderData = typeof options.placeholderData === 'function' ? options.placeholderData() : options.placeholderData;
776
+
777
+ if (options.select && typeof placeholderData !== 'undefined') {
778
+ try {
779
+ placeholderData = options.select(placeholderData);
780
+ this.selectError = null;
781
+ } catch (selectError) {
782
+ if (process.env.NODE_ENV !== 'production') {
783
+ this.client.getLogger().error(selectError);
784
+ }
785
+
786
+ this.selectError = selectError;
787
+ }
788
+ }
789
+ }
790
+
791
+ if (typeof placeholderData !== 'undefined') {
792
+ status = 'success';
793
+ data = replaceData(prevResult == null ? void 0 : prevResult.data, placeholderData, options);
794
+ isPlaceholderData = true;
795
+ }
796
+ }
797
+
798
+ if (this.selectError) {
799
+ error = this.selectError;
800
+ data = this.selectResult;
801
+ errorUpdatedAt = Date.now();
802
+ status = 'error';
803
+ }
804
+
805
+ const isFetching = fetchStatus === 'fetching';
806
+ const isLoading = status === 'loading';
807
+ const isError = status === 'error';
808
+ const result = {
809
+ status,
810
+ fetchStatus,
811
+ isLoading,
812
+ isSuccess: status === 'success',
813
+ isError,
814
+ isInitialLoading: isLoading && isFetching,
815
+ data,
816
+ dataUpdatedAt,
817
+ error,
818
+ errorUpdatedAt,
819
+ failureCount: state.fetchFailureCount,
820
+ failureReason: state.fetchFailureReason,
821
+ errorUpdateCount: state.errorUpdateCount,
822
+ isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,
823
+ isFetchedAfterMount: state.dataUpdateCount > queryInitialState.dataUpdateCount || state.errorUpdateCount > queryInitialState.errorUpdateCount,
824
+ isFetching,
825
+ isRefetching: isFetching && !isLoading,
826
+ isLoadingError: isError && state.dataUpdatedAt === 0,
827
+ isPaused: fetchStatus === 'paused',
828
+ isPlaceholderData,
829
+ isPreviousData,
830
+ isRefetchError: isError && state.dataUpdatedAt !== 0,
831
+ isStale: isStale(query, options),
832
+ refetch: this.refetch,
833
+ remove: this.remove
834
+ };
835
+ return result;
836
+ }
837
+
838
+ updateResult(notifyOptions) {
839
+ const prevResult = this.currentResult;
840
+ const nextResult = this.createResult(this.currentQuery, this.options);
841
+ this.currentResultState = this.currentQuery.state;
842
+ this.currentResultOptions = this.options; // Only notify and update result if something has changed
843
+
844
+ if (shallowEqualObjects(nextResult, prevResult)) {
845
+ return;
846
+ }
847
+
848
+ this.currentResult = nextResult; // Determine which callbacks to trigger
849
+
850
+ const defaultNotifyOptions = {
851
+ cache: true
852
+ };
853
+
854
+ const shouldNotifyListeners = () => {
855
+ if (!prevResult) {
856
+ return true;
857
+ }
858
+
859
+ const {
860
+ notifyOnChangeProps
861
+ } = this.options;
862
+
863
+ if (notifyOnChangeProps === 'all' || !notifyOnChangeProps && !this.trackedProps.size) {
864
+ return true;
865
+ }
866
+
867
+ const includedProps = new Set(notifyOnChangeProps != null ? notifyOnChangeProps : this.trackedProps);
868
+
869
+ if (this.options.useErrorBoundary) {
870
+ includedProps.add('error');
871
+ }
872
+
873
+ return Object.keys(this.currentResult).some(key => {
874
+ const typedKey = key;
875
+ const changed = this.currentResult[typedKey] !== prevResult[typedKey];
876
+ return changed && includedProps.has(typedKey);
877
+ });
878
+ };
879
+
880
+ if ((notifyOptions == null ? void 0 : notifyOptions.listeners) !== false && shouldNotifyListeners()) {
881
+ defaultNotifyOptions.listeners = true;
882
+ }
883
+
884
+ this.notify({ ...defaultNotifyOptions,
885
+ ...notifyOptions
886
+ });
887
+ }
888
+
889
+ updateQuery() {
890
+ const query = this.client.getQueryCache().build(this.client, this.options);
891
+
892
+ if (query === this.currentQuery) {
893
+ return;
894
+ }
895
+
896
+ const prevQuery = this.currentQuery;
897
+ this.currentQuery = query;
898
+ this.currentQueryInitialState = query.state;
899
+ this.previousQueryResult = this.currentResult;
900
+
901
+ if (this.hasListeners()) {
902
+ prevQuery == null ? void 0 : prevQuery.removeObserver(this);
903
+ query.addObserver(this);
904
+ }
905
+ }
906
+
907
+ onQueryUpdate(action) {
908
+ const notifyOptions = {};
909
+
910
+ if (action.type === 'success') {
911
+ notifyOptions.onSuccess = !action.manual;
912
+ } else if (action.type === 'error' && !isCancelledError(action.error)) {
913
+ notifyOptions.onError = true;
914
+ }
915
+
916
+ this.updateResult(notifyOptions);
917
+
918
+ if (this.hasListeners()) {
919
+ this.updateTimers();
920
+ }
921
+ }
922
+
923
+ notify(notifyOptions) {
924
+ notifyManager.batch(() => {
925
+ // First trigger the configuration callbacks
926
+ if (notifyOptions.onSuccess) {
927
+ var _this$options$onSucce, _this$options, _this$options$onSettl, _this$options2;
928
+
929
+ (_this$options$onSucce = (_this$options = this.options).onSuccess) == null ? void 0 : _this$options$onSucce.call(_this$options, this.currentResult.data);
930
+ (_this$options$onSettl = (_this$options2 = this.options).onSettled) == null ? void 0 : _this$options$onSettl.call(_this$options2, this.currentResult.data, null);
931
+ } else if (notifyOptions.onError) {
932
+ var _this$options$onError, _this$options3, _this$options$onSettl2, _this$options4;
933
+
934
+ (_this$options$onError = (_this$options3 = this.options).onError) == null ? void 0 : _this$options$onError.call(_this$options3, this.currentResult.error);
935
+ (_this$options$onSettl2 = (_this$options4 = this.options).onSettled) == null ? void 0 : _this$options$onSettl2.call(_this$options4, undefined, this.currentResult.error);
936
+ } // Then trigger the listeners
937
+
938
+
939
+ if (notifyOptions.listeners) {
940
+ this.listeners.forEach(listener => {
941
+ listener(this.currentResult);
942
+ });
943
+ } // Then the cache listeners
944
+
945
+
946
+ if (notifyOptions.cache) {
947
+ this.client.getQueryCache().notify({
948
+ query: this.currentQuery,
949
+ type: 'observerResultsUpdated'
950
+ });
951
+ }
952
+ });
953
+ }
954
+
955
+ }
956
+
957
+ function shouldLoadOnMount(query, options) {
958
+ return options.enabled !== false && !query.state.dataUpdatedAt && !(query.state.status === 'error' && options.retryOnMount === false);
959
+ }
960
+
961
+ function shouldFetchOnMount(query, options) {
962
+ return shouldLoadOnMount(query, options) || query.state.dataUpdatedAt > 0 && shouldFetchOn(query, options, options.refetchOnMount);
963
+ }
964
+
965
+ function shouldFetchOn(query, options, field) {
966
+ if (options.enabled !== false) {
967
+ const value = typeof field === 'function' ? field(query) : field;
968
+ return value === 'always' || value !== false && isStale(query, options);
969
+ }
970
+
971
+ return false;
972
+ }
973
+
974
+ function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
975
+ return options.enabled !== false && (query !== prevQuery || prevOptions.enabled === false) && (!options.suspense || query.state.status !== 'error') && isStale(query, options);
976
+ }
977
+
978
+ function isStale(query, options) {
979
+ return query.isStaleByTime(options.staleTime);
980
+ }
981
+
982
+ // CLASS
983
+ class MutationObserver extends Subscribable {
984
+ constructor(client, options) {
985
+ super();
986
+ this.client = client;
987
+ this.setOptions(options);
988
+ this.bindMethods();
989
+ this.updateResult();
990
+ }
991
+
992
+ bindMethods() {
993
+ this.mutate = this.mutate.bind(this);
994
+ this.reset = this.reset.bind(this);
995
+ }
996
+
997
+ setOptions(options) {
998
+ const prevOptions = this.options;
999
+ this.options = this.client.defaultMutationOptions(options);
1000
+
1001
+ if (!shallowEqualObjects(prevOptions, this.options)) {
1002
+ this.client.getMutationCache().notify({
1003
+ type: 'observerOptionsUpdated',
1004
+ mutation: this.currentMutation,
1005
+ observer: this
1006
+ });
1007
+ }
1008
+ }
1009
+
1010
+ onUnsubscribe() {
1011
+ if (!this.listeners.length) {
1012
+ var _this$currentMutation;
1013
+
1014
+ (_this$currentMutation = this.currentMutation) == null ? void 0 : _this$currentMutation.removeObserver(this);
1015
+ }
1016
+ }
1017
+
1018
+ onMutationUpdate(action) {
1019
+ this.updateResult(); // Determine which callbacks to trigger
1020
+
1021
+ const notifyOptions = {
1022
+ listeners: true
1023
+ };
1024
+
1025
+ if (action.type === 'success') {
1026
+ notifyOptions.onSuccess = true;
1027
+ } else if (action.type === 'error') {
1028
+ notifyOptions.onError = true;
1029
+ }
1030
+
1031
+ this.notify(notifyOptions);
1032
+ }
1033
+
1034
+ getCurrentResult() {
1035
+ return this.currentResult;
1036
+ }
1037
+
1038
+ reset() {
1039
+ this.currentMutation = undefined;
1040
+ this.updateResult();
1041
+ this.notify({
1042
+ listeners: true
1043
+ });
1044
+ }
1045
+
1046
+ mutate(variables, options) {
1047
+ this.mutateOptions = options;
1048
+
1049
+ if (this.currentMutation) {
1050
+ this.currentMutation.removeObserver(this);
1051
+ }
1052
+
1053
+ this.currentMutation = this.client.getMutationCache().build(this.client, { ...this.options,
1054
+ variables: typeof variables !== 'undefined' ? variables : this.options.variables
1055
+ });
1056
+ this.currentMutation.addObserver(this);
1057
+ return this.currentMutation.execute();
1058
+ }
1059
+
1060
+ updateResult() {
1061
+ const state = this.currentMutation ? this.currentMutation.state : getDefaultState();
1062
+ const result = { ...state,
1063
+ isLoading: state.status === 'loading',
1064
+ isSuccess: state.status === 'success',
1065
+ isError: state.status === 'error',
1066
+ isIdle: state.status === 'idle',
1067
+ mutate: this.mutate,
1068
+ reset: this.reset
1069
+ };
1070
+ this.currentResult = result;
1071
+ }
1072
+
1073
+ notify(options) {
1074
+ notifyManager.batch(() => {
1075
+ // First trigger the mutate callbacks
1076
+ if (this.mutateOptions) {
1077
+ if (options.onSuccess) {
1078
+ var _this$mutateOptions$o, _this$mutateOptions, _this$mutateOptions$o2, _this$mutateOptions2;
1079
+
1080
+ (_this$mutateOptions$o = (_this$mutateOptions = this.mutateOptions).onSuccess) == null ? void 0 : _this$mutateOptions$o.call(_this$mutateOptions, this.currentResult.data, this.currentResult.variables, this.currentResult.context);
1081
+ (_this$mutateOptions$o2 = (_this$mutateOptions2 = this.mutateOptions).onSettled) == null ? void 0 : _this$mutateOptions$o2.call(_this$mutateOptions2, this.currentResult.data, null, this.currentResult.variables, this.currentResult.context);
1082
+ } else if (options.onError) {
1083
+ var _this$mutateOptions$o3, _this$mutateOptions3, _this$mutateOptions$o4, _this$mutateOptions4;
1084
+
1085
+ (_this$mutateOptions$o3 = (_this$mutateOptions3 = this.mutateOptions).onError) == null ? void 0 : _this$mutateOptions$o3.call(_this$mutateOptions3, this.currentResult.error, this.currentResult.variables, this.currentResult.context);
1086
+ (_this$mutateOptions$o4 = (_this$mutateOptions4 = this.mutateOptions).onSettled) == null ? void 0 : _this$mutateOptions$o4.call(_this$mutateOptions4, undefined, this.currentResult.error, this.currentResult.variables, this.currentResult.context);
1087
+ }
1088
+ } // Then trigger the listeners
1089
+
1090
+
1091
+ if (options.listeners) {
1092
+ this.listeners.forEach(listener => {
1093
+ listener(this.currentResult);
1094
+ });
1095
+ }
1096
+ });
1097
+ }
1098
+
1099
+ }
1100
+
1101
+ var shim = {exports: {}};
1102
+
1103
+ var useSyncExternalStoreShim_production_min = {};
1104
+
1105
+ /**
1106
+ * @license React
1107
+ * use-sync-external-store-shim.production.min.js
1108
+ *
1109
+ * Copyright (c) Facebook, Inc. and its affiliates.
1110
+ *
1111
+ * This source code is licensed under the MIT license found in the
1112
+ * LICENSE file in the root directory of this source tree.
1113
+ */
1114
+
1115
+ var hasRequiredUseSyncExternalStoreShim_production_min;
1116
+
1117
+ function requireUseSyncExternalStoreShim_production_min () {
1118
+ if (hasRequiredUseSyncExternalStoreShim_production_min) return useSyncExternalStoreShim_production_min;
1119
+ hasRequiredUseSyncExternalStoreShim_production_min = 1;
1120
+ var e=React__default;function h(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var k="function"===typeof Object.is?Object.is:h,l=e.useState,m=e.useEffect,n=e.useLayoutEffect,p=e.useDebugValue;function q(a,b){var d=b(),f=l({inst:{value:d,getSnapshot:b}}),c=f[0].inst,g=f[1];n(function(){c.value=d;c.getSnapshot=b;r(c)&&g({inst:c});},[a,d,b]);m(function(){r(c)&&g({inst:c});return a(function(){r(c)&&g({inst:c});})},[a]);p(d);return d}
1121
+ function r(a){var b=a.getSnapshot;a=a.value;try{var d=b();return !k(a,d)}catch(f){return !0}}function t(a,b){return b()}var u="undefined"===typeof window||"undefined"===typeof window.document||"undefined"===typeof window.document.createElement?t:q;useSyncExternalStoreShim_production_min.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:u;
1122
+ return useSyncExternalStoreShim_production_min;
1123
+ }
1124
+
1125
+ var useSyncExternalStoreShim_development = {};
1126
+
1127
+ /**
1128
+ * @license React
1129
+ * use-sync-external-store-shim.development.js
1130
+ *
1131
+ * Copyright (c) Facebook, Inc. and its affiliates.
1132
+ *
1133
+ * This source code is licensed under the MIT license found in the
1134
+ * LICENSE file in the root directory of this source tree.
1135
+ */
1136
+
1137
+ var hasRequiredUseSyncExternalStoreShim_development;
1138
+
1139
+ function requireUseSyncExternalStoreShim_development () {
1140
+ if (hasRequiredUseSyncExternalStoreShim_development) return useSyncExternalStoreShim_development;
1141
+ hasRequiredUseSyncExternalStoreShim_development = 1;
1142
+
1143
+ if (process.env.NODE_ENV !== "production") {
1144
+ (function() {
1145
+
1146
+ /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
1147
+ if (
1148
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
1149
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===
1150
+ 'function'
1151
+ ) {
1152
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
1153
+ }
1154
+ var React = React__default;
1155
+
1156
+ var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
1157
+
1158
+ function error(format) {
1159
+ {
1160
+ {
1161
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
1162
+ args[_key2 - 1] = arguments[_key2];
1163
+ }
1164
+
1165
+ printWarning('error', format, args);
1166
+ }
1167
+ }
1168
+ }
1169
+
1170
+ function printWarning(level, format, args) {
1171
+ // When changing this logic, you might want to also
1172
+ // update consoleWithStackDev.www.js as well.
1173
+ {
1174
+ var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
1175
+ var stack = ReactDebugCurrentFrame.getStackAddendum();
1176
+
1177
+ if (stack !== '') {
1178
+ format += '%s';
1179
+ args = args.concat([stack]);
1180
+ } // eslint-disable-next-line react-internal/safe-string-coercion
1181
+
1182
+
1183
+ var argsWithFormat = args.map(function (item) {
1184
+ return String(item);
1185
+ }); // Careful: RN currently depends on this prefix
1186
+
1187
+ argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
1188
+ // breaks IE9: https://github.com/facebook/react/issues/13610
1189
+ // eslint-disable-next-line react-internal/no-production-logging
1190
+
1191
+ Function.prototype.apply.call(console[level], console, argsWithFormat);
1192
+ }
1193
+ }
1194
+
1195
+ /**
1196
+ * inlined Object.is polyfill to avoid requiring consumers ship their own
1197
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
1198
+ */
1199
+ function is(x, y) {
1200
+ return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
1201
+ ;
1202
+ }
1203
+
1204
+ var objectIs = typeof Object.is === 'function' ? Object.is : is;
1205
+
1206
+ // dispatch for CommonJS interop named imports.
1207
+
1208
+ var useState = React.useState,
1209
+ useEffect = React.useEffect,
1210
+ useLayoutEffect = React.useLayoutEffect,
1211
+ useDebugValue = React.useDebugValue;
1212
+ var didWarnOld18Alpha = false;
1213
+ var didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works
1214
+ // because of a very particular set of implementation details and assumptions
1215
+ // -- change any one of them and it will break. The most important assumption
1216
+ // is that updates are always synchronous, because concurrent rendering is
1217
+ // only available in versions of React that also have a built-in
1218
+ // useSyncExternalStore API. And we only use this shim when the built-in API
1219
+ // does not exist.
1220
+ //
1221
+ // Do not assume that the clever hacks used by this hook also work in general.
1222
+ // The point of this shim is to replace the need for hacks by other libraries.
1223
+
1224
+ function useSyncExternalStore(subscribe, getSnapshot, // Note: The shim does not use getServerSnapshot, because pre-18 versions of
1225
+ // React do not expose a way to check if we're hydrating. So users of the shim
1226
+ // will need to track that themselves and return the correct value
1227
+ // from `getSnapshot`.
1228
+ getServerSnapshot) {
1229
+ {
1230
+ if (!didWarnOld18Alpha) {
1231
+ if (React.startTransition !== undefined) {
1232
+ didWarnOld18Alpha = true;
1233
+
1234
+ 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.');
1235
+ }
1236
+ }
1237
+ } // Read the current snapshot from the store on every render. Again, this
1238
+ // breaks the rules of React, and only works here because of specific
1239
+ // implementation details, most importantly that updates are
1240
+ // always synchronous.
1241
+
1242
+
1243
+ var value = getSnapshot();
1244
+
1245
+ {
1246
+ if (!didWarnUncachedGetSnapshot) {
1247
+ var cachedValue = getSnapshot();
1248
+
1249
+ if (!objectIs(value, cachedValue)) {
1250
+ error('The result of getSnapshot should be cached to avoid an infinite loop');
1251
+
1252
+ didWarnUncachedGetSnapshot = true;
1253
+ }
1254
+ }
1255
+ } // Because updates are synchronous, we don't queue them. Instead we force a
1256
+ // re-render whenever the subscribed state changes by updating an some
1257
+ // arbitrary useState hook. Then, during render, we call getSnapshot to read
1258
+ // the current value.
1259
+ //
1260
+ // Because we don't actually use the state returned by the useState hook, we
1261
+ // can save a bit of memory by storing other stuff in that slot.
1262
+ //
1263
+ // To implement the early bailout, we need to track some things on a mutable
1264
+ // object. Usually, we would put that in a useRef hook, but we can stash it in
1265
+ // our useState hook instead.
1266
+ //
1267
+ // To force a re-render, we call forceUpdate({inst}). That works because the
1268
+ // new object always fails an equality check.
1269
+
1270
+
1271
+ var _useState = useState({
1272
+ inst: {
1273
+ value: value,
1274
+ getSnapshot: getSnapshot
1275
+ }
1276
+ }),
1277
+ inst = _useState[0].inst,
1278
+ forceUpdate = _useState[1]; // Track the latest getSnapshot function with a ref. This needs to be updated
1279
+ // in the layout phase so we can access it during the tearing check that
1280
+ // happens on subscribe.
1281
+
1282
+
1283
+ useLayoutEffect(function () {
1284
+ inst.value = value;
1285
+ inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the
1286
+ // commit phase if there was an interleaved mutation. In concurrent mode
1287
+ // this can happen all the time, but even in synchronous mode, an earlier
1288
+ // effect may have mutated the store.
1289
+
1290
+ if (checkIfSnapshotChanged(inst)) {
1291
+ // Force a re-render.
1292
+ forceUpdate({
1293
+ inst: inst
1294
+ });
1295
+ }
1296
+ }, [subscribe, value, getSnapshot]);
1297
+ useEffect(function () {
1298
+ // Check for changes right before subscribing. Subsequent changes will be
1299
+ // detected in the subscription handler.
1300
+ if (checkIfSnapshotChanged(inst)) {
1301
+ // Force a re-render.
1302
+ forceUpdate({
1303
+ inst: inst
1304
+ });
1305
+ }
1306
+
1307
+ var handleStoreChange = function () {
1308
+ // TODO: Because there is no cross-renderer API for batching updates, it's
1309
+ // up to the consumer of this library to wrap their subscription event
1310
+ // with unstable_batchedUpdates. Should we try to detect when this isn't
1311
+ // the case and print a warning in development?
1312
+ // The store changed. Check if the snapshot changed since the last time we
1313
+ // read from the store.
1314
+ if (checkIfSnapshotChanged(inst)) {
1315
+ // Force a re-render.
1316
+ forceUpdate({
1317
+ inst: inst
1318
+ });
1319
+ }
1320
+ }; // Subscribe to the store and return a clean-up function.
1321
+
1322
+
1323
+ return subscribe(handleStoreChange);
1324
+ }, [subscribe]);
1325
+ useDebugValue(value);
1326
+ return value;
1327
+ }
1328
+
1329
+ function checkIfSnapshotChanged(inst) {
1330
+ var latestGetSnapshot = inst.getSnapshot;
1331
+ var prevValue = inst.value;
1332
+
1333
+ try {
1334
+ var nextValue = latestGetSnapshot();
1335
+ return !objectIs(prevValue, nextValue);
1336
+ } catch (error) {
1337
+ return true;
1338
+ }
1339
+ }
1340
+
1341
+ function useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {
1342
+ // Note: The shim does not use getServerSnapshot, because pre-18 versions of
1343
+ // React do not expose a way to check if we're hydrating. So users of the shim
1344
+ // will need to track that themselves and return the correct value
1345
+ // from `getSnapshot`.
1346
+ return getSnapshot();
1347
+ }
1348
+
1349
+ var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');
1350
+
1351
+ var isServerEnvironment = !canUseDOM;
1352
+
1353
+ var shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore;
1354
+ var useSyncExternalStore$2 = React.useSyncExternalStore !== undefined ? React.useSyncExternalStore : shim;
1355
+
1356
+ useSyncExternalStoreShim_development.useSyncExternalStore = useSyncExternalStore$2;
1357
+ /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
1358
+ if (
1359
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
1360
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===
1361
+ 'function'
1362
+ ) {
1363
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
1364
+ }
1365
+
1366
+ })();
1367
+ }
1368
+ return useSyncExternalStoreShim_development;
1369
+ }
1370
+
1371
+ (function (module) {
1372
+
1373
+ if (process.env.NODE_ENV === 'production') {
1374
+ module.exports = requireUseSyncExternalStoreShim_production_min();
1375
+ } else {
1376
+ module.exports = requireUseSyncExternalStoreShim_development();
1377
+ }
1378
+ } (shim));
1379
+
1380
+ // Temporary workaround due to an issue with react-native uSES - https://github.com/TanStack/query/pull/3601
1381
+ const useSyncExternalStore = shim.exports.useSyncExternalStore;
1382
+
1383
+ const defaultContext = /*#__PURE__*/React.createContext(undefined);
1384
+ const QueryClientSharingContext = /*#__PURE__*/React.createContext(false); // If we are given a context, we will use it.
1385
+ // Otherwise, if contextSharing is on, we share the first and at least one
1386
+ // instance of the context across the window
1387
+ // to ensure that if React Query is used across
1388
+ // different bundles or microfrontends they will
1389
+ // all use the same **instance** of context, regardless
1390
+ // of module scoping.
1391
+
1392
+ function getQueryClientContext(context, contextSharing) {
1393
+ if (context) {
1394
+ return context;
1395
+ }
1396
+
1397
+ if (contextSharing && typeof window !== 'undefined') {
1398
+ if (!window.ReactQueryClientContext) {
1399
+ window.ReactQueryClientContext = defaultContext;
1400
+ }
1401
+
1402
+ return window.ReactQueryClientContext;
1403
+ }
1404
+
1405
+ return defaultContext;
1406
+ }
1407
+
1408
+ const useQueryClient = ({
1409
+ context
1410
+ } = {}) => {
1411
+ const queryClient = React.useContext(getQueryClientContext(context, React.useContext(QueryClientSharingContext)));
1412
+
1413
+ if (!queryClient) {
1414
+ throw new Error('No QueryClient set, use QueryClientProvider to set one');
1415
+ }
1416
+
1417
+ return queryClient;
1418
+ };
1419
+
1420
+ const IsRestoringContext = /*#__PURE__*/React.createContext(false);
1421
+ const useIsRestoring = () => React.useContext(IsRestoringContext);
1422
+ IsRestoringContext.Provider;
1423
+
1424
+ function createValue() {
1425
+ let isReset = false;
1426
+ return {
1427
+ clearReset: () => {
1428
+ isReset = false;
1429
+ },
1430
+ reset: () => {
1431
+ isReset = true;
1432
+ },
1433
+ isReset: () => {
1434
+ return isReset;
1435
+ }
1436
+ };
1437
+ }
1438
+
1439
+ const QueryErrorResetBoundaryContext = /*#__PURE__*/React.createContext(createValue()); // HOOK
1440
+
1441
+ const useQueryErrorResetBoundary = () => React.useContext(QueryErrorResetBoundaryContext); // COMPONENT
1442
+
1443
+ function shouldThrowError$1(_useErrorBoundary, params) {
1444
+ // Allow useErrorBoundary function to override throwing behavior on a per-error basis
1445
+ if (typeof _useErrorBoundary === 'function') {
1446
+ return _useErrorBoundary(...params);
1447
+ }
1448
+
1449
+ return !!_useErrorBoundary;
1450
+ }
1451
+
1452
+ function useMutation(arg1, arg2, arg3) {
1453
+ const options = parseMutationArgs(arg1, arg2, arg3);
1454
+ const queryClient = useQueryClient({
1455
+ context: options.context
1456
+ });
1457
+ const [observer] = React.useState(() => new MutationObserver(queryClient, options));
1458
+ React.useEffect(() => {
1459
+ observer.setOptions(options);
1460
+ }, [observer, options]);
1461
+ const result = useSyncExternalStore(React.useCallback(onStoreChange => observer.subscribe(notifyManager.batchCalls(onStoreChange)), [observer]), () => observer.getCurrentResult(), () => observer.getCurrentResult());
1462
+ const mutate = React.useCallback((variables, mutateOptions) => {
1463
+ observer.mutate(variables, mutateOptions).catch(noop);
1464
+ }, [observer]);
1465
+
1466
+ if (result.error && shouldThrowError$1(observer.options.useErrorBoundary, [result.error])) {
1467
+ throw result.error;
1468
+ }
1469
+
1470
+ return { ...result,
1471
+ mutate,
1472
+ mutateAsync: result.mutate
1473
+ };
1474
+ } // eslint-disable-next-line @typescript-eslint/no-empty-function
1475
+
1476
+ function noop() {}
1477
+
1478
+ // This is basically just React Query's useBaseQuery with a few changes for Legend-State:
1479
+ const ensurePreventErrorBoundaryRetry = (options, errorResetBoundary) => {
1480
+ if (options.suspense || options.useErrorBoundary) {
1481
+ // Prevent retrying failed query if the error boundary has not been reset yet
1482
+ if (!errorResetBoundary.isReset()) {
1483
+ options.retryOnMount = false;
1484
+ }
1485
+ }
1486
+ };
1487
+ const useClearResetErrorBoundary = (errorResetBoundary) => {
1488
+ React.useEffect(() => {
1489
+ errorResetBoundary.clearReset();
1490
+ }, [errorResetBoundary]);
1491
+ };
1492
+ function shouldThrowError(_useErrorBoundary, params) {
1493
+ // Allow useErrorBoundary function to override throwing behavior on a per-error basis
1494
+ if (typeof _useErrorBoundary === 'function') {
1495
+ return _useErrorBoundary(...params);
1496
+ }
1497
+ return !!_useErrorBoundary;
1498
+ }
1499
+ const getHasError = ({ result, errorResetBoundary, useErrorBoundary, query, }) => {
1500
+ return (result.isError &&
1501
+ !errorResetBoundary.isReset() &&
1502
+ !result.isFetching &&
1503
+ shouldThrowError(useErrorBoundary, [result.error, query]));
1504
+ };
1505
+ function useObservableQuery(options, mutationOptions) {
1506
+ const Observer = QueryObserver;
1507
+ const queryClient = useQueryClient({ context: options.context });
1508
+ const isRestoring = useIsRestoring();
1509
+ const errorResetBoundary = useQueryErrorResetBoundary();
1510
+ const defaultedOptions = queryClient.defaultQueryOptions(options);
1511
+ // Make sure results are optimistically set in fetching state before subscribing or updating options
1512
+ defaultedOptions._optimisticResults = isRestoring ? 'isRestoring' : 'optimistic';
1513
+ // Include callbacks in batch renders
1514
+ if (defaultedOptions.onError) {
1515
+ defaultedOptions.onError = notifyManager.batchCalls(defaultedOptions.onError);
1516
+ }
1517
+ if (defaultedOptions.onSuccess) {
1518
+ defaultedOptions.onSuccess = notifyManager.batchCalls(defaultedOptions.onSuccess);
1519
+ }
1520
+ if (defaultedOptions.onSettled) {
1521
+ defaultedOptions.onSettled = notifyManager.batchCalls(defaultedOptions.onSettled);
1522
+ }
1523
+ if (defaultedOptions.suspense) {
1524
+ // Always set stale time when using suspense to prevent
1525
+ // fetching again when directly mounting after suspending
1526
+ if (typeof defaultedOptions.staleTime !== 'number') {
1527
+ defaultedOptions.staleTime = 1000;
1528
+ }
1529
+ }
1530
+ ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary);
1531
+ useClearResetErrorBoundary(errorResetBoundary);
1532
+ const [observer] = React.useState(() => new Observer(queryClient, defaultedOptions));
1533
+ const result = observer.getOptimisticResult(defaultedOptions);
1534
+ // useSyncExternalStore was here in useBaseQuery but is removed for Legend-State.
1535
+ React.useEffect(() => {
1536
+ // Do not notify on updates because of changes in the options because
1537
+ // these changes should already be reflected in the optimistic result.
1538
+ observer.setOptions(defaultedOptions, { listeners: false });
1539
+ }, [defaultedOptions, observer]);
1540
+ // Handle suspense
1541
+ if (defaultedOptions.suspense && result.isLoading && result.isFetching && !isRestoring) {
1542
+ throw observer
1543
+ .fetchOptimistic(defaultedOptions)
1544
+ .then(({ data }) => {
1545
+ var _a, _b;
1546
+ (_a = defaultedOptions.onSuccess) === null || _a === void 0 ? void 0 : _a.call(defaultedOptions, data);
1547
+ (_b = defaultedOptions.onSettled) === null || _b === void 0 ? void 0 : _b.call(defaultedOptions, data, null);
1548
+ })
1549
+ .catch((error) => {
1550
+ var _a, _b;
1551
+ errorResetBoundary.clearReset();
1552
+ (_a = defaultedOptions.onError) === null || _a === void 0 ? void 0 : _a.call(defaultedOptions, error);
1553
+ (_b = defaultedOptions.onSettled) === null || _b === void 0 ? void 0 : _b.call(defaultedOptions, undefined, error);
1554
+ });
1555
+ }
1556
+ // Handle error boundary
1557
+ if (getHasError({
1558
+ result,
1559
+ errorResetBoundary,
1560
+ useErrorBoundary: defaultedOptions.useErrorBoundary,
1561
+ query: observer.getCurrentQuery(),
1562
+ })) {
1563
+ throw result.error;
1564
+ }
1565
+ // Legend-State changes from here down
1566
+ let mutator;
1567
+ if (mutationOptions) {
1568
+ // eslint-disable-next-line react-hooks/rules-of-hooks
1569
+ mutator = useMutation(mutationOptions);
1570
+ }
1571
+ const { obs, unsubscribe } = React.useMemo(() => {
1572
+ const obs = observable(observer.getCurrentResult());
1573
+ let isSetting = false;
1574
+ // If there is a mutator watch for changes as long as they don't come from the the query observer
1575
+ if (mutator) {
1576
+ observe(() => {
1577
+ const data = obs.data.get();
1578
+ // Don't want to call mutate if there's no data or this coming from the query changing
1579
+ if (data && !isSetting) {
1580
+ mutator.mutate(data);
1581
+ }
1582
+ });
1583
+ }
1584
+ const unsubscribe = observer.subscribe((result) => {
1585
+ isSetting = true;
1586
+ try {
1587
+ // Update the observable with the latest value
1588
+ obs.set(result);
1589
+ }
1590
+ finally {
1591
+ // If set causes a crash for some reason we still need to reset isSetting
1592
+ isSetting = false;
1593
+ }
1594
+ });
1595
+ return { obs, unsubscribe };
1596
+ }, []);
1597
+ // Unsubscribe from the query observer on unmount
1598
+ useUnmount(unsubscribe);
1599
+ // Return the observable
1600
+ return obs;
1601
+ }
1602
+
1603
+ export { useObservableQuery };
1604
+ //# sourceMappingURL=useObservableQuery.mjs.map