reactjrx 1.110.0 → 1.112.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/dist/index.cjs +132 -2831
  2. package/dist/index.d.ts +2 -9
  3. package/dist/index.js +116 -2799
  4. package/dist/lib/queries/useConcatMutation$.d.ts +99 -0
  5. package/dist/lib/{deprecated/client/utils → utils}/makeObservable.d.ts +8 -8
  6. package/dist/lib/utils/react/useLiveRef.d.ts +1 -1
  7. package/dist/tests/utils.d.ts +0 -10
  8. package/package.json +11 -9
  9. package/dist/lib/deprecated/client/QueryClient.d.ts +0 -48
  10. package/dist/lib/deprecated/client/QueryClient.rq.test.d.ts +0 -1
  11. package/dist/lib/deprecated/client/QueryClient.types.rq.test.d.ts +0 -1
  12. package/dist/lib/deprecated/client/focusManager.d.ts +0 -19
  13. package/dist/lib/deprecated/client/focusManager.rq.test.d.ts +0 -1
  14. package/dist/lib/deprecated/client/keys/hashKey.d.ts +0 -3
  15. package/dist/lib/deprecated/client/keys/hashKey.test.d.ts +0 -1
  16. package/dist/lib/deprecated/client/keys/matchKey.d.ts +0 -4
  17. package/dist/lib/deprecated/client/keys/matchKey.test.d.ts +0 -1
  18. package/dist/lib/deprecated/client/keys/nanoid.d.ts +0 -1
  19. package/dist/lib/deprecated/client/keys/partialMatchKey.d.ts +0 -5
  20. package/dist/lib/deprecated/client/keys/partialMatchKey.rq.test.d.ts +0 -1
  21. package/dist/lib/deprecated/client/keys/types.d.ts +0 -10
  22. package/dist/lib/deprecated/client/mutations/cache/MutationCache.d.ts +0 -24
  23. package/dist/lib/deprecated/client/mutations/cache/mutationCache.rq.test.d.ts +0 -1
  24. package/dist/lib/deprecated/client/mutations/cache/types.d.ts +0 -68
  25. package/dist/lib/deprecated/client/mutations/mutation/Mutation.d.ts +0 -35
  26. package/dist/lib/deprecated/client/mutations/mutation/delayWhenNetworkOnline.d.ts +0 -4
  27. package/dist/lib/deprecated/client/mutations/mutation/executeMutation.d.ts +0 -7
  28. package/dist/lib/deprecated/client/mutations/mutation/mutation.options.test.d.ts +0 -1
  29. package/dist/lib/deprecated/client/mutations/mutation/observeUntilFinished.d.ts +0 -3
  30. package/dist/lib/deprecated/client/mutations/mutation/types.d.ts +0 -53
  31. package/dist/lib/deprecated/client/mutations/mutation/waitForNetworkOnError.d.ts +0 -6
  32. package/dist/lib/deprecated/client/mutations/mutations.test.d.ts +0 -1
  33. package/dist/lib/deprecated/client/mutations/observers/MutationObserver.d.ts +0 -38
  34. package/dist/lib/deprecated/client/mutations/observers/mutationObserver.rq.test.d.ts +0 -1
  35. package/dist/lib/deprecated/client/mutations/observers/mutationObserver.test.d.ts +0 -1
  36. package/dist/lib/deprecated/client/mutations/observers/types.d.ts +0 -65
  37. package/dist/lib/deprecated/client/mutations/runner/MutationRunner.d.ts +0 -20
  38. package/dist/lib/deprecated/client/mutations/runner/mutationRunner.test.d.ts +0 -1
  39. package/dist/lib/deprecated/client/mutations/types.d.ts +0 -53
  40. package/dist/lib/deprecated/client/mutations/utils/defaultMutationState.d.ts +0 -2
  41. package/dist/lib/deprecated/client/mutations/utils/distinctUntilStateChanged.d.ts +0 -3
  42. package/dist/lib/deprecated/client/mutations/utils/filters.d.ts +0 -3
  43. package/dist/lib/deprecated/client/onlineManager.d.ts +0 -10
  44. package/dist/lib/deprecated/client/queries/cache/QueryCache.d.ts +0 -33
  45. package/dist/lib/deprecated/client/queries/cache/types.d.ts +0 -45
  46. package/dist/lib/deprecated/client/queries/observer/QueryObserver.d.ts +0 -65
  47. package/dist/lib/deprecated/client/queries/observer/QueryObserver.rq.test.d.ts +0 -1
  48. package/dist/lib/deprecated/client/queries/observer/QueryObserver.types.rq.test.d.ts +0 -1
  49. package/dist/lib/deprecated/client/queries/observer/queryStateHelpers.d.ts +0 -9
  50. package/dist/lib/deprecated/client/queries/observer/types.d.ts +0 -242
  51. package/dist/lib/deprecated/client/queries/query/Query.d.ts +0 -71
  52. package/dist/lib/deprecated/client/queries/query/delayOnNetworkMode.d.ts +0 -6
  53. package/dist/lib/deprecated/client/queries/query/delayUntilFocus.d.ts +0 -2
  54. package/dist/lib/deprecated/client/queries/query/execution/completeFnIfNotMoreObservers.d.ts +0 -2
  55. package/dist/lib/deprecated/client/queries/query/execution/executeQuery.d.ts +0 -20
  56. package/dist/lib/deprecated/client/queries/query/getDefaultState.d.ts +0 -4
  57. package/dist/lib/deprecated/client/queries/query/operators.d.ts +0 -14
  58. package/dist/lib/deprecated/client/queries/query/query.rq.test.d.ts +0 -1
  59. package/dist/lib/deprecated/client/queries/query/query.test.d.ts +0 -1
  60. package/dist/lib/deprecated/client/queries/query/state/whenNewData.d.ts +0 -8
  61. package/dist/lib/deprecated/client/queries/query/types.d.ts +0 -95
  62. package/dist/lib/deprecated/client/queries/retryer/CancelledError.d.ts +0 -6
  63. package/dist/lib/deprecated/client/queries/retryer/types.d.ts +0 -4
  64. package/dist/lib/deprecated/client/queries/retryer/utils.d.ts +0 -2
  65. package/dist/lib/deprecated/client/queries/types.d.ts +0 -113
  66. package/dist/lib/deprecated/client/queries/utils.d.ts +0 -16
  67. package/dist/lib/deprecated/client/store.d.ts +0 -25
  68. package/dist/lib/deprecated/client/tests/utils.d.ts +0 -10
  69. package/dist/lib/deprecated/client/types.d.ts +0 -80
  70. package/dist/lib/deprecated/client/utils/keepPreviousData.d.ts +0 -1
  71. package/dist/lib/deprecated/react/QueryClientProvider.d.ts +0 -7
  72. package/dist/lib/deprecated/react/QueryClientProvider.rq.test.d.ts +0 -1
  73. package/dist/lib/deprecated/react/mutations/types.d.ts +0 -18
  74. package/dist/lib/deprecated/react/mutations/useIsMutating.d.ts +0 -3
  75. package/dist/lib/deprecated/react/mutations/useIsMutating.test.d.ts +0 -1
  76. package/dist/lib/deprecated/react/mutations/useMutation.d.ts +0 -4
  77. package/dist/lib/deprecated/react/mutations/useMutation.keys.test.d.ts +0 -1
  78. package/dist/lib/deprecated/react/mutations/useMutation.rq.test.d.ts +0 -1
  79. package/dist/lib/deprecated/react/mutations/useMutation.switch.test.d.ts +0 -1
  80. package/dist/lib/deprecated/react/mutations/useMutation.test.d.ts +0 -1
  81. package/dist/lib/deprecated/react/mutations/useMutationState.d.ts +0 -9
  82. package/dist/lib/deprecated/react/mutations/useMutationState.test.d.ts +0 -1
  83. package/dist/lib/deprecated/react/queries/QueryErrorResetBoundary.d.ts +0 -11
  84. package/dist/lib/deprecated/react/queries/QueryOptions.rq.types.typeTest.d.ts +0 -1
  85. package/dist/lib/deprecated/react/queries/errorBoundaryUtils.d.ts +0 -12
  86. package/dist/lib/deprecated/react/queries/isRestoring.d.ts +0 -3
  87. package/dist/lib/deprecated/react/queries/queryOptions.d.ts +0 -18
  88. package/dist/lib/deprecated/react/queries/types.d.ts +0 -11
  89. package/dist/lib/deprecated/react/queries/useBaseQuery.d.ts +0 -6
  90. package/dist/lib/deprecated/react/queries/useForeverQuery.d.ts +0 -8
  91. package/dist/lib/deprecated/react/queries/useIsFetching.d.ts +0 -3
  92. package/dist/lib/deprecated/react/queries/useIsFetching.rq.test.d.ts +0 -1
  93. package/dist/lib/deprecated/react/queries/useQuery.d.ts +0 -8
  94. package/dist/lib/deprecated/react/queries/useQuery.deduplication.test.d.ts +0 -1
  95. package/dist/lib/deprecated/react/queries/useQuery.invalidation.test.d.ts +0 -1
  96. package/dist/lib/deprecated/react/queries/useQuery.keys.test.d.ts +0 -1
  97. package/dist/lib/deprecated/react/queries/useQuery.rq.types.test.d.ts +0 -1
  98. package/dist/lib/deprecated/react/queries/useQuery.test.d.ts +0 -1
  99. package/dist/lib/deprecated/react/useQueryClient.d.ts +0 -2
package/dist/index.js CHANGED
@@ -1,20 +1,11 @@
1
1
  var __defProp = Object.defineProperty;
2
- var __typeError = (msg) => {
3
- throw TypeError(msg);
4
- };
5
2
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
3
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
- var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
8
- var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
9
- var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
10
- var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
11
- var _trigger$, _mutationRunner, _currentMutationSubject, _visibility$, _focusedSubject, _client, _currentQuery, _fetchSubject, _currentQueryInitialState, _lastResult, _lastQueryWithDefinedData, _observers, _observerCount, _cancelSubject, _executeSubject, _store, _defaultOptions, _initialState, _notifySubject, _store2, _mutationCache, _queryCache, _mutationDefaults, _queryDefaults, _defaultOptions2;
12
- import * as React from "react";
13
4
  import { useRef, useMemo, useCallback, useSyncExternalStore, useEffect, useState, createContext, memo, useContext } from "react";
14
- import { isObservable, from, of, defer, startWith, identity, distinctUntilChanged, tap, catchError, EMPTY, Subject, BehaviorSubject, skip, first, map, switchMap, zip, share, merge, throttleTime, asyncScheduler, concatMap, scan, throwError, timer, takeUntil, fromEvent, take, delay, defaultIfEmpty, Observable, takeWhile, filter, last, mergeMap as mergeMap$1, shareReplay, ignoreElements, noop as noop$1, pairwise, NEVER, interval, withLatestFrom, retry, iif, isEmpty, concat, toArray, combineLatest, endWith, lastValueFrom } from "rxjs";
5
+ import { isObservable, from, of, defer, startWith, identity, distinctUntilChanged, tap, catchError, EMPTY, Subject, BehaviorSubject, retry, skip, first, map, switchMap, zip, share, merge, throttleTime, asyncScheduler, concatMap, scan, throwError, timer, takeUntil, fromEvent, take, delay, defaultIfEmpty, filter, noop } from "rxjs";
15
6
  import { catchError as catchError$1, mergeMap, retryWhen, concatMap as concatMap$1, first as first$1, tap as tap$1 } from "rxjs/operators";
