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