reactjrx 1.62.0 → 1.67.3

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.
Files changed (57) hide show
  1. package/dist/index.cjs +1 -2101
  2. package/dist/index.d.ts +2 -1
  3. package/dist/index.js +1641 -1801
  4. package/dist/lib/queries/client/cache/registerResultInCache.d.ts +1 -1
  5. package/dist/lib/queries/client/createClient.d.ts +20 -7
  6. package/dist/lib/queries/client/fetch/notifyQueryResult.d.ts +1 -1
  7. package/dist/lib/queries/client/fetch/queryFetch.d.ts +2 -2
  8. package/dist/lib/queries/client/mutations/cache/MutationCache.d.ts +35 -0
  9. package/dist/lib/queries/client/mutations/cache/mutationCache.test.d.ts +1 -0
  10. package/dist/lib/queries/client/mutations/cache/types.d.ts +68 -0
  11. package/dist/lib/queries/client/mutations/defaultMutationState.d.ts +2 -2
  12. package/dist/lib/queries/client/mutations/filters.d.ts +1 -1
  13. package/dist/lib/queries/client/mutations/mutation/Mutation.d.ts +36 -0
  14. package/dist/lib/queries/client/mutations/mutation/executeMutation.d.ts +6 -0
  15. package/dist/lib/queries/client/mutations/mutation/mutation.options.test.d.ts +1 -0
  16. package/dist/lib/queries/client/mutations/mutation/types.d.ts +51 -0
  17. package/dist/lib/queries/client/mutations/mutations.test.d.ts +1 -0
  18. package/dist/lib/queries/client/mutations/observers/MutationObserver.d.ts +42 -0
  19. package/dist/lib/queries/client/mutations/observers/mutationObserver.rq.test.d.ts +1 -0
  20. package/dist/lib/queries/client/mutations/observers/mutationObserver.test.d.ts +1 -0
  21. package/dist/lib/queries/client/mutations/observers/types.d.ts +65 -0
  22. package/dist/lib/queries/client/mutations/runner/MutationRunner.d.ts +17 -0
  23. package/dist/lib/queries/client/mutations/runner/mutationRunner.test.d.ts +1 -0
  24. package/dist/lib/queries/client/mutations/types.d.ts +7 -101
  25. package/dist/lib/queries/client/operators.d.ts +6 -2
  26. package/dist/lib/queries/client/refetch/client.d.ts +1 -1
  27. package/dist/lib/queries/client/store/createQueryStore.d.ts +1 -1
  28. package/dist/lib/queries/client/store/updateStoreWithNewQuery.d.ts +1 -1
  29. package/dist/lib/queries/client/tests/utils.d.ts +4 -0
  30. package/dist/lib/queries/client/triggers.d.ts +1 -1
  31. package/dist/lib/queries/client/types.d.ts +2 -1
  32. package/dist/lib/queries/client/utils/functionAsObservable.d.ts +2 -0
  33. package/dist/lib/queries/client/utils/wrapInPromise.d.ts +3 -0
  34. package/dist/lib/queries/react/Provider.d.ts +3 -71
  35. package/dist/lib/queries/react/mutations/types.d.ts +18 -0
  36. package/dist/lib/queries/react/mutations/useIsMutating.d.ts +1 -1
  37. package/dist/lib/queries/react/mutations/useMutation.d.ts +3 -19
  38. package/dist/lib/queries/react/mutations/useMutation.rq.test.d.ts +1 -0
  39. package/dist/lib/queries/react/mutations/useMutationState.d.ts +5 -3
  40. package/dist/lib/queries/react/{helpers.d.ts → queries/helpers.d.ts} +6 -5
  41. package/dist/lib/queries/react/{types.d.ts → queries/types.d.ts} +1 -1
  42. package/dist/lib/queries/react/queries/useQuery.d.ts +1 -1
  43. package/dist/lib/queries/react/triggers/activityTrigger.d.ts +1 -1
  44. package/dist/lib/queries/react/triggers/networkTrigger.d.ts +1 -1
  45. package/dist/lib/utils/{retryBackoff.d.ts → operators/retryBackoff.d.ts} +5 -3
  46. package/dist/lib/utils/operators/trackSubscriptions.d.ts +2 -0
  47. package/dist/tests/utils.d.ts +4 -1
  48. package/package.json +3 -1
  49. package/dist/lib/queries/client/mutations/Mutation.d.ts +0 -15
  50. package/dist/lib/queries/client/mutations/MutationClient.d.ts +0 -91
  51. package/dist/lib/queries/client/mutations/MutationResultObserver.d.ts +0 -32
  52. package/dist/lib/queries/client/mutations/createMutationRunner.d.ts +0 -15
  53. package/dist/lib/queries/client/mutations/operators.d.ts +0 -3
  54. package/dist/lib/utils/trackSubscriptions.d.ts +0 -2
  55. /package/dist/lib/queries/{react → client}/keys/nanoid.d.ts +0 -0
  56. /package/dist/lib/utils/{emitToSubject.d.ts → operators/emitToSubject.d.ts} +0 -0
  57. /package/dist/lib/utils/{shareLatest.d.ts → operators/shareLatest.d.ts} +0 -0