16
- import { hashKey as hashKey$1, useQueryClient as useQueryClient$1, useQuery as useQuery$1, useMutation as useMutation$1 } from "@tanstack/react-query";
17
- import { jsx, jsxs } from "react/jsx-runtime";
7
+ import { hashKey, useQueryClient, useQuery, useMutation } from "@tanstack/react-query";
8
+ import { jsx } from "react/jsx-runtime";
18
9
  const useLiveRef = (value) => {
19
10
  const ref = useRef(value);
20
11
  useMemo(() => {
@@ -26,12 +17,12 @@ function isPromiseLike(value) {
26
17
  return value instanceof Promise || value && typeof value === "object" && "then" in value && typeof value.then === "function" && "catch" in value && value.catch === "function";
27
18
  }
28
19
  function makeObservable(something) {
29
- if (isObservable(something)) return something;
30
- if (isPromiseLike(something)) return from(something);
31
- if (typeof something !== "function") return of(something);
20
+ if (isObservable(something)) return () => something;
21
+ if (isPromiseLike(something)) return () => from(something);
22
+ if (typeof something !== "function") return () => of(something);
32
23
  const somethingAsFunction = something;
33
- return defer(() => {
34
- const result = somethingAsFunction();
24
+ return (params) => defer(() => {
25
+ const result = somethingAsFunction(params);
35
26
  if (isPromiseLike(result)) {
36
27
  return from(result);
37
28
  }
@@ -59,7 +50,7 @@ function useObserve(source$, optionsOrDeps, maybeDeps) {
59
50
  const subscribe = useCallback(
60
51
  (next) => {
61
52
  const source = sourceRef.current;
62
- const sub = makeObservable(source).pipe(
53
+ const sub = makeObservable(source)().pipe(
63
54
  optionsRef.current.defaultValue ? startWith(optionsRef.current.defaultValue) : identity,
64
55
  /**
65
56
  * @important there is already a Object.is comparison in place from react
@@ -91,7 +82,7 @@ function useObserve(source$, optionsOrDeps, maybeDeps) {
91
82
  function useSubscribe(source, deps = []) {
92
83
  const sourceRef = useLiveRef(source);
93
84
  useEffect(() => {
94
- const sub = makeObservable(sourceRef.current).pipe(
85
+ const sub = makeObservable(sourceRef.current)().pipe(
95
86
  catchError((error) => {
96
87
  console.error(error);
97
88
  return EMPTY;
@@ -107,7 +98,7 @@ function useSubscribe(source, deps = []) {
107
98
  ]);
108
99
  }
109
100
  const useConstant = (fn) => {
110
- const ref = useRef();
101
+ const ref = useRef(void 0);
111
102
  if (!ref.current) {
112
103
  ref.current = fn();
113
104
  }
@@ -191,6 +182,27 @@ const useLiveBehaviorSubject = (state) => {
191
182
  }, [state, subject]);
192
183
  return subject;
193
184
  };
185
+ function useSubscribeEffect(source, unsafeOptions, deps = []) {
186
+ const options = unsafeOptions != null && !Array.isArray(unsafeOptions) ? unsafeOptions : {};
187
+ const retryOption = options.retry ?? true;
188
+ const onErrorRef = useLiveRef(
189
+ options.onError ?? ((error) => {
190
+ console.error(error);
191
+ })
192
+ );
193
+ const sourceAsObservable = useCallback(() => makeObservable(source)(), deps);
194
+ const enhancerMakeObservable = useCallback(
195
+ () => sourceAsObservable().pipe(
196
+ catchError((error) => {
197
+ onErrorRef.current(error);
198
+ throw error;
199
+ }),
200
+ retryOption ? retry() : identity
201
+ ),
202
+ [sourceAsObservable, retryOption, onErrorRef]
203
+ );
204
+ useSubscribe(enhancerMakeObservable, deps);
205
+ }
194
206
  const SIGNAL_RESET = Symbol("SIGNAL_RESET");
195
207
  function signal(config = {}) {
196
208
  const normalizedConfig = {
@@ -642,7 +654,7 @@ class QueryClient$ {
642
654
  return this.queryMap.get(queryHash);
643
655
  }
644
656
  setQuery(queryKey, query$, signal2) {
645
- const queryHash = hashKey$1(queryKey);
657
+ const queryHash = hashKey(queryKey);
646
658
  const sharedQuery$ = query$.pipe(
647
659
  /**
648
660
  * abort signal is triggered on:
@@ -691,23 +703,23 @@ class QueryClient$ {
691
703
  });
692
704
  }
693
705
  }
694
- const Context$1 = createContext(void 0);
706
+ const Context = createContext(void 0);
695
707
  const QueryClientProvider$ = memo(
696
708
  ({
697
709
  children,
698
- client: _client2
710
+ client: _client
699
711
  }) => {
700
- const [client] = useState(() => _client2 ?? new QueryClient$());
712
+ const [client] = useState(() => _client ?? new QueryClient$());
701
713
  useEffect(() => {
702
714
  return () => {
703
715
  client.destroy();
704
716
  };
705
717
  }, [client]);
706
- return /* @__PURE__ */ jsx(Context$1.Provider, { value: client, children });
718
+ return /* @__PURE__ */ jsx(Context.Provider, { value: client, children });
707
719
  }
708
720
  );
709
721
  const useQueryClient$ = () => {
710
- const client = useContext(Context$1);
722
+ const client = useContext(Context);
711
723
  if (!client) {
712
724
  throw new Error(
713
725
  "useReactJrxQueryClient must be used within a ReactJrxQueryProvider"
@@ -716,14 +728,14 @@ const useQueryClient$ = () => {
716
728
  return client;
717
729
  };
718
730
  function useQuery$(options, queryClient) {
719
- const _queryClient = useQueryClient$1(queryClient);
731
+ const _queryClient = useQueryClient(queryClient);
720
732
  const queryClient$ = useQueryClient$();
721
733
  const queryFnAsync = (context) => {
722
734
  return new Promise((resolve, reject) => {
723
735
  const getSource = () => defer(
724
736
  () => typeof options.queryFn === "function" ? options.queryFn(context) : options.queryFn
725
737
  );
726
- const queryHash = hashKey$1(context.queryKey);
738
+ const queryHash = hashKey(context.queryKey);
727
739
  const queryCacheEntry = queryClient$.getQuery(queryHash) ?? queryClient$.setQuery(context.queryKey, getSource(), context.signal);
728
740
  const query$ = queryCacheEntry.query$;
729
741
  query$.pipe(
@@ -766,7 +778,7 @@ function useQuery$(options, queryClient) {
766
778
  });
767
779
  });
768
780
  };
769
- const result = useQuery$1(
781
+ const result = useQuery(
770
782
  {
771
783
  ...options,
772
784
  queryFn: queryFnAsync
@@ -783,29 +795,28 @@ function useMutation$(options, queryClient) {
783
795
  isSuccess: false,
784
796
  isIdle: true
785
797
  });
786
- const mutationFnAsync = (variables) => {
787
- let lastData;
788
- return new Promise((resolve, reject) => {
789
- const source = typeof options.mutationFn === "function" ? options.mutationFn(variables) : options.mutationFn;
790
- source.pipe(take(1)).subscribe({
791
- next: (data) => {
792
- lastData = { value: data };
793
- },
794
- error: (error) => {
795
- reject(error);
796
- },
797
- complete: () => {
798
- if (lastData === void 0)
799
- return reject(new Error("Stream completed without any data"));
800
- resolve(lastData.value);
801
- }
802
- });
803
- });
804
- };
805
- const result = useMutation$1(
798
+ const result = useMutation(
806
799
  {
807
800
  ...options,
808
- mutationFn: mutationFnAsync
801
+ mutationFn: (variables) => {
802
+ let lastData;
803
+ return new Promise((resolve, reject) => {
804
+ const source = typeof options.mutationFn === "function" ? options.mutationFn(variables) : options.mutationFn;
805
+ source.pipe(take(1)).subscribe({
806
+ next: (data) => {
807
+ lastData = { value: data };
808
+ },
809
+ error: (error) => {
810
+ reject(error);
811
+ },
812
+ complete: () => {
813
+ if (lastData === void 0)
814
+ return reject(new Error("Stream completed without any data"));
815
+ resolve(lastData.value);
816
+ }
817
+ });
818
+ });
819
+ }
809
820
  },
810
821
  queryClient
811
822
  );
@@ -830,7 +841,7 @@ function useSwitchMutation$(options, queryClient) {
830
841
  const mutateSwitch = useCallback(
831
842
  (variables) => {
832
843
  cancel();
833
- mutate(variables);
844
+ return mutate(variables);
834
845
  },
835
846
  [mutate, cancel]
836
847
  );
@@ -843,2759 +854,68 @@ function useSwitchMutation$(options, queryClient) {
843
854
  );
844
855
  return { ...rest, mutate: mutateSwitch, mutateAsync: mutateAsyncSwitch };
845
856
  }
846
- function hasObjectPrototype(o) {
847
- return Object.prototype.toString.call(o) === "[object Object]";
848
- }
849
- function isPlainObject(o) {
850
- if (!hasObjectPrototype(o)) {
851
- return false;
852
- }
853
- const ctor = o.constructor;
854
- if (typeof ctor === "undefined") {
855
- return true;
856
- }
857
- const prot = ctor.prototype;
858
- if (!hasObjectPrototype(prot)) {
859
- return false;
860
- }
861
- if (!prot.hasOwnProperty("isPrototypeOf")) {
862
- return false;
863
- }
864
- return true;
865
- }
866
- const hashKey = (queryKey) => {
867
- return JSON.stringify(
868
- queryKey,
869
- (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => {
870
- result[key] = val[key];
871
- return result;
872
- }, {}) : val
873
- );
874
- };
875
- const nanoid = (size = 21) => crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
876
- byte &= 63;
877
- if (byte < 36) {
878
- id += byte.toString(36);
879
- } else if (byte < 62) {
880
- id += (byte - 26).toString(36).toUpperCase();
881
- } else if (byte > 62) {
882
- id += "-";
883
- } else {
884
- id += "_";
885
- }
886
- return id;
887
- }, "");
888
- const getDefaultMutationState = () => ({
889
- context: void 0,
890
- data: void 0,
891
- error: null,
892
- status: "idle",
893
- submittedAt: 0,
894
- variables: void 0,
895
- failureCount: 0,
896
- failureReason: null,
897
- isPaused: false
898
- });
899
- function trackSubscriptions(onCountUpdate) {
900
- let count = 0;
901
- return function refCountOperatorFunction(source) {
902
- return new Observable((observer) => {
903
- count++;
904
- const sub = source.subscribe(observer);
905
- onCountUpdate(count);
906
- return () => {
907
- count--;
908
- onCountUpdate(count);
909
- sub.unsubscribe();
910
- };
911
- });
912
- };
913
- }
914
- const observeUntilFinished = (source) => source.pipe(
915
- takeWhile(
916
- (result) => result.status !== "error" && result.status !== "success",
917
- true
918
- )
919
- );
920
- class MutationRunner {
921
- constructor({
922
- __queryFinalizeHook
923
- } = {}) {
924
- __privateAdd(this, _trigger$, new Subject());
925
- __publicField(this, "state$");
926
- const refCountSubject = new BehaviorSubject(0);
927
- const noMoreObservers$ = refCountSubject.pipe(
928
- filter((value) => value === 0)
929
- );
930
- this.state$ = __privateGet(this, _trigger$).pipe(
931
- concatMap(({ args, mutation, options }) => {
932
- const mapOperator = options.mapOperator ?? "merge";
933
- const mergeTrigger$ = __privateGet(this, _trigger$).pipe(
934
- filter(() => mapOperator === "merge")
935
- );
936
- const switchTrigger$ = __privateGet(this, _trigger$).pipe(
937
- filter(() => mapOperator === "switch"),
938
- tap(() => {
939
- mutation.cancel();
940
- })
941
- );
942
- const deferExecution$ = defer(() => {
943
- mutation.execute(args);
944
- return EMPTY;
945
- });
946
- const resetState$ = mutation.state$.pipe(
947
- observeUntilFinished,
948
- last(),
949
- mergeMap$1(() => mutation.state$),
950
- takeUntil(__privateGet(this, _trigger$))
951
- );
952
- const stateUntilFinished$ = mutation.state$.pipe(
953
- observeUntilFinished,
954
- skip(1)
955
- );
956
- const observeUntil$ = merge(
957
- noMoreObservers$,
958
- mergeTrigger$,
959
- switchTrigger$,
960
- mutation.cancelled$
961
- );
962
- return merge(
963
- stateUntilFinished$,
964
- resetState$,
965
- /**
966
- * We defer execution so that we return at least
967
- * the current state first (same mechanism is used for query)
968
- */
969
- deferExecution$
970
- ).pipe(
971
- map((state) => ({ state, mutation })),
972
- __queryFinalizeHook ?? identity,
973
- takeUntil(observeUntil$)
857
+ function useContactMutation$(options, queryClient) {
858
+ const client = useQueryClient(queryClient);
859
+ const mutationKey = options.mutationKey;
860
+ const { mutateAsync, ...rest } = useMutation$(
861
+ {
862
+ ...options,
863
+ onMutate({ variables }) {
864
+ var _a;
865
+ return (_a = options.onMutate) == null ? void 0 : _a.call(options, variables);
866
+ },
867
+ onSuccess(data, variables, context) {
868
+ var _a;
869
+ return (_a = options.onSuccess) == null ? void 0 : _a.call(options, data, variables.variables, context);
870
+ },
871
+ onError(error, variables, context) {
872
+ var _a;
873
+ return (_a = options.onError) == null ? void 0 : _a.call(options, error, variables.variables, context);
874
+ },
875
+ onSettled(data, error, variables, context) {
876
+ var _a;
877
+ return (_a = options.onSettled) == null ? void 0 : _a.call(options, data, error, variables.variables, context);
878
+ },
879
+ mutationFn: ({ ready$, variables }) => {
880
+ const source = typeof options.mutationFn === "function" ? options.mutationFn(variables) : options.mutationFn;
881
+ return ready$.pipe(
882
+ filter((isReady) => isReady),
883
+ first(),
884
+ switchMap(() => source)
974
885
  );
975
- }),
976
- shareReplay({
977
- refCount: true,
978
- bufferSize: 1
979
- }),
980
- trackSubscriptions((count) => {
981
- refCountSubject.next(count);
982
- })
983
- );
984
- }
985
- trigger({
986
- args,
987
- options,
988
- mutation
989
- }) {
990
- __privateGet(this, _trigger$).next({ args, options, mutation });
991
- }
992
- }
993
- _trigger$ = new WeakMap();
994
- function partialMatchKey(a, b) {
995
- if (a === b) {
996
- return true;
997
- }
998
- if (typeof a !== typeof b) {
999
- return false;
1000
- }
1001
- if (a && b && typeof a === "object" && typeof b === "object") {
1002
- return !Object.keys(b).some((key) => !partialMatchKey(a[key], b[key]));
1003
- }
1004
- return false;
1005
- }
1006
- const matchKey = (keyA, keyB, { exact = false } = {}) => {
1007
- if (exact) {
1008
- return hashKey(keyA) === hashKey(keyB);
1009
- }
1010
- return partialMatchKey(keyA, keyB);
1011
- };
1012
- const distinctUntilStateChanged = (stream) => stream.pipe(
1013
- distinctUntilChanged(
1014
- ({ data: prevData, ...prev }, { data: currData, ...curr }) => shallowEqual(prev, curr) && shallowEqual(prevData, currData)
1015
- )
1016
- );
1017
- class MutationObserver {
1018
- constructor(client, options = {}, mutationRunner) {
1019
- __privateAdd(this, _mutationRunner);
1020
- __privateAdd(this, _currentMutationSubject, new BehaviorSubject(void 0));
1021
- /**
1022
- * @important
1023
- * Used to maintain persistance to latest mutation. This ensure
1024
- * - mutation does not get garbage collected
1025
- * - mutation mutate options are run on finish
1026
- */
1027
- __publicField(this, "observed$");
1028
- __publicField(this, "getObserverResultFromState", (state) => {
1029
- return {
1030
- ...getDefaultMutationState(),
1031
- ...state,
1032
- isSuccess: state.status === "success",
1033
- isPending: state.status === "pending",
1034
- isIdle: state.status === "idle",
1035
- isError: state.status === "error",
1036
- // eslint-disable-next-line @typescript-eslint/unbound-method
1037
- mutate: this.mutate,
1038
- // eslint-disable-next-line @typescript-eslint/unbound-method
1039
- reset: this.reset
1040
- };
1041
- });
1042
- var _a;
1043
- this.client = client;
1044
- this.options = options;
1045
- this.options.mutationKey = ((_a = this.options) == null ? void 0 : _a.mutationKey) ?? [nanoid()];
1046
- __privateSet(this, _mutationRunner, mutationRunner ?? new MutationRunner(this.options));
1047
- this.mutate = this.mutate.bind(this);
1048
- this.reset = this.reset.bind(this);
1049
- __privateGet(this, _currentMutationSubject).pipe(
1050
- filter(isDefined),
1051
- mergeMap$1(
1052
- (mutation) => __privateGet(this, _mutationRunner).state$.pipe(
1053
- takeUntil(
1054
- mutation.mutation.state$.pipe(observeUntilFinished, last())
1055
- )
1056
- )
1057
- )
1058
- ).subscribe();
1059
- this.observed$ = __privateGet(this, _currentMutationSubject).pipe(
1060
- switchMap((maybeMutation) => {
1061
- return (maybeMutation == null ? void 0 : maybeMutation.mutation.state$.pipe(
1062
- // last(),
1063
- map((state) => ({
1064
- state,
1065
- options: maybeMutation.options
1066
- }))
1067
- )) ?? EMPTY;
1068
- }),
1069
- tap(({ state, options: options2 }) => {
1070
- if (state.status === "error") {
1071
- (options2 == null ? void 0 : options2.onError) && (options2 == null ? void 0 : options2.onError(
1072
- state.error,
1073
- state.variables,
1074
- state.context
1075
- ));
1076
- (options2 == null ? void 0 : options2.onSettled) && (options2 == null ? void 0 : options2.onSettled(
1077
- state.data,
1078
- state.error,
1079
- state.variables,
1080
- state.context
1081
- ));
1082
- }
1083
- if (state.status === "success") {
1084
- (options2 == null ? void 0 : options2.onSuccess) && (options2 == null ? void 0 : options2.onSuccess(
1085
- state.data,
1086
- state.variables,
1087
- state.context
1088
- ));
1089
- (options2 == null ? void 0 : options2.onSettled) && (options2 == null ? void 0 : options2.onSettled(
1090
- state.data,
1091
- state.error,
1092
- state.variables,
1093
- state.context
1094
- ));
1095
- }
1096
- }),
1097
- ignoreElements()
1098
- );
1099
- }
1100
- setOptions(options) {
1101
- var _a;
1102
- const prevOptions = this.options;
1103
- this.options = this.client.defaultMutationOptions({
1104
- mutationKey: this.options.mutationKey,
1105
- ...options
1106
- });
1107
- const currentMutation = (_a = __privateGet(this, _currentMutationSubject).getValue()) == null ? void 0 : _a.mutation;
1108
- if (this.options.mutationKey && prevOptions.mutationKey && !matchKey(this.options.mutationKey, prevOptions.mutationKey, {
1109
- exact: true
1110
- })) {
1111
- this.reset();
1112
- } else {
1113
- currentMutation == null ? void 0 : currentMutation.setOptions(this.options);
1114
- }
1115
- }
1116
- observe() {
1117
- var _a;
1118
- const lastValue = this.getObserverResultFromState(
1119
- ((_a = __privateGet(this, _currentMutationSubject).getValue()) == null ? void 0 : _a.mutation.state) ?? getDefaultMutationState()
1120
- );
1121
- const mutationResult$ = __privateGet(this, _mutationRunner).state$.pipe(
1122
- distinctUntilChanged(
1123
- ({ mutation: prevMutation, state: { data: prevData, ...prev } }, { mutation: currentMutation, state: { data: currData, ...curr } }) => prevMutation === currentMutation && shallowEqual(prev, curr) && shallowEqual(prevData, currData)
1124
- ),
1125
- map(({ state }) => state),
1126
- scan((acc, current) => {
1127
- return {
1128
- ...acc,
1129
- ...current,
1130
- ...current.status === "pending" && {
1131
- data: current.data ?? acc.data
1132
- },
1133
- ...current.status === "pending" && {
1134
- error: current.error ?? acc.error
1135
- }
1136
- };
1137
- }),
1138
- map((state) => this.getObserverResultFromState(state))
1139
- );
1140
- const defaultStateOnMutationCancel$ = __privateGet(this, _currentMutationSubject).pipe(
1141
- filter(isDefined),
1142
- switchMap((mutation) => mutation.mutation.cancelled$),
1143
- map(() => this.getObserverResultFromState(getDefaultMutationState()))
1144
- );
1145
- const result$ = merge(
1146
- this.observed$,
1147
- mutationResult$,
1148
- defaultStateOnMutationCancel$
1149
- ).pipe(distinctUntilStateChanged);
1150
- return { result$, lastValue };
1151
- }
1152
- /**
1153
- * @important
1154
- * Compliance react-query only
1155
- */
1156
- subscribe(subscription) {
1157
- const sub = this.observe().result$.subscribe((result) => {
1158
- subscription(result);
1159
- });
1160
- return () => {
1161
- sub.unsubscribe();
1162
- };
1163
- }
1164
- async mutate(variables, options = {}) {
1165
- const mutation = this.client.getMutationCache().build(this.client, this.options);
1166
- __privateGet(this, _currentMutationSubject).next({ mutation, options });
1167
- __privateGet(this, _mutationRunner).trigger({
1168
- args: variables,
1169
- options: this.options,
1170
- mutation
1171
- });
1172
- return await new Promise((resolve, reject) => {
1173
- mutation.state$.pipe(observeUntilFinished, last()).subscribe({
1174
- error: (error) => {
1175
- reject(error);
1176
- },
1177
- next: (data) => {
1178
- if (data.error) {
1179
- reject(data.error);
1180
- } else {
1181
- resolve(data.data);
1182
- }
1183
- }
1184
- });
1185
- });
1186
- }
1187
- getCurrentResult() {
1188
- var _a;
1189
- const mutation = this.client.getMutationCache().find({ exact: true, mutationKey: (_a = this.options) == null ? void 0 : _a.mutationKey });
1190
- return this.getObserverResultFromState(
1191
- (mutation == null ? void 0 : mutation.state) ?? getDefaultMutationState()
1192
- );
1193
- }
1194
- reset() {
1195
- const { mutation } = __privateGet(this, _currentMutationSubject).getValue() ?? {};
1196
- __privateGet(this, _currentMutationSubject).next(void 0);
1197
- mutation == null ? void 0 : mutation.cancel();
1198
- }
1199
- }
1200
- _mutationRunner = new WeakMap();
1201
- _currentMutationSubject = new WeakMap();
1202
- const Context = createContext(void 0);
1203
- const ClientEffect = ({ client }) => {
1204
- useEffect(() => {
1205
- client.mount();
1206
- return () => {
1207
- client.unmount();
1208
- };
1209
- }, [client]);
1210
- return null;
1211
- };
1212
- const QueryClientProvider = memo(
1213
- ({ children, client }) => {
1214
- const value = useMemo(() => client, [client]);
1215
- return /* @__PURE__ */ jsxs(Context.Provider, { value, children: [
1216
- /* @__PURE__ */ jsx(ClientEffect, { client }),
1217
- children
1218
- ] });
1219
- }
1220
- );
1221
- const useQueryClient = (queryClient) => {
1222
- const client = useContext(Context);
1223
- if (queryClient) {
1224
- return queryClient;
1225
- }
1226
- if (!client) {
1227
- throw new Error("No QueryClient set, use QueryClientProvider to set one");
1228
- }
1229
- return client;
1230
- };
1231
- function noop() {
1232
- }
1233
- function useMutation(options, queryClient) {
1234
- const defaultQueryClient = useQueryClient(queryClient);
1235
- const optionsRef = useLiveRef(options);
1236
- const defaultKey = useConstant(() => [nanoid()]);
1237
- const serializedKey = hashKey(options.mutationKey ?? defaultKey.current);
1238
- const [mutationObserver] = useState(
1239
- () => new MutationObserver(
1240
- defaultQueryClient,
1241
- options
1242
- )
1243
- );
1244
- useEffect(() => {
1245
- mutationObserver.setOptions(options);
1246
- }, [mutationObserver, options]);
1247
- const observedMutation = useMemo(() => {
1248
- return mutationObserver.observe();
1249
- }, [serializedKey, mutationObserver]);
1250
- const result = useObserve(observedMutation.result$) ?? observedMutation.lastValue;
1251
- const mutate = useCallback(
1252
- (variables, mutateOptions) => {
1253
- mutationObserver.mutate(variables, mutateOptions).catch(noop);
886
+ }
1254
887
  },
1255
- [mutationObserver]
888
+ queryClient
1256
889
  );
1257
- useEffect(() => {
1258
- return () => {
1259
- if (optionsRef.current.cancelOnUnMount) {
1260
- mutationObserver.reset();
1261
- }
1262
- };
1263
- }, [mutationObserver, optionsRef]);
1264
- return { ...result, mutate, mutateAsync: result.mutate };
1265
- }
1266
- function emitToSubject(subject) {
1267
- return (source$) => source$.pipe(
1268
- tap$1((value) => {
1269
- subject.next(value);
1270
- })
890
+ const mutateAsyncConcat = useCallback(
891
+ async (variables) => {
892
+ const mutations = client.getMutationCache().findAll({
893
+ mutationKey,
894
+ exact: true
895
+ });
896
+ const subject = new BehaviorSubject(false);
897
+ const result = mutateAsync({ variables, ready$: subject });
898
+ await Promise.all(
899
+ mutations.map((mutation) => mutation.continue().catch(noop))
900
+ );
901
+ subject.next(true);
902
+ return await result.finally(() => {
903
+ subject.complete();
904
+ });
905
+ },
906
+ [mutateAsync, client, mutationKey]
1271
907
  );
1272
- }
1273
- class OnlineManager {
1274
- constructor() {
1275
- __publicField(this, "isOnlineSubject", new BehaviorSubject(true));
1276
- __publicField(this, "online$", this.isOnlineSubject.pipe(distinctUntilChanged()));
1277
- __publicField(this, "backToOnline$", this.online$.pipe(
1278
- filter((isOnline) => isOnline),
1279
- first()
1280
- ));
1281
- merge(
1282
- isServer ? EMPTY : fromEvent(window, "offline").pipe(map(() => false)),
1283
- isServer ? EMPTY : fromEvent(window, "online").pipe(map(() => true))
1284
- ).pipe(emitToSubject(this.isOnlineSubject)).subscribe();
1285
- }
1286
- isOnline() {
1287
- return this.isOnlineSubject.getValue();
1288
- }
1289
- setOnline(online) {
1290
- const changed = this.isOnlineSubject.getValue() !== online;
1291
- if (changed) {
1292
- this.isOnlineSubject.next(online);
1293
- }
1294
- }
1295
- }
1296
- const onlineManager = new OnlineManager();
1297
- function isStale(query, options) {
1298
- return query.isStaleByTime(options.staleTime);
1299
- }
1300
- function shouldLoadOnMount(query, options) {
1301
- return options.enabled !== false && !query.state.dataUpdatedAt && !(query.state.status === "error" && options.retryOnMount === false) && query.state.fetchStatus !== "fetching";
1302
- }
1303
- function shouldFetchOnMount(query, options) {
1304
- return shouldLoadOnMount(query, options) || query.state.dataUpdatedAt > 0 && shouldFetchOn(query, options, options.refetchOnMount);
1305
- }
1306
- function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
1307
- return query.state.fetchStatus !== "fetching" && options.enabled !== false && (query !== prevQuery || prevOptions.enabled === false) && (!options.suspense || query.state.status !== "error") && isStale(query, options);
1308
- }
1309
- function shouldFetchOnWindowFocus(query, options) {
1310
- return shouldFetchOn(query, options, options.refetchOnWindowFocus);
1311
- }
1312
- function shouldFetchOn(query, options, field) {
1313
- if (options.enabled !== false) {
1314
- const value = typeof field === "function" ? field(query) : field;
1315
- if (value === "idle") {
1316
- return query.state.fetchStatus === "idle";
1317
- }
1318
- return value === "always" || value !== false && isStale(query, options);
1319
- }
1320
- return false;
1321
- }
1322
- function canFetch(networkMode) {
1323
- return (networkMode ?? "online") === "online" ? onlineManager.isOnline() : true;
1324
- }
1325
- function filterObjectByKey(obj, keys) {
1326
- return keys.reduce(
1327
- (acc, key) => {
1328
- if (key in obj) {
1329
- return { ...acc, [key]: obj[key] };
1330
- }
1331
- return acc;
908
+ const mutateConcat = useCallback(
909
+ (variables) => {
910
+ mutateAsyncConcat(variables).catch(noop);
1332
911
  },
1333
- {}
912
+ [mutateAsyncConcat]
1334
913
  );
914
+ return { ...rest, mutate: mutateConcat, mutateAsync: mutateAsyncConcat };
1335
915
  }
1336
- function isPlainArray(value) {
1337
- return Array.isArray(value) && value.length === Object.keys(value).length;
1338
- }
1339
- function replaceEqualDeep(a, b) {
1340
- if (a === b) {
1341
- return a;
1342
- }
1343
- const array = isPlainArray(a) && isPlainArray(b);
1344
- if (array || isPlainObject(a) && isPlainObject(b)) {
1345
- const aItems = array ? a : Object.keys(a);
1346
- const aSize = aItems.length;
1347
- const bItems = array ? b : Object.keys(b);
1348
- const bSize = bItems.length;
1349
- const copy = array ? [] : {};
1350
- let equalItems = 0;
1351
- for (let i = 0; i < bSize; i++) {
1352
- const key = array ? i : bItems[i];
1353
- if (!array && a[key] === void 0 && b[key] === void 0 && aItems.includes(key)) {
1354
- copy[key] = void 0;
1355
- equalItems++;
1356
- } else {
1357
- copy[key] = replaceEqualDeep(a[key], b[key]);
1358
- if (copy[key] === a[key] && a[key] !== void 0) {
1359
- equalItems++;
1360
- }
1361
- }
1362
- }
1363
- return aSize === bSize && equalItems === aSize ? a : copy;
1364
- }
1365
- return b;
1366
- }
1367
- function hashQueryKeyByOptions(queryKey, options) {
1368
- const hashFn = (options == null ? void 0 : options.queryKeyHashFn) ?? hashKey;
1369
- return hashFn(queryKey);
1370
- }
1371
- function matchQuery(filters, query) {
1372
- const {
1373
- type = "all",
1374
- exact,
1375
- fetchStatus,
1376
- predicate,
1377
- queryKey,
1378
- stale
1379
- } = filters;
1380
- if (queryKey) {
1381
- if (exact) {
1382
- if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
1383
- return false;
1384
- }
1385
- } else if (!partialMatchKey(query.queryKey, queryKey)) {
1386
- return false;
1387
- }
1388
- }
1389
- if (type !== "all") {
1390
- const isActive = query.isActive();
1391
- if (type === "active" && !isActive) {
1392
- return false;
1393
- }
1394
- if (type === "inactive" && isActive) {
1395
- return false;
1396
- }
1397
- }
1398
- if (typeof stale === "boolean" && query.isStale() !== stale) {
1399
- return false;
1400
- }
1401
- if (typeof fetchStatus !== "undefined" && fetchStatus !== query.state.fetchStatus) {
1402
- return false;
1403
- }
1404
- if (predicate && !predicate(query)) {
1405
- return false;
1406
- }
1407
- return true;
1408
- }
1409
- function timeUntilStale(updatedAt, staleTime) {
1410
- return Math.max(updatedAt + (staleTime ?? 0) - Date.now(), 0);
1411
- }
1412
- function functionalUpdate(updater, input) {
1413
- return typeof updater === "function" ? updater(input) : updater;
1414
- }
1415
- function replaceData(prevData, data, options) {
1416
- if (typeof options.structuralSharing === "function") {
1417
- return options.structuralSharing(prevData, data);
1418
- } else if (options.structuralSharing !== false) {
1419
- return replaceEqualDeep(prevData, data);
1420
- }
1421
- return data;
1422
- }
1423
- const skipToken = Symbol();
1424
- const reduceState = ({
1425
- getOptions,
1426
- getState,
1427
- initialState
1428
- }) => (source) => source.pipe(
1429
- scan((acc, { command, state: current }) => {
1430
- if (command === "reset") return { ...acc, ...current };
1431
- if (command === "cancel") {
1432
- const status2 = acc.status === "pending" ? "pending" : current.status ?? acc.status;
1433
- return { ...acc, ...current, status: status2 };
1434
- }
1435
- const currentData = current.data;
1436
- const weHaveNewData = currentData !== void 0 && currentData !== acc.data;
1437
- const weHaveDataKeyInCurrent = "data" in current;
1438
- const newSuccessStatus = current.status === "success";
1439
- const hasData = acc.data !== void 0;
1440
- const hasError = acc.error !== void 0 || acc.error !== null;
1441
- const status = current.status ?? acc.status;
1442
- const newData = weHaveNewData ? replaceData(getState().data, currentData, getOptions()) : weHaveDataKeyInCurrent ? current.data : acc.data;
1443
- const previousStatusIsSuccessOrError = acc.status === "error" || acc.status === "success";
1444
- const errorUpdateCount = current.status === "error" && (acc.status === "error" && acc.fetchStatus === "fetching" || acc.status !== "error") ? acc.errorUpdateCount + 1 : acc.errorUpdateCount;
1445
- const dataUpdateCount = weHaveNewData ? acc.dataUpdateCount + 1 : current.dataUpdateCount ?? acc.dataUpdateCount;
1446
- const newPendingStatusOnHold = current.status === "pending" && previousStatusIsSuccessOrError && // (dataUpdateCount !== 0 || errorUpdateCount !== 0)
1447
- (hasData || hasError);
1448
- const error = status === "pending" ? null : current.error ?? acc.error;
1449
- return {
1450
- ...acc,
1451
- ...current,
1452
- status,
1453
- error,
1454
- errorUpdateCount,
1455
- ...newSuccessStatus && {
1456
- isInvalidated: false
1457
- },
1458
- data: newData,
1459
- dataUpdateCount,
1460
- ...newPendingStatusOnHold && {
1461
- status: acc.status
1462
- }
1463
- };
1464
- }, initialState)
1465
- );
1466
- const isQueryFinished = (source) => source.pipe(
1467
- map(
1468
- ({ status, fetchStatus }) => fetchStatus === "idle" && (status === "success" || status === "error")
1469
- )
1470
- );
1471
- const takeUntilFinished = (source) => source.pipe(
1472
- takeWhile((result) => {
1473
- const isFetchingOrPaused = result.fetchStatus !== "idle";
1474
- return isFetchingOrPaused;
1475
- }, true)
1476
- );
1477
- class FocusManager {
1478
- constructor() {
1479
- __privateAdd(this, _visibility$, merge(
1480
- isServer ? EMPTY : fromEvent(document, "visibilitychange"),
1481
- isServer ? EMPTY : fromEvent(window, "visibilitychange")
1482
- ).pipe(map(() => document.visibilityState)));
1483
- __privateAdd(this, _focusedSubject, new BehaviorSubject(
1484
- isServer ? true : document.visibilityState === "visible"
1485
- ));
1486
- // public readonly focused$ = this.#focusedSubject.pipe(distinctUntilChanged())
1487
- __publicField(this, "focused$", __privateGet(this, _focusedSubject));
1488
- __publicField(this, "focusRegained$", this.focused$.pipe(
1489
- skip(1),
1490
- filter((visibility) => visibility)
1491
- ));
1492
- __privateGet(this, _visibility$).pipe(
1493
- tap((value) => {
1494
- __privateGet(this, _focusedSubject).next(value === "visible");
1495
- })
1496
- ).subscribe();
1497
- }
1498
- isFocused() {
1499
- return __privateGet(this, _focusedSubject).getValue();
1500
- }
1501
- setFocused(focused) {
1502
- const changed = __privateGet(this, _focusedSubject).getValue() !== (focused ?? true);
1503
- if (changed) {
1504
- __privateGet(this, _focusedSubject).next(focused ?? true);
1505
- }
1506
- }
1507
- subscribe(fn) {
1508
- const sub = this.focused$.subscribe(fn);
1509
- return () => {
1510
- sub.unsubscribe();
1511
- };
1512
- }
1513
- /**
1514
- * @important
1515
- * You do not need that outside of testing. This is bad practice but necessary in order
1516
- * to not mess too much with rq tests files.
1517
- *
1518
- * Use it after mocking to force the manager to hold mocked value.
1519
- */
1520
- refresh() {
1521
- document.dispatchEvent(new Event("visibilitychange"));
1522
- }
1523
- }
1524
- _visibility$ = new WeakMap();
1525
- _focusedSubject = new WeakMap();
1526
- const focusManager = new FocusManager();
1527
- const whenNewData = (source) => source.pipe(
1528
- filter((state) => state.status === "success"),
1529
- map((state) => ({
1530
- data: state.data,
1531
- status: state.status,
1532
- dataUpdatedAt: state.dataUpdatedAt
1533
- })),
1534
- distinctUntilChanged(shallowEqual)
1535
- );
1536
- class QueryObserver {
1537
- constructor(client, options) {
1538
- __privateAdd(this, _client);
1539
- __privateAdd(this, _currentQuery);
1540
- __privateAdd(this, _fetchSubject, new Subject());
1541
- /**
1542
- * Used to subscribe to changes in either query or options (or both).
1543
- * We need to be able to track change to both of them at the same time
1544
- * in order to react accordingly and in order (such as refetch on options change)
1545
- */
1546
- __publicField(this, "queryUpdateSubject", new Subject());
1547
- /**
1548
- * Mostly used to compare the state before and after mount
1549
- */
1550
- __privateAdd(this, _currentQueryInitialState);
1551
- /**
1552
- * Mostly used for internal optimization such as not
1553
- * running selectors twice, etc
1554
- */
1555
- __privateAdd(this, _lastResult);
1556
- // This property keeps track of the last query with defined data.
1557
- // It will be used to pass the previous data and query to the placeholder function between renders.
1558
- __privateAdd(this, _lastQueryWithDefinedData);
1559
- __privateAdd(this, _observers, 0);
1560
- __publicField(this, "getObserverResultFromQuery", ({
1561
- options,
1562
- query,
1563
- optimisticResult,
1564
- prevResult: {
1565
- result: prevResult,
1566
- options: prevResultOptions,
1567
- state: prevResultState,
1568
- select: prevSelect,
1569
- selectError: prevSelectError,
1570
- selectResult: prevSelectResult
1571
- }
1572
- }) => {
1573
- var _a;
1574
- const state = query.state;
1575
- const isPending = query.state.status === "pending";
1576
- const prevQuery = __privateGet(this, _currentQuery);
1577
- const prevOptions = this.options;
1578
- const queryChange = query !== prevQuery;
1579
- const queryInitialState = queryChange ? query.state : __privateGet(this, _currentQueryInitialState);
1580
- let { errorUpdatedAt, fetchStatus, error } = state;
1581
- if (optimisticResult) {
1582
- const mounted = !!__privateGet(this, _observers);
1583
- const fetchOnMount = !mounted && shouldFetchOnMount(query, options);
1584
- const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
1585
- if (fetchOnMount || fetchOptionally) {
1586
- fetchStatus = canFetch(query.options.networkMode) ? "fetching" : "paused";
1587
- }
1588
- }
1589
- const isLoading = isPending && fetchStatus === "fetching";
1590
- let data;
1591
- let selectError = prevSelectError;
1592
- let selectFn = prevSelect ?? null;
1593
- let selectResult = prevSelectResult;
1594
- if (options.select && typeof state.data !== "undefined") {
1595
- if (prevResult && state.data === (prevResultState == null ? void 0 : prevResultState.data) && options.select === prevSelect) {
1596
- data = prevSelectResult;
1597
- } else {
1598
- try {
1599
- selectFn = options.select;
1600
- data = options.select(state.data);
1601
- data = replaceData(prevResult == null ? void 0 : prevResult.data, data, options);
1602
- selectResult = data;
1603
- selectError = null;
1604
- } catch (error2) {
1605
- data = prevSelectResult;
1606
- selectError = error2;
1607
- }
1608
- }
1609
- } else {
1610
- data = state.data;
1611
- selectError = null;
1612
- }
1613
- let status = fetchStatus !== "idle" && !state.dataUpdatedAt ? "pending" : state.status;
1614
- if (selectError) {
1615
- error = selectError;
1616
- data = prevSelectResult;
1617
- errorUpdatedAt = (prevResult == null ? void 0 : prevResult.errorUpdatedAt) ?? errorUpdatedAt;
1618
- status = "error";
1619
- }
1620
- const isError = status === "error";
1621
- let isPlaceholderData = false;
1622
- if (typeof options.placeholderData !== "undefined" && typeof data === "undefined" && status === "pending") {
1623
- let placeholderData;
1624
- if ((prevResult == null ? void 0 : prevResult.isPlaceholderData) && options.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) {
1625
- placeholderData = prevResult.data;
1626
- } else {
1627
- placeholderData = typeof options.placeholderData === "function" ? options.placeholderData(
1628
- (_a = __privateGet(this, _lastQueryWithDefinedData)) == null ? void 0 : _a.state.data,
1629
- __privateGet(this, _lastQueryWithDefinedData)
1630
- ) : options.placeholderData;
1631
- if (options.select && typeof placeholderData !== "undefined") {
1632
- try {
1633
- placeholderData = options.select(placeholderData);
1634
- } catch (selectError2) {
1635
- }
1636
- }
1637
- }
1638
- if (typeof placeholderData !== "undefined") {
1639
- status = "success";
1640
- data = replaceData(
1641
- prevResult == null ? void 0 : prevResult.data,
1642
- placeholderData,
1643
- options
1644
- );
1645
- isPlaceholderData = true;
1646
- }
1647
- }
1648
- const isFetching = fetchStatus === "fetching";
1649
- const result = {
1650
- status,
1651
- fetchStatus,
1652
- isPending,
1653
- isSuccess: status === "success",
1654
- isError,
1655
- isInitialLoading: isLoading,
1656
- isLoading,
1657
- data,
1658
- dataUpdatedAt: state.dataUpdatedAt,
1659
- error,
1660
- errorUpdatedAt,
1661
- failureCount: state.fetchFailureCount,
1662
- failureReason: state.fetchFailureReason,
1663
- errorUpdateCount: state.errorUpdateCount,
1664
- isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,
1665
- isFetchedAfterMount: state.dataUpdateCount > queryInitialState.dataUpdateCount || state.errorUpdateCount > queryInitialState.errorUpdateCount,
1666
- isFetching,
1667
- isRefetching: isFetching && !isPending,
1668
- isLoadingError: isError && state.dataUpdatedAt === 0,
1669
- isPaused: fetchStatus === "paused",
1670
- isPlaceholderData,
1671
- isRefetchError: isError && state.dataUpdatedAt !== 0,
1672
- isStale: isStale(query, options),
1673
- // eslint-disable-next-line @typescript-eslint/unbound-method
1674
- refetch: this.refetch
1675
- };
1676
- return {
1677
- result,
1678
- selectError,
1679
- select: selectFn,
1680
- selectResult
1681
- };
1682
- });
1683
- this.options = options;
1684
- __privateSet(this, _client, client);
1685
- this.bindMethods();
1686
- __privateSet(this, _currentQuery, this.setOptions(options));
1687
- const query = __privateGet(this, _currentQuery);
1688
- __privateSet(this, _currentQueryInitialState, query.state);
1689
- const { result, select } = this.getObserverResultFromQuery({
1690
- query,
1691
- options: this.options,
1692
- prevResult: {
1693
- options: this.options,
1694
- state: query.state
1695
- }
1696
- });
1697
- __privateSet(this, _lastResult, {
1698
- state: query.state,
1699
- options,
1700
- result,
1701
- select
1702
- });
1703
- }
1704
- bindMethods() {
1705
- this.refetch = this.refetch.bind(this);
1706
- }
1707
- setOptions(options) {
1708
- const prevOptions = this.options;
1709
- this.options = __privateGet(this, _client).defaultQueryOptions(options);
1710
- if (!shallowEqual(this.options, prevOptions)) {
1711
- __privateGet(this, _client).getQueryCache().notify({
1712
- type: "observerOptionsUpdated",
1713
- query: __privateGet(this, _currentQuery),
1714
- observer: this
1715
- });
1716
- }
1717
- if (typeof this.options.enabled !== "undefined" && typeof this.options.enabled !== "boolean") {
1718
- throw new Error("Expected enabled to be a boolean");
1719
- }
1720
- const query = this.buildQuery(this.options);
1721
- if (query !== __privateGet(this, _currentQuery)) {
1722
- __privateSet(this, _currentQueryInitialState, query.state);
1723
- __privateSet(this, _currentQuery, query);
1724
- }
1725
- this.queryUpdateSubject.next({
1726
- options: this.options,
1727
- query
1728
- });
1729
- return query;
1730
- }
1731
- buildQuery(options) {
1732
- const query = __privateGet(this, _client).getQueryCache().build(__privateGet(this, _client), options);
1733
- if (!query.options.queryFn && this.options.queryFn) {
1734
- query.setOptions(options);
1735
- }
1736
- return query;
1737
- }
1738
- getCurrentResult() {
1739
- const result = this.getObserverResultFromQuery({
1740
- options: this.options,
1741
- prevResult: __privateGet(this, _lastResult),
1742
- query: __privateGet(this, _currentQuery)
1743
- });
1744
- return result.result;
1745
- }
1746
- getCurrentQuery() {
1747
- return __privateGet(this, _currentQuery);
1748
- }
1749
- getOptimisticResult(options) {
1750
- const query = this.buildQuery(options);
1751
- const observedResult = this.getObserverResultFromQuery({
1752
- query,
1753
- options,
1754
- optimisticResult: true,
1755
- prevResult: __privateGet(this, _lastResult)
1756
- });
1757
- if (shouldAssignObserverCurrentProperties(this, observedResult.result)) {
1758
- this.updateResult({ query, ...observedResult });
1759
- }
1760
- return observedResult.result;
1761
- }
1762
- updateResult({
1763
- query,
1764
- result,
1765
- selectError,
1766
- select,
1767
- selectResult
1768
- }) {
1769
- __privateGet(this, _lastResult).state = query.state;
1770
- __privateGet(this, _lastResult).result = result;
1771
- __privateGet(this, _lastResult).selectResult = selectResult;
1772
- if (selectError !== void 0) {
1773
- __privateGet(this, _lastResult).selectError = selectError;
1774
- }
1775
- if (select !== void 0) {
1776
- __privateGet(this, _lastResult).select = select;
1777
- }
1778
- __privateGet(this, _lastResult).options = this.options;
1779
- if (query.state.data !== void 0) {
1780
- __privateSet(this, _lastQueryWithDefinedData, query);
1781
- }
1782
- __privateGet(this, _client).getQueryCache().notify({
1783
- query: __privateGet(this, _currentQuery),
1784
- type: "observerResultsUpdated"
1785
- });
1786
- }
1787
- async refetch({ ...options } = {}) {
1788
- return await this.fetch({
1789
- ...options
1790
- });
1791
- }
1792
- async fetch(fetchOptions) {
1793
- const query = this.buildQuery(this.options);
1794
- if (query !== __privateGet(this, _currentQuery)) {
1795
- __privateSet(this, _currentQuery, query);
1796
- __privateSet(this, _currentQueryInitialState, query.state);
1797
- this.queryUpdateSubject.next({
1798
- options: this.options,
1799
- query
1800
- });
1801
- }
1802
- const finalFetchOptions = {
1803
- ...fetchOptions,
1804
- cancelRefetch: (fetchOptions == null ? void 0 : fetchOptions.cancelRefetch) ?? true
1805
- };
1806
- __privateGet(this, _currentQuery).fetch(this.options, finalFetchOptions).catch(noop$1);
1807
- __privateGet(this, _fetchSubject).next({
1808
- query,
1809
- fetchOptions: finalFetchOptions
1810
- });
1811
- await query.getFetchResultAsPromise();
1812
- const { result } = this.getObserverResultFromQuery({
1813
- query,
1814
- options: this.options,
1815
- prevResult: __privateGet(this, _lastResult)
1816
- });
1817
- return result;
1818
- }
1819
- /**
1820
- * feature parity with rq, not used internally
1821
- */
1822
- subscribe(listener) {
1823
- const sub = this.observe().subscribe(listener);
1824
- return () => {
1825
- sub.unsubscribe();
1826
- };
1827
- }
1828
- observe() {
1829
- const observedQuery = __privateGet(this, _currentQuery);
1830
- const currentQuery$ = this.queryUpdateSubject.pipe(
1831
- map(({ query }) => query),
1832
- startWith(__privateGet(this, _currentQuery)),
1833
- distinctUntilChanged()
1834
- );
1835
- const watchForImplicitRefetch$ = this.queryUpdateSubject.pipe(
1836
- startWith({
1837
- query: __privateGet(this, _currentQuery),
1838
- options: this.options
1839
- }),
1840
- pairwise(),
1841
- tap(
1842
- ([{ options: prevOptions, query: prevQuery }, { options, query }]) => {
1843
- if (shouldFetchOptionally(query, prevQuery, options, prevOptions)) {
1844
- this.fetch().catch(noop$1);
1845
- }
1846
- }
1847
- ),
1848
- ignoreElements()
1849
- );
1850
- const observedQuery$ = currentQuery$.pipe(
1851
- switchMap((query) => query.observe(this)),
1852
- ignoreElements()
1853
- );
1854
- const result$ = merge(
1855
- /**
1856
- * It's important to observe the query before we subscribe to its result
1857
- * later in the chain of merge to get the first result right after fetch
1858
- */
1859
- observedQuery$,
1860
- watchForImplicitRefetch$,
1861
- currentQuery$.pipe(
1862
- switchMap((query) => {
1863
- const options = this.options;
1864
- const options$ = this.queryUpdateSubject.pipe(
1865
- startWith({ query, options }),
1866
- filter((update) => update.query === query),
1867
- map((update) => update.options),
1868
- distinctUntilChanged(),
1869
- shareReplay(1)
1870
- );
1871
- const queryFetch$ = __privateGet(this, _fetchSubject).pipe(
1872
- filter((update) => update.query === query)
1873
- );
1874
- const currentQueryIsStale$ = query.state$.pipe(
1875
- whenNewData,
1876
- switchMap(
1877
- (state) => this.options.staleTime === Infinity ? NEVER : (this.options.staleTime ?? 0) <= 0 ? of(state).pipe(delay(1)) : timer(this.options.staleTime ?? 1)
1878
- ),
1879
- takeWhile(() => this.options.enabled ?? true)
1880
- );
1881
- const comparisonFunction = (objA, objB) => {
1882
- const notifyOnChangeProps = options.notifyOnChangeProps;
1883
- const notifyOnChangePropsValue = typeof notifyOnChangeProps === "function" ? notifyOnChangeProps() : notifyOnChangeProps;
1884
- const reducedFunction = Array.isArray(notifyOnChangePropsValue) ? notifyOnChangePropsValue.length === 0 ? () => true : (objA2, objB2) => {
1885
- const reducedObjA = filterObjectByKey(
1886
- objA2,
1887
- notifyOnChangePropsValue
1888
- );
1889
- const reducedObjB = filterObjectByKey(
1890
- objB2,
1891
- notifyOnChangePropsValue
1892
- );
1893
- return shallowEqual(reducedObjA, reducedObjB);
1894
- } : shallowEqual;
1895
- return reducedFunction(objA, objB);
1896
- };
1897
- const queryInternallyFetchedUpdate$ = queryFetch$.pipe(
1898
- switchMap(() => query.state$),
1899
- takeUntilFinished
1900
- );
1901
- const refetchInterval$ = options$.pipe(
1902
- map(({ refetchInterval, refetchIntervalInBackground }) => {
1903
- const computedRefetchInterval = (typeof refetchInterval === "function" ? refetchInterval(__privateGet(this, _currentQuery)) : refetchInterval) ?? false;
1904
- return {
1905
- refetchInterval: computedRefetchInterval,
1906
- refetchIntervalInBackground
1907
- };
1908
- }),
1909
- distinctUntilChanged(shallowEqual),
1910
- switchMap(({ refetchInterval, refetchIntervalInBackground }) => {
1911
- return !refetchInterval ? NEVER : interval(refetchInterval).pipe(
1912
- tap(() => {
1913
- if (
1914
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
1915
- refetchIntervalInBackground || focusManager.isFocused()
1916
- ) {
1917
- this.fetch({ cancelRefetch: false }).catch(noop$1);
1918
- }
1919
- })
1920
- );
1921
- }),
1922
- ignoreElements()
1923
- );
1924
- const isMaybeEnabled$ = options$.pipe(
1925
- map(({ enabled }) => enabled ?? true),
1926
- distinctUntilChanged()
1927
- );
1928
- const disabled$ = isMaybeEnabled$.pipe(
1929
- filter((enabled) => !enabled),
1930
- map(() => query.state)
1931
- );
1932
- const onFocusRegain$ = isMaybeEnabled$.pipe(
1933
- filter((enabled) => enabled),
1934
- switchMap(() => focusManager.focusRegained$),
1935
- withLatestFrom(options$),
1936
- tap(([, options2]) => {
1937
- if (shouldFetchOnWindowFocus(query, options2)) {
1938
- this.fetch({ cancelRefetch: false }).catch(noop$1);
1939
- }
1940
- }),
1941
- ignoreElements()
1942
- );
1943
- const stateObservedOnDisabled$ = disabled$.pipe(
1944
- map(() => query.state)
1945
- );
1946
- const updateResult = (source) => {
1947
- return source.pipe(
1948
- withLatestFrom(options$),
1949
- map(([, currentOptions]) => {
1950
- const result = this.getObserverResultFromQuery({
1951
- query,
1952
- options: currentOptions,
1953
- prevResult: __privateGet(this, _lastResult)
1954
- });
1955
- this.updateResult({ query, ...result });
1956
- return result.result;
1957
- })
1958
- );
1959
- };
1960
- const stateUpdate$ = merge(
1961
- stateObservedOnDisabled$,
1962
- queryInternallyFetchedUpdate$,
1963
- query.state$,
1964
- // options$,
1965
- currentQueryIsStale$
1966
- );
1967
- const observedResult$ = stateUpdate$.pipe(
1968
- updateResult,
1969
- // This one ensure we don't re-trigger same state
1970
- distinctUntilChanged(shallowEqual),
1971
- // This one make sure we dispatch based on user preference
1972
- distinctUntilChanged(comparisonFunction)
1973
- );
1974
- return merge(refetchInterval$, onFocusRegain$, observedResult$);
1975
- })
1976
- ).pipe(
1977
- trackSubscriptions((count) => __privateSet(this, _observers, count)),
1978
- tap({
1979
- subscribe: () => {
1980
- if (shouldFetchOnMount(observedQuery, this.options)) {
1981
- this.fetch().catch(noop$1);
1982
- }
1983
- }
1984
- })
1985
- )
1986
- );
1987
- return result$;
1988
- }
1989
- destroy() {
1990
- }
1991
- }
1992
- _client = new WeakMap();
1993
- _currentQuery = new WeakMap();
1994
- _fetchSubject = new WeakMap();
1995
- _currentQueryInitialState = new WeakMap();
1996
- _lastResult = new WeakMap();
1997
- _lastQueryWithDefinedData = new WeakMap();
1998
- _observers = new WeakMap();
1999
- function shouldAssignObserverCurrentProperties(observer, optimisticResult) {
2000
- if (!shallowEqual(observer.getCurrentResult(), optimisticResult)) {
2001
- return true;
2002
- }
2003
- return false;
2004
- }
2005
- const IsRestoringContext = React.createContext(false);
2006
- const useIsRestoring = () => React.useContext(IsRestoringContext);
2007
- IsRestoringContext.Provider;
2008
- function createValue() {
2009
- let isReset = false;
2010
- return {
2011
- clearReset: () => {
2012
- isReset = false;
2013
- },
2014
- reset: () => {
2015
- isReset = true;
2016
- },
2017
- isReset: () => {
2018
- return isReset;
2019
- }
2020
- };
2021
- }
2022
- const QueryErrorResetBoundaryContext = React.createContext(createValue());
2023
- const useQueryErrorResetBoundary = () => React.useContext(QueryErrorResetBoundaryContext);
2024
- function shouldThrowError(throwError2, params) {
2025
- if (typeof throwError2 === "function") {
2026
- return throwError2(...params);
2027
- }
2028
- return !!throwError2;
2029
- }
2030
- const getHasError = ({
2031
- result,
2032
- errorResetBoundary,
2033
- throwOnError,
2034
- query
2035
- }) => {
2036
- return result.isError && !errorResetBoundary.isReset() && !result.isFetching && query && shouldThrowError(throwOnError, [result.error, query]);
2037
- };
2038
- function useBaseQuery(options, Observer, queryClient) {
2039
- if (process.env.NODE_ENV !== "production") {
2040
- if (typeof options !== "object" || Array.isArray(options)) {
2041
- throw new Error(
2042
- 'Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object'
2043
- );
2044
- }
2045
- }
2046
- const client = useQueryClient(queryClient);
2047
- const isRestoring = useIsRestoring();
2048
- const errorResetBoundary = useQueryErrorResetBoundary();
2049
- const defaultedOptions = client.defaultQueryOptions(options);
2050
- defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : "optimistic";
2051
- const [observer] = useState(
2052
- () => new Observer(
2053
- client,
2054
- defaultedOptions
2055
- )
2056
- );
2057
- const result$ = useConstant(() => observer.observe());
2058
- const optimisticResult = useLiveRef(
2059
- observer.getOptimisticResult(defaultedOptions)
2060
- );
2061
- const result = optimisticResult.current;
2062
- useObserve(
2063
- () => result$.current.pipe(
2064
- /**
2065
- * By the time this observer runs the result may have changed (eg: synchronous setData).
2066
- * It's important to not skip the first result (even tho most of the time they are equal).
2067
- * We only skip if they are the same.
2068
- */
2069
- filter((result2) => !shallowEqual(result2, optimisticResult.current))
2070
- ),
2071
- []
2072
- );
2073
- useEffect(() => {
2074
- observer.setOptions(defaultedOptions);
2075
- }, [defaultedOptions, observer]);
2076
- const error = result.error;
2077
- if (error && getHasError({
2078
- result,
2079
- errorResetBoundary,
2080
- throwOnError: defaultedOptions.throwOnError,
2081
- query: client.getQueryCache().get(defaultedOptions.queryHash)
2082
- })) {
2083
- throw error;
2084
- }
2085
- return optimisticResult.current;
2086
- }
2087
- function useQuery(options, queryClient) {
2088
- return useBaseQuery(options, QueryObserver, queryClient);
2089
- }
2090
- function useForeverQuery(options, queryClient) {
2091
- return useBaseQuery(
2092
- {
2093
- refetchOnMount: "idle",
2094
- refetchOnReconnect: false,
2095
- refetchInterval: false,
2096
- refetchOnWindowFocus: false,
2097
- ...options
2098
- },
2099
- QueryObserver,
2100
- queryClient
2101
- );
2102
- }
2103
- function useSubscribeEffect(source, unsafeOptions, deps = []) {
2104
- const options = unsafeOptions != null && !Array.isArray(unsafeOptions) ? unsafeOptions : {};
2105
- const retryOption = options.retry ?? true;
2106
- const onErrorRef = useLiveRef(
2107
- options.onError ?? ((error) => {
2108
- console.error(error);
2109
- })
2110
- );
2111
- const sourceAsObservable = useCallback(() => makeObservable(source), deps);
2112
- const enhancerMakeObservable = useCallback(
2113
- () => sourceAsObservable().pipe(
2114
- catchError((error) => {
2115
- onErrorRef.current(error);
2116
- throw error;
2117
- }),
2118
- retryOption ? retry() : identity
2119
- ),
2120
- [sourceAsObservable, retryOption, onErrorRef]
2121
- );
2122
- useSubscribe(enhancerMakeObservable, deps);
2123
- }
2124
- const delayWhenNetworkOnline = () => (source) => {
2125
- return merge(
2126
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
2127
- of({ isPaused: true }),
2128
- onlineManager.backToOnline$.pipe(
2129
- mergeMap$1(
2130
- () => (
2131
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
2132
- merge(of({ isPaused: false }), source)
2133
- )
2134
- )
2135
- )
2136
- );
2137
- };
2138
- const waitForNetworkOnError = (source) => {
2139
- let attempt = 0;
2140
- return source.pipe(
2141
- catchError((error) => {
2142
- attempt++;
2143
- if (attempt <= 1 && !onlineManager.isOnline()) {
2144
- return merge(
2145
- of({
2146
- failureCount: attempt,
2147
- failureReason: error
2148
- }),
2149
- /**
2150
- * @important
2151
- * timer needed to be iso RQ, so the state returned by mutation include both previous and next one
2152
- */
2153
- timer(1).pipe(
2154
- mergeMap$1(
2155
- () => throwError(() => error).pipe(delayWhenNetworkOnline())
2156
- )
2157
- )
2158
- );
2159
- } else {
2160
- return throwError(() => error);
2161
- }
2162
- })
2163
- );
2164
- };
2165
- const executeMutation = ({
2166
- variables,
2167
- state,
2168
- options
2169
- }) => {
2170
- const isPaused = state.isPaused;
2171
- const defaultFn = async () => await Promise.reject(new Error("No mutationFn found"));
2172
- const mutationFn = options.mutationFn ?? defaultFn;
2173
- const onMutateFactory = () => {
2174
- var _a;
2175
- return ((_a = options.onMutate) == null ? void 0 : _a.call(options, variables)) ?? void 0;
2176
- };
2177
- const contextFromOnMutate$ = makeObservable(onMutateFactory);
2178
- contextFromOnMutate$.pipe(
2179
- tap((context) => {
2180
- if (context === void 0) {
2181
- throw new Error("onMutate returned undefined");
2182
- }
2183
- })
2184
- );
2185
- const rawContext$ = of(state.context);
2186
- const context$ = iif(() => isPaused, rawContext$, contextFromOnMutate$).pipe(
2187
- shareReplay(1)
2188
- );
2189
- const onError = (error, context, attempt) => {
2190
- const onError$ = makeObservable(
2191
- () => {
2192
- var _a;
2193
- return (_a = options.onError) == null ? void 0 : _a.call(options, error, variables, context);
2194
- }
2195
- );
2196
- return onError$.pipe(
2197
- catchError(() => of(error)),
2198
- map(
2199
- () => ({
2200
- failureCount: attempt,
2201
- error,
2202
- failureReason: error,
2203
- context,
2204
- status: "error"
2205
- })
2206
- )
2207
- );
2208
- };
2209
- const queryRunner$ = context$.pipe(
2210
- switchMap((context) => {
2211
- const fn$ = typeof mutationFn === "function" ? makeObservable(() => mutationFn(variables)) : mutationFn;
2212
- const sharedFn$ = fn$.pipe(share());
2213
- const completeWithoutValue$ = sharedFn$.pipe(
2214
- isEmpty(),
2215
- tap((isEmppty) => {
2216
- if (isEmppty) {
2217
- throw new Error("Mutation completed without any emission (EMPTY)");
2218
- }
2219
- }),
2220
- ignoreElements()
2221
- );
2222
- const finalFn$ = merge(sharedFn$, completeWithoutValue$).pipe(
2223
- map(
2224
- (data) => ({
2225
- result: {
2226
- data
2227
- },
2228
- error: null,
2229
- context
2230
- })
2231
- ),
2232
- waitForNetworkOnError,
2233
- retryBackoff({
2234
- ...options,
2235
- retry: (attempt, error) => {
2236
- const retry2 = options.retry ?? 0;
2237
- if (typeof retry2 === "function") return retry2(attempt, error);
2238
- if (typeof retry2 === "boolean") return retry2;
2239
- return attempt < retry2;
2240
- },
2241
- caughtError: (attempt, error) => (
2242
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
2243
- of({
2244
- failureCount: attempt,
2245
- failureReason: error
2246
- })
2247
- ),
2248
- catchError: (attempt, error) => onError(error, context, attempt).pipe(
2249
- map((data) => ({
2250
- ...data,
2251
- result: void 0
2252
- }))
2253
- )
2254
- }),
2255
- takeWhile(
2256
- ({ result, error }) => (result == null ? void 0 : result.data) === void 0 && error === void 0,
2257
- true
2258
- )
2259
- );
2260
- if (onlineManager.isOnline() || options.networkMode === "offlineFirst" || options.networkMode === "always") {
2261
- return finalFn$;
2262
- } else {
2263
- return finalFn$.pipe(delayWhenNetworkOnline());
2264
- }
2265
- })
2266
- );
2267
- const initState$ = of({
2268
- ...state,
2269
- variables,
2270
- status: "pending",
2271
- isPaused: false,
2272
- failureCount: 0,
2273
- failureReason: null,
2274
- submittedAt: state.submittedAt ?? (/* @__PURE__ */ new Date()).getTime()
2275
- });
2276
- const mutation$ = merge(
2277
- initState$,
2278
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
2279
- context$.pipe(map((context) => ({ context }))),
2280
- queryRunner$.pipe(
2281
- switchMap(({ result: mutationData, error, ...restState }) => {
2282
- if (!mutationData && !error)
2283
- return of({
2284
- ...restState
2285
- });
2286
- const success$ = error ? of(null) : makeObservable(
2287
- () => {
2288
- var _a;
2289
- return (_a = options.onSuccess) == null ? void 0 : _a.call(
2290
- options,
2291
- mutationData == null ? void 0 : mutationData.data,
2292
- variables,
2293
- restState.context
2294
- );
2295
- }
2296
- );
2297
- const onOptionSettled$ = makeObservable(
2298
- () => {
2299
- var _a;
2300
- return (_a = options.onSettled) == null ? void 0 : _a.call(
2301
- options,
2302
- mutationData == null ? void 0 : mutationData.data,
2303
- error,
2304
- variables,
2305
- restState.context
2306
- );
2307
- }
2308
- );
2309
- const settled$ = onOptionSettled$.pipe(
2310
- catchError((error2) => mutationData ? of(mutationData) : of(error2))
2311
- );
2312
- const result$ = concat(success$, settled$).pipe(
2313
- toArray(),
2314
- map(
2315
- () => error ? {
2316
- error,
2317
- data: void 0,
2318
- variables,
2319
- ...restState
2320
- } : {
2321
- status: "success",
2322
- error,
2323
- data: mutationData == null ? void 0 : mutationData.data,
2324
- variables,
2325
- failureCount: 0,
2326
- failureReason: null,
2327
- ...restState
2328
- }
2329
- ),
2330
- catchError(
2331
- (error2) => onError(error2, restState.context, 0).pipe(
2332
- map((data) => ({
2333
- ...data,
2334
- data: void 0
2335
- }))
2336
- )
2337
- )
2338
- );
2339
- return result$;
2340
- })
2341
- )
2342
- ).pipe(
2343
- scan((acc, current) => {
2344
- return {
2345
- ...acc,
2346
- ...current,
2347
- data: current.data ?? acc.data,
2348
- error: current.error ?? acc.error
2349
- };
2350
- }, getDefaultMutationState())
2351
- );
2352
- return mutation$;
2353
- };
2354
- class Mutation {
2355
- constructor({
2356
- options,
2357
- mutationCache,
2358
- state
2359
- }) {
2360
- __privateAdd(this, _observerCount, new BehaviorSubject(0));
2361
- __privateAdd(this, _cancelSubject, new Subject());
2362
- __privateAdd(this, _executeSubject, new Subject());
2363
- __publicField(this, "state", getDefaultMutationState());
2364
- __publicField(this, "state$");
2365
- __publicField(this, "options");
2366
- __publicField(this, "observerCount$", __privateGet(this, _observerCount).asObservable());
2367
- __publicField(this, "cancelled$", __privateGet(this, _cancelSubject).asObservable());
2368
- this.options = options;
2369
- this.state = state ?? this.state;
2370
- const resetPendingState$ = __privateGet(this, _cancelSubject).pipe(
2371
- filter(() => this.state.status === "pending"),
2372
- map(() => ({
2373
- status: "idle"
2374
- }))
2375
- );
2376
- const executionState$ = __privateGet(this, _executeSubject).pipe(
2377
- switchMap(
2378
- (variables) => executeMutation({
2379
- options: {
2380
- ...this.options,
2381
- onMutate: (variables2) => {
2382
- const onCacheMutate$ = makeObservable(
2383
- () => {
2384
- var _a, _b;
2385
- return (_b = (_a = mutationCache.config).onMutate) == null ? void 0 : _b.call(
2386
- _a,
2387
- variables2,
2388
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2389
- this
2390
- );
2391
- }
2392
- );
2393
- const optionsOnMutate = () => {
2394
- var _a, _b;
2395
- return (_b = (_a = this.options).onMutate) == null ? void 0 : _b.call(_a, variables2);
2396
- };
2397
- const onOptionMutate$ = makeObservable(optionsOnMutate);
2398
- const context$ = onCacheMutate$.pipe(
2399
- mergeMap$1(() => onOptionMutate$)
2400
- );
2401
- return context$;
2402
- },
2403
- onError: (error, variables2, context) => {
2404
- const onCacheError$ = makeObservable(
2405
- () => {
2406
- var _a, _b;
2407
- return (_b = (_a = mutationCache.config).onError) == null ? void 0 : _b.call(
2408
- _a,
2409
- error,
2410
- variables2,
2411
- context,
2412
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2413
- this
2414
- );
2415
- }
2416
- );
2417
- const onOptionError$ = makeObservable(
2418
- () => {
2419
- var _a, _b;
2420
- return (_b = (_a = this.options).onError) == null ? void 0 : _b.call(_a, error, variables2, context);
2421
- }
2422
- );
2423
- return concat(onCacheError$, onOptionError$).pipe(toArray());
2424
- },
2425
- onSettled: (data, error, variables2, context) => {
2426
- const onCacheSuccess$ = makeObservable(
2427
- () => {
2428
- var _a, _b;
2429
- return (_b = (_a = mutationCache.config).onSettled) == null ? void 0 : _b.call(
2430
- _a,
2431
- data,
2432
- error,
2433
- variables2,
2434
- context,
2435
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2436
- this
2437
- );
2438
- }
2439
- );
2440
- const onOptionSettled$ = makeObservable(
2441
- () => {
2442
- var _a, _b;
2443
- return (_b = (_a = this.options).onSettled) == null ? void 0 : _b.call(_a, data, error, variables2, context);
2444
- }
2445
- );
2446
- return concat(onCacheSuccess$, onOptionSettled$).pipe(toArray());
2447
- },
2448
- onSuccess: (data, variables2, context) => {
2449
- const onCacheSuccess$ = makeObservable(
2450
- () => {
2451
- var _a, _b;
2452
- return (_b = (_a = mutationCache.config).onSuccess) == null ? void 0 : _b.call(
2453
- _a,
2454
- data,
2455
- variables2,
2456
- context,
2457
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2458
- this
2459
- );
2460
- }
2461
- );
2462
- const onOptionSuccess$ = makeObservable(
2463
- () => {
2464
- var _a, _b;
2465
- return (_b = (_a = this.options).onSuccess) == null ? void 0 : _b.call(_a, data, variables2, context);
2466
- }
2467
- );
2468
- return concat(onCacheSuccess$, onOptionSuccess$).pipe(toArray());
2469
- }
2470
- },
2471
- state: this.state,
2472
- variables
2473
- }).pipe(takeUntil(__privateGet(this, _cancelSubject)))
2474
- )
2475
- );
2476
- const stateChange$ = merge(resetPendingState$, executionState$);
2477
- this.state$ = stateChange$.pipe(
2478
- startWith(this.state),
2479
- scan(
2480
- (acc, partialState) => ({
2481
- ...acc,
2482
- ...partialState
2483
- }),
2484
- this.state
2485
- ),
2486
- distinctUntilStateChanged,
2487
- tap((value) => {
2488
- this.state = value;
2489
- }),
2490
- shareReplay(1),
2491
- trackSubscriptions((count) => {
2492
- __privateGet(this, _observerCount).next(count);
2493
- })
2494
- );
2495
- }
2496
- get meta() {
2497
- return this.options.meta;
2498
- }
2499
- setOptions(options) {
2500
- this.options = { ...this.options, ...options };
2501
- }
2502
- /**
2503
- * @important
2504
- * The resulting observable will complete as soon as the mutation
2505
- * is over, unlike the state which can be re-subscribed later.
2506
- */
2507
- execute(variables) {
2508
- __privateGet(this, _executeSubject).next(variables);
2509
- __privateGet(this, _executeSubject).complete();
2510
- return this.state$.pipe(observeUntilFinished);
2511
- }
2512
- continue() {
2513
- return this.execute(this.state.variables);
2514
- }
2515
- /**
2516
- * Cancel if needed and finalize the mutation.
2517
- * The mutation will be garbage collected automatically
2518
- * when no more observers are listening
2519
- */
2520
- cancel() {
2521
- __privateGet(this, _cancelSubject).next();
2522
- __privateGet(this, _cancelSubject).complete();
2523
- }
2524
- }
2525
- _observerCount = new WeakMap();
2526
- _cancelSubject = new WeakMap();
2527
- _executeSubject = new WeakMap();
2528
- const createPredicateForFilters = ({
2529
- mutationKey,
2530
- status,
2531
- predicate,
2532
- exact = true
2533
- } = {}) => {
2534
- const finalPredicate = (mutation) => {
2535
- if (exact && mutationKey !== void 0 && mutation.options.mutationKey !== void 0 && !matchKey(mutation.options.mutationKey, mutationKey, { exact })) {
2536
- return false;
2537
- }
2538
- if (!exact && mutationKey !== void 0 && mutation.options.mutationKey !== void 0 && !matchKey(mutation.options.mutationKey, mutationKey, { exact })) {
2539
- return false;
2540
- }
2541
- if (status && mutation.state.status !== status) return false;
2542
- if (predicate) {
2543
- return predicate(mutation);
2544
- }
2545
- return true;
2546
- };
2547
- return finalPredicate;
2548
- };
2549
- class Store {
2550
- constructor() {
2551
- /**
2552
- * @important
2553
- * Query store. Could be turned into a map for more performance.
2554
- */
2555
- __publicField(this, "entriesSubject", new BehaviorSubject([]));
2556
- __publicField(this, "changeSubject", new Subject());
2557
- __publicField(this, "entries$", this.entriesSubject.pipe(share()));
2558
- __publicField(this, "added$", this.changeSubject.pipe(
2559
- filter(({ type }) => type === "added"),
2560
- map(({ entity }) => entity),
2561
- share()
2562
- ));
2563
- __publicField(this, "removed$", this.changeSubject.pipe(
2564
- filter(({ type }) => type === "removed"),
2565
- map(({ entity }) => entity),
2566
- share()
2567
- ));
2568
- __publicField(this, "stateChange$", merge(
2569
- this.entriesSubject.pipe(
2570
- first(),
2571
- mergeMap$1((entities) => from(entities))
2572
- ),
2573
- this.added$
2574
- ).pipe(
2575
- mergeMap$1(
2576
- (entity) => entity.state$.pipe(
2577
- map(() => entity),
2578
- takeUntil(
2579
- this.removed$.pipe(
2580
- filter((removedMutation) => removedMutation === entity)
2581
- )
2582
- )
2583
- )
2584
- ),
2585
- share()
2586
- ));
2587
- }
2588
- getValues() {
2589
- return this.entriesSubject.getValue();
2590
- }
2591
- remove(entity) {
2592
- this.entriesSubject.next(
2593
- this.entriesSubject.getValue().filter((toRemove) => entity !== toRemove)
2594
- );
2595
- this.changeSubject.next({ type: "removed", entity });
2596
- }
2597
- add(entity) {
2598
- this.entriesSubject.next([...this.entriesSubject.getValue(), entity]);
2599
- this.changeSubject.next({ type: "added", entity });
2600
- }
2601
- find(predicate) {
2602
- return this.entriesSubject.getValue().find(predicate);
2603
- }
2604
- }
2605
- class MutationCache {
2606
- constructor(config = {}) {
2607
- __privateAdd(this, _store, new Store());
2608
- this.config = config;
2609
- }
2610
- build(client, options, state) {
2611
- const mutation = new Mutation({
2612
- mutationCache: this,
2613
- options: client.defaultMutationOptions(options),
2614
- state
2615
- });
2616
- mutation.state$.pipe(
2617
- /**
2618
- * Once a mutation is finished and there are no more observers than us
2619
- * we start the process of cleaning it up based on gc settings
2620
- */
2621
- filter(({ status }) => status === "success" || status === "error"),
2622
- switchMap(
2623
- () => mutation.observerCount$.pipe(
2624
- filter((count) => count <= 1),
2625
- take(1)
2626
- )
2627
- ),
2628
- // defaults to 5mn
2629
- switchMap(() => {
2630
- return timer(mutation.options.gcTime ?? 5 * 60 * 1e3);
2631
- }),
2632
- take(1)
2633
- ).subscribe({
2634
- complete: () => {
2635
- this.remove(mutation);
2636
- }
2637
- });
2638
- __privateGet(this, _store).add(mutation);
2639
- return mutation;
2640
- }
2641
- getAll() {
2642
- return this.findAll();
2643
- }
2644
- remove(mutationToRemove) {
2645
- const toRemove = __privateGet(this, _store).getValues().find((mutation) => {
2646
- return mutation === mutationToRemove;
2647
- });
2648
- toRemove == null ? void 0 : toRemove.cancel();
2649
- __privateGet(this, _store).remove(mutationToRemove);
2650
- }
2651
- find(filters) {
2652
- const defaultedFilters = { exact: true, ...filters };
2653
- const predicate = createPredicateForFilters(defaultedFilters);
2654
- return __privateGet(this, _store).getValues().find((mutation) => predicate(mutation));
2655
- }
2656
- findAll(filters = {}) {
2657
- const defaultedFilters = { exact: true, ...filters };
2658
- const predicate = createPredicateForFilters(defaultedFilters);
2659
- return __privateGet(this, _store).getValues().filter((mutation) => predicate(mutation)).map((mutation) => mutation);
2660
- }
2661
- observe() {
2662
- const value$ = __privateGet(this, _store).stateChange$.pipe(startWith());
2663
- return value$;
2664
- }
2665
- /**
2666
- * @important
2667
- * ISO api react-query
2668
- */
2669
- subscribe(listener) {
2670
- const sub = merge(
2671
- __privateGet(this, _store).added$.pipe(
2672
- tap((mutation) => {
2673
- listener({
2674
- type: "added",
2675
- mutation
2676
- });
2677
- })
2678
- ),
2679
- __privateGet(this, _store).removed$.pipe(
2680
- tap((mutation) => {
2681
- listener({
2682
- type: "removed",
2683
- mutation
2684
- });
2685
- })
2686
- ),
2687
- __privateGet(this, _store).stateChange$.pipe(
2688
- tap((mutation) => {
2689
- listener({
2690
- type: "updated",
2691
- action: {
2692
- ...mutation.state,
2693
- type: "success"
2694
- },
2695
- mutation
2696
- });
2697
- })
2698
- )
2699
- ).subscribe();
2700
- return () => {
2701
- sub.unsubscribe();
2702
- };
2703
- }
2704
- resumePausedMutations() {
2705
- const pausedMutations = this.findAll({
2706
- predicate: (mutation) => mutation.state.isPaused
2707
- });
2708
- if (!pausedMutations.length) return EMPTY;
2709
- const mutations$ = pausedMutations.map((mutation) => mutation.continue());
2710
- return combineLatest(mutations$);
2711
- }
2712
- clear() {
2713
- this.getAll().forEach((mutation) => {
2714
- this.remove(mutation);
2715
- });
2716
- }
2717
- }
2718
- _store = new WeakMap();
2719
- function getDefaultState(options) {
2720
- const data = typeof options.initialData === "function" ? options.initialData() : options.initialData;
2721
- const hasData = typeof data !== "undefined";
2722
- const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === "function" ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;
2723
- return {
2724
- data,
2725
- dataUpdateCount: 0,
2726
- dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,
2727
- error: null,
2728
- errorUpdateCount: 0,
2729
- errorUpdatedAt: 0,
2730
- fetchFailureCount: 0,
2731
- fetchFailureReason: null,
2732
- fetchMeta: null,
2733
- isInvalidated: false,
2734
- status: hasData ? "success" : "pending",
2735
- fetchStatus: "idle"
2736
- };
2737
- }
2738
- const delayUntilFocus = (source) => {
2739
- return defer(() => {
2740
- if (!focusManager.isFocused()) {
2741
- return focusManager.focusRegained$.pipe(mergeMap$1(() => source));
2742
- }
2743
- return source;
2744
- });
2745
- };
2746
- const delayOnNetworkMode = (options) => {
2747
- let attempts = 0;
2748
- return (source) => {
2749
- const runWhenOnline$ = onlineManager.backToOnline$.pipe(
2750
- mergeMap$1(
2751
- () => merge(
2752
- of({ fetchStatus: "fetching" }),
2753
- source
2754
- )
2755
- )
2756
- );
2757
- return defer(() => {
2758
- attempts++;
2759
- if (!onlineManager.isOnline() && options.networkMode === "offlineFirst" && attempts > 1) {
2760
- return merge(
2761
- of({ fetchStatus: "paused" }),
2762
- runWhenOnline$
2763
- );
2764
- }
2765
- if (!onlineManager.isOnline() && options.networkMode !== "always" && options.networkMode !== "offlineFirst") {
2766
- return merge(
2767
- of({ fetchStatus: "paused" }),
2768
- runWhenOnline$
2769
- );
2770
- }
2771
- return source;
2772
- });
2773
- };
2774
- };
2775
- const completeFnIfNotMoreObservers = (observers$) => (source) => {
2776
- const hasDataSubject = new Subject();
2777
- const hasDataAndNoObservers$ = hasDataSubject.pipe(
2778
- first(),
2779
- /**
2780
- * Since we set hasDataSubject synchronously, we need to wait
2781
- * for the next tick to make sure observable chain received this data at least
2782
- */
2783
- delay(1),
2784
- mergeMap$1(() => observers$.pipe(filter((value) => value === 0)))
2785
- );
2786
- return source.pipe(
2787
- tap(() => {
2788
- hasDataSubject.next();
2789
- }),
2790
- takeUntil(hasDataAndNoObservers$)
2791
- );
2792
- };
2793
- const executeQuery = (options) => {
2794
- const defaultFn = async () => await Promise.reject(new Error("No query found"));
2795
- if (process.env.NODE_ENV !== "production") {
2796
- if (options.queryFn === skipToken) {
2797
- console.error(
2798
- `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`
2799
- );
2800
- }
2801
- }
2802
- let fnIsComplete = false;
2803
- const queryFn = options.queryFn && options.queryFn !== skipToken ? options.queryFn : defaultFn;
2804
- const abortController = new AbortController();
2805
- const queryFnContext = {
2806
- meta: options.meta,
2807
- queryKey: options.queryKey
2808
- };
2809
- const addSignalProperty = (object) => {
2810
- Object.defineProperty(object, "signal", {
2811
- enumerable: true,
2812
- get: () => {
2813
- options.onSignalConsumed();
2814
- return abortController.signal;
2815
- }
2816
- });
2817
- };
2818
- addSignalProperty(queryFnContext);
2819
- const fn$ = typeof queryFn === "function" ? (
2820
- // eslint-disable-next-line @typescript-eslint/promise-function-async
2821
- makeObservable(
2822
- () => queryFn(queryFnContext)
2823
- )
2824
- ) : queryFn;
2825
- const execution$ = fn$.pipe(
2826
- completeFnIfNotMoreObservers(options.observers$),
2827
- tap({
2828
- complete: () => {
2829
- fnIsComplete = true;
2830
- }
2831
- }),
2832
- map(
2833
- (data) => ({
2834
- data
2835
- })
2836
- ),
2837
- // takeUntil(hasDataAndNoObservers$),
2838
- delayOnNetworkMode(options),
2839
- retryBackoff({
2840
- ...options,
2841
- retryAfter: () => of(true).pipe(delayUntilFocus),
2842
- catchError: (attempt, error) => of({
2843
- status: "error",
2844
- fetchStatus: "idle",
2845
- fetchFailureCount: attempt,
2846
- fetchFailureReason: error,
2847
- error
2848
- }),
2849
- caughtError: (attempt, error) => (
2850
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
2851
- of({
2852
- fetchFailureCount: attempt,
2853
- fetchFailureReason: error
2854
- })
2855
- )
2856
- }),
2857
- mergeMap$1((state) => {
2858
- if (!("data" in state)) return of(state);
2859
- return of({
2860
- ...state,
2861
- status: "success",
2862
- fetchStatus: "idle",
2863
- fetchFailureCount: 0,
2864
- fetchFailureReason: null,
2865
- dataUpdatedAt: (/* @__PURE__ */ new Date()).getTime()
2866
- }).pipe(
2867
- /**
2868
- * Because we don't know yet whether the fn is an observable or a promise we wait
2869
- * for next tick and check if the function has been complete. This prevent having
2870
- * two dispatch for promise where we would have extra "fetching" & "idle" dispatch
2871
- *
2872
- * @important
2873
- * Another reason why this delay is necessary is to pass RQ tests. This is because
2874
- * their flow expect a sequence of results to sometimes happens in a specific
2875
- * way. If we have non promise function, we have results faster than what RQ expect
2876
- * due to this library architecture and some variables are impossible to determine
2877
- * correctly (eg: isFetchedAfterMount). There is nothing wrong, it's just a way to
2878
- * force any function as promise (or more specifically to return in next tick).
2879
- *
2880
- * There is in theory no problem associated to that.
2881
- */
2882
- delay(1),
2883
- map(
2884
- (state2) => fnIsComplete ? state2 : { ...state2, fetchStatus: "fetching" }
2885
- )
2886
- );
2887
- }),
2888
- /**
2889
- * When the fn complete we can release the fetch status, if it was already released
2890
- * before shallow compare will not update the state, otherwise it's our chance to catch
2891
- * the end of observable fn.
2892
- */
2893
- endWith({ fetchStatus: "idle" }),
2894
- share()
2895
- );
2896
- const initialResult$ = of({
2897
- status: "pending",
2898
- fetchStatus: onlineManager.isOnline() ? "fetching" : "paused"
2899
- });
2900
- return {
2901
- state$: merge(
2902
- initialResult$,
2903
- execution$
2904
- // emitOnComplete$
2905
- ).pipe(share()),
2906
- abortController
2907
- };
2908
- };
2909
- class CancelledError {
2910
- constructor(options) {
2911
- __publicField(this, "revert");
2912
- __publicField(this, "silent");
2913
- this.revert = options == null ? void 0 : options.revert;
2914
- this.silent = options == null ? void 0 : options.silent;
2915
- }
2916
- }
2917
- const resetStyle = { backgroundColor: "transparent", color: "inherit" };
2918
- function createLogger(env) {
2919
- const _logger = {
2920
- namespaces: [
2921
- {
2922
- name: "@reactjrx",
2923
- style: { backgroundColor: "#d02f4e", color: "white" }
2924
- }
2925
- ],
2926
- namespace(name, style) {
2927
- const logger = createLogger();
2928
- logger.namespaces.push({
2929
- name,
2930
- style: style ?? resetStyle
2931
- });
2932
- return logger;
2933
- },
2934
- printNamespaces() {
2935
- return {
2936
- namespaces: _logger.namespaces.map(({ name }) => `%c ${name} %c`).join(" "),
2937
- styles: _logger.namespaces.reduce((acc, { style }) => {
2938
- acc.push(
2939
- `background-color: ${style.backgroundColor}; color: ${style.color};`
2940
- );
2941
- acc.push("background-color: transparent; color: inherit;");
2942
- return acc;
2943
- }, [])
2944
- };
2945
- },
2946
- print(method, ...message) {
2947
- return _logger;
2948
- },
2949
- printWithoutNamespace(method, ...message) {
2950
- return _logger;
2951
- },
2952
- log(...message) {
2953
- return _logger.print("log", ...message);
2954
- },
2955
- warn(...message) {
2956
- return _logger.print("warn", ...message);
2957
- },
2958
- error(...message) {
2959
- return _logger.print("error", ...message);
2960
- },
2961
- group(...message) {
2962
- return _logger.print("group", ...message);
2963
- },
2964
- groupEnd() {
2965
- return _logger;
2966
- }
2967
- };
2968
- return _logger;
2969
- }
2970
- const Logger = createLogger();
2971
- class Query {
2972
- constructor(config) {
2973
- __publicField(this, "queryKey");
2974
- __publicField(this, "queryHash");
2975
- __publicField(this, "gcTime");
2976
- __publicField(this, "options");
2977
- __privateAdd(this, _defaultOptions);
2978
- __privateAdd(this, _initialState);
2979
- __publicField(this, "state");
2980
- // @todo to share with mutation
2981
- __publicField(this, "executeSubject", new Subject());
2982
- __publicField(this, "cancelSubject", new Subject());
2983
- __publicField(this, "setDataSubject", new Subject());
2984
- __publicField(this, "invalidatedSubject", new Subject());
2985
- __publicField(this, "resetSubject", new Subject());
2986
- __publicField(this, "destroySubject", new Subject());
2987
- __publicField(this, "observersSubject", new BehaviorSubject([]));
2988
- __publicField(this, "abortSignalConsumed", false);
2989
- __publicField(this, "observerCount$", this.observersSubject.asObservable().pipe(map((observers) => observers.length)));
2990
- __publicField(this, "observers$", this.observersSubject.asObservable());
2991
- __publicField(this, "state$");
2992
- __privateSet(this, _defaultOptions, config.defaultOptions);
2993
- this.options = this.setOptions(config.options);
2994
- this.queryKey = config.queryKey;
2995
- this.queryHash = config.queryHash;
2996
- __privateSet(this, _initialState, config.state ?? getDefaultState(this.options));
2997
- this.state = __privateGet(this, _initialState);
2998
- this.gcTime = this.updateGcTime(this.options.gcTime);
2999
- this.state$ = merge(
3000
- this.resetSubject.pipe(
3001
- map(() => ({ command: "reset", state: __privateGet(this, _initialState) }))
3002
- ),
3003
- this.invalidatedSubject.pipe(
3004
- filter(() => !this.state.isInvalidated),
3005
- map(() => ({
3006
- command: "invalidate",
3007
- state: {
3008
- isInvalidated: true
3009
- }
3010
- }))
3011
- ),
3012
- this.cancelSubject.pipe(
3013
- filter(() => {
3014
- const isQueryOnError = this.state.error && this.state.status === "error";
3015
- return !isQueryOnError;
3016
- }),
3017
- map((options) => ({
3018
- command: "cancel",
3019
- state: {
3020
- status: (options == null ? void 0 : options.revert) ? this.state.status : "error",
3021
- fetchStatus: "idle",
3022
- error: new CancelledError(options)
3023
- }
3024
- }))
3025
- ),
3026
- this.executeSubject.pipe(
3027
- mergeMap$1(() => {
3028
- let noMoreObserversActive = false;
3029
- const cancelFromNewRefetch$ = this.executeSubject.pipe(
3030
- // should not be needed since the fetch return current promise
3031
- // in case we don't cancel
3032
- filter((options) => (options == null ? void 0 : options.cancelRefetch) !== false)
3033
- );
3034
- const detectNoMoreObserversActive$ = this.observers$.pipe(
3035
- pairwise(),
3036
- tap(([prevObservers, currentObservers]) => {
3037
- if (currentObservers.length === 0 && prevObservers.length > 0) {
3038
- noMoreObserversActive = true;
3039
- } else {
3040
- noMoreObserversActive = false;
3041
- }
3042
- }),
3043
- ignoreElements()
3044
- );
3045
- const { state$: functionExecution$, abortController } = executeQuery({
3046
- ...this.options,
3047
- observers$: this.observerCount$,
3048
- queryKey: this.queryKey,
3049
- retry: (attempt, error) => {
3050
- const retry2 = this.options.retry ?? true;
3051
- if (typeof retry2 === "function") return retry2(attempt, error);
3052
- if (typeof retry2 === "boolean") return retry2;
3053
- return attempt < retry2;
3054
- },
3055
- retryAfterDelay: () => {
3056
- if (noMoreObserversActive) return false;
3057
- return true;
3058
- },
3059
- onSignalConsumed: () => {
3060
- this.abortSignalConsumed = true;
3061
- }
3062
- });
3063
- const executionAbortedFromSignal$ = this.observerCount$.pipe(
3064
- filter((count) => count === 0 && this.abortSignalConsumed),
3065
- tap(() => {
3066
- this.cancelSubject.next({ revert: true });
3067
- })
3068
- );
3069
- const cancelExecution$ = merge(
3070
- this.cancelSubject,
3071
- cancelFromNewRefetch$,
3072
- this.resetSubject,
3073
- executionAbortedFromSignal$
3074
- ).pipe(
3075
- tap(() => {
3076
- if (this.abortSignalConsumed) {
3077
- abortController.abort();
3078
- }
3079
- })
3080
- );
3081
- return merge(functionExecution$, detectNoMoreObserversActive$).pipe(
3082
- map((state) => ({
3083
- command: "execute",
3084
- state
3085
- })),
3086
- takeUntil(cancelExecution$)
3087
- );
3088
- })
3089
- ),
3090
- this.setDataSubject.pipe(
3091
- map(({ data, options }) => ({
3092
- command: "setData",
3093
- state: {
3094
- status: "success",
3095
- data,
3096
- dataUpdatedAt: (options == null ? void 0 : options.updatedAt) !== void 0 ? options.updatedAt : (/* @__PURE__ */ new Date()).getTime()
3097
- }
3098
- }))
3099
- )
3100
- ).pipe(
3101
- reduceState({
3102
- initialState: this.state,
3103
- getOptions: () => this.options,
3104
- getState: () => this.state
3105
- }),
3106
- startWith(__privateGet(this, _initialState)),
3107
- distinctUntilChanged(shallowEqual),
3108
- tap((state) => {
3109
- this.state = state;
3110
- }),
3111
- catchError((e) => {
3112
- Logger.error(e);
3113
- throw e;
3114
- }),
3115
- takeUntil(this.destroySubject),
3116
- shareReplay({ bufferSize: 1, refCount: false })
3117
- );
3118
- }
3119
- setOptions(options) {
3120
- this.options = { ...__privateGet(this, _defaultOptions), ...options };
3121
- this.updateGcTime(this.options.gcTime);
3122
- return this.options;
3123
- }
3124
- get meta() {
3125
- return this.options.meta;
3126
- }
3127
- get success$() {
3128
- return this.state$.pipe(
3129
- map(({ data, status }) => ({ data, status })),
3130
- distinctUntilChanged(shallowEqual),
3131
- filter(({ status }) => status === "success")
3132
- );
3133
- }
3134
- get error$() {
3135
- return this.state$.pipe(
3136
- map(({ error, status }) => ({ error, status })),
3137
- distinctUntilChanged(shallowEqual),
3138
- filter(({ status }) => status === "error")
3139
- );
3140
- }
3141
- get settled$() {
3142
- return this.state$.pipe(
3143
- map(({ status }) => ({ status })),
3144
- distinctUntilChanged(shallowEqual),
3145
- filter(({ status }) => status === "success" || status === "error")
3146
- );
3147
- }
3148
- observe(observer) {
3149
- const state$ = this.state$.pipe(
3150
- tap({
3151
- subscribe: () => {
3152
- this.observersSubject.next([
3153
- observer,
3154
- ...this.observersSubject.getValue()
3155
- ]);
3156
- },
3157
- unsubscribe: () => {
3158
- this.observersSubject.next(
3159
- this.observersSubject.getValue().filter((item) => item !== observer)
3160
- );
3161
- }
3162
- })
3163
- );
3164
- return state$;
3165
- }
3166
- getObserversCount() {
3167
- return this.observersSubject.getValue().length;
3168
- }
3169
- // @todo this can be shared with mutation
3170
- updateGcTime(newGcTime) {
3171
- this.gcTime = Math.max(
3172
- this.gcTime || 0,
3173
- newGcTime ?? (isServer ? Infinity : 5 * 60 * 1e3)
3174
- );
3175
- return this.gcTime;
3176
- }
3177
- isActive() {
3178
- return this.observersSubject.getValue().some((observer) => observer.options.enabled !== false);
3179
- }
3180
- isDisabled() {
3181
- return this.getObserversCount() > 0 && !this.isActive();
3182
- }
3183
- isStale() {
3184
- return this.state.isInvalidated || !this.state.dataUpdatedAt || this.observersSubject.getValue().some((observer) => observer.getCurrentResult().isStale);
3185
- }
3186
- isStaleByTime(staleTime = 0) {
3187
- return this.state.isInvalidated || !this.state.dataUpdatedAt || !timeUntilStale(this.state.dataUpdatedAt, staleTime);
3188
- }
3189
- async getFetchResultAsPromise() {
3190
- return await new Promise((resolve, reject) => {
3191
- this.state$.pipe(takeUntilFinished, last()).subscribe({
3192
- error: reject,
3193
- next: (data) => {
3194
- if (data.error) {
3195
- reject(data.error);
3196
- } else {
3197
- resolve(data.data);
3198
- }
3199
- }
3200
- });
3201
- });
3202
- }
3203
- async fetch(options, fetchOptions) {
3204
- const { cancelRefetch } = fetchOptions ?? {};
3205
- if (this.state.fetchStatus !== "idle") {
3206
- const shouldCancelRequest = !!this.state.dataUpdatedAt && cancelRefetch;
3207
- if (!shouldCancelRequest) {
3208
- return await this.getFetchResultAsPromise();
3209
- }
3210
- }
3211
- if (options) {
3212
- this.setOptions(options);
3213
- }
3214
- this.executeSubject.next(fetchOptions);
3215
- return await this.getFetchResultAsPromise();
3216
- }
3217
- setData(newData, options) {
3218
- const data = replaceData(this.state.data, newData, this.options);
3219
- this.setDataSubject.next({ data, options });
3220
- return data;
3221
- }
3222
- invalidate() {
3223
- this.invalidatedSubject.next();
3224
- }
3225
- async cancel(options) {
3226
- this.cancelSubject.next(options);
3227
- }
3228
- // @todo merge with mutation
3229
- destroy() {
3230
- this.destroySubject.next();
3231
- this.destroySubject.complete();
3232
- this.executeSubject.complete();
3233
- }
3234
- // @todo merge with mutation
3235
- reset() {
3236
- this.resetSubject.next();
3237
- }
3238
- }
3239
- _defaultOptions = new WeakMap();
3240
- _initialState = new WeakMap();
3241
- class QueryCache {
3242
- // protected mountSubscriptions: Subscription[]
3243
- constructor(config = {}) {
3244
- // readonly #queries: QueryStore = new Map<string, Query>()
3245
- __privateAdd(this, _notifySubject, new Subject());
3246
- __privateAdd(this, _store2, new Store());
3247
- this.config = config;
3248
- }
3249
- mount() {
3250
- }
3251
- unmount() {
3252
- }
3253
- notify(event) {
3254
- __privateGet(this, _notifySubject).next(event);
3255
- }
3256
- observeIsFetching(filters) {
3257
- const value$ = __privateGet(this, _store2).stateChange$.pipe(
3258
- // we force a first result
3259
- startWith(),
3260
- map(() => {
3261
- const filteredEntities = this.findAll({
3262
- ...filters,
3263
- fetchStatus: "fetching"
3264
- });
3265
- return filteredEntities.length;
3266
- }),
3267
- distinctUntilChanged()
3268
- );
3269
- return value$;
3270
- }
3271
- getAll() {
3272
- return [...__privateGet(this, _store2).getValues()];
3273
- }
3274
- findAll(filters = {}) {
3275
- const queries = this.getAll();
3276
- return Object.keys(filters).length > 0 ? queries.filter((query) => matchQuery(filters, query)) : queries;
3277
- }
3278
- build(client, options, state) {
3279
- const queryKey = options.queryKey ?? [nanoid()];
3280
- const queryHash = options.queryHash ?? hashQueryKeyByOptions(queryKey, options);
3281
- let query = this.get(queryHash);
3282
- if (!query) {
3283
- query = new Query({
3284
- cache: this,
3285
- queryKey,
3286
- queryHash,
3287
- options: client.defaultQueryOptions(options),
3288
- state,
3289
- defaultOptions: client.getQueryDefaults(queryKey)
3290
- });
3291
- this.add(query);
3292
- }
3293
- return query;
3294
- }
3295
- add(query) {
3296
- if (!__privateGet(this, _store2).find((entity) => entity.queryHash === query.queryHash)) {
3297
- __privateGet(this, _store2).add(query);
3298
- const noMoreObservers$ = query.observerCount$.pipe(
3299
- filter((count) => count < 1),
3300
- take(1)
3301
- );
3302
- query.success$.subscribe(() => {
3303
- var _a, _b;
3304
- (_b = (_a = this.config).onSuccess) == null ? void 0 : _b.call(_a, query.state.data, query);
3305
- });
3306
- query.error$.subscribe(() => {
3307
- var _a, _b;
3308
- (_b = (_a = this.config).onError) == null ? void 0 : _b.call(_a, query.state.error, query);
3309
- });
3310
- query.settled$.subscribe(() => {
3311
- var _a, _b;
3312
- (_b = (_a = this.config).onSettled) == null ? void 0 : _b.call(
3313
- _a,
3314
- query.state.data,
3315
- query.state.error,
3316
- query
3317
- );
3318
- });
3319
- query.state$.pipe(
3320
- /**
3321
- * Once a mutation is finished and there are no more observers than us
3322
- * we start the process of cleaning it up based on gc settings
3323
- */
3324
- isQueryFinished,
3325
- switchMap((isFinished) => {
3326
- return !isFinished ? NEVER : noMoreObservers$.pipe(
3327
- // defaults to 5mn
3328
- switchMap(() => {
3329
- if (query.gcTime === Infinity) return NEVER;
3330
- setTimeout(noop$1, query.gcTime);
3331
- return timer(query.gcTime);
3332
- })
3333
- );
3334
- }),
3335
- take(1)
3336
- ).subscribe({
3337
- complete: () => {
3338
- this.remove(query);
3339
- }
3340
- });
3341
- }
3342
- }
3343
- get(queryHash) {
3344
- return __privateGet(this, _store2).find((query) => query.queryHash === queryHash);
3345
- }
3346
- find(filters) {
3347
- const defaultedFilters = { exact: true, ...filters };
3348
- return this.getAll().find(
3349
- (query) => matchQuery(defaultedFilters, query)
3350
- );
3351
- }
3352
- subscribe(fn) {
3353
- const sub = merge(
3354
- __privateGet(this, _notifySubject).pipe(tap(fn))
3355
- // this.#store.added$.pipe(
3356
- // mergeMap((query) => {
3357
- // fn({
3358
- // query,
3359
- // type: "added"
3360
- // })
3361
- // return query.observers$.pipe(
3362
- // tap((observer) => {
3363
- // fn({
3364
- // type: "observerAdded",
3365
- // observer: observer as unknown as QueryObserver<
3366
- // any,
3367
- // any,
3368
- // any,
3369
- // any,
3370
- // any
3371
- // >,
3372
- // query
3373
- // })
3374
- // })
3375
- // )
3376
- // })
3377
- // )
3378
- ).subscribe();
3379
- return () => {
3380
- sub.unsubscribe();
3381
- };
3382
- }
3383
- remove(query) {
3384
- const queryInMap = __privateGet(this, _store2).find((entity) => entity === query);
3385
- if (queryInMap) {
3386
- query.destroy();
3387
- if (queryInMap === query) {
3388
- __privateGet(this, _store2).remove(query);
3389
- }
3390
- }
3391
- }
3392
- clear() {
3393
- }
3394
- }
3395
- _notifySubject = new WeakMap();
3396
- _store2 = new WeakMap();
3397
- class QueryClient {
3398
- // #destroy = () => {}
3399
- constructor({
3400
- mutationCache,
3401
- queryCache,
3402
- defaultOptions
3403
- } = {}) {
3404
- __privateAdd(this, _mutationCache);
3405
- __privateAdd(this, _queryCache);
3406
- __privateAdd(this, _mutationDefaults, /* @__PURE__ */ new Map());
3407
- __privateAdd(this, _queryDefaults, /* @__PURE__ */ new Map());
3408
- __privateAdd(this, _defaultOptions2);
3409
- __privateSet(this, _mutationCache, mutationCache ?? new MutationCache());
3410
- __privateSet(this, _queryCache, queryCache ?? new QueryCache());
3411
- __privateSet(this, _defaultOptions2, defaultOptions ?? {});
3412
- }
3413
- mount() {
3414
- }
3415
- unmount() {
3416
- }
3417
- getMutationCache() {
3418
- return __privateGet(this, _mutationCache);
3419
- }
3420
- getQueryCache() {
3421
- return __privateGet(this, _queryCache);
3422
- }
3423
- defaultMutationOptions(options) {
3424
- return {
3425
- ...__privateGet(this, _defaultOptions2).mutations,
3426
- ...(options == null ? void 0 : options.mutationKey) && this.getMutationDefaults(options.mutationKey),
3427
- ...options
3428
- };
3429
- }
3430
- defaultQueryOptions(options) {
3431
- if (options._defaulted) {
3432
- return options;
3433
- }
3434
- const defaultedOptions = {
3435
- ...__privateGet(this, _defaultOptions2).queries,
3436
- ...this.getQueryDefaults(options.queryKey),
3437
- ...options,
3438
- _defaulted: true
3439
- };
3440
- if (!defaultedOptions.queryHash) {
3441
- defaultedOptions.queryHash = hashQueryKeyByOptions(
3442
- defaultedOptions.queryKey,
3443
- defaultedOptions
3444
- );
3445
- }
3446
- if (defaultedOptions.refetchOnReconnect === void 0) {
3447
- defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== "always";
3448
- }
3449
- if (defaultedOptions.throwOnError === void 0) {
3450
- defaultedOptions.throwOnError = !!defaultedOptions.suspense;
3451
- }
3452
- if (!defaultedOptions.networkMode && defaultedOptions.persister) {
3453
- defaultedOptions.networkMode = "offlineFirst";
3454
- }
3455
- if (defaultedOptions.enabled !== true && defaultedOptions.queryFn === skipToken) {
3456
- defaultedOptions.enabled = false;
3457
- }
3458
- return defaultedOptions;
3459
- }
3460
- async fetchQuery(options) {
3461
- const defaultedOptions = this.defaultQueryOptions(options);
3462
- if (typeof defaultedOptions.retry === "undefined") {
3463
- defaultedOptions.retry = false;
3464
- }
3465
- const query = __privateGet(this, _queryCache).build(this, defaultedOptions);
3466
- return query.isStaleByTime(defaultedOptions.staleTime) ? await query.fetch(defaultedOptions) : await Promise.resolve(query.state.data);
3467
- }
3468
- async prefetchQuery(options) {
3469
- await this.fetchQuery(options).then(noop$1).catch(noop$1);
3470
- }
3471
- async resetQueries(filters, options) {
3472
- const queryCache = __privateGet(this, _queryCache);
3473
- const refetchFilters = {
3474
- type: "active",
3475
- ...filters
3476
- };
3477
- queryCache.findAll(filters).forEach((query) => {
3478
- query.reset();
3479
- });
3480
- await this.refetchQueries(refetchFilters, options);
3481
- }
3482
- async refetchQueries(filters = {}, options) {
3483
- const fetchOptions = {
3484
- ...options,
3485
- cancelRefetch: (options == null ? void 0 : options.cancelRefetch) ?? true
3486
- };
3487
- const promises = __privateGet(this, _queryCache).findAll(filters).filter((query) => !query.isDisabled()).map(async (query) => {
3488
- let promise = query.fetch(void 0, fetchOptions);
3489
- if (!fetchOptions.throwOnError) {
3490
- promise = promise.catch(noop$1);
3491
- }
3492
- return query.state.fetchStatus === "paused" ? void 0 : await promise;
3493
- });
3494
- await Promise.all(promises).then(noop$1);
3495
- }
3496
- getQueryData(queryKey) {
3497
- var _a;
3498
- const options = this.defaultQueryOptions({ queryKey });
3499
- return (_a = __privateGet(this, _queryCache).get(options.queryHash)) == null ? void 0 : _a.state.data;
3500
- }
3501
- setQueryData(queryKey, updater, options) {
3502
- const defaultedOptions = this.defaultQueryOptions({ queryKey });
3503
- const query = __privateGet(this, _queryCache).get(
3504
- defaultedOptions.queryHash
3505
- );
3506
- const prevData = query == null ? void 0 : query.state.data;
3507
- const data = functionalUpdate(updater, prevData);
3508
- if (data === void 0) {
3509
- return void 0;
3510
- }
3511
- return __privateGet(this, _queryCache).build(this, defaultedOptions).setData(data, { ...options, manual: true });
3512
- }
3513
- getMutationDefaults(mutationKey) {
3514
- const defaults = [...__privateGet(this, _mutationDefaults).values()];
3515
- let result = {};
3516
- defaults.forEach((queryDefault) => {
3517
- if (matchKey(mutationKey, queryDefault.mutationKey)) {
3518
- result = { ...result, ...queryDefault.defaultOptions };
3519
- }
3520
- });
3521
- return result;
3522
- }
3523
- getQueryState(queryKey) {
3524
- var _a;
3525
- return (_a = __privateGet(this, _queryCache).find({ queryKey })) == null ? void 0 : _a.state;
3526
- }
3527
- setMutationDefaults(mutationKey, options) {
3528
- __privateGet(this, _mutationDefaults).set(hashKey(mutationKey), {
3529
- mutationKey,
3530
- defaultOptions: options
3531
- });
3532
- }
3533
- setQueryDefaults(queryKey, options) {
3534
- __privateGet(this, _queryDefaults).set(hashKey(queryKey), {
3535
- queryKey,
3536
- defaultOptions: options
3537
- });
3538
- }
3539
- getQueryDefaults(queryKey) {
3540
- const defaults = [...__privateGet(this, _queryDefaults).values()];
3541
- let result = {};
3542
- defaults.forEach((queryDefault) => {
3543
- if (partialMatchKey(queryKey, queryDefault.queryKey)) {
3544
- result = { ...result, ...queryDefault.defaultOptions };
3545
- }
3546
- });
3547
- return result;
3548
- }
3549
- removeQueries(filters) {
3550
- const queryCache = __privateGet(this, _queryCache);
3551
- queryCache.findAll(filters).forEach((query) => {
3552
- queryCache.remove(query);
3553
- });
3554
- }
3555
- async cancelQueries(filters = {}, cancelOptions = {}) {
3556
- const defaultedCancelOptions = { revert: true, ...cancelOptions };
3557
- const promises = __privateGet(this, _queryCache).findAll(filters).map(async (query) => {
3558
- await query.cancel(defaultedCancelOptions);
3559
- });
3560
- await Promise.all(promises).then(noop$1).catch(noop$1);
3561
- }
3562
- async invalidateQueries(filters = {}, options = {}) {
3563
- __privateGet(this, _queryCache).findAll(filters).forEach((query) => {
3564
- query.invalidate();
3565
- });
3566
- if (filters.refetchType === "none") {
3567
- await Promise.resolve();
3568
- return;
3569
- }
3570
- const refetchFilters = {
3571
- ...filters,
3572
- type: filters.refetchType ?? filters.type ?? "active"
3573
- };
3574
- await this.refetchQueries(refetchFilters, options);
3575
- }
3576
- async resumePausedMutations() {
3577
- return await lastValueFrom(__privateGet(this, _mutationCache).resumePausedMutations());
3578
- }
3579
- isFetching(filters) {
3580
- return __privateGet(this, _queryCache).findAll({ ...filters, fetchStatus: "fetching" }).length;
3581
- }
3582
- clear() {
3583
- __privateGet(this, _queryCache).clear();
3584
- __privateGet(this, _mutationCache).clear();
3585
- }
3586
- }
3587
- _mutationCache = new WeakMap();
3588
- _queryCache = new WeakMap();
3589
- _mutationDefaults = new WeakMap();
3590
- _queryDefaults = new WeakMap();
3591
- _defaultOptions2 = new WeakMap();
3592
916
  export {
3593
- Context$1 as Context,
3594
- MutationCache,
3595
- QueryCache,
3596
- QueryClient,
917
+ Context,
3597
918
  QueryClient$,
3598
- QueryClientProvider,
3599
919
  QueryClientProvider$,
3600
920
  SIGNAL_RESET,
3601
921
  arrayEqual,
@@ -3609,20 +929,17 @@ export {
3609
929
  retryBackoff,
3610
930
  signal,
3611
931
  useBehaviorSubject,
932
+ useContactMutation$,
3612
933
  useEffectOnce,
3613
- useForeverQuery,
3614
934
  useLiveBehaviorSubject,
3615
935
  useLiveRef,
3616
936
  useMount,
3617
- useMutation,
3618
937
  useMutation$,
3619
938
  useObservableCallback,
3620
939
  useObservableState,
3621
940
  useObserve,
3622
941
  usePersistSignals,
3623
- useQuery,
3624
942
  useQuery$,
3625
- useQueryClient,
3626
943
  useQueryClient$,
3627
944
  useSignal,
3628
945
  useSignalValue,