package/dist/index.cjs CHANGED
@@ -1,2101 +1 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4
- var __publicField = (obj, key, value) => {
5
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
6
- return value;
7
- };
8
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
9
- const react = require("react");
10
- const rxjs = require("rxjs");
11
- const operators = require("rxjs/operators");
12
- const jsxRuntime = require("react/jsx-runtime");
13
- const useLiveRef = (value) => {
14
- const ref = react.useRef(value);
15
- react.useMemo(() => {
16
- ref.current = value;
17
- }, [value]);
18
- return ref;
19
- };
20
- function primitiveEqual(objA, objB) {
21
- if (typeof objA === "string" && objA === objB)
22
- return true;
23
- if (typeof objA === "number" && objA === objB)
24
- return true;
25
- if (typeof objA === "boolean" && objA === objB)
26
- return true;
27
- if (typeof objA === "symbol" && objA === objB)
28
- return true;
29
- if (typeof objA === "bigint" && objA === objB)
30
- return true;
31
- if (typeof objA === "undefined" && objA === objB)
32
- return true;
33
- if (objA === null && objA === objB)
34
- return true;
35
- return false;
36
- }
37
- function useObserve(source$, unsafeOptions, unsafeDeps) {
38
- const options = unsafeOptions != null && !Array.isArray(unsafeOptions) ? unsafeOptions : {
39
- defaultValue: void 0,
40
- key: "",
41
- unsubscribeOnUnmount: true
42
- };
43
- const deps = unsafeDeps == null && Array.isArray(unsafeOptions) ? unsafeOptions : typeof source$ === "function" ? unsafeDeps ?? [] : [source$];
44
- const valueRef = react.useRef(
45
- "getValue" in source$ && typeof source$.getValue === "function" ? source$.getValue() : options.defaultValue
46
- );
47
- const sourceRef = useLiveRef(source$);
48
- const optionsRef = useLiveRef(options);
49
- const subscribe = react.useCallback(
50
- (next) => {
51
- const source = sourceRef.current;
52
- const makeObservable = typeof source === "function" ? source : () => source;
53
- const sub = makeObservable().pipe(
54
- /**
55
- * @important
56
- * We only check primitives because underlying subscription might
57
- * be using objects and keeping same reference but pushing new
58
- * properties values
59
- */
60
- rxjs.distinctUntilChanged(primitiveEqual),
61
- rxjs.tap((value) => {
62
- valueRef.current = value;
63
- }),
64
- rxjs.finalize(next),
65
- rxjs.catchError((error) => {
66
- console.error(error);
67
- valueRef.current = void 0;
68
- return rxjs.EMPTY;
69
- })
70
- ).subscribe(next);
71
- return () => {
72
- if (optionsRef.current.unsubscribeOnUnmount === false)
73
- return;
74
- sub.unsubscribe();
75
- };
76
- },
77
- [...deps]
78
- );
79
- const getSnapshot = react.useCallback(() => {
80
- return valueRef.current;
81
- }, []);
82
- const result = react.useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
83
- return result;
84
- }
85
- function useSubscribe(source, deps = []) {
86
- const sourceRef = useLiveRef(source);
87
- const sourceAsObservable = typeof source === "function" ? void 0 : source;
88
- react.useEffect(() => {
89
- const source2 = sourceRef.current;
90
- const makeObservable = typeof source2 === "function" ? source2 : () => source2;
91
- const sub = makeObservable().pipe(
92
- rxjs.catchError((error) => {
93
- console.error(
94
- "Uncaught error at useSubscribe. Please consider adding a catchError or other handling."
95
- );
96
- console.error(error);
97
- return rxjs.EMPTY;
98
- })
99
- ).subscribe();
100
- return () => {
101
- sub.unsubscribe();
102
- };
103
- }, [...deps, sourceAsObservable]);
104
- }
105
- const useConstant = (fn) => {
106
- const ref = react.useRef();
107
- if (!ref.current) {
108
- ref.current = fn();
109
- }
110
- react.useEffect(() => {
111
- if (process.env.NODE_ENV === "development")
112
- ;
113
- }, []);
114
- return ref;
115
- };
116
- const useSubject = ({
117
- onBeforeComplete,
118
- completeOnUnmount = true
119
- } = {}) => {
120
- const subject = useConstant(() => new rxjs.Subject());
121
- const completed = react.useRef(false);
122
- const onBeforeCompleteRef = useLiveRef(onBeforeComplete);
123
- const completeOnUnmountRef = useLiveRef(completeOnUnmount);
124
- react.useEffect(() => {
125
- if (completed.current) {
126
- subject.current = new rxjs.Subject();
127
- completed.current = false;
128
- }
129
- return () => {
130
- if (!completeOnUnmountRef.current) {
131
- completed.current = true;
132
- return;
133
- }
134
- if (!completed.current) {
135
- if (onBeforeCompleteRef.current != null)
136
- onBeforeCompleteRef.current();
137
- subject.current.complete();
138
- completed.current = true;
139
- }
140
- };
141
- }, []);
142
- return subject;
143
- };
144
- const useObserveCallback = (callback, deps) => {
145
- const trigger$ = useSubject();
146
- useSubscribe(() => callback(trigger$.current), [trigger$, ...deps]);
147
- const trigger2 = react.useCallback((arg) => {
148
- trigger$.current.next(arg);
149
- }, []);
150
- return [trigger2, trigger$];
151
- };
152
- function trigger(mapper = rxjs.identity) {
153
- const subject = new rxjs.Subject();
154
- return [
155
- subject.asObservable(),
156
- (...args) => {
157
- subject.next(mapper(...args));
158
- }
159
- ];
160
- }
161
- const useBehaviorSubject = (state) => {
162
- const subject = useConstant(() => new rxjs.BehaviorSubject(state));
163
- const completed = react.useRef(false);
164
- react.useEffect(() => {
165
- if (completed.current) {
166
- subject.current = new rxjs.BehaviorSubject(state);
167
- completed.current = false;
168
- }
169
- return () => {
170
- if (!completed.current) {
171
- subject.current.complete();
172
- completed.current = true;
173
- }
174
- };
175
- }, []);
176
- return subject;
177
- };
178
- const SIGNAL_RESET = Symbol("SIGNAL_RESET");
179
- function signal(config) {
180
- const { default: defaultValue2 } = config ?? {};
181
- const subject = new rxjs.BehaviorSubject(defaultValue2);
182
- const setValue = (arg) => {
183
- if (typeof arg === "function") {
184
- const change = arg(subject.getValue());
185
- if (change === subject.getValue())
186
- return;
187
- subject.next(change);
188
- return;
189
- }
190
- if (arg === SIGNAL_RESET) {
191
- subject.next(defaultValue2 ?? void 0);
192
- return;
193
- }
194
- subject.next(arg);
195
- };
196
- const getValue = () => subject.getValue();
197
- return {
198
- setValue,
199
- getValue,
200
- config,
201
- subject
202
- };
203
- }
204
- function useSignalValue(signal2, selector) {
205
- const selectorOrDefault = selector ?? ((v) => v);
206
- return useObserve(
207
- () => signal2.subject.pipe(
208
- rxjs.map((value) => selectorOrDefault(value)),
209
- rxjs.distinctUntilChanged()
210
- ),
211
- {
212
- defaultValue: selectorOrDefault(signal2.getValue())
213
- },
214
- []
215
- );
216
- }
217
- const normalizeStore = (store) => {
218
- if (!store || typeof store !== "object") {
219
- return void 0;
220
- }
221
- return store;
222
- };
223
- const createSharedStoreAdapter = ({
224
- adapter,
225
- key
226
- }) => ({
227
- getItem: async (itemKey) => {
228
- const unsafeStore = await adapter.getItem(key);
229
- const store = normalizeStore(unsafeStore) ?? {};
230
- if (itemKey in store) {
231
- return store[itemKey];
232
- }
233
- return void 0;
234
- },
235
- setItem: async (itemKey, value) => {
236
- const unsafeStore = await adapter.getItem(key);
237
- const store = normalizeStore(unsafeStore) ?? {};
238
- await adapter.setItem(key, { ...store, [itemKey]: value });
239
- }
240
- });
241
- const createLocalforageAdapter = (forage) => ({
242
- getItem: async (key) => {
243
- const serializedValue = await forage.getItem(key);
244
- if (!serializedValue)
245
- return void 0;
246
- return JSON.parse(serializedValue);
247
- },
248
- setItem: async (key, value) => {
249
- await forage.setItem(key, JSON.stringify(value));
250
- }
251
- });
252
- const createLocalStorageAdapter = (forage) => ({
253
- getItem: async (key) => {
254
- const serializedValue = forage.getItem(key);
255
- if (!serializedValue)
256
- return void 0;
257
- return JSON.parse(serializedValue);
258
- },
259
- setItem: async (key, value) => {
260
- forage.setItem(key, JSON.stringify(value));
261
- }
262
- });
263
- const IDENTIFIER_PERSISTANCE_KEY = "__reactjrx";
264
- const getNormalizedPersistanceValue = (unknownValue) => {
265
- if (typeof unknownValue === "object" && unknownValue !== null && IDENTIFIER_PERSISTANCE_KEY in unknownValue && unknownValue[IDENTIFIER_PERSISTANCE_KEY] === IDENTIFIER_PERSISTANCE_KEY) {
266
- return unknownValue;
267
- }
268
- return void 0;
269
- };
270
- const persistValue = async ({
271
- adapter,
272
- signal: signal2,
273
- version
274
- }) => {
275
- const state = signal2.getValue();
276
- const value = {
277
- value: state,
278
- [IDENTIFIER_PERSISTANCE_KEY]: IDENTIFIER_PERSISTANCE_KEY,
279
- migrationVersion: version
280
- };
281
- await adapter.setItem(signal2.config.key, value);
282
- };
283
- const hydrateValueToSignal = ({
284
- adapter,
285
- version,
286
- signal: signal2
287
- }) => {
288
- return rxjs.from(adapter.getItem(signal2.config.key)).pipe(
289
- rxjs.switchMap((value) => {
290
- const normalizedValue = getNormalizedPersistanceValue(value);
291
- if (!normalizedValue)
292
- return rxjs.of(value);
293
- if (normalizedValue.migrationVersion !== void 0 && version > normalizedValue.migrationVersion) {
294
- return rxjs.of(value);
295
- }
296
- signal2.setValue(value.value);
297
- return rxjs.of(value);
298
- })
299
- );
300
- };
301
- const usePersistSignals = ({
302
- entries = [],
303
- onReady,
304
- adapter = createLocalStorageAdapter(localStorage)
305
- }) => {
306
- const entriesRef = useLiveRef(entries);
307
- const onReadyRef = useLiveRef(onReady);
308
- const adapterRef = useLiveRef(adapter);
309
- const isHydrated = useObserve(
310
- () => {
311
- const entries2 = entriesRef.current;
312
- const stream = entries2.length === 0 ? rxjs.of(true) : rxjs.zip(
313
- ...entries2.map(
314
- ({ signal: signal2, version }) => hydrateValueToSignal({
315
- adapter: adapterRef.current,
316
- signal: signal2,
317
- version
318
- })
319
- )
320
- ).pipe(rxjs.map(() => true));
321
- return stream.pipe(
322
- rxjs.tap(() => {
323
- if (onReadyRef.current != null)
324
- onReadyRef.current();
325
- }),
326
- rxjs.catchError((error) => {
327
- console.error("Unable to hydrate", error);
328
- return rxjs.EMPTY;
329
- })
330
- );
331
- },
332
- { defaultValue: false },
333
- []
334
- );
335
- useSubscribe(() => {
336
- return !isHydrated ? rxjs.EMPTY : rxjs.merge(
337
- ...entriesRef.current.map(
338
- ({ signal: signal2, version }) => signal2.subject.pipe(
339
- rxjs.throttleTime(500, rxjs.asyncScheduler, {
340
- trailing: true
341
- }),
342
- rxjs.switchMap(
343
- () => rxjs.from(
344
- persistValue({ adapter: adapterRef.current, signal: signal2, version })
345
- )
346
- )
347
- )
348
- )
349
- );
350
- }, [isHydrated, adapterRef]);
351
- return { isHydrated };
352
- };
353
- const useUnmountObservable = () => {
354
- const subject = useSubject({
355
- onBeforeComplete: () => {
356
- subject.current.next();
357
- }
358
- });
359
- return subject;
360
- };
361
- function getDelay(backoffDelay, maxInterval) {
362
- return Math.min(backoffDelay, maxInterval);
363
- }
364
- function exponentialBackoffDelay(iteration, initialInterval) {
365
- return Math.pow(2, iteration) * initialInterval;
366
- }
367
- function retryBackoff(config) {
368
- const {
369
- initialInterval,
370
- maxRetries = Infinity,
371
- maxInterval = Infinity,
372
- shouldRetry = () => true,
373
- resetOnSuccess = false,
374
- backoffDelay = exponentialBackoffDelay
375
- } = typeof config === "number" ? { initialInterval: config } : config;
376
- return (source) => rxjs.defer(() => {
377
- let index = 0;
378
- return source.pipe(
379
- operators.retryWhen((errors) => {
380
- return errors.pipe(
381
- operators.concatMap((error) => {
382
- const attempt = index++;
383
- return rxjs.iif(
384
- () => attempt < maxRetries && shouldRetry(attempt, error),
385
- rxjs.timer(
386
- getDelay(backoffDelay(attempt, initialInterval), maxInterval)
387
- ),
388
- rxjs.throwError(error)
389
- );
390
- })
391
- );
392
- }),
393
- operators.tap(() => {
394
- if (resetOnSuccess) {
395
- index = 0;
396
- }
397
- })
398
- );
399
- });
400
- }
401
- const Context = react.createContext({
402
- client: null
403
- });
404
- const ClientEffect = ({
405
- client
406
- }) => {
407
- react.useEffect(() => {
408
- const destroy = client.start();
409
- return () => {
410
- destroy();
411
- };
412
- }, [client]);
413
- return null;
414
- };
415
- const QueryClientProvider = react.memo(
416
- ({ children, client }) => {
417
- const value = react.useMemo(() => ({ client: client.client }), [client]);
418
- return /* @__PURE__ */ jsxRuntime.jsxs(Context.Provider, { value, children: [
419
- /* @__PURE__ */ jsxRuntime.jsx(ClientEffect, { client: value.client }),
420
- children
421
- ] });
422
- }
423
- );
424
- const useQueryClient = ({ unsafe = false } = {}) => {
425
- const context = react.useContext(Context);
426
- if (!unsafe && context.client === null) {
427
- throw new Error("You forgot to register the provider");
428
- }
429
- return context.client;
430
- };
431
- const serializeObject = (object) => {
432
- if (Array.isArray(object)) {
433
- return object.reduce((acc, value, index) => {
434
- if (index === object.length - 1)
435
- return `${acc}${serializeObject(value)}]`;
436
- return `${acc}${serializeObject(value)},`;
437
- }, "[");
438
- }
439
- if (object === void 0)
440
- return "";
441
- return JSON.stringify(object, Object.keys(object).sort());
442
- };
443
- const serializeKey = (key) => {
444
- if (key.length === 0)
445
- return "[]";
446
- return serializeObject(key);
447
- };
448
- const nanoid = (size = 21) => crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
449
- byte &= 63;
450
- if (byte < 36) {
451
- id += byte.toString(36);
452
- } else if (byte < 62) {
453
- id += (byte - 26).toString(36).toUpperCase();
454
- } else if (byte > 62) {
455
- id += "-";
456
- } else {
457
- id += "_";
458
- }
459
- return id;
460
- }, "");
461
- function useMutation(options, queryClient) {
462
- const defaultQueryClient = useQueryClient({ unsafe: !!queryClient });
463
- const finalQueryClient = (queryClient == null ? void 0 : queryClient.client) ?? defaultQueryClient;
464
- const optionsRef = useLiveRef(options);
465
- const defaultKey = useConstant(() => [nanoid()]);
466
- const key = serializeKey(options.mutationKey ?? defaultKey.current);
467
- const observedMutation = react.useMemo(
468
- () => finalQueryClient.mutationClient.mutationResultObserver.observe({
469
- key
470
- }),
471
- [key]
472
- );
473
- const result = useObserve(observedMutation.result$) ?? observedMutation.lastValue;
474
- const mutate = react.useCallback(
475
- (mutationArgs) => {
476
- finalQueryClient.mutationClient.mutate({
477
- options: {
478
- ...optionsRef.current,
479
- mutationKey: optionsRef.current.mutationKey ?? defaultKey.current
480
- },
481
- args: mutationArgs
482
- });
483
- },
484
- [finalQueryClient, key]
485
- );
486
- const cancel = react.useCallback(() => {
487
- finalQueryClient.mutationClient.cancel({
488
- key: optionsRef.current.mutationKey ?? defaultKey.current
489
- });
490
- }, [finalQueryClient]);
491
- react.useEffect(() => {
492
- return () => {
493
- if (optionsRef.current.cancelOnUnMount) {
494
- finalQueryClient.mutationClient.cancel({
495
- key: optionsRef.current.mutationKey ?? defaultKey.current
496
- });
497
- }
498
- };
499
- }, []);
500
- return { mutate, cancel, ...result };
501
- }
502
- const arrayEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
503
- function shallowEqual(objA, objB) {
504
- if (objA === null || objA === void 0 || objB === void 0) {
505
- return objA === objB;
506
- }
507
- if (typeof objA !== "object" || typeof objB !== "object") {
508
- return objA === objB;
509
- }
510
- if (objA.constructor !== (objB == null ? void 0 : objB.constructor)) {
511
- return false;
512
- }
513
- const keysA = Object.keys(objA);
514
- const keysB = Object.keys(objB);
515
- if (keysA.length !== keysB.length) {
516
- return false;
517
- }
518
- for (const key of keysA) {
519
- if (!objB.hasOwnProperty(key) || objA[key] !== objB[key]) {
520
- return false;
521
- }
522
- }
523
- return true;
524
- }
525
- function isDefined(arg) {
526
- return arg !== null && arg !== void 0;
527
- }
528
- const createActivityTrigger = (params$) => {
529
- return params$.pipe(
530
- rxjs.switchMap(({ options: { refetchOnWindowFocus = true } }) => {
531
- const shouldRunTrigger = typeof refetchOnWindowFocus === "function" ? refetchOnWindowFocus({}) : refetchOnWindowFocus;
532
- return shouldRunTrigger !== false ? rxjs.merge(
533
- rxjs.fromEvent(document, "visibilitychange").pipe(
534
- rxjs.filter(() => !document.hidden),
535
- rxjs.map(() => ({
536
- type: "refetch",
537
- ignoreStale: shouldRunTrigger === "always"
538
- }))
539
- ),
540
- rxjs.fromEvent(window, "focus").pipe(
541
- rxjs.map(() => ({
542
- type: "refetch",
543
- ignoreStale: shouldRunTrigger === "always"
544
- }))
545
- )
546
- ) : rxjs.EMPTY;
547
- })
548
- );
549
- };
550
- const createNetworkTrigger = (params$) => {
551
- return params$.pipe(
552
- rxjs.switchMap(({ options: { refetchOnReconnect = true } }) => {
553
- const shouldRunTrigger = typeof refetchOnReconnect === "function" ? refetchOnReconnect({}) : refetchOnReconnect;
554
- return shouldRunTrigger !== false ? rxjs.fromEvent(window, "online").pipe(
555
- rxjs.map(() => ({
556
- type: "refetch",
557
- ignoreStale: shouldRunTrigger === "always"
558
- }))
559
- ) : rxjs.EMPTY;
560
- })
561
- );
562
- };
563
- const useQueryParams = ({
564
- queryKey,
565
- queryFn,
566
- ...options
567
- }) => {
568
- const params$ = useBehaviorSubject({ queryKey, options, queryFn });
569
- react.useEffect(() => {
570
- params$.current.next({
571
- queryKey,
572
- options,
573
- queryFn
574
- });
575
- }, [queryKey, options, queryFn]);
576
- return params$;
577
- };
578
- const defaultValue = {
579
- data: void 0,
580
- isLoading: true,
581
- error: void 0,
582
- status: "loading",
583
- fetchStatus: "idle"
584
- };
585
- function useQuery({
586
- queryKey,
587
- queryFn,
588
- ...options
589
- }) {
590
- const internalRefresh$ = useSubject();
591
- const client = useQueryClient();
592
- const params$ = useQueryParams({ queryFn, queryKey, ...options });
593
- const result = useObserve(
594
- () => {
595
- const key$ = params$.current.pipe(rxjs.map(({ queryKey: queryKey2 }) => queryKey2 ?? []));
596
- const initialTrigger$ = rxjs.of(null);
597
- const newKeyTrigger$ = key$.pipe(
598
- rxjs.distinctUntilChanged(arrayEqual),
599
- rxjs.skip(1)
600
- );
601
- const isQueryObject = (query) => !!query && typeof query !== "function";
602
- const newObservableObjectQuery$ = params$.current.pipe(
603
- rxjs.map(({ queryFn: queryFn2 }) => queryFn2),
604
- rxjs.filter(isQueryObject),
605
- rxjs.distinctUntilChanged(shallowEqual),
606
- isQueryObject(params$.current.getValue().queryFn) ? rxjs.skip(1) : rxjs.identity
607
- );
608
- const fn$ = params$.current.pipe(
609
- rxjs.map(({ queryFn: queryFn2 }) => queryFn2),
610
- rxjs.filter(isDefined)
611
- );
612
- const options$ = params$.current.pipe(rxjs.map(({ options: options2 }) => options2));
613
- const activityRefetch$ = createActivityTrigger(params$.current);
614
- const networkRefetch$ = createNetworkTrigger(params$.current);
615
- const newQueryTrigger$ = rxjs.merge(
616
- initialTrigger$,
617
- newKeyTrigger$,
618
- newObservableObjectQuery$
619
- );
620
- const trigger$ = rxjs.merge(
621
- internalRefresh$.current,
622
- rxjs.merge(activityRefetch$, networkRefetch$).pipe(rxjs.throttleTime(500))
623
- );
624
- return newQueryTrigger$.pipe(
625
- rxjs.withLatestFrom(key$),
626
- rxjs.switchMap(([, key]) => {
627
- const { result$ } = client.query({
628
- key,
629
- fn$,
630
- options$,
631
- trigger$
632
- });
633
- return result$.pipe(
634
- rxjs.scan(
635
- (previousValue, { data: currentData, ...currentValue }) => ({
636
- data: void 0,
637
- ...previousValue,
638
- ...currentValue,
639
- isLoading: currentValue.status === "loading",
640
- ...currentData && {
641
- data: currentData.result
642
- }
643
- }),
644
- {}
645
- )
646
- );
647
- })
648
- /**
649
- * @important
650
- * We skip the first result as it is comparable to default passed value.
651
- * This is assuming all query are async and does not return a result right away.
652
- * This is a design choice.
653
- */
654
- // params$.current.getValue().options.enabled !== false
655
- // ? skip(1)
656
- // : identity
657
- );
658
- },
659
- {
660
- defaultValue: {
661
- ...defaultValue,
662
- isLoading: params$.current.getValue().options.enabled !== false
663
- }
664
- },
665
- [client]
666
- );
667
- const refetch = react.useCallback(() => {
668
- internalRefresh$.current.next({ type: "refetch", ignoreStale: true });
669
- }, [client]);
670
- return { ...result, refetch };
671
- }
672
- function useSubscribeEffect(source, unsafeOptions, deps = []) {
673
- const options = unsafeOptions != null && !Array.isArray(unsafeOptions) ? unsafeOptions : {};
674
- const retryOption = options.retry ?? true;
675
- const isSourceFn = typeof source === "function";
676
- const makeObservable = react.useCallback(
677
- isSourceFn ? source : () => source,
678
- isSourceFn ? deps : [source]
679
- );
680
- const enhancerMakeObservable = react.useCallback(
681
- () => makeObservable().pipe(
682
- rxjs.catchError((error) => {
683
- console.error(error);
684
- throw error;
685
- }),
686
- retryOption ? rxjs.retry() : rxjs.identity
687
- ),
688
- [makeObservable]
689
- );
690
- useSubscribe(enhancerMakeObservable, deps);
691
- }
692
- const retryOnError = (options) => retryBackoff({
693
- initialInterval: 100,
694
- ...typeof options.retry === "function" ? {
695
- shouldRetry: options.retry
696
- } : {
697
- maxRetries: options.retry === false ? 0 : options.retry ?? 3
698
- }
699
- });
700
- const mergeResults$1 = (stream$) => stream$.pipe(
701
- rxjs.scan(
702
- (acc, current) => {
703
- return {
704
- ...acc,
705
- ...current
706
- };
707
- },
708
- {
709
- data: void 0,
710
- error: void 0,
711
- fetchStatus: "idle",
712
- status: "loading"
713
- }
714
- ),
715
- rxjs.distinctUntilChanged(
716
- ({ data: prevData, ...prev }, { data: currData, ...curr }) => shallowEqual(prev, curr) && shallowEqual(prevData, currData)
717
- )
718
- );
719
- const resetStyle = { backgroundColor: "transparent", color: "inherit" };
720
- function createLogger(env) {
721
- const _logger = {
722
- namespaces: [
723
- {
724
- name: "@reactjrx",
725
- style: { backgroundColor: "#d02f4e", color: "white" }
726
- }
727
- ],
728
- namespace(name, style) {
729
- const logger2 = createLogger(env);
730
- logger2.namespaces.push({
731
- name,
732
- style: style ?? resetStyle
733
- });
734
- return logger2;
735
- },
736
- printNamespaces() {
737
- return {
738
- namespaces: _logger.namespaces.map(({ name }) => `%c ${name} %c`).join(" "),
739
- styles: _logger.namespaces.reduce((acc, { style }) => {
740
- acc.push(
741
- `background-color: ${style.backgroundColor}; color: ${style.color};`
742
- );
743
- acc.push("background-color: transparent; color: inherit;");
744
- return acc;
745
- }, [])
746
- };
747
- },
748
- print(method, ...message) {
749
- if (env === "development") {
750
- const { namespaces, styles } = _logger.printNamespaces();
751
- console[method](namespaces, ...styles, ...message);
752
- }
753
- return _logger;
754
- },
755
- printWithoutNamespace(method, ...message) {
756
- if (env === "development") {
757
- console[method](...message);
758
- }
759
- return _logger;
760
- },
761
- log(...message) {
762
- return _logger.print("log", ...message);
763
- },
764
- warn(...message) {
765
- return _logger.print("warn", ...message);
766
- },
767
- error(...message) {
768
- return _logger.print("error", ...message);
769
- },
770
- group(...message) {
771
- return _logger.print("group", ...message);
772
- },
773
- groupEnd() {
774
- if (env === "development") {
775
- console.groupEnd();
776
- }
777
- return _logger;
778
- }
779
- };
780
- return _logger;
781
- }
782
- const Logger = createLogger("production");
783
- const logger$3 = Logger.namespace("store");
784
- const createDebugger = (store$) => {
785
- return store$.pipe(
786
- rxjs.map(
787
- (value) => [...value.keys()].reduce((acc, key) => {
788
- var _a;
789
- acc[key] = (_a = value.get(key)) == null ? void 0 : _a.getValue();
790
- return acc;
791
- }, {})
792
- ),
793
- rxjs.distinctUntilChanged(shallowEqual)
794
- ).subscribe((value) => {
795
- logger$3.log("store", "update", value);
796
- });
797
- };
798
- const createQueryStore = () => {
799
- const store = /* @__PURE__ */ new Map();
800
- const store$ = new rxjs.BehaviorSubject(store);
801
- const queryEventSubject = new rxjs.Subject();
802
- const queryTriggerSubject = new rxjs.Subject();
803
- const notify = () => {
804
- store$.next(store);
805
- };
806
- const setValue = (key, value) => {
807
- store.set(key, new rxjs.BehaviorSubject(value));
808
- notify();
809
- };
810
- const getValue = (serializedKey) => {
811
- var _a;
812
- return (_a = store.get(serializedKey)) == null ? void 0 : _a.getValue();
813
- };
814
- const getValue$ = (key) => {
815
- return store$.pipe(
816
- rxjs.map(() => store.get(key)),
817
- rxjs.filter(isDefined),
818
- rxjs.map((entry) => entry.getValue()),
819
- rxjs.distinctUntilChanged(shallowEqual)
820
- );
821
- };
822
- const updateValue = (key, value) => {
823
- const existingObject = store.get(key);
824
- if (!existingObject)
825
- return;
826
- if (typeof value === "function") {
827
- existingObject.next({
828
- ...existingObject.getValue(),
829
- ...value(existingObject.getValue())
830
- });
831
- } else {
832
- existingObject.next({ ...existingObject.getValue(), ...value });
833
- }
834
- store$.next(store);
835
- };
836
- const updateMany = (value, predicate = () => true) => {
837
- store.forEach((oldValue$) => {
838
- const oldValue = oldValue$.getValue();
839
- if (predicate(oldValue)) {
840
- oldValue$.next({ ...oldValue, ...value });
841
- }
842
- });
843
- store$.next(store);
844
- };
845
- const deleteValue = (key) => {
846
- store.delete(key);
847
- store$.next(store);
848
- };
849
- const addRunner = (key, stream) => {
850
- updateValue(key, (old) => ({
851
- ...old,
852
- runners: [...old.runners, stream]
853
- }));
854
- return () => {
855
- var _a;
856
- const newListeners = ((_a = store.get(key)) == null ? void 0 : _a.getValue().runners.filter((reference) => reference !== stream)) ?? [];
857
- updateValue(key, (old) => ({
858
- ...old,
859
- runners: newListeners
860
- }));
861
- };
862
- };
863
- const start = () => {
864
- const debugger$ = createDebugger(store$);
865
- return () => {
866
- debugger$.unsubscribe();
867
- };
868
- };
869
- return {
870
- set: setValue,
871
- get: getValue,
872
- get$: getValue$,
873
- delete: deleteValue,
874
- update: updateValue,
875
- keys: () => store.keys(),
876
- updateMany,
877
- addRunner,
878
- store$,
879
- queryEvent$: queryEventSubject.asObservable(),
880
- dispatchQueryEvent: (event) => {
881
- queryEventSubject.next(event);
882
- },
883
- queryTrigger$: queryTriggerSubject.asObservable(),
884
- dispatchQueryTrigger: (event) => {
885
- queryTriggerSubject.next(event);
886
- },
887
- size: () => store.size,
888
- start
889
- };
890
- };
891
- const createQueryTrigger = ({
892
- options$,
893
- queryStore,
894
- key
895
- }) => {
896
- const enabledOption$ = options$.pipe(
897
- rxjs.map(({ enabled = true }) => enabled),
898
- rxjs.distinctUntilChanged()
899
- );
900
- const enabledTrigger$ = enabledOption$.pipe(
901
- rxjs.skip(1),
902
- rxjs.filter((enabled) => enabled)
903
- );
904
- return rxjs.merge(
905
- queryStore.queryTrigger$.pipe(
906
- rxjs.filter((event) => key === event.key),
907
- rxjs.map(({ trigger: trigger2 }) => trigger2)
908
- ),
909
- enabledTrigger$.pipe(
910
- rxjs.map(() => ({
911
- type: "enabled",
912
- ignoreStale: false
913
- }))
914
- )
915
- );
916
- };
917
- const deduplicate = (key, queryStore) => (source) => {
918
- if (key === serializeKey([]))
919
- return source;
920
- return rxjs.defer(() => {
921
- var _a;
922
- const sourceFromStore = (_a = queryStore.get(key)) == null ? void 0 : _a.deduplication_fn;
923
- if (sourceFromStore)
924
- return sourceFromStore;
925
- let sourceToDeduplicate;
926
- const deleteFromStore = () => {
927
- var _a2;
928
- if (((_a2 = queryStore.get(key)) == null ? void 0 : _a2.deduplication_fn) === sourceToDeduplicate) {
929
- queryStore.update(key, {
930
- deduplication_fn: void 0
931
- });
932
- }
933
- };
934
- sourceToDeduplicate = source.pipe(
935
- /**
936
- * Ideally we would want to remove the query from the store only on finalize,
937
- * which means whenever the query complete or error. Unfortunately finalize is
938
- * triggered after a new stream arrive which create a concurrency issue.
939
- * tap is triggered correctly synchronously and before a new query arrive.
940
- */
941
- rxjs.tap({
942
- error: deleteFromStore,
943
- complete: deleteFromStore
944
- }),
945
- /**
946
- * Because tap is not called on unsubscription we still need to handle the case.
947
- */
948
- rxjs.finalize(deleteFromStore),
949
- rxjs.shareReplay({
950
- refCount: true,
951
- bufferSize: 1
952
- })
953
- );
954
- queryStore.update(key, {
955
- deduplication_fn: sourceToDeduplicate
956
- });
957
- return sourceToDeduplicate;
958
- });
959
- };
960
- const notifyQueryResult = (options$) => (stream$) => stream$.pipe(
961
- rxjs.withLatestFrom(options$),
962
- rxjs.map(([result, options]) => {
963
- var _a, _b;
964
- if (result.error) {
965
- (_a = options.onError) == null ? void 0 : _a.call(options, result.error);
966
- } else {
967
- (_b = options.onSuccess) == null ? void 0 : _b.call(options, result);
968
- }
969
- return result;
970
- })
971
- );
972
- const registerResultInCache = ({
973
- queryStore,
974
- serializedKey,
975
- options
976
- }) => (stream) => stream.pipe(
977
- rxjs.tap(({ data }) => {
978
- if (data == null ? void 0 : data.result) {
979
- const result = data == null ? void 0 : data.result;
980
- queryStore.update(serializedKey, {
981
- ...options.cacheTime !== 0 && {
982
- cache_fnResult: { result }
983
- }
984
- });
985
- }
986
- })
987
- );
988
- const createQueryFetch = ({
989
- options$,
990
- options,
991
- fn,
992
- queryStore,
993
- serializedKey,
994
- trigger: trigger2,
995
- trigger$
996
- }) => {
997
- const enabledOption$ = options$.pipe(
998
- rxjs.map(({ enabled = true }) => enabled),
999
- rxjs.distinctUntilChanged()
1000
- );
1001
- const disabled$ = enabledOption$.pipe(
1002
- rxjs.distinctUntilChanged(),
1003
- rxjs.filter((enabled) => !enabled)
1004
- );
1005
- const deferredQuery = rxjs.defer(() => {
1006
- const queryOrResponse = typeof fn === "function" ? fn() : fn;
1007
- return rxjs.from(queryOrResponse);
1008
- });
1009
- const fnExecution$ = deferredQuery.pipe(
1010
- retryOnError(options),
1011
- deduplicate(serializedKey, queryStore),
1012
- rxjs.tap(() => {
1013
- queryStore.dispatchQueryEvent({
1014
- key: serializedKey,
1015
- type: "fetchSuccess"
1016
- });
1017
- queryStore.update(serializedKey, {
1018
- lastFetchedAt: (/* @__PURE__ */ new Date()).getTime()
1019
- });
1020
- }),
1021
- rxjs.map((result) => ({
1022
- status: "success",
1023
- data: { result },
1024
- error: void 0
1025
- })),
1026
- rxjs.endWith({
1027
- fetchStatus: "idle"
1028
- }),
1029
- rxjs.catchError((error) => {
1030
- queryStore.dispatchQueryEvent({
1031
- key: serializedKey,
1032
- type: "fetchError"
1033
- });
1034
- return rxjs.of({
1035
- fetchStatus: "idle",
1036
- status: "error",
1037
- data: void 0,
1038
- error
1039
- });
1040
- }),
1041
- notifyQueryResult(options$),
1042
- registerResultInCache({ serializedKey, options, queryStore })
1043
- );
1044
- const newCache$ = queryStore.queryEvent$.pipe(
1045
- rxjs.filter(
1046
- (event) => event.key === serializedKey && event.type === "queryDataSet"
1047
- ),
1048
- rxjs.map(() => {
1049
- var _a, _b;
1050
- return (_b = (_a = queryStore.get(serializedKey)) == null ? void 0 : _a.cache_fnResult) == null ? void 0 : _b.result;
1051
- }),
1052
- rxjs.filter(isDefined),
1053
- rxjs.map((result) => ({
1054
- status: "success",
1055
- data: { result }
1056
- })),
1057
- /**
1058
- * @important
1059
- * To avoid cache update being returned being the first result is returned.
1060
- * For example if user set query data inside onSuccess callback, we simulate
1061
- * a small delay to ensure it happens after.
1062
- */
1063
- rxjs.delay(1)
1064
- );
1065
- const execution$ = rxjs.merge(
1066
- disabled$.pipe(
1067
- rxjs.take(1),
1068
- rxjs.map(() => ({
1069
- fetchStatus: "idle"
1070
- }))
1071
- ),
1072
- rxjs.merge(
1073
- rxjs.of({ fetchStatus: "fetching", error: void 0 }),
1074
- fnExecution$
1075
- ).pipe(rxjs.takeUntil(disabled$)),
1076
- newCache$
1077
- ).pipe(rxjs.takeUntil(trigger$));
1078
- const query = queryStore.get(serializedKey);
1079
- const cacheResult = query == null ? void 0 : query.cache_fnResult;
1080
- const hasCache = !!cacheResult;
1081
- const ignoreStale = trigger2.type === "refetch" && trigger2.ignoreStale;
1082
- if (hasCache) {
1083
- if (!(query == null ? void 0 : query.isStale) && !ignoreStale) {
1084
- return rxjs.of({
1085
- fetchStatus: "idle",
1086
- status: "success",
1087
- data: { result: cacheResult.result },
1088
- error: void 0
1089
- });
1090
- } else {
1091
- return rxjs.merge(
1092
- rxjs.of({
1093
- fetchStatus: "fetching",
1094
- status: "success",
1095
- data: { result: cacheResult.result },
1096
- error: void 0
1097
- }),
1098
- execution$
1099
- );
1100
- }
1101
- }
1102
- return execution$;
1103
- };
1104
- const compareKeys = (keyA, keyB, { exact = false } = {}) => {
1105
- if (exact) {
1106
- return serializeKey(keyA) === serializeKey(keyB);
1107
- }
1108
- return keyA.reduce((acc, value, index) => {
1109
- if (!acc)
1110
- return false;
1111
- if (value === void 0) {
1112
- const hasNextItemInLineNotUndefined = keyA.slice(index, keyA.length - 1).some((item) => item !== void 0);
1113
- if (!hasNextItemInLineNotUndefined) {
1114
- return true;
1115
- }
1116
- }
1117
- return serializeObject(value) === serializeObject(keyB[index]);
1118
- }, true);
1119
- };
1120
- const logger$2 = Logger.namespace("invalidation");
1121
- const createInvalidationClient = ({
1122
- queryStore
1123
- }) => {
1124
- const invalidateQueries = ({
1125
- queryKey,
1126
- exact = false,
1127
- predicate
1128
- } = {}) => {
1129
- let keysToRefetch = [];
1130
- if (queryKey) {
1131
- logger$2.log(`invalidation requested for`, queryKey);
1132
- queryStore.updateMany({ isStale: true }, (entry) => {
1133
- const isValid = compareKeys(queryKey, entry.queryKey, { exact });
1134
- if (isValid) {
1135
- keysToRefetch.push(serializeKey(entry.queryKey));
1136
- }
1137
- return isValid;
1138
- });
1139
- } else if (predicate) {
1140
- queryStore.updateMany({ isStale: true }, (entry) => {
1141
- const isValid = predicate(entry);
1142
- if (isValid) {
1143
- keysToRefetch.push(serializeKey(entry.queryKey));
1144
- }
1145
- return isValid;
1146
- });
1147
- } else {
1148
- logger$2.log(`Invalidation requested for all queries`);
1149
- queryStore.updateMany({ isStale: true });
1150
- keysToRefetch = Array.from(queryStore.keys());
1151
- }
1152
- keysToRefetch.forEach((key) => {
1153
- queryStore.update(key, {
1154
- deduplication_fn: void 0
1155
- });
1156
- queryStore.dispatchQueryTrigger({
1157
- key,
1158
- trigger: { ignoreStale: true, type: "refetch" }
1159
- });
1160
- });
1161
- };
1162
- return {
1163
- invalidateQueries
1164
- };
1165
- };
1166
- const createRefetchClient = (_) => {
1167
- const pipeQueryResult = ({
1168
- options$
1169
- }) => (stream) => {
1170
- const sharedStream = stream.pipe(rxjs.share());
1171
- return rxjs.merge(
1172
- sharedStream,
1173
- sharedStream.pipe(
1174
- rxjs.filter(
1175
- (result) => !!result.data && result.fetchStatus !== "fetching"
1176
- ),
1177
- rxjs.distinctUntilChanged((prev, curr) => prev.data === curr.data),
1178
- rxjs.withLatestFrom(options$),
1179
- rxjs.map(([, { refetchInterval }]) => refetchInterval),
1180
- rxjs.filter(isDefined),
1181
- rxjs.switchMap((refetchInterval) => {
1182
- if (typeof refetchInterval === "number") {
1183
- return rxjs.timer(refetchInterval).pipe(
1184
- rxjs.map(() => ({
1185
- type: "refetch",
1186
- ignoreStale: true
1187
- })),
1188
- rxjs.switchMap(() => rxjs.EMPTY)
1189
- );
1190
- }
1191
- return rxjs.EMPTY;
1192
- })
1193
- )
1194
- );
1195
- };
1196
- const refetchQueries = (_2) => {
1197
- };
1198
- return {
1199
- pipeQueryResult,
1200
- refetchQueries
1201
- };
1202
- };
1203
- const difference = (a, b) => a.filter((element) => !b.includes(element));
1204
- const createQueryListener = (store, onQuery) => store.store$.pipe(
1205
- rxjs.map((store2) => [...store2.keys()]),
1206
- rxjs.startWith([]),
1207
- rxjs.pairwise(),
1208
- rxjs.mergeMap(([previousKeys, currentKeys]) => {
1209
- const newKeys = difference(currentKeys, previousKeys);
1210
- return rxjs.merge(
1211
- ...newKeys.map((key) => {
1212
- const deleted$ = store.store$.pipe(
1213
- rxjs.map(() => store.get(key)),
1214
- rxjs.filter((item) => item === void 0)
1215
- );
1216
- return rxjs.merge(rxjs.NEVER, rxjs.of(key)).pipe(
1217
- rxjs.tap(() => {
1218
- }),
1219
- onQuery,
1220
- rxjs.finalize(() => {
1221
- }),
1222
- rxjs.takeUntil(deleted$)
1223
- );
1224
- })
1225
- );
1226
- })
1227
- );
1228
- const mapStoreQueryToRunnerOptions = (stream) => stream.pipe(
1229
- rxjs.switchMap((entry) => rxjs.combineLatest(entry.runners)),
1230
- rxjs.map((runnerValues) => runnerValues.map(({ options }) => options))
1231
- );
1232
- const mapOptionsToOption$1 = (stream) => stream.pipe(
1233
- rxjs.map(
1234
- (options) => options.reduce(
1235
- (acc, value) => {
1236
- return {
1237
- ...acc,
1238
- lowestStaleTime: value.staleTime === void 0 ? acc.lowestStaleTime : Math.min(
1239
- value.staleTime ?? Infinity,
1240
- acc.lowestStaleTime ?? Infinity
1241
- )
1242
- };
1243
- },
1244
- { lowestStaleTime: void 0 }
1245
- )
1246
- ),
1247
- rxjs.distinctUntilChanged(shallowEqual)
1248
- );
1249
- const onlyFetchEventDone = (key) => (stream) => stream.pipe(
1250
- rxjs.filter(
1251
- (event) => event.key === key && (event.type === "fetchError" || event.type === "fetchSuccess")
1252
- )
1253
- );
1254
- const markAsStale = ({
1255
- queryStore
1256
- }) => (stream) => stream.pipe(
1257
- rxjs.switchMap((key) => {
1258
- const query$ = queryStore.get$(key);
1259
- return queryStore.queryEvent$.pipe(
1260
- onlyFetchEventDone(key),
1261
- rxjs.switchMap(
1262
- () => query$.pipe(
1263
- mapStoreQueryToRunnerOptions,
1264
- mapOptionsToOption$1,
1265
- rxjs.tap(({ lowestStaleTime = 0 }) => {
1266
- var _a;
1267
- if (lowestStaleTime === 0) {
1268
- logger$2.log(key, "marked as stale!", {
1269
- staleTime: lowestStaleTime
1270
- });
1271
- queryStore.update(key, { isStale: true });
1272
- } else if ((_a = queryStore.get(key)) == null ? void 0 : _a.isStale) {
1273
- logger$2.log(key, "marked non stale", {
1274
- staleTime: lowestStaleTime
1275
- });
1276
- queryStore.update(key, { isStale: false });
1277
- }
1278
- }),
1279
- rxjs.filter(
1280
- ({ lowestStaleTime }) => lowestStaleTime !== Infinity && lowestStaleTime !== 0
1281
- ),
1282
- rxjs.switchMap(({ lowestStaleTime = 0 }) => rxjs.timer(lowestStaleTime)),
1283
- rxjs.tap(() => {
1284
- var _a;
1285
- if (!((_a = queryStore.get(key)) == null ? void 0 : _a.isStale)) {
1286
- logger$2.log(key, "marked as stale!");
1287
- queryStore.update(key, { isStale: true });
1288
- }
1289
- })
1290
- )
1291
- ),
1292
- rxjs.map(() => key)
1293
- );
1294
- })
1295
- );
1296
- const mapOptionsToOption = (stream) => stream.pipe(
1297
- rxjs.map(
1298
- (options) => options.reduce(
1299
- (acc, value) => {
1300
- return {
1301
- ...acc,
1302
- lowestCacheTime: value.cacheTime === void 0 ? acc.lowestCacheTime : Math.min(
1303
- value.cacheTime ?? Infinity,
1304
- acc.lowestCacheTime ?? Infinity
1305
- )
1306
- };
1307
- },
1308
- { lowestCacheTime: void 0 }
1309
- )
1310
- ),
1311
- rxjs.distinctUntilChanged(shallowEqual)
1312
- );
1313
- const onCacheUpdate = (stream) => stream.pipe(
1314
- rxjs.map((item) => item.cache_fnResult),
1315
- rxjs.distinctUntilChanged(shallowEqual)
1316
- );
1317
- const invalidateCache = ({
1318
- queryStore
1319
- }) => (stream) => stream.pipe(
1320
- rxjs.switchMap((key) => {
1321
- const query$ = queryStore.get$(key);
1322
- const invalidateCache$ = query$.pipe(
1323
- onCacheUpdate,
1324
- rxjs.switchMap(
1325
- () => query$.pipe(
1326
- mapStoreQueryToRunnerOptions,
1327
- mapOptionsToOption,
1328
- rxjs.switchMap(
1329
- ({
1330
- lowestCacheTime = 5 * 60 * 1e3
1331
- /* 5mn */
1332
- }) => rxjs.timer(lowestCacheTime).pipe(
1333
- rxjs.tap(() => {
1334
- queryStore.update(key, { cache_fnResult: void 0 });
1335
- })
1336
- )
1337
- )
1338
- )
1339
- )
1340
- );
1341
- return invalidateCache$.pipe(rxjs.map(() => key));
1342
- })
1343
- );
1344
- const garbageCache = ({
1345
- queryStore
1346
- }) => (stream) => stream.pipe(
1347
- rxjs.switchMap((key) => {
1348
- const query$ = queryStore.get$(key);
1349
- return query$.pipe(
1350
- rxjs.filter((entry) => !entry.cache_fnResult),
1351
- rxjs.map((entry) => entry.runners.length > 0),
1352
- rxjs.pairwise(),
1353
- rxjs.filter(([hadRunners, hasRunners]) => hadRunners && !hasRunners),
1354
- rxjs.tap(() => {
1355
- queryStore.delete(key);
1356
- }),
1357
- rxjs.map(() => key)
1358
- );
1359
- })
1360
- );
1361
- const getInitialQueryEntity = ({ key }) => ({
1362
- isStale: true,
1363
- queryKey: key,
1364
- runners: []
1365
- });
1366
- const updateStoreWithNewQuery = ({
1367
- queryStore,
1368
- serializedKey,
1369
- runner$,
1370
- options$,
1371
- key
1372
- }) => (stream) => stream.pipe(
1373
- rxjs.withLatestFrom(options$),
1374
- rxjs.map(([trigger2, options]) => {
1375
- if (key.length === 0)
1376
- return [trigger2, void 0];
1377
- if (trigger2.type !== "initial")
1378
- return [trigger2, void 0];
1379
- if (!queryStore.get(serializedKey)) {
1380
- queryStore.set(serializedKey, getInitialQueryEntity({ key }));
1381
- } else {
1382
- queryStore.update(serializedKey, {
1383
- queryKey: key,
1384
- ...options.markStale && {
1385
- isStale: true
1386
- }
1387
- });
1388
- }
1389
- return [trigger2, queryStore.addRunner(serializedKey, runner$)];
1390
- })
1391
- );
1392
- const logger$1 = Logger.namespace("cache");
1393
- const createCacheClient = ({
1394
- queryStore
1395
- }) => {
1396
- const setQueryData = ({
1397
- queryKey,
1398
- updater
1399
- }) => {
1400
- const serializedKey = serializeKey(queryKey);
1401
- if (queryKey.length === 0)
1402
- return;
1403
- logger$1.log("set cache for query", serializeKey);
1404
- if (!queryStore.get(serializedKey)) {
1405
- queryStore.set(serializedKey, getInitialQueryEntity({ key: queryKey }));
1406
- }
1407
- queryStore.update(serializedKey, (entity) => {
1408
- var _a;
1409
- if (typeof updater === "function") {
1410
- const callableUpdater = updater;
1411
- return {
1412
- ...entity,
1413
- cache_fnResult: {
1414
- result: callableUpdater(
1415
- (_a = entity.cache_fnResult) == null ? void 0 : _a.result
1416
- )
1417
- }
1418
- };
1419
- }
1420
- return {
1421
- ...entity,
1422
- cache_fnResult: {
1423
- result: updater
1424
- }
1425
- };
1426
- });
1427
- queryStore.dispatchQueryEvent({
1428
- key: serializedKey,
1429
- type: "queryDataSet"
1430
- });
1431
- };
1432
- return {
1433
- setQueryData
1434
- };
1435
- };
1436
- const logger = Logger.namespace("refetch");
1437
- const markQueryAsStaleIfRefetch = ({
1438
- key,
1439
- serializedKey,
1440
- queryStore
1441
- }) => (stream) => {
1442
- return stream.pipe(
1443
- rxjs.tap((trigger2) => {
1444
- if (trigger2.type !== "refetch")
1445
- return;
1446
- const query = queryStore.get(serializedKey);
1447
- if (query && trigger2.ignoreStale && !query.isStale) {
1448
- logger.log(key, "marked stale by trigger!");
1449
- queryStore.update(serializedKey, {
1450
- isStale: true
1451
- });
1452
- }
1453
- })
1454
- );
1455
- };
1456
- const dispatchExternalRefetchToAllQueries = ({
1457
- queryStore,
1458
- serializedKey
1459
- }) => (stream) => stream.pipe(
1460
- rxjs.tap((trigger2) => {
1461
- if (trigger2.type === "refetch") {
1462
- queryStore.update(serializedKey, {
1463
- deduplication_fn: void 0
1464
- });
1465
- queryStore.dispatchQueryTrigger({
1466
- key: serializedKey,
1467
- trigger: trigger2
1468
- });
1469
- }
1470
- }),
1471
- rxjs.filter((trigger2) => trigger2.type !== "refetch")
1472
- );
1473
- const getDefaultMutationState = () => ({
1474
- context: void 0,
1475
- data: void 0,
1476
- error: null,
1477
- status: "idle",
1478
- submittedAt: 0,
1479
- variables: void 0
1480
- });
1481
- const mergeResults = (stream$) => stream$.pipe(
1482
- rxjs.scan((acc, current) => {
1483
- return {
1484
- ...acc,
1485
- ...current,
1486
- data: current.data ?? acc.data,
1487
- error: current.error ?? acc.error
1488
- };
1489
- }, getDefaultMutationState()),
1490
- rxjs.distinctUntilChanged(
1491
- ({ data: prevData, ...prev }, { data: currData, ...curr }) => shallowEqual(prev, curr) && shallowEqual(prevData, currData)
1492
- )
1493
- );
1494
- class Mutation {
1495
- constructor({
1496
- args,
1497
- ...options
1498
- }) {
1499
- __publicField(this, "stateSubject", new rxjs.ReplaySubject(1));
1500
- /**
1501
- * @important
1502
- * convenience over usage of stateSubject for sync access
1503
- */
1504
- __publicField(this, "state", getDefaultMutationState());
1505
- __publicField(this, "options");
1506
- __publicField(this, "mutation$");
1507
- this.options = options;
1508
- const mutationFn = options.mutationFn;
1509
- this.state.variables = args;
1510
- this.stateSubject.next(this.state);
1511
- const mutationFnObservable = typeof mutationFn === "function" ? rxjs.defer(() => rxjs.from(mutationFn(args))) : mutationFn;
1512
- const queryRunner$ = mutationFnObservable.pipe(
1513
- retryOnError(options),
1514
- rxjs.take(1),
1515
- rxjs.map((data) => ({ data, isError: false })),
1516
- rxjs.catchError((error) => {
1517
- console.error(error);
1518
- if (options.onError != null) {
1519
- options.onError(error, args);
1520
- }
1521
- return rxjs.of({ data: error, isError: true });
1522
- })
1523
- );
1524
- const initState$ = rxjs.of({
1525
- ...this.state,
1526
- status: "pending",
1527
- submittedAt: (/* @__PURE__ */ new Date()).getTime()
1528
- });
1529
- this.mutation$ = rxjs.merge(
1530
- initState$,
1531
- queryRunner$.pipe(
1532
- rxjs.map(({ data, isError }) => {
1533
- if (!isError) {
1534
- if (options.onSuccess != null)
1535
- options.onSuccess(data, args);
1536
- }
1537
- return isError ? {
1538
- status: "error",
1539
- error: data,
1540
- data: void 0
1541
- } : {
1542
- status: "success",
1543
- error: null,
1544
- data
1545
- };
1546
- })
1547
- )
1548
- ).pipe(
1549
- mergeResults,
1550
- rxjs.tap((value) => {
1551
- this.state = { ...this.state, ...value };
1552
- this.stateSubject.next(this.state);
1553
- }),
1554
- options.__queryRunnerHook ?? rxjs.identity,
1555
- rxjs.share()
1556
- );
1557
- }
1558
- }
1559
- const createMutationRunner = ({
1560
- __queryFinalizeHook,
1561
- __queryInitHook,
1562
- __queryTriggerHook
1563
- }) => {
1564
- const trigger$ = new rxjs.Subject();
1565
- const cancel$ = new rxjs.Subject();
1566
- let closed = false;
1567
- const mapOperator$ = new rxjs.BehaviorSubject("merge");
1568
- const mutationsSubject = new rxjs.BehaviorSubject([]);
1569
- const destroy = () => {
1570
- if (closed) {
1571
- throw new Error("Trying to close an already closed mutation");
1572
- }
1573
- closed = true;
1574
- mapOperator$.complete();
1575
- mutationsSubject.complete();
1576
- trigger$.complete();
1577
- cancel$.next();
1578
- cancel$.complete();
1579
- };
1580
- const stableMapOperator$ = mapOperator$.pipe(
1581
- rxjs.filter(isDefined),
1582
- rxjs.distinctUntilChanged()
1583
- );
1584
- const mutation$ = stableMapOperator$.pipe(
1585
- __queryInitHook ?? rxjs.identity,
1586
- rxjs.mergeMap((mapOperator) => {
1587
- const switchOperator = mapOperator === "concat" ? rxjs.concatMap : mapOperator === "switch" ? rxjs.switchMap : rxjs.mergeMap;
1588
- let mutationsForCurrentMapOperatorSubject = [];
1589
- const removeMutation = (mutation) => {
1590
- mutationsForCurrentMapOperatorSubject = mutationsForCurrentMapOperatorSubject.filter(
1591
- (item) => item !== mutation
1592
- );
1593
- mutationsSubject.next(
1594
- mutationsSubject.getValue().filter((item) => item !== mutation)
1595
- );
1596
- };
1597
- return trigger$.pipe(
1598
- rxjs.takeUntil(stableMapOperator$.pipe(rxjs.skip(1))),
1599
- rxjs.map(({ args, options }) => {
1600
- const mutation = new Mutation({
1601
- args,
1602
- ...options,
1603
- mapOperator
1604
- });
1605
- mutationsForCurrentMapOperatorSubject = [
1606
- ...mutationsForCurrentMapOperatorSubject,
1607
- mutation
1608
- ];
1609
- mutationsSubject.next([...mutationsSubject.getValue(), mutation]);
1610
- return mutation;
1611
- }),
1612
- switchOperator((mutation) => {
1613
- if (!mutationsSubject.getValue().includes(mutation))
1614
- return rxjs.of({});
1615
- const queryIsOver$ = mutation.mutation$.pipe(
1616
- rxjs.map(({ data, error }) => error || data)
1617
- );
1618
- const isThisCurrentFunctionLastOneCalled = trigger$.pipe(
1619
- rxjs.take(1),
1620
- rxjs.map(() => mapOperator === "concat"),
1621
- rxjs.startWith(true),
1622
- rxjs.takeUntil(queryIsOver$)
1623
- );
1624
- const result$ = rxjs.combineLatest([
1625
- mutation.mutation$,
1626
- isThisCurrentFunctionLastOneCalled
1627
- ]).pipe(
1628
- rxjs.map(([result, isLastMutationCalled]) => {
1629
- if ((result.status === "success" || result.status === "error") && !isLastMutationCalled) {
1630
- return {};
1631
- }
1632
- return result;
1633
- }),
1634
- rxjs.takeUntil(cancel$.pipe()),
1635
- mergeResults,
1636
- rxjs.finalize(() => {
1637
- removeMutation(mutation);
1638
- })
1639
- );
1640
- return result$;
1641
- }),
1642
- mergeResults,
1643
- __queryTriggerHook ?? rxjs.identity
1644
- );
1645
- }),
1646
- __queryFinalizeHook ?? rxjs.identity,
1647
- rxjs.shareReplay(1)
1648
- );
1649
- cancel$.subscribe(() => {
1650
- if (mutationsSubject.getValue().length === 0)
1651
- return;
1652
- mutationsSubject.next([]);
1653
- });
1654
- return {
1655
- mutation$,
1656
- trigger: ({
1657
- args,
1658
- options
1659
- }) => {
1660
- mapOperator$.next(options.mapOperator);
1661
- trigger$.next({ args, options });
1662
- },
1663
- cancel$,
1664
- destroy,
1665
- mutationsSubject,
1666
- getClosed: () => closed
1667
- };
1668
- };
1669
- const createPredicateForFilters = ({
1670
- mutationKey,
1671
- status,
1672
- predicate
1673
- } = {}) => {
1674
- const defaultPredicate = (mutation) => {
1675
- if (mutationKey !== void 0 && // @todo optimize
1676
- serializeKey(mutation.options.mutationKey) !== serializeKey(mutationKey)) {
1677
- return false;
1678
- }
1679
- if (status && mutation.state.status !== status)
1680
- return false;
1681
- return true;
1682
- };
1683
- const finalPredicate = predicate ?? defaultPredicate;
1684
- return finalPredicate;
1685
- };
1686
- class MutationResultObserver {
1687
- constructor(mutationRunnersByKey$) {
1688
- /**
1689
- * Mutation result subject. It can be used whether there is a mutation
1690
- * running or not and can be directly observed.
1691
- *
1692
- * @important
1693
- * - automatically cleaned as soon as the last mutation is done for a given key
1694
- */
1695
- __publicField(this, "mutationResults$", new rxjs.BehaviorSubject(/* @__PURE__ */ new Map()));
1696
- mutationRunnersByKey$.pipe(
1697
- rxjs.switchMap((mapItem) => {
1698
- const runners = Array.from(mapItem.values()).map((runner) => {
1699
- const serializedMutationKey = serializeKey(runner.mutationKey);
1700
- return runner.mutation$.pipe(
1701
- rxjs.tap((result) => {
1702
- this.updateResultForKey({
1703
- serializedMutationKey,
1704
- result
1705
- });
1706
- }),
1707
- rxjs.finalize(() => {
1708
- this.deleteResultForKey({ serializedMutationKey });
1709
- })
1710
- );
1711
- });
1712
- return rxjs.merge(...runners);
1713
- })
1714
- ).subscribe();
1715
- }
1716
- getDefaultResultValue() {
1717
- return {
1718
- ...getDefaultMutationState(),
1719
- isSuccess: false,
1720
- isPending: false,
1721
- isIdle: true,
1722
- isError: false
1723
- };
1724
- }
1725
- deleteResultForKey({
1726
- serializedMutationKey
1727
- }) {
1728
- const resultMap = this.mutationResults$.getValue();
1729
- resultMap.delete(serializedMutationKey);
1730
- this.mutationResults$.next(resultMap);
1731
- }
1732
- updateResultForKey({
1733
- serializedMutationKey,
1734
- result
1735
- }) {
1736
- const resultForKeySubject = this.mutationResults$.getValue().get(serializedMutationKey);
1737
- const valueForResult = {
1738
- ...this.getDefaultResultValue(),
1739
- ...result,
1740
- isSuccess: result.status === "success",
1741
- isPending: result.status === "pending",
1742
- isIdle: result.status === "idle",
1743
- isError: result.status === "error"
1744
- };
1745
- if (!resultForKeySubject) {
1746
- const resultMap = this.mutationResults$.getValue();
1747
- resultMap.set(
1748
- serializedMutationKey,
1749
- new rxjs.BehaviorSubject(valueForResult)
1750
- );
1751
- this.mutationResults$.next(resultMap);
1752
- } else {
1753
- resultForKeySubject == null ? void 0 : resultForKeySubject.next(valueForResult);
1754
- }
1755
- }
1756
- observe({ key }) {
1757
- var _a;
1758
- const currentResultValue = (_a = this.mutationResults$.getValue().get(key)) == null ? void 0 : _a.getValue();
1759
- const lastValue = currentResultValue ?? this.getDefaultResultValue();
1760
- const result$ = this.mutationResults$.pipe(
1761
- rxjs.switchMap((resultMap) => {
1762
- const subject = resultMap.get(key);
1763
- return subject ?? rxjs.EMPTY;
1764
- })
1765
- ).pipe(rxjs.filter(isDefined));
1766
- return { result$, lastValue };
1767
- }
1768
- destroy() {
1769
- this.mutationResults$.complete();
1770
- }
1771
- }
1772
- class MutationClient {
1773
- constructor() {
1774
- /**
1775
- * Contain all active mutation for a given key.
1776
- * A mutation ca have several triggers running (it is not necessarily one function running)
1777
- *
1778
- * @important
1779
- * - automatically cleaned as soon as the last mutation is done for a given key
1780
- */
1781
- __publicField(this, "mutationRunnersByKey$", new rxjs.BehaviorSubject(/* @__PURE__ */ new Map()));
1782
- __publicField(this, "mutate$", new rxjs.Subject());
1783
- __publicField(this, "cancel$", new rxjs.Subject());
1784
- /**
1785
- * Observable to track how many running mutations per runner
1786
- */
1787
- __publicField(this, "isMutatingSubject", new rxjs.BehaviorSubject([]));
1788
- /**
1789
- * List of all mutations running
1790
- */
1791
- __publicField(this, "mutationsSubject", new rxjs.BehaviorSubject([]));
1792
- __publicField(this, "mutationResultObserver", new MutationResultObserver(
1793
- this.mutationRunnersByKey$
1794
- ));
1795
- this.mutate$.pipe(
1796
- rxjs.tap(({ options, args }) => {
1797
- const { mutationKey } = options;
1798
- const serializedMutationKey = serializeKey(mutationKey);
1799
- let mutationForKey = this.getMutationRunnersByKey(
1800
- serializedMutationKey
1801
- );
1802
- if (!mutationForKey) {
1803
- mutationForKey = {
1804
- ...createMutationRunner(options),
1805
- mutationKey
1806
- };
1807
- this.setMutationRunnersByKey(serializedMutationKey, mutationForKey);
1808
- mutationForKey.mutation$.subscribe();
1809
- mutationForKey.mutationsSubject.pipe(
1810
- rxjs.distinctUntilChanged(shallowEqual),
1811
- rxjs.skip(1),
1812
- rxjs.filter((items) => items.length === 0)
1813
- ).subscribe(() => {
1814
- mutationForKey == null ? void 0 : mutationForKey.destroy();
1815
- this.deleteMutationRunnersByKey(serializedMutationKey);
1816
- });
1817
- }
1818
- mutationForKey.trigger({ args, options });
1819
- })
1820
- ).subscribe();
1821
- this.cancel$.pipe(
1822
- rxjs.tap(({ key }) => {
1823
- var _a;
1824
- const serializedKey = serializeKey(key);
1825
- (_a = this.mutationRunnersByKey$.getValue().get(serializedKey)) == null ? void 0 : _a.cancel$.next();
1826
- })
1827
- ).subscribe();
1828
- this.mutationRunnersByKey$.pipe(
1829
- rxjs.switchMap((mapItem) => {
1830
- const mutationRunners = Array.from(mapItem.values());
1831
- const mutations$ = rxjs.combineLatest(
1832
- mutationRunners.map(
1833
- (runner) => runner.mutationsSubject.pipe(
1834
- rxjs.map((mutations) => mutations.map((mutation) => mutation))
1835
- )
1836
- )
1837
- );
1838
- return mutations$.pipe(
1839
- rxjs.map(
1840
- (mutationsByKeys) => mutationsByKeys.reduce((acc, value) => [...acc, ...value], [])
1841
- )
1842
- );
1843
- }),
1844
- rxjs.startWith([]),
1845
- rxjs.distinctUntilChanged(shallowEqual)
1846
- ).subscribe(this.mutationsSubject);
1847
- }
1848
- /**
1849
- * @helper
1850
- */
1851
- setMutationRunnersByKey(key, value) {
1852
- const map2 = this.mutationRunnersByKey$.getValue();
1853
- map2.set(key, value);
1854
- this.mutationRunnersByKey$.next(map2);
1855
- }
1856
- /**
1857
- * @helper
1858
- */
1859
- deleteMutationRunnersByKey(key) {
1860
- const map2 = this.mutationRunnersByKey$.getValue();
1861
- map2.delete(key);
1862
- this.mutationRunnersByKey$.next(map2);
1863
- }
1864
- /**
1865
- * @helper
1866
- */
1867
- getMutationRunnersByKey(key) {
1868
- return this.mutationRunnersByKey$.getValue().get(key);
1869
- }
1870
- useIsMutating(filters = {}) {
1871
- const predicate = createPredicateForFilters(filters);
1872
- const reduceByNumber = (entries) => entries.reduce((acc, mutation) => {
1873
- return predicate(mutation) && mutation.state.status === "pending" ? 1 + acc : acc;
1874
- }, 0);
1875
- const lastValue = reduceByNumber(this.mutationsSubject.getValue());
1876
- const value$ = this.mutationsSubject.pipe(
1877
- rxjs.switchMap((mutations) => {
1878
- const mutationsOnStateUpdate = mutations.map(
1879
- (mutation) => mutation.stateSubject.pipe(rxjs.map(() => mutation))
1880
- );
1881
- return mutationsOnStateUpdate.length === 0 ? rxjs.of([]) : rxjs.combineLatest(mutationsOnStateUpdate);
1882
- }),
1883
- rxjs.map(reduceByNumber),
1884
- rxjs.distinctUntilChanged()
1885
- );
1886
- return { value$, lastValue };
1887
- }
1888
- mutationState({
1889
- filters,
1890
- select
1891
- } = {}) {
1892
- const predicate = createPredicateForFilters(filters);
1893
- const finalSelect = select ?? ((mutation) => mutation.state);
1894
- const lastValue = this.mutationsSubject.getValue().reduce((acc, mutation) => {
1895
- const result = [...acc, mutation];
1896
- return result;
1897
- }, []).filter(predicate).map((mutation) => finalSelect(mutation));
1898
- const value$ = this.mutationsSubject.pipe(
1899
- rxjs.switchMap((mutations) => {
1900
- const mutationsOnStateUpdate = mutations.map(
1901
- (mutation) => mutation.stateSubject.pipe(
1902
- rxjs.filter(() => predicate(mutation)),
1903
- rxjs.map(() => finalSelect(mutation))
1904
- )
1905
- );
1906
- return mutationsOnStateUpdate.length === 0 ? rxjs.of([]) : rxjs.combineLatest(mutationsOnStateUpdate);
1907
- }),
1908
- rxjs.distinctUntilChanged(shallowEqual)
1909
- );
1910
- return { value$, lastValue };
1911
- }
1912
- mutate(params) {
1913
- this.mutate$.next(params);
1914
- }
1915
- /**
1916
- * This will cancel any current mutation runnings.
1917
- * No discrimination process
1918
- */
1919
- cancel(params) {
1920
- this.cancel$.next(params);
1921
- }
1922
- destroy() {
1923
- this.cancel$.complete();
1924
- this.mutate$.complete();
1925
- this.mutationResultObserver.destroy();
1926
- this.mutationRunnersByKey$.complete();
1927
- this.isMutatingSubject.complete();
1928
- this.mutationsSubject.complete();
1929
- }
1930
- }
1931
- const createClient = () => {
1932
- const queryStore = createQueryStore();
1933
- const invalidationClient = createInvalidationClient({ queryStore });
1934
- const cacheClient = createCacheClient({ queryStore });
1935
- const refetchClient = createRefetchClient();
1936
- const mutationClient = new MutationClient();
1937
- let hasCalledStart = false;
1938
- const query = ({
1939
- key,
1940
- fn$: maybeFn$,
1941
- fn: maybeFn,
1942
- trigger$: externalTrigger$ = new rxjs.Subject(),
1943
- options$ = new rxjs.BehaviorSubject({})
1944
- }) => {
1945
- if (!hasCalledStart) {
1946
- throw new Error("You forgot to start client");
1947
- }
1948
- const serializedKey = serializeKey(key);
1949
- const fn$ = maybeFn$ ?? (maybeFn ? rxjs.of(maybeFn) : rxjs.NEVER);
1950
- Logger.log("query$)", serializedKey);
1951
- const runner$ = options$.pipe(rxjs.map((options) => ({ options })));
1952
- let deleteRunner = () => {
1953
- };
1954
- const trigger$ = rxjs.merge(
1955
- externalTrigger$.pipe(
1956
- dispatchExternalRefetchToAllQueries({
1957
- queryStore,
1958
- serializedKey
1959
- })
1960
- ),
1961
- createQueryTrigger({
1962
- options$,
1963
- key: serializedKey,
1964
- queryStore
1965
- })
1966
- ).pipe(rxjs.share());
1967
- const result$ = rxjs.merge(
1968
- rxjs.of({
1969
- type: "initial"
1970
- }),
1971
- trigger$
1972
- ).pipe(
1973
- updateStoreWithNewQuery({
1974
- key,
1975
- queryStore,
1976
- runner$,
1977
- serializedKey,
1978
- options$
1979
- }),
1980
- rxjs.map(([value, deleteRunnerFn]) => {
1981
- if (deleteRunnerFn) {
1982
- deleteRunner = deleteRunnerFn;
1983
- }
1984
- return value;
1985
- }),
1986
- markQueryAsStaleIfRefetch({
1987
- key,
1988
- options$,
1989
- queryStore,
1990
- serializedKey
1991
- }),
1992
- rxjs.withLatestFrom(fn$, options$),
1993
- rxjs.map(([trigger2, fn, options]) => ({ trigger: trigger2, fn, options })),
1994
- rxjs.map((value) => {
1995
- Logger.log(serializedKey, "query trigger", {
1996
- trigger: value.trigger,
1997
- options: value.options
1998
- });
1999
- return value;
2000
- }),
2001
- rxjs.filter(({ options }) => options.enabled !== false),
2002
- rxjs.mergeMap(
2003
- ({ fn, options, trigger: trigger2 }) => createQueryFetch({
2004
- options$,
2005
- options,
2006
- fn,
2007
- queryStore,
2008
- serializedKey,
2009
- trigger: trigger2,
2010
- trigger$
2011
- })
2012
- ),
2013
- mergeResults$1,
2014
- rxjs.withLatestFrom(options$),
2015
- rxjs.takeWhile(([result, options]) => {
2016
- const shouldStop = result.data !== void 0 && options.terminateOnFirstResult;
2017
- return !shouldStop;
2018
- }, true),
2019
- rxjs.map(([result]) => result),
2020
- rxjs.finalize(() => {
2021
- deleteRunner();
2022
- })
2023
- );
2024
- return {
2025
- result$
2026
- };
2027
- };
2028
- const queryListener$ = createQueryListener(
2029
- queryStore,
2030
- (stream) => stream.pipe(
2031
- rxjs.switchMap((key) => {
2032
- const key$ = rxjs.of(key);
2033
- return rxjs.merge(
2034
- invalidateCache({
2035
- queryStore
2036
- })(key$),
2037
- markAsStale({
2038
- queryStore
2039
- })(key$),
2040
- garbageCache({
2041
- queryStore
2042
- })(key$)
2043
- );
2044
- })
2045
- )
2046
- );
2047
- const start = () => {
2048
- hasCalledStart = true;
2049
- const queryListenerSub = queryListener$.subscribe();
2050
- const started = [queryStore.start()];
2051
- return () => {
2052
- started.forEach((destroy2) => {
2053
- destroy2();
2054
- });
2055
- queryListenerSub.unsubscribe();
2056
- };
2057
- };
2058
- const destroy = () => {
2059
- mutationClient.destroy();
2060
- };
2061
- return {
2062
- start,
2063
- query,
2064
- queryStore,
2065
- mutationClient,
2066
- ...invalidationClient,
2067
- ...cacheClient,
2068
- ...refetchClient,
2069
- destroy
2070
- };
2071
- };
2072
- class QueryClient {
2073
- constructor() {
2074
- __publicField(this, "client");
2075
- this.client = createClient();
2076
- }
2077
- }
2078
- exports.QueryClient = QueryClient;
2079
- exports.QueryClientProvider = QueryClientProvider;
2080
- exports.SIGNAL_RESET = SIGNAL_RESET;
2081
- exports.createClient = createClient;
2082
- exports.createLocalforageAdapter = createLocalforageAdapter;
2083
- exports.createSharedStoreAdapter = createSharedStoreAdapter;
2084
- exports.exponentialBackoffDelay = exponentialBackoffDelay;
2085
- exports.getDelay = getDelay;
2086
- exports.retryBackoff = retryBackoff;
2087
- exports.signal = signal;
2088
- exports.trigger = trigger;
2089
- exports.useBehaviorSubject = useBehaviorSubject;
2090
- exports.useLiveRef = useLiveRef;
2091
- exports.useMutation = useMutation;
2092
- exports.useObserve = useObserve;
2093
- exports.useObserveCallback = useObserveCallback;
2094
- exports.usePersistSignals = usePersistSignals;
2095
- exports.useQuery = useQuery;
2096
- exports.useQueryClient = useQueryClient;
2097
- exports.useSignalValue = useSignalValue;
2098
- exports.useSubject = useSubject;
2099
- exports.useSubscribe = useSubscribe;
2100
- exports.useSubscribeEffect = useSubscribeEffect;
2101
- exports.useUnmountObservable = useUnmountObservable;
1
+ "use strict";var fe=Object.defineProperty;var de=(r,t,n)=>t in r?fe(r,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):r[t]=n;var S=(r,t,n)=>(de(r,typeof t!="symbol"?t+"":t,n),n),he=(r,t,n)=>{if(!t.has(r))throw TypeError("Cannot "+n)};var x=(r,t,n)=>(he(r,t,"read from private field"),n?n.call(r):t.get(r)),z=(r,t,n)=>{if(t.has(r))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(r):t.set(r,n)};Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const b=require("react"),e=require("rxjs"),P=require("rxjs/operators"),D=require("react/jsx-runtime"),R=r=>{const t=b.useRef(r);return b.useMemo(()=>{t.current=r},[r]),t};function ge(r,t){return typeof r=="string"&&r===t||typeof r=="number"&&r===t||typeof r=="boolean"&&r===t||typeof r=="symbol"&&r===t||typeof r=="bigint"&&r===t||typeof r>"u"&&r===t||r===null&&r===t}function N(r,t,n){const s=t!=null&&!Array.isArray(t)?t:{defaultValue:void 0,key:"",unsubscribeOnUnmount:!0},i=n==null&&Array.isArray(t)?t:typeof r=="function"?n??[]:[r],a=b.useRef("getValue"in r&&typeof r.getValue=="function"?r.getValue():s.defaultValue),u=R(r),p=R(s),f=b.useCallback(g=>{const l=u.current,o=(typeof l=="function"?l:()=>l)().pipe(e.distinctUntilChanged(ge),e.tap(m=>{a.current=m}),e.finalize(g),e.catchError(m=>(console.error(m),a.current=void 0,e.EMPTY))).subscribe(g);return()=>{p.current.unsubscribeOnUnmount!==!1&&o.unsubscribe()}},[...i]),d=b.useCallback(()=>a.current,[]);return b.useSyncExternalStore(f,d,d)}function Y(r,t=[]){const n=R(r),s=typeof r=="function"?void 0:r;b.useEffect(()=>{const i=n.current,u=(typeof i=="function"?i:()=>i)().pipe(e.catchError(p=>(console.error("Uncaught error at useSubscribe. Please consider adding a catchError or other handling."),console.error(p),e.EMPTY))).subscribe();return()=>{u.unsubscribe()}},[...t,s,n])}const J=r=>{const t=b.useRef();return t.current||(t.current=r()),b.useEffect(()=>{process.env.NODE_ENV},[]),t},K=({onBeforeComplete:r,completeOnUnmount:t=!0}={})=>{const n=J(()=>new e.Subject),s=b.useRef(!1),i=R(r),a=R(t);return b.useEffect(()=>(s.current&&(n.current=new e.Subject,s.current=!1),()=>{if(!a.current){s.current=!0;return}s.current||(i.current!=null&&i.current(),n.current.complete(),s.current=!0)}),[a,i,n]),n},me=(r,t)=>{const n=K();return Y(()=>r(n.current),[n,...t]),[b.useCallback(i=>{n.current.next(i)},[n]),n]};function be(r=e.identity){const t=new e.Subject;return[t.asObservable(),(...n)=>{t.next(r(...n))}]}const X=r=>{const t=J(()=>new e.BehaviorSubject(r)),n=b.useRef(!1),s=b.useRef(r);return b.useEffect(()=>(n.current&&(t.current=new e.BehaviorSubject(s.current),n.current=!1),()=>{n.current||(t.current.complete(),n.current=!0)}),[t]),t},Z=Symbol("SIGNAL_RESET");function ye(r){const{default:t}=r??{},n=new e.BehaviorSubject(t);return{setValue:a=>{if(typeof a=="function"){const u=a(n.getValue());if(u===n.getValue())return;n.next(u);return}if(a===Z){n.next(t??void 0);return}n.next(a)},getValue:()=>n.getValue(),config:r,subject:n}}function Se(r,t){const n=t??(s=>s);return N(()=>r.subject.pipe(e.map(s=>n(s)),e.distinctUntilChanged()),{defaultValue:n(r.getValue())},[])}const H=r=>{if(!(!r||typeof r!="object"))return r},ve=({adapter:r,key:t})=>({getItem:async n=>{const s=await r.getItem(t),i=H(s)??{};if(n in i)return i[n]},setItem:async(n,s)=>{const i=await r.getItem(t),a=H(i)??{};await r.setItem(t,{...a,[n]:s})}}),$e=r=>({getItem:async t=>{const n=await r.getItem(t);if(n)return JSON.parse(n)},setItem:async(t,n)=>{await r.setItem(t,JSON.stringify(n))}}),we=r=>({getItem:async t=>{const n=r.getItem(t);if(n)return JSON.parse(n)},setItem:async(t,n)=>{r.setItem(t,JSON.stringify(n))}}),j="__reactjrx",Ee=r=>{if(typeof r=="object"&&r!==null&&j in r&&r[j]===j)return r},Ce=async({adapter:r,signal:t,version:n})=>{const i={value:t.getValue(),[j]:j,migrationVersion:n};await r.setItem(t.config.key,i)},Me=({adapter:r,version:t,signal:n})=>e.from(r.getItem(n.config.key)).pipe(e.switchMap(s=>{const i=Ee(s);return!i||i.migrationVersion!==void 0&&t>i.migrationVersion||n.setValue(s.value),e.of(s)})),Re=({entries:r=[],onReady:t,adapter:n=we(localStorage)})=>{const s=R(r),i=R(t),a=R(n),u=N(()=>{const p=s.current;return(p.length===0?e.of(!0):e.zip(...p.map(({signal:d,version:h})=>Me({adapter:a.current,signal:d,version:h}))).pipe(e.map(()=>!0))).pipe(e.tap(()=>{i.current!=null&&i.current()}),e.catchError(d=>(console.error("Unable to hydrate",d),e.EMPTY)))},{defaultValue:!1},[]);return Y(()=>u?e.merge(...s.current.map(({signal:p,version:f})=>p.subject.pipe(e.throttleTime(500,e.asyncScheduler,{trailing:!0}),e.switchMap(()=>e.from(Ce({adapter:a.current,signal:p,version:f})))))):e.EMPTY,[u,a]),{isHydrated:u}},Oe=()=>{const r=K({onBeforeComplete:()=>{r.current.next()}});return r};function q(r,t){return Math.min(r,t)}function ee(r,t){return Math.pow(2,r)*t}function te(r){const{initialInterval:t,maxRetries:n=1/0,maxInterval:s=1/0,shouldRetry:i=()=>!0,resetOnSuccess:a=!1,backoffDelay:u=ee}=r;return p=>e.defer(()=>{let f=0;const d=(h,g)=>h<n&&i(h,g);return p.pipe(P.catchError(h=>{var l;if(f++,!d(f-1,h))throw h;const g=(l=r.caughtError)==null?void 0:l.call(r,f,h);if(!g)throw h;return e.merge(g,e.throwError(()=>h))}),P.retryWhen(h=>h.pipe(P.concatMap(g=>{const l=f-1;return e.iif(()=>d(l,g),e.timer(q(u(l,t),s)),e.throwError(()=>g))}))),P.catchError(h=>{if(r.catchError)return r.catchError(f,h);throw h}),P.tap(()=>{a&&(f=0)}))})}const re=b.createContext({client:null}),xe=({client:r})=>(b.useEffect(()=>{const t=r.mount();return()=>{t()}},[r]),null),Te=b.memo(({children:r,client:t})=>{const n=b.useMemo(()=>({client:t}),[t]);return D.jsxs(re.Provider,{value:n,children:[D.jsx(xe,{client:n.client}),r]})}),G=({unsafe:r=!1}={})=>{const t=b.useContext(re);if(!r&&t.client===null)throw new Error("You forgot to register the provider");return t.client},L=r=>Array.isArray(r)?r.reduce((t,n,s)=>s===r.length-1?`${t}${L(n)}]`:`${t}${L(n)},`,"["):r===void 0?"":JSON.stringify(r,Object.keys(r).sort()),O=r=>r.length===0?"[]":L(r),ne=(r=21)=>crypto.getRandomValues(new Uint8Array(r)).reduce((t,n)=>(n&=63,n<36?t+=n.toString(36):n<62?t+=(n-26).toString(36).toUpperCase():n>62?t+="-":t+="_",t),""),U=()=>({context:void 0,data:void 0,error:null,status:"idle",submittedAt:0,variables:void 0,failureCount:0,failureReason:null,isPaused:!1});function I(r){return r!=null}function C(r,t){if(r==null||t===void 0||typeof r!="object"||typeof t!="object")return r===t;if(r.constructor!==(t==null?void 0:t.constructor))return!1;const n=Object.keys(r),s=Object.keys(t);if(n.length!==s.length)return!1;for(const i of n)if(!t.hasOwnProperty(i)||r[i]!==t[i])return!1;return!0}function se(r){let t=0;return function(s){return new e.Observable(i=>{t++,r(t);const a=s.subscribe(i);return()=>{t--,r(t),a.unsubscribe()}})}}class Ve{constructor({__queryFinalizeHook:t}={}){S(this,"trigger$",new e.Subject);S(this,"mapOperator$",new e.BehaviorSubject("merge"));S(this,"state$");const n=new e.BehaviorSubject(0),s=n.pipe(e.filter(a=>a===0)),i=this.mapOperator$.pipe(e.filter(I),e.distinctUntilChanged());this.state$=i.pipe(e.mergeMap(a=>{const u=a==="concat"?e.concatMap:a==="switch"?e.switchMap:e.mergeMap,p=this.trigger$.pipe(e.filter(()=>a==="merge"));return this.trigger$.pipe(e.takeUntil(i.pipe(e.skip(1))),u(({args:f,mutation:d})=>{const h=e.defer(()=>(d.execute(f),e.EMPTY)),g=d.observeTillFinished().pipe(e.last(),e.mergeMap(()=>d.state$),e.takeUntil(this.trigger$)),l=d.observeTillFinished().pipe(e.skip(1));return e.merge(l,g,h).pipe(t??e.identity,e.takeUntil(e.merge(s,p)))}),e.scan((f,d)=>({...f,...d,...d.status==="pending"&&{data:d.data??f.data},...d.status==="pending"&&{error:d.error??f.error}}),U()),e.distinctUntilChanged(({data:f,...d},{data:h,...g})=>C(d,g)&&C(f,h)))}),e.shareReplay({refCount:!0,bufferSize:1}),se(a=>{n.next(a)}))}trigger({args:t,options:n,mutation:s}){n.mapOperator&&this.mapOperator$.next(n.mapOperator),this.trigger$.next({args:t,options:n,mutation:s})}}var T;class ke{constructor(t,n={},s){S(this,"numberOfObservers",0);S(this,"mutationRunner");z(this,T,new e.BehaviorSubject(void 0));S(this,"observed$");S(this,"result$");S(this,"getObserverResultFromState",t=>({...U(),...t,isSuccess:t.status==="success",isPending:t.status==="pending",isIdle:t.status==="idle",isError:t.status==="error",mutate:this.mutate,reset:this.reset}));var i;this.client=t,this.options=n,this.options.mutationKey=((i=this.options)==null?void 0:i.mutationKey)??[ne()],this.mutationRunner=s??new Ve(this.options),this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this),this.result$=this.mutationRunner.state$.pipe(e.map(a=>({state:this.getObserverResultFromState(a),options:{}}))),x(this,T).pipe(e.filter(I),e.mergeMap(a=>this.mutationRunner.state$.pipe(e.takeUntil(a.mutation.observeTillFinished().pipe(e.last()))))).subscribe(),this.observed$=x(this,T).pipe(e.switchMap(a=>(a==null?void 0:a.mutation.state$.pipe(e.map(u=>({state:this.getObserverResultFromState(u),options:a.options}))))??e.EMPTY),e.mergeMap(({state:a,options:u})=>(a.status==="error"&&(u!=null&&u.onError&&(u==null||u.onError(a.error,a.variables,a.context)),u!=null&&u.onSettled&&(u==null||u.onSettled(a.data,a.error,a.variables,a.context))),a.status==="success"&&(u!=null&&u.onSuccess&&(u==null||u.onSuccess(a.data,a.variables,a.context)),u!=null&&u.onSettled&&(u==null||u.onSettled(a.data,a.error,a.variables,a.context))),e.EMPTY)))}setOptions(t){this.options=this.client.defaultMutationOptions({mutationKey:this.options.mutationKey,...t}),this.options.mutationKey&&this.client.getMutationCache().findAll({exact:!0,mutationKey:this.options.mutationKey}).forEach(n=>{n.setOptions(t)})}observe(){var s;const t=this.getObserverResultFromState(((s=x(this,T).getValue())==null?void 0:s.mutation.state)??U());return{result$:e.merge(this.observed$,this.result$).pipe(e.map(({state:i})=>(console.log({state:i}),i))),lastValue:t}}subscribe(t){const n=this.observe().result$.subscribe(s=>{t(s)});return()=>{n.unsubscribe()}}async mutate(t,n={}){const s=this.client.getMutationCache().build(this.client,this.options);return x(this,T).next({mutation:s,options:n}),this.mutationRunner.trigger({args:t,options:this.options,mutation:s}),await new Promise((i,a)=>{s.observeTillFinished().pipe(e.last()).subscribe({error:u=>{a(u)},next:u=>{u.error?a(u.error):i(u.data)}})})}getCurrentResult(){var n;const t=this.client.getMutationCache().find({exact:!0,mutationKey:(n=this.options)==null?void 0:n.mutationKey});return this.getObserverResultFromState((t==null?void 0:t.state)??U())}reset(){var t;(t=x(this,T).getValue())==null||t.mutation.reset()}cancel(){var t;console.log("cancel"),(t=x(this,T).getValue())==null||t.mutation.destroy()}}T=new WeakMap;function Ue(){}function Ie(r,t){const n=G({unsafe:!!t}),s=t??n,i=R(r),a=J(()=>[ne()]),u=O(r.mutationKey??a.current),[p]=b.useState(()=>new ke(s,r));b.useEffect(()=>{},[p,r]);const f=b.useMemo(()=>p.observe(),[u,p]),d=N(f.result$)??f.lastValue,h=b.useCallback((g,l)=>{p.mutate(g,l).catch(Ue)},[p]);return b.useEffect(()=>()=>{i.current.cancelOnUnMount&&p.cancel()},[p,i]),{...d,mutate:h,mutateAsync:d.mutate}}const ie=(r,t)=>r.length===t.length&&r.every((n,s)=>n===t[s]),Qe=r=>r.pipe(e.switchMap(({options:{refetchOnWindowFocus:t=!0}})=>{const n=typeof t=="function"?t({}):t;return n!==!1?e.merge(e.fromEvent(document,"visibilitychange").pipe(e.filter(()=>!document.hidden),e.map(()=>({type:"refetch",ignoreStale:n==="always"}))),e.fromEvent(window,"focus").pipe(e.map(()=>({type:"refetch",ignoreStale:n==="always"})))):e.EMPTY})),Pe=r=>r.pipe(e.switchMap(({options:{refetchOnReconnect:t=!0}})=>{const n=typeof t=="function"?t({}):t;return n!==!1?e.fromEvent(window,"online").pipe(e.map(()=>({type:"refetch",ignoreStale:n==="always"}))):e.EMPTY})),je=({queryKey:r,queryFn:t,...n})=>{const s=X({queryKey:r,options:n,queryFn:t});return b.useEffect(()=>{s.current.next({queryKey:r,options:n,queryFn:t})},[r,n,t,s]),s},Fe={data:void 0,isLoading:!0,error:void 0,status:"loading",fetchStatus:"idle"};function Le({queryKey:r,queryFn:t,...n}){const s=K(),i=G(),a=je({queryFn:t,queryKey:r,...n}),u=N(()=>{const f=a.current.pipe(e.map(({queryKey:v})=>v??[])),d=e.of(null),h=f.pipe(e.distinctUntilChanged(ie),e.skip(1)),g=v=>!!v&&typeof v!="function",l=a.current.pipe(e.map(({queryFn:v})=>v),e.filter(g),e.distinctUntilChanged(C),g(a.current.getValue().queryFn)?e.skip(1):e.identity),c=a.current.pipe(e.map(({queryFn:v})=>v),e.filter(I)),o=a.current.pipe(e.map(({options:v})=>v)),m=Qe(a.current),w=Pe(a.current),y=e.merge(d,h,l),V=e.merge(s.current,e.merge(m,w).pipe(e.throttleTime(500)));return y.pipe(e.withLatestFrom(f),e.switchMap(([,v])=>{const{result$:$}=i.client.query({key:v,fn$:c,options$:o,trigger$:V});return $.pipe(e.scan((M,{data:k,...B})=>({data:void 0,...M,...B,isLoading:B.status==="loading",...k&&{data:k.result}}),{}))}))},{defaultValue:{...Fe,isLoading:a.current.getValue().options.enabled!==!1}},[i]),p=b.useCallback(()=>{s.current.next({type:"refetch",ignoreStale:!0})},[s]);return{...u,refetch:p}}function _e(r,t,n=[]){const i=(t!=null&&!Array.isArray(t)?t:{}).retry??!0,a=typeof r=="function",u=b.useCallback(a?r:()=>r,a?n:[r]),p=b.useCallback(()=>u().pipe(e.catchError(f=>{throw console.error(f),f}),i?e.retry():e.identity),[u,i]);Y(p,n)}const ae=({retryDelay:r,retry:t,...n})=>te({initialInterval:typeof r=="number"?r:100,...typeof t=="function"?{shouldRetry:t}:{maxRetries:t===!1?0:t??0},...n}),Ne=r=>r.pipe(e.scan((t,n)=>({...t,...n}),{data:void 0,error:void 0,fetchStatus:"idle",status:"loading"}),e.distinctUntilChanged(({data:t,...n},{data:s,...i})=>C(n,i)&&C(t,s))),Ae={backgroundColor:"transparent",color:"inherit"};function ue(r){const t={namespaces:[{name:"@reactjrx",style:{backgroundColor:"#d02f4e",color:"white"}}],namespace(n,s){const i=ue(r);return i.namespaces.push({name:n,style:s??Ae}),i},printNamespaces(){return{namespaces:t.namespaces.map(({name:n})=>`%c ${n} %c`).join(" "),styles:t.namespaces.reduce((n,{style:s})=>(n.push(`background-color: ${s.backgroundColor}; color: ${s.color};`),n.push("background-color: transparent; color: inherit;"),n),[])}},print(n,...s){if(r==="development"){const{namespaces:i,styles:a}=t.printNamespaces();console[n](i,...a,...s)}return t},printWithoutNamespace(n,...s){return r==="development"&&console[n](...s),t},log(...n){return t.print("log",...n)},warn(...n){return t.print("warn",...n)},error(...n){return t.print("error",...n)},group(...n){return t.print("group",...n)},groupEnd(){return r==="development"&&console.groupEnd(),t}};return t}const Q=ue("production"),Ye=Q.namespace("store"),Ke=r=>r.pipe(e.map(t=>[...t.keys()].reduce((n,s)=>{var i;return n[s]=(i=t.get(s))==null?void 0:i.getValue(),n},{})),e.distinctUntilChanged(C)).subscribe(t=>{Ye.log("store","update",t)}),ze=()=>{const r=new Map,t=new e.BehaviorSubject(r),n=new e.Subject,s=new e.Subject,i=()=>{t.next(r)},a=(c,o)=>{r.set(c,new e.BehaviorSubject(o)),i()},u=c=>{var o;return(o=r.get(c))==null?void 0:o.getValue()},p=c=>t.pipe(e.map(()=>r.get(c)),e.filter(I),e.map(o=>o.getValue()),e.distinctUntilChanged(C)),f=(c,o)=>{const m=r.get(c);m&&(typeof o=="function"?m.next({...m.getValue(),...o(m.getValue())}):m.next({...m.getValue(),...o}),t.next(r))},d=(c,o=()=>!0)=>{r.forEach(m=>{const w=m.getValue();o(w)&&m.next({...w,...c})}),t.next(r)},h=c=>{r.delete(c),t.next(r)},g=(c,o)=>(f(c,m=>({...m,runners:[...m.runners,o]})),()=>{var w;const m=((w=r.get(c))==null?void 0:w.getValue().runners.filter(y=>y!==o))??[];f(c,y=>({...y,runners:m}))}),l=()=>{const c=Ke(t);return()=>{c.unsubscribe()}};return{set:a,get:u,get$:p,delete:h,update:f,keys:()=>r.keys(),updateMany:d,addRunner:g,store$:t,queryEvent$:n.asObservable(),dispatchQueryEvent:c=>{n.next(c)},queryTrigger$:s.asObservable(),dispatchQueryTrigger:c=>{s.next(c)},size:()=>r.size,start:l}},We=({options$:r,queryStore:t,key:n})=>{const i=r.pipe(e.map(({enabled:a=!0})=>a),e.distinctUntilChanged()).pipe(e.skip(1),e.filter(a=>a));return e.merge(t.queryTrigger$.pipe(e.filter(a=>n===a.key),e.map(({trigger:a})=>a)),i.pipe(e.map(()=>({type:"enabled",ignoreStale:!1}))))},Je=(r,t)=>n=>r===O([])?n:e.defer(()=>{var u;const s=(u=t.get(r))==null?void 0:u.deduplication_fn;if(s)return s;let i;const a=()=>{var p;((p=t.get(r))==null?void 0:p.deduplication_fn)===i&&t.update(r,{deduplication_fn:void 0})};return i=n.pipe(e.tap({error:a,complete:a}),e.finalize(a),e.shareReplay({refCount:!0,bufferSize:1})),t.update(r,{deduplication_fn:i}),i}),Ge=r=>t=>t.pipe(e.withLatestFrom(r),e.map(([n,s])=>{var i,a;return n.error?(i=s.onError)==null||i.call(s,n.error):(a=s.onSuccess)==null||a.call(s,n),n})),Be=({queryStore:r,serializedKey:t,options:n})=>s=>s.pipe(e.tap(({data:i})=>{if(i!=null&&i.result){const a=i==null?void 0:i.result;r.update(t,{...n.cacheTime!==0&&{cache_fnResult:{result:a}}})}})),De=({options$:r,options:t,fn:n,queryStore:s,serializedKey:i,trigger:a,trigger$:u})=>{const f=r.pipe(e.map(({enabled:y=!0})=>y),e.distinctUntilChanged()).pipe(e.distinctUntilChanged(),e.filter(y=>!y)),h=e.defer(()=>{const y=typeof n=="function"?n():n;return e.from(y)}).pipe(ae(t),Je(i,s),e.tap(()=>{s.dispatchQueryEvent({key:i,type:"fetchSuccess"}),s.update(i,{lastFetchedAt:new Date().getTime()})}),e.map(y=>({status:"success",data:{result:y},error:void 0})),e.endWith({fetchStatus:"idle"}),e.catchError(y=>(s.dispatchQueryEvent({key:i,type:"fetchError"}),e.of({fetchStatus:"idle",status:"error",data:void 0,error:y}))),Ge(r),Be({serializedKey:i,options:t,queryStore:s})),g=s.queryEvent$.pipe(e.filter(y=>y.key===i&&y.type==="queryDataSet"),e.map(()=>{var y,V;return(V=(y=s.get(i))==null?void 0:y.cache_fnResult)==null?void 0:V.result}),e.filter(I),e.map(y=>({status:"success",data:{result:y}})),e.delay(1)),l=e.merge(f.pipe(e.take(1),e.map(()=>({fetchStatus:"idle"}))),e.merge(e.of({fetchStatus:"fetching",error:void 0}),h).pipe(e.takeUntil(f)),g).pipe(e.takeUntil(u)),c=s.get(i),o=c==null?void 0:c.cache_fnResult,m=!!o,w=a.type==="refetch"&&a.ignoreStale;return m?!(c!=null&&c.isStale)&&!w?e.of({fetchStatus:"idle",status:"success",data:{result:o.result},error:void 0}):e.merge(e.of({fetchStatus:"fetching",status:"success",data:{result:o.result},error:void 0}),l):l},A=(r,t,{exact:n=!1}={})=>n?O(r)===O(t):r.reduce((s,i,a)=>s?i===void 0&&!r.slice(a,r.length-1).some(p=>p!==void 0)?!0:L(i)===L(t[a]):!1,!0),F=Q.namespace("invalidation"),He=({queryStore:r})=>({invalidateQueries:({queryKey:n,exact:s=!1,predicate:i}={})=>{let a=[];n?(F.log("invalidation requested for",n),r.updateMany({isStale:!0},u=>{const p=A(n,u.queryKey,{exact:s});return p&&a.push(O(u.queryKey)),p})):i?r.updateMany({isStale:!0},u=>{const p=i(u);return p&&a.push(O(u.queryKey)),p}):(F.log("Invalidation requested for all queries"),r.updateMany({isStale:!0}),a=Array.from(r.keys())),a.forEach(u=>{r.update(u,{deduplication_fn:void 0}),r.dispatchQueryTrigger({key:u,trigger:{ignoreStale:!0,type:"refetch"}})})}}),Xe=r=>({pipeQueryResult:({options$:s})=>i=>{const a=i.pipe(e.share());return e.merge(a,a.pipe(e.filter(u=>!!u.data&&u.fetchStatus!=="fetching"),e.distinctUntilChanged((u,p)=>u.data===p.data),e.withLatestFrom(s),e.map(([,{refetchInterval:u}])=>u),e.filter(I),e.switchMap(u=>typeof u=="number"?e.timer(u).pipe(e.map(()=>({type:"refetch",ignoreStale:!0})),e.switchMap(()=>e.EMPTY)):e.EMPTY)))},refetchQueries:s=>{}}),Ze=(r,t)=>r.filter(n=>!t.includes(n)),qe=(r,t)=>r.store$.pipe(e.map(n=>[...n.keys()]),e.startWith([]),e.pairwise(),e.mergeMap(([n,s])=>{const i=Ze(s,n);return e.merge(...i.map(a=>{const u=r.store$.pipe(e.map(()=>r.get(a)),e.filter(p=>p===void 0));return e.merge(e.NEVER,e.of(a)).pipe(e.tap(()=>{}),t,e.finalize(()=>{}),e.takeUntil(u))}))})),ce=r=>r.pipe(e.switchMap(t=>e.combineLatest(t.runners)),e.map(t=>t.map(({options:n})=>n))),et=r=>r.pipe(e.map(t=>t.reduce((n,s)=>({...n,lowestStaleTime:s.staleTime===void 0?n.lowestStaleTime:Math.min(s.staleTime??1/0,n.lowestStaleTime??1/0)}),{lowestStaleTime:void 0})),e.distinctUntilChanged(C)),tt=r=>t=>t.pipe(e.filter(n=>n.key===r&&(n.type==="fetchError"||n.type==="fetchSuccess"))),rt=({queryStore:r})=>t=>t.pipe(e.switchMap(n=>{const s=r.get$(n);return r.queryEvent$.pipe(tt(n),e.switchMap(()=>s.pipe(ce,et,e.tap(({lowestStaleTime:i=0})=>{var a;i===0?(F.log(n,"marked as stale!",{staleTime:i}),r.update(n,{isStale:!0})):(a=r.get(n))!=null&&a.isStale&&(F.log(n,"marked non stale",{staleTime:i}),r.update(n,{isStale:!1}))}),e.filter(({lowestStaleTime:i})=>i!==1/0&&i!==0),e.switchMap(({lowestStaleTime:i=0})=>e.timer(i)),e.tap(()=>{var i;(i=r.get(n))!=null&&i.isStale||(F.log(n,"marked as stale!"),r.update(n,{isStale:!0}))}))),e.map(()=>n))})),nt=r=>r.pipe(e.map(t=>t.reduce((n,s)=>({...n,lowestCacheTime:s.cacheTime===void 0?n.lowestCacheTime:Math.min(s.cacheTime??1/0,n.lowestCacheTime??1/0)}),{lowestCacheTime:void 0})),e.distinctUntilChanged(C)),st=r=>r.pipe(e.map(t=>t.cache_fnResult),e.distinctUntilChanged(C)),it=({queryStore:r})=>t=>t.pipe(e.switchMap(n=>{const s=r.get$(n);return s.pipe(st,e.switchMap(()=>s.pipe(ce,nt,e.switchMap(({lowestCacheTime:a=5*60*1e3})=>e.timer(a).pipe(e.tap(()=>{r.update(n,{cache_fnResult:void 0})})))))).pipe(e.map(()=>n))})),at=({queryStore:r})=>t=>t.pipe(e.switchMap(n=>r.get$(n).pipe(e.filter(i=>!i.cache_fnResult),e.map(i=>i.runners.length>0),e.pairwise(),e.filter(([i,a])=>i&&!a),e.tap(()=>{r.delete(n)}),e.map(()=>n)))),oe=({key:r})=>({isStale:!0,queryKey:r,runners:[]}),ut=({queryStore:r,serializedKey:t,runner$:n,options$:s,key:i})=>a=>a.pipe(e.withLatestFrom(s),e.map(([u,p])=>i.length===0?[u,void 0]:u.type!=="initial"?[u,void 0]:(r.get(t)?r.update(t,{queryKey:i,...p.markStale&&{isStale:!0}}):r.set(t,oe({key:i})),[u,r.addRunner(t,n)]))),ct=Q.namespace("cache"),ot=({queryStore:r})=>({setQueryData:({queryKey:n,updater:s})=>{const i=O(n);n.length!==0&&(ct.log("set cache for query",O),r.get(i)||r.set(i,oe({key:n})),r.update(i,a=>{var u;return typeof s=="function"?{...a,cache_fnResult:{result:s((u=a.cache_fnResult)==null?void 0:u.result)}}:{...a,cache_fnResult:{result:s}}}),r.dispatchQueryEvent({key:i,type:"queryDataSet"}))}}),lt=Q.namespace("refetch"),pt=({key:r,serializedKey:t,queryStore:n})=>s=>s.pipe(e.tap(i=>{if(i.type!=="refetch")return;const a=n.get(t);a&&i.ignoreStale&&!a.isStale&&(lt.log(r,"marked stale by trigger!"),n.update(t,{isStale:!0}))})),ft=({queryStore:r,serializedKey:t})=>n=>n.pipe(e.tap(s=>{s.type==="refetch"&&(r.update(t,{deduplication_fn:void 0}),r.dispatchQueryTrigger({key:t,trigger:s}))}),e.filter(s=>s.type!=="refetch")),E=r=>e.defer(()=>{const t=r();return t instanceof Promise?e.from(t):t instanceof e.Observable?t:e.of(t)}),dt=({variables:r,state:t,options:n})=>{const s=t.isPaused,i=async()=>await Promise.reject(new Error("No mutationFn found")),a=n.mutationFn??i,p=e.iif(()=>s,e.of(t.context),E(()=>{var l;return((l=n.onMutate)==null?void 0:l.call(n,r))??void 0})).pipe(e.share()),f=(l,c,o)=>(console.error(l),E(()=>{var w;return(w=n.onError)==null?void 0:w.call(n,l,r,c)}).pipe(e.catchError(()=>e.of(l)),e.map(()=>({failureCount:o,error:l,failureReason:l,context:c,status:"error"})))),d=p.pipe(e.switchMap(l=>(typeof a=="function"?E(()=>a(r)):a).pipe(e.map(o=>({result:{data:o},error:null,context:l})),ae({...n,caughtError:(o,m)=>e.of({failureCount:o,failureReason:m}),catchError:(o,m)=>f(m,l,o).pipe(e.map(w=>({...w,result:void 0})))}),e.takeWhile(({result:o,error:m})=>(o==null?void 0:o.data)===void 0&&m===void 0,!0)))),h=e.of({...t,variables:r,status:"pending",isPaused:!1,failureCount:0,failureReason:null,submittedAt:t.submittedAt??new Date().getTime()});return e.merge(h,p.pipe(e.map(l=>({context:l}))),d.pipe(e.switchMap(({result:l,error:c,...o})=>{if(!l&&!c)return e.of({...o});const m=c?e.of(null):E(()=>{var v;return(v=n.onSuccess)==null?void 0:v.call(n,l==null?void 0:l.data,r,o.context)}),y=E(()=>{var v;return(v=n.onSettled)==null?void 0:v.call(n,l==null?void 0:l.data,c,r,o.context)}).pipe(e.catchError(v=>l?e.of(l):e.of(v)));return e.concat(m,y).pipe(e.toArray(),e.map(()=>c?{error:c,data:void 0,variables:r,...o}:{status:"success",error:c,data:l==null?void 0:l.data,variables:r,...o}),e.catchError(v=>f(v,o.context,0).pipe(e.map($=>({...$,data:void 0})))))}))).pipe(e.scan((l,c)=>({...l,...c,data:c.data??l.data,error:c.error??l.error}),U()),e.distinctUntilChanged(({data:l,...c},{data:o,...m})=>C(c,m)&&C(l,o)))};class ht{constructor({options:t,mutationCache:n,state:s}){S(this,"mutationCache");S(this,"observerCount",new e.BehaviorSubject(0));S(this,"destroySubject",new e.Subject);S(this,"resetSubject",new e.Subject);S(this,"executeSubject",new e.Subject);S(this,"state",U());S(this,"state$");S(this,"options");S(this,"observerCount$",this.observerCount.asObservable());S(this,"destroyed$",this.destroySubject.asObservable());this.options=t,this.mutationCache=n,this.state=s??this.state;const i=e.of(this.state),a=this.resetSubject.pipe(e.map(()=>U())),u=this.executeSubject.pipe(e.switchMap(p=>dt({options:{...this.options,onMutate:f=>{const d=E(()=>{var g,l;return(l=(g=n.config).onMutate)==null?void 0:l.call(g,f,this)}),h=E(()=>{var g,l;return((l=(g=this.options).onMutate)==null?void 0:l.call(g,f))??void 0});return d.pipe(e.mergeMap(()=>h))},onError:(f,d,h)=>{const g=E(()=>{var c,o;return(o=(c=n.config).onError)==null?void 0:o.call(c,f,d,h,this)}),l=E(()=>{var c,o;return(o=(c=this.options).onError)==null?void 0:o.call(c,f,d,h)});return e.concat(g,l).pipe(e.toArray())},onSettled:(f,d,h,g)=>{const l=E(()=>{var o,m;return(m=(o=n.config).onSettled)==null?void 0:m.call(o,f,d,h,g,this)}),c=E(()=>{var o,m;return(m=(o=this.options).onSettled)==null?void 0:m.call(o,f,d,h,g)});return e.concat(l,c).pipe(e.toArray())},onSuccess:(f,d,h)=>{const g=E(()=>{var c,o;return(o=(c=n.config).onSuccess)==null?void 0:o.call(c,f,d,h,this)}),l=E(()=>{var c,o;return(o=(c=this.options).onSuccess)==null?void 0:o.call(c,f,d,h)});return e.concat(g,l).pipe(e.toArray())}},state:this.state,variables:p})),e.tap(p=>{this.state={...this.state,...p}}),e.takeUntil(this.destroySubject));this.state$=e.merge(i,u,a).pipe(e.shareReplay({bufferSize:1,refCount:!1}),e.takeUntil(this.destroySubject),se(p=>{this.observerCount.next(p)}))}get meta(){return this.options.meta}setOptions(t){this.options={...this.options,...t}}observeTillFinished(){return this.state$.pipe(e.takeWhile(t=>t.status!=="error"&&t.status!=="success",!0))}execute(t){return this.executeSubject.next(t),this.executeSubject.complete(),this.observeTillFinished()}continue(){return this.execute(this.state.variables)}destroy(){this.destroySubject.next(),this.destroySubject.complete(),this.executeSubject.complete()}reset(){this.resetSubject.next(),this.resetSubject.complete(),this.destroy()}}const W=({mutationKey:r,status:t,predicate:n,exact:s=!0}={})=>a=>s&&r!==void 0&&a.options.mutationKey!==void 0&&!A(a.options.mutationKey,r,{exact:s})||!s&&r!==void 0&&a.options.mutationKey!==void 0&&!A(r,a.options.mutationKey,{exact:s})||t&&a.state.status!==t?!1:n?n(a):!0;class le{constructor(t={}){S(this,"mutationsSubject",new e.BehaviorSubject([]));S(this,"mutations$",this.mutationsSubject.pipe(e.map(t=>t.map(n=>n)),e.distinctUntilChanged(ie),e.share()));S(this,"added$",this.mutations$.pipe(e.pairwise(),e.map(([t,n])=>n.filter(s=>!t.includes(s))[0]),e.filter(I),e.share()));S(this,"removed$",this.mutations$.pipe(e.pairwise(),e.map(([t,n])=>t.filter(s=>!n.includes(s))),e.mergeMap(t=>e.from(t)),e.share()));S(this,"stateChange$",this.added$.pipe(e.mergeMap(t=>t.state$.pipe(e.map(()=>t),e.takeUntil(this.removed$.pipe(e.filter(n=>n===t))))),e.share()));this.config=t}build(t,n,s){const i=new ht({mutationCache:this,options:t.defaultMutationOptions(n),state:s});return i.state$.pipe(e.filter(({status:a})=>a==="success"||a==="error"),e.switchMap(()=>i.observerCount$.pipe(e.filter(a=>a<=1),e.take(1))),e.switchMap(()=>e.timer(i.options.gcTime??5*60*1e3)),e.take(1)).subscribe({complete:()=>{this.mutationsSubject.next(this.mutationsSubject.getValue().filter(a=>i!==a))}}),this.mutationsSubject.next([...this.mutationsSubject.getValue(),i]),i}getAll(){return this.findAll()}remove(t){const n=this.mutationsSubject.getValue().find(s=>s===t);n==null||n.destroy()}find(t){const n={exact:!0,...t},s=W(n);return this.mutationsSubject.getValue().find(i=>s(i))}findAll(t={}){const n={exact:!0,...t},s=W(n);return this.mutationsSubject.getValue().filter(i=>s(i)).map(i=>i)}observe({filters:t,select:n}={}){const s=W(t),i=n??(p=>p.state),a=this.getAll().reduce((p,f)=>[...p,f],[]).filter(s).map(p=>i(p));return{value$:this.stateChange$.pipe(e.startWith(),e.map(()=>this.getAll().filter(s).map(i)),e.distinctUntilChanged(C)),lastValue:a}}subscribe(t){const n=e.merge(this.added$.pipe(e.tap(s=>{t({type:"added",mutation:s})})),this.removed$.pipe(e.tap(s=>{t({type:"removed",mutation:s})})),this.stateChange$.pipe(e.tap(s=>{t({type:"updated",action:{...s.state,type:"success"},mutation:s})}))).subscribe();return()=>{n.unsubscribe()}}resumePausedMutations(){const t=this.findAll({predicate:s=>s.state.isPaused});if(!t.length)return e.EMPTY;const n=t.map(s=>s.continue());return e.combineLatest(n)}clear(){this.getAll().forEach(t=>{this.remove(t)})}}const pe=()=>{const r=ze(),t=He({queryStore:r}),n=ot({queryStore:r}),s=Xe();let i=!1;const a=({key:d,fn$:h,fn:g,trigger$:l=new e.Subject,options$:c=new e.BehaviorSubject({})})=>{if(!i)throw new Error("You forgot to start client");const o=O(d),m=h??(g?e.of(g):e.NEVER);Q.log("query$)",o);const w=c.pipe(e.map($=>({options:$})));let y=()=>{};const V=e.merge(l.pipe(ft({queryStore:r,serializedKey:o})),We({options$:c,key:o,queryStore:r})).pipe(e.share());return{result$:e.merge(e.of({type:"initial"}),V).pipe(ut({key:d,queryStore:r,runner$:w,serializedKey:o,options$:c}),e.map(([$,M])=>(M&&(y=M),$)),pt({key:d,options$:c,queryStore:r,serializedKey:o}),e.withLatestFrom(m,c),e.map(([$,M,k])=>({trigger:$,fn:M,options:k})),e.map($=>(Q.log(o,"query trigger",{trigger:$.trigger,options:$.options}),$)),e.filter(({options:$})=>$.enabled!==!1),e.mergeMap(({fn:$,options:M,trigger:k})=>De({options$:c,options:M,fn:$,queryStore:r,serializedKey:o,trigger:k,trigger$:V})),Ne,e.withLatestFrom(c),e.takeWhile(([$,M])=>!($.data!==void 0&&M.terminateOnFirstResult),!0),e.map(([$])=>$),e.finalize(()=>{y()}))}},u=qe(r,d=>d.pipe(e.switchMap(h=>{const g=e.of(h);return e.merge(it({queryStore:r})(g),rt({queryStore:r})(g),at({queryStore:r})(g))})));return{start:()=>{i=!0;const d=u.subscribe(),h=[r.start()];return()=>{h.forEach(g=>{g()}),d.unsubscribe()}},query:a,queryStore:r,...t,...n,...s,destroy:()=>{}}};var _;class gt{constructor({mutationCache:t}={mutationCache:new le}){S(this,"client");S(this,"mutationCache");z(this,_,new Map);this.mutationCache=t,this.client=pe()}mount(){const t=this.client.start();return()=>{t()}}getMutationCache(){return this.mutationCache}defaultMutationOptions(t){return{...(t==null?void 0:t.mutationKey)&&this.getMutationDefaults(t.mutationKey),...t}}getMutationDefaults(t){const n=[...x(this,_).values()];let s={};return n.forEach(i=>{A(t,i.mutationKey)&&(s={...s,...i.defaultOptions})}),s}setMutationDefaults(t,n){x(this,_).set(O(t),{mutationKey:t,defaultOptions:n})}async resumePausedMutations(){return await e.lastValueFrom(this.mutationCache.resumePausedMutations())}clear(){}}_=new WeakMap;exports.MutationCache=le;exports.QueryClient=gt;exports.QueryClientProvider=Te;exports.SIGNAL_RESET=Z;exports.createClient=pe;exports.createLocalforageAdapter=$e;exports.createSharedStoreAdapter=ve;exports.exponentialBackoffDelay=ee;exports.getDelay=q;exports.retryBackoff=te;exports.signal=ye;exports.trigger=be;exports.useBehaviorSubject=X;exports.useLiveRef=R;exports.useMutation=Ie;exports.useObserve=N;exports.useObserveCallback=me;exports.usePersistSignals=Re;exports.useQuery=Le;exports.useQueryClient=G;exports.useSignalValue=Se;exports.useSubject=K;exports.useSubscribe=Y;exports.useSubscribeEffect=_e;exports.useUnmountObservable=Oe;